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/patterns.py ADDED
@@ -0,0 +1,830 @@
1
+ """Waste in how queries are called: loops, repeats and polls, as patterns with evidence.
2
+
3
+ A pattern is a way a query is called that multiplies its work, read from the inventory's loops (`loop_context`) and,
4
+ when a real database was pulled (`codecop db pull`), from the measured workload. It is a candidate with evidence, never a
5
+ win: removing it is a code change (or a change of schedule, or a cache) that the developer or their coding agent makes,
6
+ and what CodeCop can prove about that change is stated with it (`changes`).
7
+
8
+ Kinds, from the code (no agent, no network):
9
+
10
+ n_plus_one a query per item of a loop whose collection is another query's result (the driver), and the query
11
+ takes the item. One query for all items (IN, or a join into the driver) does the same work.
12
+ per_item a query per item of a loop over anything else (a parameter, a field, a list built in code, a long
13
+ literal list), taking the item: batchable by IN or a join.
14
+ fan_out a query per item of a loop, inside which a step through time (or a fixed count) repeats it again:
15
+ items x windows.
16
+ same_input a query inside a loop that does not take the loop's variable: the same statement every turn.
17
+ poll a query inside a loop that waits between passes (a sleep, a ticker): how often it runs is the
18
+ cost. A trade-off against freshness, never a verified win.
19
+
20
+ Kinds, from the measured workload (each shape counted once; see `accounting`):
21
+
22
+ fires_together shapes whose run counts agree within a tolerance: the signature of one loop or one run that sends
23
+ them all. "In production only" unless their call sites share a pattern or a function.
24
+ hot_small a shape run very often that returns few rows: a lookup, a probe or a poll. Rarely a cache.
25
+ heavy_aggregate an aggregate run often that reads a lot each time: a rollup is a trade-off.
26
+ large_result a shape that hands many rows to the application per run: what the code does with them decides.
27
+ offset_paging OFFSET paging measured in production: depth is a parameter, not in the log.
28
+
29
+ Set aside (counted, not patterns): a loop that already batches (`chunk`), a retry, a long-running worker loop, a
30
+ short literal list, a lone step through time, a loop of unknown kind.
31
+
32
+ Confidence is three states in words: `code_and_production` (the structure is in the code and the counts agree with
33
+ it), `production_only` (shapes fire together; no code located), `code_only` (no measurement, or the log disagrees:
34
+ `notes` says which). The code side is `verified` only when every caller hop and the driver were resolved by a call
35
+ the code makes and the query is known to take (or not take) the loop's variable; otherwise `guessed`.
36
+
37
+ Thresholds are settings under `[patterns]` in codecop.toml (DEFAULTS). Nothing here sends SQL text, a database or a host
38
+ name: patterns name call sites by id, file, line and function (already in the inventory) and carry counts.
39
+ """
40
+
41
+ from __future__ import annotations
42
+
43
+ import hashlib
44
+ import re
45
+ from collections import Counter, defaultdict
46
+ from datetime import datetime, timezone
47
+
48
+ SCHEMA_VERSION = 1
49
+
50
+ DEFAULTS = {
51
+ "max_hop": 10, # caller hops between a loop and its query that are considered
52
+ "max_loop_lines": 400, # lines of a loop read from the source to tell a retry or a guarded branch
53
+ "fixed_min_items": 20, # a literal list or count shorter than this is bounded and small: set aside
54
+ "max_members": 50, # call sites listed per pattern (`member_count` keeps the full number)
55
+ "agree_tolerance": 0.25, # measured per-turn ratio within this share of the code's figure: they agree
56
+ "together_tolerance": 0.01, # run counts within 1% of each other fire together
57
+ "together_min_runs": 500, # shapes run fewer times are not grouped
58
+ "hot_min_runs": 1000, # hot, small result
59
+ "hot_max_rows": 10,
60
+ "aggregate_min_runs": 100, # heavy aggregate
61
+ "aggregate_min_bytes_per_run": 10_000_000,
62
+ "large_result_rows": 10_000, # rows returned per run
63
+ "report_detail": 30, # patterns whose loop report.html draws (the table lists every one)
64
+ }
65
+
66
+ STATIC_KINDS = ("n_plus_one", "fan_out", "per_item", "same_input", "poll")
67
+ MEASURED_KINDS = ("fires_together", "hot_small", "heavy_aggregate", "large_result", "offset_paging")
68
+ KINDS = STATIC_KINDS + MEASURED_KINDS
69
+ KIND_LABEL = {
70
+ "n_plus_one": "Query per row of another query", "fan_out": "Query per item and per window", "per_item": "Query per item of a list",
71
+ "same_input": "Same query every turn", "poll": "Query in a polling loop", "fires_together": "Queries that fire together",
72
+ "hot_small": "Hot query, tiny result", "heavy_aggregate": "Heavy aggregate recomputed", "large_result": "Large result handed to the code",
73
+ "offset_paging": "OFFSET paging",
74
+ }
75
+ # what a change that removes the pattern touches, and what CodeCop could ever call verified about it
76
+ CHANGES = {
77
+ "n_plus_one": [("batch_into_one_query", "code", "data_side_verifiable"), ("join_into_driver", "code", "data_side_verifiable")],
78
+ "per_item": [("batch_into_one_query", "code", "data_side_verifiable")],
79
+ "fan_out": [("batch_into_one_query", "code", "data_side_verifiable"), ("read_only_what_changed", "code", "evidence_only"),
80
+ ("run_less_often", "frequency", "trade_off")],
81
+ "same_input": [("move_out_of_loop", "code", "evidence_only")],
82
+ "poll": [("cheaper_probe", "query", "data_side_verifiable"), ("longer_interval_or_push", "frequency", "trade_off")],
83
+ "fires_together": [("one_pass", "code", "data_side_verifiable"), ("run_less_often", "frequency", "trade_off")],
84
+ "hot_small": [("cache_or_dictionary", "source", "trade_off"), ("run_less_often", "frequency", "trade_off")],
85
+ "heavy_aggregate": [("rollup_or_materialized_view", "source", "trade_off")],
86
+ "large_result": [("filter_in_query", "query", "data_side_verifiable")],
87
+ "offset_paging": [("keyset_paging", "code", "data_side_verifiable")],
88
+ }
89
+ # what no data CodeCop reads today can say, per kind
90
+ UNKNOWNS = {
91
+ "n_plus_one": ["batched_query_not_benchmarked"], "per_item": ["batched_query_not_benchmarked", "items_per_turn"],
92
+ "fan_out": ["batched_query_not_benchmarked", "how_often_the_data_changes"],
93
+ "same_input": ["repeated_parameters"], "poll": ["how_often_the_data_changes", "senders"],
94
+ "fires_together": ["which_loop"], "hot_small": ["repeated_parameters", "how_often_the_data_changes"],
95
+ "heavy_aggregate": ["how_often_the_data_changes"], "large_result": ["what_the_code_does_with_rows"], "offset_paging": ["page_depth"],
96
+ }
97
+ SET_ASIDE = ("already_batches", "retry", "leaves_when_done", "long_running", "small_fixed_list", "time_steps_only", "unknown_loop",
98
+ "loop_writes", "loaded_once_per_instance", "guarded_by_loop_variable", "loop_variable_may_reach", "runs_once_then_leaves",
99
+ "one_off_code")
100
+ READS = ("select",)
101
+ WRITES = ("insert", "update", "delete", "upsert", "merge", "replace")
102
+ POLL_BASES = ("waits between passes", "ranges over a ticker", "waits on a channel")
103
+ RETRY_BASES = ("named as a retry", "tries again when a pass fails")
104
+ RETRY_WORDS = re.compile(r"\b(?:retr(?:y|ies|ied|ying)\w*|\w*[Rr]etr(?:y|ies)\w*|tries|attempts?|backoff|isRepeatableError)\b")
105
+ BREAK_WORDS = re.compile(r"\b(?:break|return)\b")
106
+ CONFIDENCE = ("code_and_production", "production_only", "code_only")
107
+ WATERMARK = re.compile(r"\b[\w.`\"]*(?:updated|modified|changed|created|inserted|time|_at|ts|version|seq|id)\w*[`\"]?\s*>=?\s*(?:\?|\$\d+|\{)", re.I)
108
+
109
+
110
+ LIST_DEFAULTS = {
111
+ "one_off_roles": ["migration"], # code that runs once (a data migration): its loops are counted, not patterns
112
+ }
113
+
114
+
115
+ def settings_of(config: dict | None) -> dict:
116
+ """The `[patterns]` table of codecop.toml over the defaults. Values of the wrong type are ignored."""
117
+ out = {**DEFAULTS, **{k: list(v) for k, v in LIST_DEFAULTS.items()}}
118
+ for k, v in (config or {}).items():
119
+ if k in DEFAULTS and isinstance(v, (int, float)) and not isinstance(v, bool):
120
+ out[k] = type(DEFAULTS[k])(v)
121
+ elif k in LIST_DEFAULTS and isinstance(v, list) and all(isinstance(x, str) for x in v):
122
+ out[k] = list(v)
123
+ return out
124
+
125
+
126
+ class Source:
127
+ """Reads a loop's text from the repository, when it is there, to tell a retry from a poll and a branch taken for one
128
+ item from a repeated query. Without the repository every answer is None and nothing is refined."""
129
+
130
+ def __init__(self, root, max_lines: int):
131
+ from pathlib import Path
132
+ self.root = Path(root) if root else None
133
+ self.max_lines = max_lines
134
+ self._files: dict[str, list[str] | None] = {}
135
+
136
+ def lines(self, rel: str) -> list[str] | None:
137
+ if self.root is None or not rel:
138
+ return None
139
+ if rel not in self._files:
140
+ try:
141
+ p = (self.root / rel).resolve()
142
+ if self.root.resolve() not in p.parents:
143
+ self._files[rel] = None
144
+ else:
145
+ self._files[rel] = p.read_text(errors="replace").splitlines()
146
+ except OSError:
147
+ self._files[rel] = None
148
+ if len(self._files) > 256:
149
+ self._files.pop(next(iter(self._files)))
150
+ return self._files.get(rel)
151
+
152
+ def loop(self, rel: str, line: int) -> tuple[int, int, str] | None:
153
+ """(first line, last line, text) of the loop that starts at `line`: braces counted, or indentation for Python."""
154
+ ls = self.lines(rel)
155
+ if not ls or not (1 <= line <= len(ls)):
156
+ return None
157
+ start = line - 1
158
+ if rel.endswith(".py"):
159
+ indent = len(ls[start]) - len(ls[start].lstrip())
160
+ end = start
161
+ for i in range(start + 1, min(len(ls), start + self.max_lines)):
162
+ t = ls[i]
163
+ if t.strip() and len(t) - len(t.lstrip()) <= indent:
164
+ break
165
+ end = i
166
+ return start + 1, end + 1, "\n".join(ls[start:end + 1])
167
+ depth, opened = 0, False
168
+ for i in range(start, min(len(ls), start + self.max_lines)):
169
+ t = re.sub(r'"(?:[^"\\]|\\.)*"|\'(?:[^\'\\]|\\.)*\'|`[^`]*`|//.*$', "", ls[i])
170
+ for ch in t:
171
+ if ch == "{":
172
+ depth += 1
173
+ opened = True
174
+ elif ch == "}":
175
+ depth -= 1
176
+ if opened and depth <= 0:
177
+ return start + 1, i + 1, "\n".join(ls[start:i + 1])
178
+ if not opened and i > start + 3:
179
+ return None
180
+ return None
181
+
182
+
183
+ def _fp(*parts) -> str:
184
+ return "pat_" + hashlib.sha1("|".join(str(p) for p in parts).encode()).hexdigest()[:12]
185
+
186
+
187
+ def _ids(driver) -> list[str]:
188
+ if isinstance(driver, dict):
189
+ return [str(x) for x in driver.get("site_ids") or []]
190
+ if isinstance(driver, list):
191
+ return [str(x) for x in driver]
192
+ if isinstance(driver, str):
193
+ return [driver]
194
+ return []
195
+
196
+
197
+ def _set_aside_reason(loop: dict, fixed_min: int) -> str | None:
198
+ kind, basis = loop.get("kind"), loop.get("kind_basis") or ""
199
+ if kind == "chunk":
200
+ return "already_batches"
201
+ if kind == "retry-poll":
202
+ if basis in POLL_BASES:
203
+ return None
204
+ return "retry" if basis in RETRY_BASES else "long_running"
205
+ if kind == "fixed":
206
+ return None if (loop.get("count") or 0) >= fixed_min else "small_fixed_list"
207
+ if kind == "time-window":
208
+ return "time_steps_only"
209
+ if kind == "per-item":
210
+ return None
211
+ return "unknown_loop"
212
+
213
+
214
+ def _loop_key(loop: dict) -> tuple:
215
+ return (loop.get("file") or "", int(loop.get("line") or 0))
216
+
217
+
218
+ def _guessed(loop: dict) -> list[str]:
219
+ out = []
220
+ if loop.get("verified") is False:
221
+ out.append("guessed_call" if loop.get("form") != "framework" else "framework_calls_per_row")
222
+ if loop.get("named_not_called_at_hop"):
223
+ out.append("named_not_called")
224
+ if loop.get("uses_loop_var") is None:
225
+ out.append("loop_variable_not_traced")
226
+ drv = loop.get("driver")
227
+ if isinstance(drv, dict) and drv.get("verified") is False:
228
+ out.append("driver_guessed")
229
+ return out
230
+
231
+
232
+ def _bare_table(name) -> str:
233
+ return re.sub(r'[`"\[\]]', "", str(name or "")).split(".")[-1].lower()
234
+
235
+
236
+ def _lazy_assumed(site: dict) -> bool:
237
+ """A lazy ORM load whose instances were loaded outside the function, so whether that query eager-loads the
238
+ relationship was assumed, not read (discover's `low` confidence): the caller's query may well have `joinedload`
239
+ for it. Such a member is guessed, not traced."""
240
+ o = site.get("orm") or {}
241
+ return o.get("operation") == "lazy_load" and str(o.get("confidence") or "").lower() == "low"
242
+
243
+
244
+ def _trace_rank(loop: dict) -> tuple:
245
+ """How well one member's path to a loop is traced, best first: resolved calls, the item followed to the query, the
246
+ nearest hop."""
247
+ return (loop.get("verified") is False, bool(loop.get("named_not_called_at_hop")), loop.get("uses_loop_var") is not True,
248
+ int(loop.get("hop") or 0))
249
+
250
+
251
+ def _entry_points(site: dict, n: int = 3) -> list[dict]:
252
+ out = []
253
+ for o in site.get("origins") or []:
254
+ if o.get("kind") in (None, "test"):
255
+ continue
256
+ out.append({"kind": o.get("kind"), "name": o.get("name"), "file": o.get("file"), "line": o.get("line")})
257
+ if len(out) >= n:
258
+ break
259
+ return out
260
+
261
+
262
+ # --------------------------------------------------------------------------- measured side
263
+
264
+ def workloads_in(db_dir) -> list["Workload"]:
265
+ """The matched workload files a `codecop db pull` left in `db_dir` (db_match.json, db_workload.json), or none."""
266
+ import json
267
+ from pathlib import Path
268
+ d = Path(db_dir)
269
+ match = d / "db_match.json"
270
+ if not match.exists():
271
+ return []
272
+ try:
273
+ matchdata = json.loads(match.read_text())
274
+ wl = d / "db_workload.json"
275
+ workload = json.loads(wl.read_text()) if wl.exists() else None
276
+ except (OSError, ValueError):
277
+ return []
278
+ return Workload.load(matchdata, workload)
279
+
280
+
281
+ class Workload:
282
+ """The matched real workload of one engine, read from db_match.json (and the shape texts in db_workload.json, read
283
+ here only to classify a shape; never written out)."""
284
+
285
+ def __init__(self, engine: str, match: dict, texts: dict[str, str], kinds: dict[str, str]):
286
+ self.engine = engine
287
+ self.window_hours = match.get("window_hours")
288
+ self.total_bytes = int((match.get("workload") or {}).get("read_bytes") or 0)
289
+ self.total_runs = int((match.get("workload") or {}).get("executions") or 0)
290
+ self.sites = {sid: row for sid, row in (match.get("sites") or {}).items() if row.get("match") in ("exact", "template")}
291
+ self.queries = [q for q in match.get("queries") or [] if kinds.get(str(q.get("hash")), "select") == "select"]
292
+ self.texts = texts
293
+
294
+ @classmethod
295
+ def load(cls, matchdata: dict | None, workload: dict | None) -> list["Workload"]:
296
+ out = []
297
+ for engine, m in ((matchdata or {}).get("engines") or {}).items():
298
+ conn = ((workload or {}).get("connections") or {}).get(engine) or {}
299
+ texts = {str(q.get("hash")): q.get("text") or "" for q in conn.get("queries") or []}
300
+ kinds = {str(q.get("hash")): q.get("kind") or "select" for q in conn.get("queries") or []}
301
+ out.append(cls(engine, m, texts, kinds))
302
+ return out
303
+
304
+
305
+ def _empty_share_at_least(q: dict) -> dict:
306
+ """PostgreSQL's pg_stat_statements has no per-run rows, only a total: at least 1 - rows / calls of the runs returned
307
+ nothing (each run that returned something returned a row). {} when the pull has the share itself, or no rows."""
308
+ runs = int(q.get("executions") or 0)
309
+ if q.get("no_result_share") is not None or not runs or q.get("result_rows") is None or q.get("spread"):
310
+ return {}
311
+ return {"no_result_share_at_least": round(max(0.0, 1.0 - int(q["result_rows"]) / runs), 6)}
312
+
313
+
314
+ def _measured_site(row: dict) -> dict:
315
+ keep = ("match", "executions", "executions_per_day", "read_bytes", "share_of_read_bytes", "rows_returned_per_run",
316
+ "bytes_read_per_run", "no_result_share", "aggregate")
317
+ return {k: row[k] for k in keep if row.get(k) is not None}
318
+
319
+
320
+ def _measured_sum(rows: list[dict], total_bytes: int) -> dict | None:
321
+ """Several call sites can be one shape: each shape is counted once."""
322
+ if not rows:
323
+ return None
324
+ seen, runs, read = set(), 0, 0
325
+ for r in rows:
326
+ key = tuple(r.get("hashes") or ()) or id(r)
327
+ if key in seen:
328
+ continue
329
+ seen.add(key)
330
+ runs += int(r.get("executions") or 0)
331
+ read += int(r.get("read_bytes") or 0)
332
+ return {"shapes": len(seen), "executions": runs, "read_bytes": read,
333
+ "share_of_read_bytes": round(read / total_bytes, 6) if total_bytes else None}
334
+
335
+
336
+ # --------------------------------------------------------------------------- detection
337
+
338
+ def _short(name) -> str:
339
+ return re.split(r"[.:]", str(name or "").replace("(*", "").replace(")", ""))[-1]
340
+
341
+
342
+ ASSIGNED = re.compile(r"(?:\b(?:let|const|var|val|final)\s+(?:mut\s+)?|^\s*)\(?([A-Za-z_$][\w$]*(?:\s*,\s*[A-Za-z_$][\w$]*)*)\)?\s*(?::[^=\n]{0,60})?(?::=|(?<![=!<>])=(?!=))")
343
+ BRANCH = re.compile(r"\b(?:case|if|elif|switch|match|when)\b|\?|=>")
344
+ STOP_WORDS = re.compile(r"ctx|context|Done|done\(|shutdown|[Ss]top|cancel|[Kk]ill|closed|quit|[Ee]xit|terminat|signal|err\b|[Ee]rror|Err\(")
345
+ TIMER = re.compile(r"[Tt]icker|time\.After|[Ss]leep|setInterval|setTimeout|[Ii]nterval|tokio::time|schedule|[Pp]oll")
346
+ RECEIVE = re.compile(r"case\s+[\w, ]+:?=\s*<-|=\s*<-\s*[\w.]+|\.recv\(\)|\.Receive\(|\.consume|\.Next\(ctx")
347
+
348
+
349
+ def _target(lines: list[str], first: int, lp: dict, site: dict) -> int:
350
+ """Index, in the loop's lines, of the query (hop 0) or of the call that leads to it; -1 when not found."""
351
+ if int(lp.get("hop") or 0) == 0:
352
+ return int(site.get("line") or 0) - first
353
+ path = lp.get("path") or []
354
+ callee = _short(path[-2]) if len(path) >= 2 else ""
355
+ return next((i for i, t in enumerate(lines) if callee and re.search(r"\b%s\s*[(<]" % re.escape(callee), t)), -1)
356
+
357
+
358
+ def _same_input_doubt(src: Source, lp: dict, site: dict) -> str | None:
359
+ """Why "the same query every turn" may not hold, read from the loop's text: the query (or the call to it) is under a
360
+ branch on the loop's variable, mentions something the loop body assigns, or leaves the loop right after it runs."""
361
+ got = src.loop(lp.get("file") or "", int(lp.get("line") or 0))
362
+ if got is None:
363
+ return None
364
+ first, _, text = got
365
+ lines = text.splitlines()
366
+ target = _target(lines, first, lp, site)
367
+ if not (0 < target < len(lines)):
368
+ return None
369
+ vars_ = [v for v in lp.get("vars") or [] if v and v != "_"]
370
+ assigned = set(vars_)
371
+ for t in lines[1:target]:
372
+ for m in ASSIGNED.finditer(t):
373
+ assigned.update(x.strip() for x in m.group(1).split(","))
374
+ assigned = {a for a in assigned if len(a) > 1 and a not in ("err", "ok", "_")}
375
+ if vars_:
376
+ words = re.compile(r"\b(?:%s)\b" % "|".join(re.escape(v) for v in vars_))
377
+ if any(BRANCH.search(t) and words.search(t) for t in lines[1:target + 1]):
378
+ return "guarded_by_loop_variable"
379
+ call = " ".join(lines[target:target + 4])
380
+ if assigned and re.search(r"\b(?:%s)\b" % "|".join(re.escape(a) for a in assigned), call):
381
+ return "loop_variable_may_reach"
382
+ if any(re.match(r"\s*(?:return|break)\b", t) for t in lines[target:target + 3]):
383
+ return "runs_once_then_leaves"
384
+ return None
385
+
386
+
387
+ def _poll_doubt(src: Source, lp: dict, site: dict) -> str | None:
388
+ """A loop that waits between passes is a poll only when it runs until it is stopped and waits on a timer. A loop
389
+ that leaves once its work is done or once the query worked is a retry or a drain; one that waits for the next
390
+ message runs the query per message (a consumer). Read from the loop's text when the repository is there; else a
391
+ loop in a method of the same name as the one it calls is a wrapper that retries."""
392
+ got = src.loop(lp.get("file") or "", int(lp.get("line") or 0))
393
+ sql = str(site.get("sql") or "")
394
+ if got is None:
395
+ path = lp.get("path") or []
396
+ if len(path) >= 2 and _short(path[-1]) == _short(path[-2]):
397
+ return "retry"
398
+ return None
399
+ lines = got[2].splitlines()
400
+ text = got[2]
401
+ if RETRY_WORDS.search(text):
402
+ return "retry"
403
+ code = [re.sub(r"\s(?://|#).*$", "", t) for t in lines]
404
+ leaves = [i for i, t in enumerate(code) if re.search(r"\b(?:break|return)\b", t)
405
+ and not STOP_WORDS.search(t + " " + (code[i - 1] if i and re.search(r"\b(?:if|case|when|elif)\b", code[i - 1]) else ""))]
406
+ if leaves:
407
+ return "already_batches" if re.search(r"\blimit\b", sql, re.I) else "leaves_when_done"
408
+ if RECEIVE.search(text) and not TIMER.search(text):
409
+ return "long_running"
410
+ return None
411
+
412
+
413
+ def _nested(inner: dict, outer: dict) -> bool:
414
+ """`inner` runs inside `outer` on the same call path: its path is the start of the outer loop's path, or both are in
415
+ one function and the inner one starts below."""
416
+ hi, ho = int(inner.get("hop") or 0), int(outer.get("hop") or 0)
417
+ if hi == ho:
418
+ return inner.get("file") == outer.get("file") and inner.get("function") == outer.get("function") and \
419
+ int(inner.get("line") or 0) > int(outer.get("line") or 0)
420
+ if hi > ho:
421
+ return False
422
+ pi, po = inner.get("path") or [], outer.get("path") or []
423
+ if hi == 0:
424
+ return True # the inner loop is in the query's own function, which every path above starts from
425
+ return bool(pi) and po[:len(pi)] == pi
426
+
427
+
428
+ def detect(inventory: dict, settings: dict | None = None, workloads: list[Workload] | None = None, root=None) -> dict:
429
+ """patterns.json: every pattern, what was set aside, and (with a workload) each measured byte assigned once.
430
+ `root` is the repository: when given, a loop's own text is read to tell a retry or a guarded branch apart."""
431
+ cfg = settings_of(settings)
432
+ src = Source(root, cfg["max_loop_lines"])
433
+ sites = [s for s in inventory.get("call_sites") or [] if not s.get("is_test")]
434
+ by_id = {s.get("id"): s for s in sites}
435
+ workloads = workloads or []
436
+ writing_loops = {_loop_key(lp) for s in sites if s.get("statement") in WRITES for lp in s.get("loop_context") or []}
437
+ written_in_loop: dict[tuple, set] = defaultdict(set) # loop -> the tables a statement under it writes
438
+ write_keys: dict[tuple, dict] = defaultdict(dict) # loop -> table -> [how each write under it picks its rows]
439
+ for s in sites:
440
+ if s.get("statement") in WRITES:
441
+ shape = _write_shape(s)
442
+ for lp in s.get("loop_context") or []:
443
+ written_in_loop[_loop_key(lp)].update(_bare_table(t) for t in (s.get("writes") or s.get("tables") or []))
444
+ for t in (s.get("writes") or s.get("tables") or []):
445
+ write_keys[_loop_key(lp)].setdefault(_bare_table(t), []).append({"site_id": s.get("id"), "file": s.get("file"),
446
+ "line": s.get("line"), **shape})
447
+ measured = {}
448
+ for w in workloads:
449
+ for sid, row in w.sites.items():
450
+ measured.setdefault(sid, (w, row))
451
+
452
+ # loops per (file, function), for an ordinal that does not move when a line does
453
+ loop_lines: dict[tuple, set] = defaultdict(set)
454
+ for s in sites:
455
+ for lp in s.get("loop_context") or []:
456
+ loop_lines[(lp.get("file") or "", lp.get("function") or "")].add(int(lp.get("line") or 0))
457
+
458
+ def ordinal(lp: dict) -> int:
459
+ lines = sorted(loop_lines[(lp.get("file") or "", lp.get("function") or "")])
460
+ line = int(lp.get("line") or 0)
461
+ return lines.index(line) if line in lines else 0
462
+
463
+ groups: dict[tuple, dict] = {}
464
+ set_aside: Counter = Counter()
465
+ set_aside_loops: dict[str, set] = defaultdict(set)
466
+ loops_seen: set = set()
467
+ sites_in_loops = 0
468
+ for s in sites:
469
+ if s.get("statement") not in READS:
470
+ continue
471
+ lc = [lp for lp in s.get("loop_context") or [] if int(lp.get("hop") or 0) <= cfg["max_hop"]]
472
+ if not lc:
473
+ continue
474
+ sites_in_loops += 1
475
+ steps = [lp for lp in lc if lp.get("kind") in ("time-window", "fixed") and lp.get("uses_loop_var") is not False]
476
+ one_off = s.get("role") in cfg["one_off_roles"]
477
+ for lp in lc:
478
+ key = _loop_key(lp)
479
+ if s.get("id") in _ids(lp.get("driver")) or s.get("loop_collection") or \
480
+ (int(lp.get("hop") or 0) == 0 and key == (s.get("file"), int(s.get("line") or 0))):
481
+ continue # the query is what the loop walks: it runs once, before the loop
482
+ loops_seen.add(key)
483
+ reason = _set_aside_reason(lp, cfg["fixed_min_items"])
484
+ kind = None
485
+ if lp.get("kind") == "retry-poll" and reason is None:
486
+ kind = "poll"
487
+ reason = _poll_doubt(src, lp, s)
488
+ elif lp.get("uses_loop_var") is False and lp.get("kind") not in ("chunk", "retry-poll"):
489
+ kind = "same_input" # whatever the loop is, the statement does not change with it
490
+ reason = "loop_writes" if key in writing_loops else \
491
+ "loaded_once_per_instance" if (s.get("orm") or {}).get("operation") == "lazy_load" else _same_input_doubt(src, lp, s)
492
+ if one_off and reason is None:
493
+ reason = "one_off_code"
494
+ if reason is not None:
495
+ set_aside[reason] += 1
496
+ set_aside_loops[reason].add(key)
497
+ continue
498
+ if kind is not None:
499
+ pass
500
+ elif lp.get("kind") == "fixed":
501
+ kind = "per_item"
502
+ elif any(t.get("kind") == "time-window" and _nested(t, lp) for t in steps):
503
+ kind = "fan_out"
504
+ elif lp.get("source") == "query" and _ids(lp.get("driver")):
505
+ kind = "n_plus_one"
506
+ else:
507
+ kind = "per_item"
508
+ g = groups.setdefault((kind,) + key, {"kind": kind, "loop": lp, "members": [], "inner": {}})
509
+ # the loop as the pattern states it is its best-traced member's view of it: whether the path to the loop
510
+ # was resolved is a property of each member's path, so a member reached through guessed hops must not
511
+ # mark the loop guessed for a member reached by resolved calls (a shape seen in langflow)
512
+ if _trace_rank(lp) < _trace_rank(g["loop"]):
513
+ g["loop"] = lp
514
+ inner = [t for t in steps if kind == "fan_out" and _loop_key(t) != key and _nested(t, lp)]
515
+ for t in inner:
516
+ g["inner"].setdefault(_loop_key(t), t)
517
+ g["members"].append((s, lp))
518
+
519
+ patterns = []
520
+ for (kind, file, line), g in groups.items():
521
+ lp = g["loop"]
522
+ members = g["members"]
523
+ guessed_why: Counter = Counter()
524
+ for _, mlp in members:
525
+ guessed_why.update(set(_guessed(mlp)))
526
+ all_guessed = Counter()
527
+ for _, mlp in members:
528
+ all_guessed[bool(_guessed(mlp))] += 1
529
+ certain = all_guessed[False] > 0 # at least one member is reached by resolved calls only
530
+ hops = [int(mlp.get("hop") or 0) for _, mlp in members]
531
+ drv_ids = []
532
+ for _, mlp in members:
533
+ for i in _ids(mlp.get("driver")):
534
+ if i not in drv_ids:
535
+ drv_ids.append(i)
536
+ driver = None
537
+ if kind in ("n_plus_one", "fan_out") and drv_ids:
538
+ d0 = next((mlp.get("driver") for _, mlp in members if isinstance(mlp.get("driver"), dict)), {}) or {}
539
+ driver = {"site_ids": drv_ids[:5], "via": d0.get("via"), "hops": d0.get("hops"),
540
+ "verified": d0.get("verified", True) is not False}
541
+ ds = by_id.get(drv_ids[0])
542
+ if ds is not None:
543
+ driver.update(file=ds.get("file"), line=ds.get("line"), symbol=ds.get("symbol"), tables=ds.get("tables") or [])
544
+ loops = [_loop_out(lp, ordinal(lp))]
545
+ for t in sorted(g["inner"].values(), key=lambda t: (-int(t.get("hop") or 0), int(t.get("line") or 0))):
546
+ loops.append(_loop_out(t, ordinal(t)))
547
+ mrows = []
548
+ for s, mlp in sorted(members, key=lambda m: (int(m[1].get("hop") or 0), m[0].get("file") or "", int(m[0].get("line") or 0))):
549
+ m = {"site_id": s.get("id"), "file": s.get("file"), "line": s.get("line"), "symbol": s.get("symbol"),
550
+ "tables": s.get("tables") or [], "engine": s.get("engine") or "", "role": "per_turn", "hop": int(mlp.get("hop") or 0),
551
+ "depends_on_loop_var": mlp.get("uses_loop_var"), "verified": not _guessed(mlp) and not _lazy_assumed(s)}
552
+ if _lazy_assumed(s):
553
+ m["lazy_load"] = "eager_option_unknown"
554
+ guessed_why["lazy_load_eager_unknown"] += 1
555
+ if mlp.get("path"):
556
+ m["path"] = [str(p) for p in mlp["path"]][:8]
557
+ got = measured.get(s.get("id"))
558
+ if got:
559
+ m["measured"] = _measured_site(got[1])
560
+ mrows.append(m)
561
+ p = {"fingerprint": _fp(kind, file, lp.get("function") or "", ordinal(lp)), "kind": kind, "label": KIND_LABEL[kind],
562
+ "engine": pattern_engine(mrows), "loops": loops, "driver": driver, "members": mrows[: cfg["max_members"]], "member_count": len(mrows),
563
+ "member_places": len({(m["file"], m["line"]) for m in mrows}),
564
+ "entry_points": _entry_points(members[0][0]),
565
+ "code": {"evidence": "verified" if certain else "guessed", "hop_min": min(hops), "hop_max": max(hops),
566
+ "guessed_why": sorted(guessed_why)},
567
+ "changes": [{"change": c, "touches": t, "proof": pr} for c, t, pr in CHANGES[kind]],
568
+ "unknowns": list(UNKNOWNS[kind])}
569
+ # the loop also writes a table its members read: a batched read ahead of the loop may not see what earlier
570
+ # items wrote (the sandbox runs the reads alone, so it cannot show sameness for that)
571
+ both = sorted(written_in_loop.get((file, line), set()) & {_bare_table(t) for m in mrows for t in m["tables"]})
572
+ if both:
573
+ p["loop_writes"] = both
574
+ # how each write of those tables picks its rows (writes.analyse): the loop benchmark judges the batched read
575
+ # against them (loopbench.results_doc)
576
+ p["loop_write_keys"] = {t: write_keys.get((file, line), {}).get(t, [])[:20] for t in both}
577
+ _measure_static(p, members, driver, measured, workloads, cfg)
578
+ patterns.append(p)
579
+
580
+ seen_in: Counter = Counter(m["site_id"] for p in patterns for m in p["members"] if m.get("measured"))
581
+ for p in patterns:
582
+ if any(seen_in[m["site_id"]] > 1 for m in p["members"] if m.get("measured")):
583
+ p["confidence_notes"].append("queries_shared_with_other_patterns")
584
+ shape_owner = _shape_owner(patterns, measured)
585
+ accounting = []
586
+ for w in workloads:
587
+ mp, acc = _measured_patterns(w, cfg, by_id, shape_owner)
588
+ patterns.extend(mp)
589
+ accounting.append(acc)
590
+
591
+ patterns.sort(key=_order)
592
+ for i, p in enumerate(patterns, 1):
593
+ p["id"] = f"P-{i:03d}"
594
+ by_kind = Counter(p["kind"] for p in patterns)
595
+ by_conf = Counter(p["confidence"] for p in patterns)
596
+ summary = {
597
+ "select_sites_in_loops": sites_in_loops, "loops": len(loops_seen), "patterns": len(patterns),
598
+ "by_kind": {k: by_kind[k] for k in KINDS if by_kind[k]},
599
+ "by_confidence": {k: by_conf[k] for k in CONFIDENCE if by_conf[k]},
600
+ "code_verified": sum(1 for p in patterns if (p.get("code") or {}).get("evidence") == "verified"),
601
+ "set_aside": {k: {"loops": len(set_aside_loops[k]), "sites": set_aside[k]} for k in SET_ASIDE if set_aside[k]},
602
+ "measured_members": sum(1 for p in patterns for m in p["members"] if m.get("measured")),
603
+ }
604
+ return {"schema_version": SCHEMA_VERSION, "generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
605
+ "settings": cfg, "window_hours": next((w.window_hours for w in workloads if w.window_hours), None),
606
+ "summary": summary, "accounting": accounting, "patterns": patterns}
607
+
608
+
609
+ def _write_shape(site: dict) -> dict:
610
+ """{kind, eq: columns its WHERE fixes to one value} of a write statement, or {kind: unknown} when its text has run-time
611
+ parts or does not parse (writes.py)."""
612
+ from . import writes
613
+ sql, _, why = writes.write_text(site, site.get("engine") or "postgres")
614
+ info = writes.analyse(sql, site.get("engine") or "postgres") if sql else None
615
+ if info is None:
616
+ return {"kind": "unknown", "why": why or "does_not_parse"}
617
+ return {"kind": info.get("kind"), "eq": sorted({c.lower() for c in (info.get("key") or {}).get("eq") or []})}
618
+
619
+
620
+ def pattern_engine(members: list[dict]) -> str:
621
+ """The engine a pattern's statements run on: the one its members name, "" when none does, "mixed" for several."""
622
+ found = {m.get("engine") for m in members if m.get("engine")}
623
+ return next(iter(found)) if len(found) == 1 else ("mixed" if found else "")
624
+
625
+
626
+ def _loop_out(lp: dict, ordinal: int) -> dict:
627
+ out = {"file": lp.get("file"), "line": lp.get("line"), "function": lp.get("function"), "ordinal": ordinal,
628
+ "kind": lp.get("kind"), "kind_basis": lp.get("kind_basis"), "form": lp.get("form"), "hop": lp.get("hop", 0),
629
+ "collection": lp.get("source"), "verified": lp.get("verified", True) is not False}
630
+ if lp.get("over"):
631
+ out["over"] = str(lp["over"])[:80]
632
+ if lp.get("vars"):
633
+ out["vars"] = list(lp["vars"])[:3]
634
+ if lp.get("count") is not None:
635
+ out["bound"] = lp["count"]
636
+ return out
637
+
638
+
639
+ def _measure_static(p: dict, members, driver, measured, workloads, cfg) -> None:
640
+ """Counts from the log beside the structure from the code, never multiplied together. A query's runs are those of
641
+ every caller of that statement, not only of this loop (`basis: all_callers`)."""
642
+ rows = [measured[s.get("id")][1] for s, _ in members if s.get("id") in measured]
643
+ w = next((measured[s.get("id")][0] for s, _ in members if s.get("id") in measured), None)
644
+ notes = []
645
+ if not rows:
646
+ p["measured"] = None
647
+ p["confidence"] = "code_only"
648
+ p["confidence_notes"] = ["no_workload"] if not workloads else ["not_in_the_log"]
649
+ return
650
+ m = _measured_sum(rows, w.total_bytes if w else 0)
651
+ m["window_hours"] = w.window_hours if w else None
652
+ m["basis"] = "all_callers"
653
+ heaviest = max(rows, key=lambda r: int(r.get("read_bytes") or 0))
654
+ m["no_result_share"] = heaviest.get("no_result_share")
655
+ m["rows_returned_per_run"] = heaviest.get("rows_returned_per_run")
656
+ agree = "not_derivable"
657
+ if driver and driver.get("site_ids"):
658
+ drow = next((measured[i][1] for i in driver["site_ids"] if i in measured), None)
659
+ if drow and drow.get("executions"):
660
+ per = int(heaviest.get("executions") or 0) / int(drow["executions"])
661
+ m["driver_executions"] = int(drow["executions"])
662
+ m["driver_rows_per_run"] = drow.get("rows_returned_per_run")
663
+ m["executions_per_driver_run"] = round(per, 3)
664
+ expect = drow.get("rows_returned_per_run")
665
+ bounds = [lp.get("bound") for lp in p["loops"][1:]]
666
+ if expect and all(bounds):
667
+ for b in bounds:
668
+ expect *= b
669
+ m["expected_per_driver_run"] = round(expect, 3)
670
+ agree = "agree" if abs(per - expect) <= cfg["agree_tolerance"] * max(expect, 1) else "disagree"
671
+ elif expect:
672
+ notes.append("inner_bound_not_in_code")
673
+ else:
674
+ notes.append("driver_not_measured")
675
+ m["code_and_log"] = agree
676
+ if agree == "disagree":
677
+ notes.append("log_disagrees_with_code")
678
+ p["measured"] = m
679
+ p["confidence"] = "code_only" if agree == "disagree" else "code_and_production"
680
+ p["confidence_notes"] = notes
681
+
682
+
683
+ def _shape_owner(patterns: list[dict], measured) -> dict:
684
+ """shape -> the first static pattern (in order) whose member runs it: each byte counted once."""
685
+ owner = {}
686
+ for p in sorted(patterns, key=_order):
687
+ for m in p["members"]:
688
+ got = measured.get(m["site_id"])
689
+ if not got:
690
+ continue
691
+ w, row = got
692
+ for h in row.get("hashes") or [m["site_id"]]:
693
+ owner.setdefault((w.engine, str(h)), p["kind"])
694
+ return owner
695
+
696
+
697
+ def _measured_patterns(w: Workload, cfg: dict, by_id: dict, owner: dict) -> tuple[list[dict], dict]:
698
+ """Patterns the workload shows, and every measured shape assigned to the first pattern it fits."""
699
+ shapes = []
700
+ for q in w.queries:
701
+ h = str(q.get("hash"))
702
+ sids = [i for i in q.get("site_ids") or [] if q.get("match") in ("exact", "template")]
703
+ shapes.append({"q": q, "hash": h, "sites": sids, "runs": int(q.get("executions") or 0), "bytes": int(q.get("read_bytes") or 0),
704
+ "rows": q.get("rows_returned_per_run"), "bpr": q.get("bytes_read_per_run"), "text": w.texts.get(h, "")})
705
+ assigned: dict[str, str] = {}
706
+ for s in shapes:
707
+ if (w.engine, s["hash"]) in owner:
708
+ assigned[s["hash"]] = owner[(w.engine, s["hash"])]
709
+ out = []
710
+ # fire together: run counts within the tolerance of the group's smallest
711
+ hot = sorted((s for s in shapes if s["runs"] >= cfg["together_min_runs"] and s["hash"] not in assigned), key=lambda s: s["runs"])
712
+ groups, cur = [], []
713
+ for s in hot:
714
+ if cur and s["runs"] > cur[0]["runs"] * (1 + cfg["together_tolerance"]):
715
+ groups.append(cur)
716
+ cur = []
717
+ cur.append(s)
718
+ if cur:
719
+ groups.append(cur)
720
+ for g in groups:
721
+ if len(g) < 2:
722
+ continue
723
+ for s in g:
724
+ assigned[s["hash"]] = "fires_together"
725
+ out.append(_measured_pattern("fires_together", g, w, by_id, cfg))
726
+ single: dict[tuple, list[dict]] = {}
727
+ for s in shapes:
728
+ if s["hash"] in assigned:
729
+ continue
730
+ rows = s["rows"]
731
+ kind = None
732
+ if s["runs"] >= cfg["hot_min_runs"] and rows is not None and rows <= cfg["hot_max_rows"]:
733
+ kind = "hot_small"
734
+ elif s["q"].get("aggregate") and s["runs"] >= cfg["aggregate_min_runs"] and (s["bpr"] or 0) >= cfg["aggregate_min_bytes_per_run"]:
735
+ kind = "heavy_aggregate"
736
+ elif rows is not None and rows >= cfg["large_result_rows"]:
737
+ kind = "large_result"
738
+ elif re.search(r"\boffset\s+(?:\?|\$\d+|\d)", s["text"], re.I):
739
+ kind = "offset_paging"
740
+ if kind is None:
741
+ continue
742
+ assigned[s["hash"]] = kind
743
+ if s["sites"]:
744
+ # Shapes of one kind sent by the same call sites are one pattern (the fingerprint is kind and call sites):
745
+ # one site whose query the log records as two shapes is not two patterns under one fingerprint.
746
+ single.setdefault((kind, tuple(sorted(s["sites"]))), []).append(s)
747
+ out += [_measured_pattern(kind, group, w, by_id, cfg) for (kind, _), group in single.items()]
748
+ # each byte once, in the order the patterns are assigned
749
+ acc: dict[str, list] = {}
750
+ for s in shapes:
751
+ k = assigned.get(s["hash"], "no_signal")
752
+ a = acc.setdefault(k, [0, 0, 0])
753
+ a[0] += 1
754
+ a[1] += s["runs"]
755
+ a[2] += s["bytes"]
756
+ order = list(STATIC_KINDS) + list(MEASURED_KINDS) + ["no_signal"]
757
+ rows = [{"kind": k, "shapes": acc[k][0], "executions": acc[k][1], "read_bytes": acc[k][2],
758
+ "share_of_read_bytes": round(acc[k][2] / w.total_bytes, 6) if w.total_bytes else None} for k in order if k in acc]
759
+ kept = sum(s["bytes"] for s in shapes)
760
+ return out, {"engine": w.engine, "window_hours": w.window_hours, "shapes": len(shapes), "read_bytes_total": w.total_bytes,
761
+ "read_bytes_in_shapes": kept, "executions_total": w.total_runs, "by_kind": rows}
762
+
763
+
764
+ def _measured_pattern(kind: str, shapes: list[dict], w: Workload, by_id: dict, cfg: dict) -> dict:
765
+ sids = []
766
+ for s in shapes:
767
+ for i in s["sites"]:
768
+ if i not in sids:
769
+ sids.append(i)
770
+ members = []
771
+ for i in sids:
772
+ site = by_id.get(i)
773
+ if site is None:
774
+ continue
775
+ row = w.sites.get(i)
776
+ members.append({"site_id": i, "file": site.get("file"), "line": site.get("line"), "symbol": site.get("symbol"),
777
+ "tables": site.get("tables") or [], "engine": site.get("engine") or "", "role": "per_turn" if kind == "fires_together" else "self",
778
+ **({"measured": _measured_site(row)} if row else {})})
779
+ runs = sum(s["runs"] for s in shapes)
780
+ read = sum(s["bytes"] for s in shapes)
781
+ tables = sorted({t for s in shapes for t in _short_tables(s["q"].get("tables"))})
782
+ heaviest = max(shapes, key=lambda s: s["bytes"])
783
+ m = {"shapes": len(shapes), "executions": runs, "read_bytes": read,
784
+ "share_of_read_bytes": round(read / w.total_bytes, 6) if w.total_bytes else None, "window_hours": w.window_hours,
785
+ "rows_returned_per_run": heaviest["rows"], "bytes_read_per_run": heaviest["bpr"],
786
+ "no_result_share": heaviest["q"].get("no_result_share"), "code_and_log": "not_derivable", **_empty_share_at_least(heaviest["q"])}
787
+ if kind == "fires_together":
788
+ m["runs_min"], m["runs_max"] = min(s["runs"] for s in shapes), max(s["runs"] for s in shapes)
789
+ m["shapes_located"] = sum(1 for s in shapes if s["sites"])
790
+ notes = []
791
+ fns = {(by_id[i].get("file"), by_id[i].get("symbol")) for i in sids if i in by_id}
792
+ if kind == "fires_together":
793
+ located = bool(members) and len(fns) == 1 and m["shapes_located"] == len(shapes)
794
+ confidence = "code_and_production" if located else "production_only"
795
+ if not located:
796
+ notes.append("source_not_located" if not members else "sites_in_different_functions")
797
+ else:
798
+ confidence = "code_and_production" if members else "production_only"
799
+ if kind == "hot_small" and re.search(WATERMARK, heaviest["text"] or ""):
800
+ notes.append("filter_looks_like_a_watermark")
801
+ first = by_id.get(sids[0]) if sids else None
802
+ return {"fingerprint": _measured_fp(kind, w.engine, sids, tables, shapes), "kind": kind, "label": KIND_LABEL[kind],
803
+ "engine": w.engine or pattern_engine(members), "loops": [], "driver": None,
804
+ "members": members[: cfg["max_members"]], "member_count": len(members), "tables": tables,
805
+ "entry_points": _entry_points(first) if first else [], "code": None, "measured": m,
806
+ "confidence": confidence, "confidence_notes": notes,
807
+ "changes": [{"change": c, "touches": t, "proof": pr} for c, t, pr in CHANGES[kind]],
808
+ "unknowns": list(UNKNOWNS[kind])}
809
+
810
+
811
+ def _measured_fp(kind: str, engine: str, sids: list[str], tables: list[str], shapes: list[dict]) -> str:
812
+ """The fingerprint of a pattern the query log shows. With located call sites: kind, engine and the sorted call-site ids
813
+ (unchanged since the first version). With none (production only, "source not located"), the tables alone are not
814
+ enough: two groups of shapes on the same tables got one fingerprint. Their normalized shape hashes are added, sorted,
815
+ so the fingerprint is the same whatever order the log lists them in and stays the same on a rescan of the same
816
+ shapes. A shape belongs to one pattern only, so two patterns of one run never share it."""
817
+ if sids:
818
+ return _fp(kind, engine, *sorted(sids))
819
+ return _fp(kind, engine, *tables, "shapes", *sorted({str(s["hash"]) for s in shapes}))
820
+
821
+
822
+ def _short_tables(names) -> list[str]:
823
+ return sorted({str(n).rsplit(".", 1)[-1].strip("`\"").lower() for n in names or [] if n})
824
+
825
+
826
+ def _order(p: dict) -> tuple:
827
+ m = p.get("measured") or {}
828
+ code = p.get("code") or {}
829
+ return (-(m.get("read_bytes") or 0), KINDS.index(p["kind"]), 0 if code.get("evidence") == "verified" else 1,
830
+ code.get("hop_min", 99), -(p.get("member_count") or 0), p.get("fingerprint"))