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/loopbench.py ADDED
@@ -0,0 +1,2071 @@
1
+ """Loop benchmark: a query run once per item of a loop (N+1, per item) against one batched statement, proven item by item.
2
+
3
+ A pattern (patterns.py) of kind `n_plus_one` or `per_item`, and the outer item loop of a `fan_out` (one time step at a
4
+ time), qualifies by rule only when its loop is traced: the member is reached by calls the code makes (not guessed hops)
5
+ and takes the loop's item (`uses_loop_var`). `same_input` (the same statement every turn) stays held back: checked by
6
+ hand it was mostly wrong. A lazy ORM load with no call in the code is not in the inventory, so it is not here.
7
+
8
+ The member must be runnable: a benchmark candidate (rank.json or observed.json) for its call site, whose statement has
9
+ an equality on one parameter that takes the item (the key, `k`). The key is found, in this order: the inventory's text
10
+ of the call names the loop variable next to that column; the parameter or column is named like the item (or the field
11
+ of it the call passes); the only equality parameter left once the ones the driver filters on too, and flags, are put
12
+ aside. Anything else is the paid agent step's.
13
+
14
+ Baseline: the member run N times, once per item, with its other parameters as they are. N comes from the driver for
15
+ `n_plus_one` (the driver query's own result on the sandbox data, when the driver is runnable and loaded with the
16
+ member; its values are the items when it returns the key's column), else from a setting (`items_typical`), or, with a
17
+ production pull, the measured runs per driver run. The heavy run has `heavy_factor` times as many items (at most
18
+ `max_items`). The items are values the member's table holds under its other filters, plus items that hold no row
19
+ (`absent_share`) and an item listed twice (`duplicate_items`), because a loop sees those too.
20
+
21
+ Variant, by rule, for the clear single-table case:
22
+
23
+ SELECT cols FROM t WHERE k = {p} AND rest -> SELECT cols, k AS codecop_k FROM t WHERE k IN (<items>) AND rest
24
+ SELECT count(), sum(x) FROM t WHERE k = {p} -> ... , k AS codecop_k ... GROUP BY k (an item with no row: the
25
+ aggregates over no rows)
26
+ ... GROUP BY g -> ... GROUP BY g, k
27
+ ... ORDER BY o LIMIT n -> ClickHouse: ORDER BY o LIMIT n BY k
28
+ PostgreSQL: ROW_NUMBER() OVER (PARTITION BY k ORDER BY o) <= n
29
+
30
+ `<items>` is written for the developer as a bound list (`IN {codecop_items:Array(T)}`, `= ANY({codecop_items:T[]})`) and run
31
+ as literals, in chunks of at most `chunk_size` items. A join, a CTE, a subquery, a window, OFFSET or a key CodeCop cannot
32
+ find is the paid agent step's (`prompt`, `estimate`: never run here).
33
+
34
+ Sameness per item: the batched result, split by `codecop_k`, must give every item the rows its own run returned: an item
35
+ with no rows, an item listed twice, and a per-item ORDER BY ... LIMIT under the single-statement tie rule (bench.py:
36
+ rows ignoring order; a LIMIT without ORDER BY compares the count; ties compare the rows before the LIMIT and the count;
37
+ a baseline that disagrees with itself is not judged). One item with other rows rejects the variant.
38
+
39
+ What "win" means here (the verdict rule). Round trips fall from N to 1 by construction: that is the change, counted,
40
+ not something the sandbox verifies. The reads are measured: summed over the N statements before, over the chunks after
41
+ (PostgreSQL: buffer pages). They may fall (N index probes become one range or hash) or rise (an IN list the planner
42
+ does not use an index for, a hash over the whole table). Fixed only when every item's rows are reproduced AND the reads
43
+ are no worse than the bench's tolerance (bench.WORSE_RATIO) on the typical and the heavy run. Statements fall and reads
44
+ rise: a trade-off ("Needs another fix"), never a win on round trips alone.
45
+
46
+ Results are written to loops.json and joined into patterns.json by fingerprint (`merge`), because patterns.json is
47
+ recomputed by every scan and report.
48
+ """
49
+
50
+ from __future__ import annotations
51
+
52
+ import copy
53
+ import json
54
+ import re
55
+ import time
56
+ import uuid
57
+ from datetime import datetime, timezone
58
+
59
+ import sqlglot
60
+ from sqlglot import exp
61
+
62
+ from . import bench as bench_mod
63
+ from .engines.base import Measurement, QueryError, SandboxError
64
+
65
+
66
+ def _dialect(engine: str) -> str:
67
+ from .engines import sql_dialect
68
+ return sql_dialect(engine)
69
+
70
+
71
+ FILE = "loops.json"
72
+ SCHEMA_VERSION = 1
73
+ LOOP_KINDS = ("n_plus_one", "per_item", "fan_out")
74
+ DEFAULTS = {
75
+ "items_typical": 50, # items per run when neither the driver nor a pull says (per_item)
76
+ "heavy_factor": 10.0, # the heavy run has this many times the typical run's items
77
+ "max_items": 5000, # ... and at most this many
78
+ "min_items": 2, # a run of fewer items is not a loop worth batching
79
+ "chunk_size": 1000, # items per batched statement (an IN list longer than this is split)
80
+ "absent_share": 0.1, # share of the items that hold no row (at least one)
81
+ "duplicate_items": 1, # items listed twice
82
+ "max_compare_rows": 500_000, # rows fetched for the per-item comparison, summed over a run; past it: not shown
83
+ "min_items_per_run_measured": 1.5, # production's runs per driver run at or under this: nothing to batch
84
+ "runs": 1, # timed runs of each batched statement (the per-item statements run once each)
85
+ "agent_cost_per_member_usd_low": 0.03,
86
+ "agent_cost_per_member_usd_high": 0.06,
87
+ "agent_max_sql_chars": 12000,
88
+ "orm_limit_value": 50,
89
+ "agent_sites_per_call": 12, # member call sites per agent call of the paid step
90
+ "agent_rounds": 3, # `codecop scan`: rounds of the loop step, an answer opening the next question (a path then its batch)
91
+ "agent_context_lines": 15, # lines of code shown around the statement and below the loop
92
+ "agent_max_columns": 60, # columns of a table shown # `LIMIT «n»` of an ORM translation is run with this many rows
93
+ }
94
+ BOOL_DEFAULTS = {"fan_out_items": True} # a fan-out's outer items, batched within one time step
95
+ RULES = ("in_list", "in_list_group_by", "in_list_limit_by", "in_list_row_number")
96
+ # what a loop pattern ends with: the four states of blockers.py; reasons of its own
97
+ REASONS = {
98
+ "fixed": ("batch_verified",),
99
+ "blocked": ("batch_reads_more", "loop_item_not_reproduced", "loop_batch_misses_writes"),
100
+ "not_judged": ("engine_not_benchmarkable", "other_engine_run", "loop_not_traced", "same_input_held_back",
101
+ "loop_member_not_runnable", "loop_member_not_a_read", "loop_writes_rows_it_reads", "loop_key_not_found",
102
+ "loop_variants_not_asked", "sameness_not_shown", "parameters_match_no_rows", "sandbox_table_not_loaded",
103
+ "sandbox_could_not_run", "bench_not_run", "statement_known_at_run_time"),
104
+ "nothing_to_gain": ("one_item_per_run",),
105
+ }
106
+ NEXT_STEP = {
107
+ "batch_verified": "batch_the_loop",
108
+ "batch_reads_more": "ask_agent_for_loop_variant",
109
+ "loop_item_not_reproduced": "ask_agent_for_loop_variant",
110
+ "engine_not_benchmarkable": "measure_by_hand",
111
+ "other_engine_run": "run_codecop_bench_for_that_engine",
112
+ "loop_not_traced": "ask_agent_to_confirm_loop_path",
113
+ "same_input_held_back": "read_the_loop_by_hand",
114
+ "loop_member_not_runnable": "ask_agent_for_loop_statement",
115
+ "loop_member_not_a_read": "read_the_loop_by_hand",
116
+ "loop_writes_rows_it_reads": "read_the_loop_by_hand",
117
+ "loop_batch_misses_writes": "move_writes_after_batched_read",
118
+ "loop_key_not_found": "ask_agent_for_loop_variant",
119
+ "loop_variants_not_asked": "ask_agent_for_loop_variant",
120
+ "sameness_not_shown": "check_parameters_select_rows",
121
+ "parameters_match_no_rows": "check_parameters_select_rows",
122
+ "sandbox_table_not_loaded": "fix_table_build",
123
+ "sandbox_could_not_run": "read_the_server_error",
124
+ "bench_not_run": "run_codecop_bench",
125
+ "statement_known_at_run_time": "ask_agent_for_loop_statement",
126
+ "one_item_per_run": "none",
127
+ }
128
+ WORDS = {
129
+ "batch_verified": "Fixed: one batched statement gives every item its own rows and reads no more than the per-item statements",
130
+ "batch_reads_more": "Trade-off: the statements fall to one, but the batched statement reads more than the per-item ones",
131
+ "loop_item_not_reproduced": "Needs another fix: the batched result does not give every item its own rows",
132
+ "engine_not_benchmarkable": "Engine not benchmarkable: its statements run on an engine CodeCop has no sandbox for (MySQL or SQL Server, say)",
133
+ "other_engine_run": "Not judged in this run: its statements run on another engine than this benchmark's; that engine's bench judges it",
134
+ "loop_not_traced": "Not judged: the loop's calls were guessed, or whether the item reaches the query was not traced; the paid "
135
+ "step can confirm the path (said as the agent's, not as traced)",
136
+ "same_input_held_back": "Evidence only: the same statement every turn; held back, because it is mostly wrong",
137
+ "loop_member_not_a_read": "Not judged: the member reads no table (an advisory lock, pg_notify, set_config): no rows to batch",
138
+ "loop_writes_rows_it_reads": "Not judged: every item's rows were reproduced with the reads alone, but the loop also writes the table it reads; a read batched ahead of the loop may miss what an earlier item wrote",
139
+ "loop_batch_misses_writes": "Needs another fix: every item's rows were reproduced by the batched read, but the loop also writes "
140
+ "rows of that table another item may read (an insert, or a write not keyed by the item); the writes "
141
+ "must move after the batched read, or the read stays per item",
142
+ "loop_member_not_runnable": "Not judged: the member has no runnable form by rule (an ORM call not translated, a part known only "
143
+ "at run time, or a table the repository does not define); the paid step writes it",
144
+ "loop_key_not_found": "Not judged: which parameter takes the item could not be told from the statement",
145
+ "loop_variants_not_asked": "Not judged: no rule batches this statement; the paid agent step was not run",
146
+ "sameness_not_shown": "Not judged: the items' rows could not be compared",
147
+ "parameters_match_no_rows": "Not judged: no item selects a row, so sameness is not shown",
148
+ "sandbox_table_not_loaded": "Not judged: a table of the loop could not be built in the sandbox",
149
+ "sandbox_could_not_run": "Not judged: the sandbox refused a statement of the loop",
150
+ "bench_not_run": "Not judged: the loop was not benchmarked yet",
151
+ "statement_known_at_run_time": "Could not be judged: part of the statement is only known at run time (a parameter with no "
152
+ "value and no column to read one from, or a part discover could not read)",
153
+ "one_item_per_run": "Nothing to gain: production runs it about once per driver run",
154
+ }
155
+ STATE_WORDS = {"fixed": "Fixed", "blocked": "Needs another fix", "not_judged": "Could not be judged", "nothing_to_gain": "Nothing to gain"}
156
+ NOT_TRACED_WHY = ("guessed_call", "named_not_called", "framework_calls_per_row", "loop_variable_not_traced", "driver_guessed", "lazy_load_eager_unknown")
157
+ CH_AGGREGATES = re.compile(r"^(?:uniq\w*|any\w*|arg(?:Min|Max)\w*|group\w*|quantile\w*|median\w*|topK\w*|\w+If|\w+State|\w+Merge|"
158
+ r"sumMap|minMap|maxMap|countDistinct|count|sum\w*|avg\w*|min|max|stddev\w*|var\w*|corr|covar\w*|"
159
+ r"bitAnd|bitOr|bitXor|histogram|entropy|simpleLinearRegression|first_value|last_value)$", re.I)
160
+ NUMERIC = re.compile(r"^(?:U?Int\d*|Float\d*|Decimal.*|int\d?|integer|bigint|smallint|numeric.*|real|double precision|float\d?|"
161
+ r"serial|bigserial|smallserial|oid)$", re.I)
162
+ MARKER = "codecop_items_marker"
163
+
164
+
165
+ def settings_of(config: dict | None) -> dict:
166
+ out = {**DEFAULTS, **BOOL_DEFAULTS}
167
+ for k, v in (config or {}).items():
168
+ if k in DEFAULTS and isinstance(v, (int, float)) and not isinstance(v, bool):
169
+ out[k] = type(DEFAULTS[k])(v)
170
+ elif k in BOOL_DEFAULTS and isinstance(v, bool):
171
+ out[k] = v
172
+ return out
173
+
174
+
175
+ def now() -> str:
176
+ return datetime.now(timezone.utc).isoformat(timespec="seconds")
177
+
178
+
179
+ # --------------------------------------------------------------------------- which patterns qualify
180
+
181
+ def _agent_confirmed(m: dict) -> bool:
182
+ return (m.get("path_confirmed") or {}).get("by") == "agent" and (m.get("path_confirmed") or {}).get("item_reaches") is True
183
+
184
+
185
+ def qualifying_members(p: dict) -> list[dict]:
186
+ """Members reached by resolved calls only that take the loop's item, and members whose path and item the paid
187
+ step confirmed by reading the code (`path_confirmed: {by: agent}`: said apart from traced)."""
188
+ return [m for m in p.get("members") or [] if (m.get("depends_on_loop_var") is True and m.get("verified") is True) or _agent_confirmed(m)]
189
+
190
+
191
+ def qualify(p: dict, cfg: dict | None = None) -> tuple[bool | None, str | None]:
192
+ """(qualifies, why not). None for a kind this benchmark is not about."""
193
+ cfg = cfg or settings_of(None)
194
+ kind = p.get("kind")
195
+ if kind == "same_input":
196
+ return False, "same_input_held_back"
197
+ if kind not in LOOP_KINDS or not p.get("loops"):
198
+ return None, None
199
+ if kind == "fan_out" and not cfg["fan_out_items"]:
200
+ return None, None
201
+ confirmed = any(_agent_confirmed(m) for m in p.get("members") or [])
202
+ if (p.get("driver") or {}).get("verified") is False and kind == "n_plus_one" and not confirmed:
203
+ return False, "loop_not_traced"
204
+ if not (p.get("loops") or [{}])[0].get("verified", True) and not confirmed:
205
+ return False, "loop_not_traced"
206
+ if not qualifying_members(p):
207
+ return False, "loop_not_traced"
208
+ return True, None
209
+
210
+
211
+ # --------------------------------------------------------------------------- the key: which parameter takes the item
212
+
213
+ PARAM = re.compile(r"\{(\w+)\s*:\s*([^{}]+?)\}")
214
+ INV_PLACEHOLDER = re.compile(r"«([^«»]*)»")
215
+
216
+
217
+ def _tokens(name: str) -> set[str]:
218
+ s = re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", str(name or ""))
219
+ out = {t for t in re.split(r"[^A-Za-z0-9]+", s.lower()) if t}
220
+ return {t[:-1] if len(t) > 3 and t.endswith("s") else t for t in out} - {"id", "ids", "the", "a", "get", "by", "of"}
221
+
222
+
223
+ def _unquote(col: str) -> str:
224
+ return re.sub(r'[`"]', "", col).rsplit(".", 1)[-1]
225
+
226
+
227
+ RUNTIME_TEXT = "statement_known_at_run_time" # blockers.RUNTIME_TEXT
228
+
229
+
230
+ def runtime_left(cand: dict, key_param: str | None) -> list[str]:
231
+ """What of a member's statement no run of the loop bench gives a value: not the item (`key_param`), not a parameter
232
+ the candidate carries, not one read from a column of the sandbox's rows (`synthesized`). blockers.unbound_parts."""
233
+ from .blockers import unbound_parts
234
+ bound = set(cand.get("params") or {}) | set(cand.get("synthesized") or {}) | ({key_param} if key_param else set())
235
+ return unbound_parts(cand.get("baseline_sql") or "", bound)
236
+
237
+
238
+ def equalities(sql: str, dialect: str) -> list[dict] | None:
239
+ """Every `<expr> = {param:Type}` of the statement's WHERE and PREWHERE: [{expr, column, param, type}]. None when the
240
+ statement does not parse."""
241
+ from .groupbench import _protect, _unprotect
242
+ from .sqlinfo import conjuncts
243
+ try:
244
+ tree = sqlglot.parse_one(_protect(sql, dialect), read=dialect)
245
+ except Exception: # a statement the parser does not take
246
+ return None
247
+ if not isinstance(tree, exp.Select):
248
+ return None
249
+ out = []
250
+ for where in (tree.args.get("prewhere"), tree.args.get("where")):
251
+ for c in conjuncts(where):
252
+ if not isinstance(c, exp.EQ):
253
+ continue
254
+ for side, other in ((c.left, c.right), (c.right, c.left)):
255
+ text = _unprotect(other.sql(dialect=dialect))
256
+ m = PARAM.fullmatch(text.strip())
257
+ if not m or side.find(exp.Placeholder) or PARAM.search(_unprotect(side.sql(dialect=dialect))):
258
+ continue
259
+ col = side.find(exp.Column)
260
+ out.append({"expr": _unprotect(side.sql(dialect=dialect)), "column": col.name if col is not None else "",
261
+ "param": m.group(1), "type": m.group(2).strip()})
262
+ break
263
+ return out
264
+
265
+
266
+ def _args_of(text: str, start: int) -> list[str]:
267
+ """The arguments of the call whose `(` is at `start`, split at top-level commas."""
268
+ depth, cur, out = 0, [], []
269
+ for ch in text[start:]:
270
+ if ch in "([{":
271
+ depth += 1
272
+ if depth == 1:
273
+ continue
274
+ elif ch in ")]}":
275
+ depth -= 1
276
+ if depth == 0:
277
+ out.append("".join(cur).strip())
278
+ return [a for a in out if a]
279
+ if depth == 1 and ch == ",":
280
+ out.append("".join(cur).strip())
281
+ cur = []
282
+ elif depth >= 1:
283
+ cur.append(ch)
284
+ return []
285
+
286
+
287
+ def passed_params(root, loop: dict, member_file: str, symbol: str) -> set[str]:
288
+ """The member function's parameters the loop hands its item to, read from the code: the call to it in the loop's
289
+ body, its keyword arguments and (by the function's own signature) its positional ones that mention the loop's
290
+ variable. Only one hop (the loop calls the member's function itself); empty when it cannot be told."""
291
+ from .patterns import Source
292
+ vars_ = [v for v in loop.get("vars") or [] if v and v != "_"]
293
+ if root is None or not vars_ or int(loop.get("hop") or 0) != 1 or not symbol:
294
+ return set()
295
+ src = Source(root, 400)
296
+ got = src.loop(loop.get("file") or "", int(loop.get("line") or 0))
297
+ if not got:
298
+ return set()
299
+ name = symbol.split(".")[-1]
300
+ named = re.compile(r"\b(?:%s)\b" % "|".join(re.escape(v) for v in vars_))
301
+ sig = None
302
+ lines = src.lines(member_file) or []
303
+ for i, t in enumerate(lines):
304
+ if re.match(r"\s*(?:async\s+)?def\s+%s\s*\(" % re.escape(name), t):
305
+ text = "\n".join(lines[i:i + 30])
306
+ params = _args_of(text, text.index("("))
307
+ sig = [re.split(r"[:=]", p)[0].strip().lstrip("*") for p in params]
308
+ sig = [p for p in sig if p and p not in ("self", "cls", "/", "")]
309
+ break
310
+ out: set[str] = set()
311
+ text = got[2]
312
+ for m in re.finditer(r"\b%s\s*\(" % re.escape(name), text):
313
+ for i, a in enumerate(_args_of(text, m.end() - 1)):
314
+ kw = re.match(r"^(\w+)\s*=(?!=)\s*(.*)$", a, re.S)
315
+ value = kw.group(2) if kw else a
316
+ if not named.search(value):
317
+ continue
318
+ if kw:
319
+ out.add(kw.group(1))
320
+ elif sig is not None and i < len(sig):
321
+ out.add(sig[i])
322
+ return out
323
+
324
+
325
+ def find_key(cand: dict, site: dict | None, loop: dict, driver_sql: str | None, dialect: str, call_text: str = "",
326
+ passed: set[str] | None = None) -> tuple[dict | None, str]:
327
+ """(key, basis): the equality whose parameter takes the loop's item, and how that was told; (None, why) when not."""
328
+ eqs = equalities(cand.get("baseline_sql") or "", dialect)
329
+ if eqs is None:
330
+ return None, "the statement does not parse"
331
+ if not eqs:
332
+ return None, "no equality on a parameter"
333
+ vars_ = [v for v in loop.get("vars") or [] if v and v != "_"]
334
+ text = str((site or {}).get("sql") or "")
335
+ # 0. the statement has one parameter and the loop's item reaches the statement (only such members are planned): it
336
+ # is that parameter
337
+ if len(eqs) == 1 and len({m.group(1) for m in PARAM.finditer(cand.get("baseline_sql") or "")}) == 1:
338
+ return eqs[0], "the statement's only parameter, and the loop's item reaches the statement"
339
+ # 1. the inventory's text names the loop variable in a value next to a column: `name = «dep.name»`
340
+ if vars_ and int(loop.get("hop") or 0) == 0:
341
+ named = re.compile(r"\b(?:%s)\b" % "|".join(re.escape(v) for v in vars_))
342
+ with_var = [m for m in INV_PLACEHOLDER.finditer(text) if named.search(m.group(1))]
343
+ if len(with_var) > 1:
344
+ # the item reaches more than one filter (a composite key, or a filter chosen per item): not one IN list
345
+ return None, "the item reaches more than one filter (a composite key)"
346
+ for m in re.finditer(r"([\w.\"`]+)\s*=\s*«([^«»]*)»", text):
347
+ if named.search(m.group(2)):
348
+ col = _unquote(m.group(1))
349
+ hit = [e for e in eqs if e["column"].lower() == col.lower()]
350
+ if len(hit) == 1:
351
+ return hit[0], "the call passes the loop's item to this column"
352
+ # 1b. one hop down: the loop hands its item to these parameters of the member's function, and the inventory's text
353
+ # names the parameter next to a column: `user_id = «user_id»`
354
+ if passed:
355
+ cols = {_unquote(m.group(1)).lower() for m in re.finditer(r"([\w.\"`]+)\s*=\s*«([^«»]*)»", text)
356
+ if re.split(r"[.\[(]", m.group(2).strip())[0] in passed}
357
+ hit = [e for e in eqs if e["column"].lower() in cols]
358
+ if len(hit) == 1:
359
+ return hit[0], "the loop passes its item to the parameter this column is compared with"
360
+ # 2. a parameter or column named like the item, or like the field of it the call passes (`c.Author.Email`)
361
+ words = set()
362
+ for v in vars_:
363
+ words |= _tokens(v)
364
+ for v in vars_:
365
+ for m in re.finditer(r"\b%s((?:\.\w+)+)" % re.escape(v), call_text or ""):
366
+ words |= _tokens(m.group(1))
367
+ if words:
368
+ hit = [e for e in eqs if (_tokens(e["param"]) | _tokens(e["column"])) & words]
369
+ if len(hit) == 1:
370
+ return hit[0], "the parameter is named like the loop's item"
371
+ # 3. the one equality left once the driver's own filters and flags are put aside
372
+ driver_cols = {e["column"].lower() for e in (equalities(driver_sql, dialect) or [])} if driver_sql else set()
373
+ params = cand.get("params") or {}
374
+
375
+ def flag(e: dict) -> bool:
376
+ v = params.get(e["param"])
377
+ return isinstance(v, bool) or str(v).lower() in ("true", "false") or re.match(r"^(?:Bool|boolean)$", e["type"], re.I) is not None
378
+ left = [e for e in eqs if e["column"].lower() not in driver_cols and not flag(e)]
379
+ if len(left) == 1:
380
+ return left[0], "the only equality on a parameter the driver does not filter on"
381
+ return None, f"{len(left) or len(eqs)} equalities could take the item"
382
+
383
+
384
+ # --------------------------------------------------------------------------- the batched statement, by rule
385
+
386
+ def _is_aggregate(node, dialect: str) -> bool:
387
+ if node.find(exp.AggFunc):
388
+ return True
389
+ return dialect == "clickhouse" and any(CH_AGGREGATES.match(f.name or "") for f in node.find_all(exp.Anonymous))
390
+
391
+
392
+ def batched(sql: str, key: dict, dialect: str) -> tuple[dict | None, str]:
393
+ """The batched form of a per-item statement: (variant, "") or (None, why no rule applies).
394
+
395
+ The variant: {rule, marker_sql, marker_unlimited, sql (with the bound list), per_item: {order_by, limit, absent}}."""
396
+ from .groupbench import _protect, _unprotect
397
+ from .sqlinfo import conjuncts
398
+ try:
399
+ tree = sqlglot.parse_one(_protect(sql, dialect), read=dialect)
400
+ except Exception:
401
+ return None, "the statement does not parse"
402
+ if not isinstance(tree, exp.Select):
403
+ return None, "not a single SELECT (a set operation)"
404
+ if tree.args.get("with_") or tree.args.get("with"):
405
+ return None, "reads a CTE"
406
+ if tree.args.get("joins"):
407
+ return None, "joins tables"
408
+ src = tree.args.get("from_") or tree.args.get("from")
409
+ base = src.this.this if src is not None and isinstance(src.this, exp.Final) else (src.this if src is not None else None)
410
+ if not isinstance(base, exp.Table):
411
+ return None, "reads a subquery"
412
+ if any(s is not tree for s in tree.find_all(exp.Select)) or tree.find(exp.Subquery):
413
+ return None, "holds a subquery"
414
+ if tree.find(exp.Window):
415
+ return None, "holds a window function"
416
+ if tree.args.get("offset") is not None:
417
+ return None, "pages with OFFSET"
418
+ limit = tree.args.get("limit")
419
+ if limit is not None and limit.args.get("expressions"):
420
+ return None, "already LIMIT n BY"
421
+ target = None
422
+ for where in (tree.args.get("prewhere"), tree.args.get("where")):
423
+ for c in conjuncts(where):
424
+ if isinstance(c, exp.EQ) and any(PARAM.fullmatch(_unprotect(s.sql(dialect=dialect)).strip() or "") and
425
+ PARAM.fullmatch(_unprotect(s.sql(dialect=dialect)).strip()).group(1) == key["param"]
426
+ for s in (c.left, c.right)):
427
+ target = c
428
+ if target is None:
429
+ return None, "the key's equality is not a top-level filter"
430
+ side = target.left if _unprotect(target.right.sql(dialect=dialect)).strip().startswith("{") else target.right
431
+ if PARAM.search(_unprotect(side.sql(dialect=dialect))):
432
+ return None, "the key's other side holds a parameter"
433
+ if len(re.findall(r"\{%s\s*:" % re.escape(key["param"]), sql)) > 1:
434
+ return None, "the key's parameter is used twice"
435
+ kexpr = side.copy()
436
+ nothing = sqlglot.parse_one("1 = 0", read=dialect)
437
+ target.replace(nothing)
438
+ # what the member returns for an item no row holds, written without any item: for an aggregate, its value over no rows
439
+ empty_sql = _unprotect(tree.sql(dialect=dialect))
440
+ nothing.replace(exp.In(this=side.copy(), expressions=[exp.column(MARKER)]))
441
+ aggregate = bool(tree.args.get("group")) or any(_is_aggregate(e, dialect) for e in tree.expressions)
442
+ group = tree.args.get("group")
443
+ if group is not None and (group.args.get("grouping_sets") or group.args.get("rollup") or group.args.get("cube") or group.args.get("totals")):
444
+ return None, "GROUPING SETS, ROLLUP or CUBE"
445
+ tree.set("expressions", list(tree.expressions) + [exp.alias_(kexpr.copy(), "codecop_k")])
446
+ absent = "no_rows"
447
+ if aggregate:
448
+ if group is None:
449
+ tree.set("group", exp.Group(expressions=[kexpr.copy()]))
450
+ absent = "aggregate_over_no_rows"
451
+ else:
452
+ group.set("expressions", list(group.expressions) + [kexpr.copy()])
453
+ order = tree.args.get("order")
454
+ aliases = {e.alias: e.this for e in tree.expressions if isinstance(e, exp.Alias)}
455
+
456
+ def resolved(o):
457
+ o = o.copy()
458
+ for c in list(o.find_all(exp.Column)):
459
+ if not c.table and c.name in aliases and not (isinstance(aliases[c.name], exp.Column) and aliases[c.name].name == c.name):
460
+ if c is o:
461
+ return aliases[c.name].copy()
462
+ c.replace(aliases[c.name].copy())
463
+ return o
464
+ order_text = ", ".join(_unprotect(o.sql(dialect=dialect)) for o in order.expressions) if order is not None else ""
465
+ limit_text = _unprotect(limit.args["expression"].sql(dialect=dialect)) if limit is not None and limit.args.get("expression") is not None else ""
466
+ if limit is not None and not limit_text:
467
+ return None, "a LIMIT CodeCop does not read"
468
+ unlimited = tree.copy()
469
+ unlimited.set("order", None)
470
+ unlimited.set("limit", None)
471
+ if limit is None:
472
+ tree.set("order", None)
473
+ rule = "in_list_group_by" if aggregate else "in_list"
474
+ main = tree
475
+ elif dialect == "clickhouse":
476
+ tree.set("limit", exp.Limit(expression=limit.args["expression"].copy(), expressions=[kexpr.copy()]))
477
+ rule = "in_list_limit_by"
478
+ main = tree
479
+ else:
480
+ inner = tree.copy()
481
+ inner.set("order", None)
482
+ inner.set("limit", None)
483
+ over = f"ROW_NUMBER() OVER (PARTITION BY {kexpr.sql(dialect=dialect)}" + (
484
+ " ORDER BY " + ", ".join(resolved(o).sql(dialect=dialect) for o in order.expressions) if order is not None else "") + ")"
485
+ inner.set("expressions", list(inner.expressions) + [exp.alias_(sqlglot.parse_one(over, read=dialect), "codecop_rn")])
486
+ main = sqlglot.parse_one(f"SELECT * FROM ({inner.sql(dialect=dialect)}) AS codecop_b WHERE codecop_rn <= {limit.args['expression'].sql(dialect=dialect)}",
487
+ read=dialect)
488
+ rule = "in_list_row_number"
489
+ marker_sql = _unprotect(main.sql(dialect=dialect))
490
+ marker_unlimited = _unprotect(unlimited.sql(dialect=dialect))
491
+ typ = key["type"]
492
+ # the list as the developer binds it: an array parameter, or on SQLite (no arrays) one JSON text parameter
493
+ bound = (f"IN {{codecop_items:Array({typ})}}" if dialect == "clickhouse" else
494
+ "IN (SELECT value FROM json_each({codecop_items:TEXT}))" if dialect == "sqlite" else f"= ANY({{codecop_items:{typ}[]}})")
495
+ return {"rule": rule, "marker_sql": marker_sql, "marker_unlimited": marker_unlimited,
496
+ "sql": marker_sql.replace(f"IN ({MARKER})", bound), "key_expr": _unprotect(kexpr.sql(dialect=dialect)),
497
+ **({"empty_sql": empty_sql} if absent == "aggregate_over_no_rows" else {}),
498
+ "per_item": {"order_by": order_text, "limit": limit_text, "absent": absent,
499
+ "split": "codecop_k" + (", codecop_rn" if rule == "in_list_row_number" else "")}}, ""
500
+
501
+
502
+ def literal(v, typ: str, dialect: str) -> str:
503
+ if v is None:
504
+ return "NULL"
505
+ t = re.sub(r"^(?:Nullable|LowCardinality)\((.*)\)$", r"\1", str(typ or "").strip())
506
+ t = re.sub(r"^(?:Nullable|LowCardinality)\((.*)\)$", r"\1", t)
507
+ s = str(v).lower() if isinstance(v, bool) else str(v)
508
+ if NUMERIC.match(t) and re.fullmatch(r"-?\d+(?:\.\d+)?(?:[eE][-+]?\d+)?", s):
509
+ return s
510
+ if dialect == "clickhouse":
511
+ return "'" + s.replace("\\", "\\\\").replace("'", "\\'") + "'"
512
+ return "'" + s.replace("'", "''") + "'"
513
+
514
+
515
+ def with_items(marker_sql: str, items: list, typ: str, dialect: str) -> str:
516
+ return marker_sql.replace(f"IN ({MARKER})", "IN (" + ", ".join(literal(v, typ, dialect) for v in items) + ")")
517
+
518
+
519
+ # --------------------------------------------------------------------------- plans
520
+
521
+ def _site_maps(rank: dict | None, observed: dict | None) -> tuple[dict, dict]:
522
+ by_site, by_place = {}, {}
523
+ for c in (rank or {}).get("candidates") or []:
524
+ if c.get("sql_from") != "query_log" and c.get("id") and c.get("baseline_sql"):
525
+ by_site.setdefault(str(c["id"]), c)
526
+ for c in (observed or {}).get("candidates") or (rank or {}).get("candidates") or []:
527
+ o = c.get("observed") or {}
528
+ if c.get("sql_from") == "query_log" and c.get("baseline_sql"):
529
+ for sid in o.get("places") or []:
530
+ by_place.setdefault(str(sid), c)
531
+ return by_site, by_place
532
+
533
+
534
+ def _call_text(root, member: dict) -> str:
535
+ from .patterns import Source
536
+ src = Source(root, 3)
537
+ lines = src.lines(member.get("file") or "") or []
538
+ i = int(member.get("line") or 0)
539
+ return "\n".join(lines[max(i - 1, 0): i + 1]) if lines else ""
540
+
541
+
542
+ PLACEHOLDER = re.compile(r"\$(\d+)|\?(?![?|&])")
543
+ COMPARE_LEFT = re.compile(r"(\"?[A-Za-z_][\w]*\"?(?:\.\"?[A-Za-z_][\w]*\"?)?)\s*(?:=|<>|!=|<=|>=|<|>|\bLIKE\b|\bILIKE\b)\s*$", re.I)
544
+ TABLE_ALIAS = re.compile(r"\b(?:FROM|JOIN)\s+([`\"\w.]+)(?:\s+(?:AS\s+)?(?!(?:WHERE|JOIN|LEFT|RIGHT|INNER|OUTER|CROSS|ON|USING|GROUP|ORDER|LIMIT|UNION|NATURAL)\b)(\w+))?", re.I)
545
+ COMPARE_RIGHT = re.compile(r"^\s*(?:=|<>|!=|<=|>=|<|>)\s*(\"?[A-Za-z_][\w]*\"?(?:\.\"?[A-Za-z_][\w]*\"?)?)", re.I)
546
+ CAST_AFTER = re.compile(r"^::\s*([A-Za-z_][\w ]*?)(?=[\s),;]|$)")
547
+
548
+
549
+ PG_RESERVED = frozenset("""all analyse analyze and any array as asc asymmetric both case cast check collate column constraint create
550
+ current_catalog current_date current_role current_time current_timestamp current_user default deferrable desc distinct do else end
551
+ except false fetch for foreign from grant group having in initially intersect into lateral leading limit localtime localtimestamp
552
+ not null offset on only or order placing primary references returning select session_user some symmetric table then to trailing
553
+ true union unique user using variadic when where window with authorization binary collation concurrently cross freeze full ilike
554
+ inner is isnull join left like natural notnull outer overlaps right similar tablesample verbose""".split())
555
+ VALUE_SLOT = re.compile(r"(?:=|<>|!=|<=|>=|<|>|\bLIKE|\bILIKE)\s*$", re.I)
556
+ LIMIT_SLOT = re.compile(r"\b(LIMIT|OFFSET)\s*$", re.I)
557
+ NAMED_PARAM = re.compile(r"%\((\w+)\)s|%s|(?<![:\w]):([A-Za-z_]\w*)")
558
+
559
+
560
+ def _outside_quotes(sql: str):
561
+ """(start, end) spans of `sql` outside string literals, quoted identifiers and comments."""
562
+ i, n, start = 0, len(sql), 0
563
+ while i < n:
564
+ ch = sql[i]
565
+ if ch in "'\"":
566
+ yield start, i
567
+ j = i + 1
568
+ while j < n:
569
+ if sql[j] == ch:
570
+ if j + 1 < n and sql[j + 1] == ch:
571
+ j += 2
572
+ continue
573
+ break
574
+ j += 1
575
+ i = start = j + 1
576
+ continue
577
+ if sql.startswith("--", i):
578
+ yield start, i
579
+ j = sql.find("\n", i)
580
+ i = start = n if j < 0 else j
581
+ continue
582
+ i += 1
583
+ yield start, n
584
+
585
+
586
+ def member_text(site: dict | None, engine: str, limit_value: int = 50) -> tuple[str | None, list[str], str]:
587
+ """The member's statement as the sandbox runs it, with its parameters as `$n`: (sql, notes, why_not).
588
+
589
+ literal / constant the code's own text; driver placeholders `%s`, `%(name)s` (psycopg) and `:name` (SQLAlchemy
590
+ text()) become `$n`
591
+ orm / template discover's translation of the ORM call (SQLAlchemy select / session.get / Query, Django
592
+ QuerySets, Prisma, ent, ...): each value it marks `«expr»` beside a comparison becomes `$n`;
593
+ `LIMIT «n»` takes the setting `orm_limit_value`; a table name PostgreSQL reserves (`user`) is
594
+ quoted. Any other `«…»` is a part of the statement only known at run time (a filter built by
595
+ a function, an optional clause, a table chosen per call): not runnable by rule.
596
+ """
597
+ if not site:
598
+ return None, [], "no call site"
599
+ sql = site.get("sql") or ""
600
+ res = site.get("resolution")
601
+ if not sql.strip():
602
+ return None, [], ("the ORM call was not translated to SQL" if res == "orm" else "the statement is not known as text")
603
+ if res not in ("literal", "constant", "orm", "template"):
604
+ return None, [], "the statement is not fixed text in the code"
605
+ notes: list[str] = []
606
+ if "«" in sql:
607
+ out, last, n = [], 0, len(re.findall(r"\$(\d+)", sql))
608
+ for m in re.finditer(r"«([^«»]*)»", sql):
609
+ before = sql[last:m.start()]
610
+ inner = m.group(1).strip()
611
+ # a value: a name, a field, an item of a mapping, or one call on such a value (`str(row.id)`)
612
+ if not re.fullmatch(r"(?:[\w.]+\()*[\w.]+(?:\[[\w.'\"]+\])*(?:\.\w+)*\)*", inner) or inner.count("(") != inner.count(")"):
613
+ return None, [], f"a part of the statement is only known at run time: «{inner[:60]}»"
614
+ if VALUE_SLOT.search(before):
615
+ n += 1
616
+ out.append(before + f"${n}")
617
+ elif LIMIT_SLOT.search(before):
618
+ out.append(before + str(int(limit_value)))
619
+ notes.append(f"{LIMIT_SLOT.search(before).group(1).upper()} «{inner[:40]}» run as {int(limit_value)} (setting orm_limit_value)")
620
+ else:
621
+ return None, [], f"a part of the statement is only known at run time: «{inner[:60]}»"
622
+ last = m.end()
623
+ out.append(sql[last:])
624
+ sql = "".join(out)
625
+ if res in ("orm", "template"):
626
+ notes.append("the ORM call's SQL as CodeCop translated it; every value it passes is a parameter")
627
+ if "«" in sql or "»" in sql:
628
+ return None, [], "a part of the statement is only known at run time"
629
+ if not re.search(r"\$\d+|\?(?![?|&])", sql):
630
+ # driver placeholders, outside quotes: %s / %(name)s (psycopg), :name (SQLAlchemy text)
631
+ out, n, names, prev = [], 0, {}, 0
632
+ for a, b in _outside_quotes(sql):
633
+ out.append(sql[prev:a]) # the quoted part before this span, as it is
634
+ part = sql[a:b]
635
+ pos = 0
636
+ for m in NAMED_PARAM.finditer(part):
637
+ key = m.group(1) or m.group(2)
638
+ if key and key in names:
639
+ num = names[key]
640
+ else:
641
+ n += 1
642
+ num = n
643
+ if key:
644
+ names[key] = num
645
+ out.append(part[pos:m.start()] + f"${num}")
646
+ pos = m.end()
647
+ out.append(part[pos:])
648
+ prev = b
649
+ out.append(sql[prev:])
650
+ if n:
651
+ sql = "".join(out)
652
+ notes.append("the driver's placeholders (%s, %(name)s, :name) read as $n")
653
+ if engine == "postgres" and res in ("orm", "template"):
654
+ for t in site.get("tables") or []:
655
+ bare = t.split(".")[-1]
656
+ if bare.lower() in PG_RESERVED or bare != bare.lower():
657
+ if not re.fullmatch(r"\w+", bare):
658
+ continue
659
+ sql = re.sub(r'(?<!["\w.])%s(?=\s*\.)' % re.escape(bare), f'"{bare}"', sql)
660
+ sql = re.sub(r'(\b(?:FROM|JOIN|UPDATE|INTO)\s+)%s\b(?!")' % re.escape(bare), rf'\1"{bare}"', sql, flags=re.I)
661
+ return sql, notes, ""
662
+
663
+
664
+ def synthesize(site: dict | None, definitions: dict[str, dict], engine: str, inventory: dict | None = None) -> tuple[dict | None, str]:
665
+ """A runnable candidate made from a loop member's own SQL, by rule, when no ranked candidate stands for it: the
666
+ statement is fixed text in the code (literal or constant), every table it reads is loaded in the sandbox, and every
667
+ placeholder (`$1`, `?`) compares a column the definition gives a type to. Its placeholders become `{pN:type}`; the
668
+ values of the ones that do not take the loop's item are read from the sandbox's rows when it runs (run_plan). A
669
+ column it reads that the loaded definition lacks is added to that definition from the repository's schema
670
+ (inventory `tables`, as definitions.complete does), so the sandbox builds it. (None, why not) otherwise."""
671
+ from .rank import _columns
672
+ if not site or site.get("statement") != "select":
673
+ return None, "not a read" if site else "no call site"
674
+ sql, text_notes, why_text = member_text(site, engine, int(DEFAULTS["orm_limit_value"]))
675
+ if sql is None:
676
+ return None, why_text
677
+ if not PLACEHOLDER.search(sql):
678
+ return None, "the statement takes no parameter"
679
+ tables = [t.split(".")[-1].lower() for t in site.get("tables") or []]
680
+ if not tables:
681
+ return None, "it reads no table (a server call such as pg_notify, not a read)"
682
+ if any(t not in definitions for t in tables):
683
+ return None, "a table it reads is not loaded in the sandbox"
684
+ types: dict[str, set[tuple[str, str]]] = {}
685
+ for t in tables:
686
+ got = _columns(definitions[t].get("create_sql") or "", definitions[t]["name"])
687
+ for col, text in (got[1] if got else {}).items():
688
+ words = text.split()
689
+ typ = words[1] if len(words) > 1 else ""
690
+ if engine == "postgres" and len(words) > 2 and words[2].lower() in ("precision", "varying"):
691
+ typ += " " + words[2]
692
+ types.setdefault(col.lower(), set()).add((t, typ.rstrip(",")))
693
+ aliases = {t: t for t in tables}
694
+ for a in TABLE_ALIAS.finditer(sql):
695
+ t = a.group(1).replace('"', "").replace("`", "").split(".")[-1].lower()
696
+ if t in tables:
697
+ aliases[(a.group(2) or t).lower()] = t
698
+ out, params, n, last = [], {}, 0, 0
699
+ for m in PLACEHOLDER.finditer(sql):
700
+ n += 1
701
+ index = int(m.group(1)) if m.group(1) else n
702
+ cast = CAST_AFTER.match(sql[m.end():]) if engine == "postgres" else None
703
+ end = m.end() + (cast.end() if cast else 0)
704
+ left, right = COMPARE_LEFT.search(sql[:m.start()]), COMPARE_RIGHT.match(sql[end:])
705
+ named = ((left or right).group(1) if (left or right) else "").replace('"', "")
706
+ col = named.split(".")[-1].lower()
707
+ found = types.get(col) or set()
708
+ if len(found) > 1 and "." in named:
709
+ # `s.id = ?` with id in two of the tables: the qualifier names the table (its alias, or the table itself)
710
+ qual = named.split(".")[-2].lower()
711
+ found = {f for f in found if aliases.get(qual) == f[0]}
712
+ if len(found) != 1:
713
+ return None, f"placeholder {m.group(0)} does not compare one column of a loaded table"
714
+ table, typ = next(iter(found))
715
+ if engine == "postgres":
716
+ # a column's declared pseudo-type is not a type a value is cast to
717
+ typ = {"serial": "integer", "serial4": "integer", "bigserial": "bigint", "serial8": "bigint", "smallserial": "smallint"}.get(typ.lower(), typ)
718
+ if not typ or "(" in typ and engine == "clickhouse":
719
+ return None, f"the type of {table}.{col} is not known"
720
+ name = f"p{index}"
721
+ params[name] = {"table": definitions[table]["name"], "column": col}
722
+ # `$1::text`: the code's own cast is the parameter's type
723
+ out.append(sql[last:m.start()] + "{" + f"{name}:{cast.group(1).strip() if cast else typ}" + "}")
724
+ last = end
725
+ out.append(sql[last:])
726
+ from .definitions import columns_read
727
+ got = columns_read("".join(out), engine)
728
+ if got is None:
729
+ return None, "the statement does not parse"
730
+ read = {(t, c.lower()) for t, cols in got[0].items() for c in cols} | {(t, c.lower()) for ts, cols in got[1].items() for t in ts for c in cols}
731
+ have = {(t, c) for c, found in types.items() for t, _typ in found}
732
+ lacking = sorted((t, c) for t, c in read if t in tables and (t, c) not in have and not any((o, c) in have for o in tables))
733
+ if lacking:
734
+ from .definitions import _add_columns, _pg_type, _quote, _schema_tables
735
+ schema = _schema_tables(inventory)
736
+ adds: dict[str, list[str]] = {}
737
+ for t, c in lacking:
738
+ col = next((x for x in (schema.get(t) or {}).get("columns") or [] if x.get("name", "").lower() == c), None)
739
+ if col is None or definitions[t].get("source") == "real catalog":
740
+ return None, f"it reads {t}.{c}, which neither the loaded definition nor the repository's schema has"
741
+ adds.setdefault(t, []).append(f"{_quote(col['name'], engine)} {_pg_type(col.get('type') or '') if engine == 'postgres' else col.get('type') or ('TEXT' if engine == 'sqlite' else 'String')}")
742
+ for t, cols in adds.items():
743
+ d = definitions[t]
744
+ d["create_sql"] = _add_columns(d["create_sql"], d["name"], cols)
745
+ d["basis"] = (d.get("basis", "") + f" Completed: {len(cols)} column(s) a loop member reads, from the repository's schema.").strip()
746
+ return {"finding": f"LM-{site.get('id')}", "id": site.get("id"), "tables": [definitions[t]["name"] for t in tables],
747
+ "baseline_sql": "".join(out), "params": {}, "variants": [], "synthesized": params,
748
+ "site": {"file": site.get("file"), "line": site.get("line")},
749
+ **({"assumptions": text_notes} if text_notes else {}),
750
+ **({"orm": site.get("orm")} if site.get("resolution") == "orm" and site.get("orm") else {})}, ""
751
+
752
+
753
+ def prepare(patterns_doc: dict, rank: dict | None, inventory: dict | None, settings: dict | None = None, root=None) -> list[dict]:
754
+ """One plan per qualifying member of every qualifying pattern: its candidate, its key, the batched variant, where
755
+ N comes from. Members that cannot run, or that no rule batches, are plans with `skip` (and `why`)."""
756
+ cfg = settings_of(settings)
757
+ by_site, by_place = _site_maps(rank, rank)
758
+ sites = {s.get("id"): s for s in (inventory or {}).get("call_sites") or []}
759
+ engine = (rank or {}).get("engine") or "clickhouse"
760
+ loaded = {d["name"].split(".")[-1].lower(): d for d in (rank or {}).get("table_definitions") or []}
761
+ plans = []
762
+ for p in patterns_doc.get("patterns") or []:
763
+ ok, _ = qualify(p, cfg)
764
+ if not ok:
765
+ continue
766
+ lp = p["loops"][0]
767
+ drv_ids = (p.get("driver") or {}).get("site_ids") or []
768
+ dcand = next((by_site.get(i) or by_place.get(i) for i in drv_ids if by_site.get(i) or by_place.get(i)), None)
769
+ dsite = sites.get(drv_ids[0]) if drv_ids else None
770
+ for i, m in enumerate(qualifying_members(p)):
771
+ plan = {"id": f"{p['id']}.{i + 1}", "pattern": p["id"], "fingerprint": p["fingerprint"], "kind": p["kind"],
772
+ "site_id": m["site_id"], "file": m.get("file"), "line": m.get("line"), "symbol": m.get("symbol"),
773
+ "tables": m.get("tables") or [], "engine": engine,
774
+ "measured_per_driver_run": (p.get("measured") or {}).get("executions_per_driver_run"),
775
+ "measured_driver_rows": (p.get("measured") or {}).get("driver_rows_per_run")}
776
+ cand = by_site.get(m["site_id"]) or by_place.get(m["site_id"])
777
+ # no candidate of this benchmark's engine: a member on another engine is that engine's to judge, one on an
778
+ # engine CodeCop has no sandbox for (MySQL, say) is never runnable, whatever else is known of it
779
+ why_engine = engine_reason(m.get("engine") or (sites.get(m["site_id"]) or {}).get("engine") or "", engine) if cand is None else None
780
+ if why_engine:
781
+ plan["skip"], plan["member_engine"] = why_engine, m.get("engine") or (sites.get(m["site_id"]) or {}).get("engine")
782
+ plans.append(plan)
783
+ continue
784
+ if cand is None and (sites.get(m["site_id"]) or {}).get("engine") in (engine, ""):
785
+ # no ranked candidate: the member's own fixed SQL on loaded tables is runnable by rule (synthesize)
786
+ cand, why_not = synthesize(sites.get(m["site_id"]), loaded, engine, inventory)
787
+ if cand is not None:
788
+ plan["synthesized"] = True
789
+ else:
790
+ # the members step (members.py) says why from the pulled catalog when it tried this member
791
+ plan["why"] = ((rank or {}).get("members_why") or {}).get(str(m["site_id"])) or why_not
792
+ if cand is None:
793
+ if not [t for t in (sites.get(m["site_id"]) or {}).get("tables") or m.get("tables") or [] if t]:
794
+ # a server call (an advisory lock, pg_notify, set_config): no table rows to batch
795
+ plan["skip"] = "loop_member_not_a_read"
796
+ else:
797
+ plan["skip"] = "loop_member_not_runnable"
798
+ plan["next_step"] = "ask_agent_for_loop_statement"
799
+ plans.append(plan)
800
+ continue
801
+ dialect = _dialect(engine)
802
+ mlp = next((x for x in (sites.get(m["site_id"]) or {}).get("loop_context") or [] if
803
+ (x.get("file"), int(x.get("line") or 0)) == (lp.get("file"), int(lp.get("line") or 0))), {**lp, "hop": m.get("hop", 0)})
804
+ if cand.get("agent_key"):
805
+ hit = [e for e in equalities(cand.get("baseline_sql") or "", dialect) or [] if e["param"] == cand["agent_key"]]
806
+ key, basis = (hit[0], "the agent named the parameter that takes the item") if len(hit) == 1 else \
807
+ (None, "the agent's key parameter is not one equality of its statement")
808
+ else:
809
+ passed = passed_params(root, mlp, m.get("file") or "", str((m.get("path") or [m.get("symbol") or ""])[0])) if root else set()
810
+ key, basis = find_key(cand, sites.get(m["site_id"]), mlp, (dcand or {}).get("baseline_sql") or (dsite or {}).get("sql"),
811
+ dialect, _call_text(root, m) if root else "", passed)
812
+ plan.update(finding=cand["finding"], cand=cand, driver=dcand, key_basis=basis)
813
+ if cand.get("sql_from") == "agent":
814
+ plan["sql_from"] = "agent"
815
+ if _agent_confirmed(m) and m.get("verified") is not True:
816
+ plan["path_confirmed"] = "agent"
817
+ if key is None:
818
+ # the paid step named the parameter that takes the item for this statement: used when it is one equality
819
+ said = {str(v.get("param")).strip("{}").split(":")[0] for v in p.get("agent_batch_variants") or []
820
+ if v.get("site_id") == m["site_id"] and v.get("param")}
821
+ cols = {mm.group(1).split(".")[-1].strip('"').lower() for v in p.get("agent_batch_variants") or [] if v.get("site_id") == m["site_id"]
822
+ for mm in re.finditer(r"([\w.\"]+)\s+AS\s+codecop_k\b", v.get("sql") or "", re.I)}
823
+ eqs_ = equalities(cand.get("baseline_sql") or "", dialect) or []
824
+ hit = [e for e in eqs_ if e["param"] in said] or [e for e in eqs_ if e["column"].lower() in cols]
825
+ if len(hit) == 1:
826
+ key, basis = hit[0], "the agent named the parameter that takes the item"
827
+ plan["key_basis"] = basis
828
+ if key is None:
829
+ plan["skip"] = "loop_key_not_found"
830
+ plans.append(plan)
831
+ continue
832
+ plan["key"] = key
833
+ left = runtime_left(cand, key["param"])
834
+ if left:
835
+ # a placeholder no value is known for (nor the item, nor a column to read one from) or a part discover could
836
+ # not read: classed here, before any sandbox run, not sent and counted as the server's syntax error
837
+ from .blockers import runtime_detail
838
+ plan["skip"], plan["why"] = RUNTIME_TEXT, runtime_detail(left)
839
+ plans.append(plan)
840
+ continue
841
+ variant, why = batched(cand["baseline_sql"], key, dialect)
842
+ agent = [v for v in p.get("agent_batch_variants") or [] if v.get("site_id") == m["site_id"] and v.get("sql")]
843
+ plan["variants"] = ([variant] if variant else []) + [
844
+ {**v, "rule": "agent", "source": "agent", **({"empty_sql": variant["empty_sql"]} if variant and variant.get("empty_sql") else {})}
845
+ for v in agent]
846
+ if variant:
847
+ variant["source"] = "mechanical"
848
+ else:
849
+ plan["no_rule"] = why
850
+ if not plan["variants"]:
851
+ plan["skip"] = "loop_variants_not_asked"
852
+ plans.append(plan)
853
+ return plans
854
+
855
+
856
+ # --------------------------------------------------------------------------- running many statements at once
857
+
858
+ def _sum(ms: list[Measurement]) -> Measurement:
859
+ from .groupbench import total
860
+ return total(ms) if ms else Measurement(ok=True)
861
+
862
+
863
+ def measure_many(sb, sql: str, plist: list[dict]) -> Measurement:
864
+ """One statement run once per parameter set, its reads summed. ClickHouse: from the query log in one read; PostgreSQL:
865
+ EXPLAIN (ANALYZE, BUFFERS) in one psql session per batch; elsewhere: the sandbox's own measure, once each."""
866
+ eng = getattr(sb, "engine", "")
867
+ if hasattr(sb, "measure_many"):
868
+ return sb.measure_many(sql, plist) # SQLite: the C counters of one run each, no warm-up
869
+ if eng == "clickhouse" and hasattr(sb, "_http"):
870
+ tag = uuid.uuid4().hex[:12]
871
+ text = sb.frozen(sql.strip().rstrip(";"))
872
+ m = Measurement(ok=False)
873
+ try:
874
+ for i, p in enumerate(plist):
875
+ sb._http(text + " FORMAT Null", p, {"query_id": f"codecop-l-{tag}-{i}", "log_queries": 1, "use_query_cache": 0,
876
+ **getattr(sb, "query_limits", {})})
877
+ sb._http("SYSTEM FLUSH LOGS")
878
+ r = (sb.rows("SELECT count() AS n, sum(read_rows) AS rr, sum(read_bytes) AS rb, sum(result_rows) AS res, max(memory_usage) AS mem, "
879
+ "sum(query_duration_ms) AS ms, sum(ProfileEvents['SelectedParts']) AS parts, sum(ProfileEvents['SelectedMarks']) AS marks "
880
+ "FROM system.query_log WHERE type = 'QueryFinish' AND query_id LIKE {p:String}", {"p": f"codecop-l-{tag}-%"}) or [{}])[0]
881
+ if int(r.get("n") or 0) != len(plist):
882
+ m.error = f"{r.get('n')} of {len(plist)} statements in system.query_log"
883
+ return m
884
+ m.read_rows, m.read_bytes, m.result_rows = int(r["rr"]), int(r["rb"]), int(r["res"])
885
+ m.memory_bytes, m.duration_ms = int(r["mem"]), float(r["ms"])
886
+ m.selected_parts, m.selected_marks = int(r["parts"]), int(r["marks"])
887
+ m.ok = True
888
+ except QueryError as e:
889
+ m.error = str(e)
890
+ return m
891
+ if eng == "postgres" and hasattr(sb, "_psql"):
892
+ from .engines.postgres import MARK, render_params, walk_plan, _total
893
+ m = Measurement(ok=True)
894
+ try:
895
+ for start in range(0, len(plist), 200):
896
+ part = plist[start:start + 200]
897
+ script = sb.SESSION + "".join(f"\\echo {MARK}\nEXPLAIN (ANALYZE, BUFFERS, TIMING OFF, FORMAT JSON) "
898
+ f"{sb.frozen(render_params(sql.strip().rstrip(';'), p))};\n" for p in part)
899
+ for chunk in [c.strip() for c in sb._psql(script).split(MARK)[1:] if c.strip()]:
900
+ plan = json.loads(chunk)[0]
901
+ root, scans, extra = plan["Plan"], [], {}
902
+ walk_plan(root, scans, extra)
903
+ m.read_rows += sum(s["rows"] for s in scans)
904
+ m.read_bytes += (int(root.get("Shared Hit Blocks") or 0) + int(root.get("Shared Read Blocks") or 0)) * getattr(sb, "block_size", 8192)
905
+ m.result_rows += int(round(_total(root, "Actual Rows")))
906
+ m.memory_bytes = max(m.memory_bytes, int(extra.get("memory_kb", 0)) * 1024)
907
+ m.duration_ms += float(plan.get("Execution Time") or 0)
908
+ except QueryError as e:
909
+ m.ok, m.error = False, str(e)
910
+ except (ValueError, KeyError, IndexError) as e:
911
+ m.ok, m.error = False, f"could not read the EXPLAIN output: {e}"
912
+ return m
913
+ return _sum([sb.measure(sql, p, 1) for p in plist])
914
+
915
+
916
+ def rows_many(sb, sql: str, plist: list[dict]) -> list[list[dict]]:
917
+ """The rows of one statement for each parameter set (PostgreSQL: one psql session per batch)."""
918
+ if getattr(sb, "engine", "") == "postgres" and hasattr(sb, "_psql"):
919
+ from .engines.postgres import MARK, render_params
920
+ out = []
921
+ for start in range(0, len(plist), 200):
922
+ part = plist[start:start + 200]
923
+ # the measuring session's extra_float_digits = 0 would print a float otherwise than sb.rows does (the batched
924
+ # rows and a second run): every row with a float then looked unrepeatable
925
+ script = sb.SESSION + "SET extra_float_digits = 1;\n" + "".join(f"\\echo {MARK}\nSELECT coalesce(json_agg(t), '[]'::json) FROM "
926
+ f"({sb.frozen(render_params(sql.strip().rstrip(';'), p))}) t;\n" for p in part)
927
+ out += [json.loads(c) for c in [c.strip() for c in sb._psql(script).split(MARK)[1:]] if c]
928
+ return out
929
+ froz = getattr(sb, "frozen", lambda s: s)
930
+ return [sb.rows(froz(sql), p) for p in plist]
931
+
932
+
933
+ # --------------------------------------------------------------------------- per-item sameness
934
+
935
+ def _canon(row: dict, drop=("codecop_k", "codecop_rn")) -> str:
936
+ """A row's values in column order. Not by name: the batched statement is written out again by the parser, and on
937
+ ClickHouse an unnamed expression's column name is its text (`formatDateTime(x,'%Y')` against `formatDateTime(x, '%Y')`)."""
938
+ return json.dumps([v for k, v in row.items() if k not in drop], default=str)
939
+
940
+
941
+ def _bag(rows: list[dict]) -> list[str]:
942
+ return sorted(_canon(r) for r in rows)
943
+
944
+
945
+ def _key_of(v) -> str:
946
+ return json.dumps(v, default=str) if not isinstance(v, str) else json.dumps(v)
947
+
948
+
949
+ def split(rows: list[dict]) -> dict[str, list[dict]]:
950
+ out: dict[str, list[dict]] = {}
951
+ for r in rows:
952
+ out.setdefault(_key_of(r.get("codecop_k")), []).append(r)
953
+ return out
954
+
955
+
956
+ def compare_item(base: list[dict], derived: list[dict], *, has_limit: bool, has_order: bool,
957
+ full=None, again=None) -> tuple[bool | None, str]:
958
+ """One item's rows against its own run, under the single-statement rules. `full()` -> (baseline rows before its
959
+ LIMIT, derived rows before the per-item LIMIT); `again()` -> the baseline's rows from a second run."""
960
+ if _bag(base) == _bag(derived):
961
+ return True, bench_mod.ROWS
962
+ if has_limit and not has_order:
963
+ return (len(base) == len(derived)), bench_mod.ROWS_ONLY
964
+ if has_limit and has_order and len(base) == len(derived) and full is not None:
965
+ b, d = full()
966
+ if _bag(b) == _bag(d):
967
+ return True, bench_mod.TIES
968
+ if again is not None and _bag(again()) != _bag(base):
969
+ return None, bench_mod.NOT_REPEATABLE
970
+ return False, bench_mod.ROWS
971
+
972
+
973
+ # --------------------------------------------------------------------------- items
974
+
975
+ def _other_filters_sql(sql: str, key: dict, dialect: str, n: int) -> str | None:
976
+ """SELECT DISTINCT <key> FROM <the member's table> WHERE <its other filters> LIMIT n."""
977
+ from .groupbench import _protect, _unprotect
978
+ from .sqlinfo import conjuncts
979
+ try:
980
+ tree = sqlglot.parse_one(_protect(sql, dialect), read=dialect)
981
+ except Exception:
982
+ return None
983
+ src = tree.args.get("from_") or tree.args.get("from")
984
+ keep = []
985
+ pre = []
986
+ for name in ("prewhere", "where"):
987
+ for c in conjuncts(tree.args.get(name)):
988
+ text = _unprotect(c.sql(dialect=dialect))
989
+ if re.search(r"\{%s\s*:" % re.escape(key["param"]), text):
990
+ continue
991
+ (pre if name == "prewhere" else keep).append(text)
992
+ out = f"SELECT DISTINCT {key['expr']} AS codecop_k FROM {_unprotect(src.this.sql(dialect=dialect))}"
993
+ if pre:
994
+ out += " PREWHERE " + " AND ".join(f"({c})" for c in pre)
995
+ if keep:
996
+ out += " WHERE " + " AND ".join(f"({c})" for c in keep)
997
+ return out + f" ORDER BY codecop_k LIMIT {int(n)}"
998
+
999
+
1000
+ def _absent(values: list, typ: str, n: int) -> list:
1001
+ t = re.sub(r"^(?:Nullable|LowCardinality)\((.*)\)$", r"\1", typ.strip())
1002
+ if re.match(r"^(?:Date|DateTime|timestamp|date|time|Bool|boolean|Enum)", t, re.I):
1003
+ return []
1004
+ if re.match(r"^(?:UUID|uuid)$", t):
1005
+ return [f"00000000-0000-4000-8000-{i:012d}" for i in range(1, n + 1)]
1006
+ if NUMERIC.match(t):
1007
+ nums = [float(v) for v in values if re.fullmatch(r"-?\d+(?:\.\d+)?", str(v))]
1008
+ top = int(max(nums)) if nums else 0
1009
+ return [top + 1_000_003 + i for i in range(n)]
1010
+ return [f"codecop-absent-{i}" for i in range(1, n + 1)]
1011
+
1012
+
1013
+ def items_for(sb, plan: dict, params: dict, n: int, cfg: dict, seed: list | None = None) -> tuple[list, dict]:
1014
+ """N items: `seed` (the driver's values) first, then values the member's table holds under its other filters, then
1015
+ items that hold no row and items listed twice. Returns (items, how)."""
1016
+ key, dialect = plan["key"], _dialect(plan["engine"])
1017
+ absent_n = max(1, int(round(n * cfg["absent_share"]))) if n >= 2 else 0
1018
+ dup = min(int(cfg["duplicate_items"]), max(n - 1, 0))
1019
+ want = max(n - absent_n - dup, 1)
1020
+ items = list(seed or [])[:want]
1021
+ if len(items) < want:
1022
+ q = _other_filters_sql(plan["cand"]["baseline_sql"], key, dialect, want * 2)
1023
+ got = []
1024
+ if q:
1025
+ others = {k: v for k, v in params.items() if k != key["param"]}
1026
+ got = [r.get("codecop_k") for r in sb.rows(getattr(sb, "frozen", lambda s: s)(q), others)]
1027
+ seen = {_key_of(v) for v in items}
1028
+ for v in got:
1029
+ if len(items) >= want:
1030
+ break
1031
+ if _key_of(v) not in seen:
1032
+ items.append(v)
1033
+ seen.add(_key_of(v))
1034
+ present = len(items)
1035
+ absent = _absent(items, key["type"], absent_n)
1036
+ items += absent
1037
+ items += items[:dup] if present else []
1038
+ return items, {"present": present, "absent": len(absent), "repeated": min(dup, present)}
1039
+
1040
+
1041
+ def _n_of(plan: dict, cfg: dict, driver_rows: int | None) -> tuple[int, str]:
1042
+ if driver_rows:
1043
+ return min(max(driver_rows, cfg["min_items"]), int(cfg["max_items"])), "driver_on_sandbox"
1044
+ rows = plan.get("measured_driver_rows")
1045
+ if rows and plan["kind"] in ("n_plus_one", "fan_out") and rows >= cfg["min_items"]:
1046
+ # the driver is not runnable here: the rows it returned per run in production are the items of one turn
1047
+ return min(int(round(rows)), int(cfg["max_items"])), "production_driver_rows"
1048
+ measured = plan.get("measured_per_driver_run")
1049
+ if measured and plan["kind"] == "per_item" and measured > 1:
1050
+ return min(int(round(measured)), int(cfg["max_items"])), "production_per_driver_run"
1051
+ return int(cfg["items_typical"]), "setting"
1052
+
1053
+
1054
+ # --------------------------------------------------------------------------- one plan on the sandbox
1055
+
1056
+ def _numbers(m: Measurement) -> dict:
1057
+ from .groupbench import _numbers as nums
1058
+ return nums(m)
1059
+
1060
+
1061
+ def reads_change(base: Measurement, var: Measurement, pages: bool, floor_bytes: int = 0, floor_rows: int = 0) -> dict:
1062
+ """Ratios of the reads, and whether they got worse beyond the bench's tolerance (pages decide on PostgreSQL)."""
1063
+ rb, rr = bench_mod.read_ratio(var.read_bytes, base.read_bytes), bench_mod.read_ratio(var.read_rows, base.read_rows)
1064
+ over_b = rb > bench_mod.WORSE_RATIO and (var.read_bytes - base.read_bytes) > floor_bytes
1065
+ over_r = rr > bench_mod.WORSE_RATIO and (var.read_rows - base.read_rows) > floor_rows
1066
+ worse = over_b if pages else (over_b or over_r)
1067
+ return {"bytes_ratio": None if rb == float("inf") else round(rb, 4), "rows_ratio": None if rr == float("inf") else round(rr, 4),
1068
+ "worse": bool(worse), "less": (rb <= bench_mod.WIN_RATIO) if pages else (min(rb, rr) <= bench_mod.WIN_RATIO and not worse)}
1069
+
1070
+
1071
+ def run_variant(sb, plan: dict, variant: dict, items: list, params: dict, base_rows: list[list[dict]], runs: int, cfg: dict,
1072
+ base_numbers: dict | None = None) -> dict:
1073
+ """The batched statement over `items` in chunks: measured, and every item's rows compared with its own run's.
1074
+ `base_numbers`: the N per-item statements' measurement, for the resource profile of a batch that reproduced them."""
1075
+ dialect = _dialect(plan["engine"])
1076
+ typ, kp = plan["key"]["type"], plan["key"]["param"]
1077
+ distinct = list({_key_of(v): v for v in items}.values())
1078
+ size = max(int(cfg["chunk_size"]), 1)
1079
+ chunks = [distinct[i:i + size] for i in range(0, len(distinct), size)]
1080
+ others = {k: v for k, v in params.items() if k != kp}
1081
+ marker = variant.get("marker_sql") or variant["sql"].replace("{codecop_items}", f"IN ({MARKER})")
1082
+ rec: dict = {"statements": len(chunks), "chunk_size": size}
1083
+ ms, rows = [], []
1084
+ froz = getattr(sb, "frozen", lambda s: s)
1085
+ try:
1086
+ for ch in chunks:
1087
+ text = with_items(marker, ch, typ, dialect)
1088
+ ms.append(sb.measure(text, others, runs))
1089
+ if not ms[-1].ok:
1090
+ raise QueryError(ms[-1].error)
1091
+ rows += sb.rows(froz(text), others)
1092
+ except QueryError as e:
1093
+ rec["measurement"] = {"ok": False, "error": str(e)[:300]}
1094
+ rec["all_match"] = None
1095
+ return rec
1096
+ rec["measurement"] = _numbers(_sum(ms))
1097
+ by = split(rows)
1098
+ per = variant.get("per_item") or {}
1099
+ has_limit, has_order = bool(per.get("limit")), bool(per.get("order_by"))
1100
+ empty_row = None
1101
+ if per.get("absent") == "aggregate_over_no_rows":
1102
+ # what an item no row holds gets: the member's aggregates over no rows, from its text with the key's filter false
1103
+ if variant.get("empty_sql"):
1104
+ empty_row = (sb.rows(froz(variant["empty_sql"]), others) or [None])[0]
1105
+ unl_cache: dict = {}
1106
+
1107
+ def unlimited_split():
1108
+ if "by" not in unl_cache:
1109
+ got = []
1110
+ for ch in chunks:
1111
+ got += sb.rows(froz(with_items(variant["marker_unlimited"], ch, typ, dialect)), others)
1112
+ unl_cache["by"] = split(got)
1113
+ return unl_cache["by"]
1114
+ limit_info = bench_mod.split_limit(plan["cand"]["baseline_sql"]) if has_limit else None
1115
+ results, compared = [], {}
1116
+ fetched = sum(len(r) for r in base_rows) + len(rows)
1117
+ for item, brows in zip(items, base_rows):
1118
+ k = _key_of(item)
1119
+ drows = by.get(k, [])
1120
+ if not drows and empty_row is not None:
1121
+ drows = [empty_row]
1122
+ if fetched > cfg["max_compare_rows"]:
1123
+ results.append(None)
1124
+ compared["not compared: too many rows (setting max_compare_rows)"] = compared.get("not compared: too many rows (setting max_compare_rows)", 0) + 1
1125
+ continue
1126
+
1127
+ def full(item=item, k=k):
1128
+ b = sb.rows(froz(limit_info["sql"]), {**others, kp: str(item)}) if limit_info else []
1129
+ return b, unlimited_split().get(k, [])
1130
+
1131
+ def again(item=item):
1132
+ return sb.rows(froz(plan["cand"]["baseline_sql"]), {**others, kp: str(item)})
1133
+ ok, how = compare_item(brows, drows, has_limit=has_limit, has_order=has_order,
1134
+ full=full if limit_info else None, again=again)
1135
+ results.append(ok)
1136
+ compared[how] = compared.get(how, 0) + 1
1137
+ rec["items_compared"] = sum(1 for r in results if r is not None)
1138
+ rec["items_reproduced"] = sum(1 for r in results if r is True)
1139
+ rec["items_differ"] = sum(1 for r in results if r is False)
1140
+ rec["items_with_rows"] = sum(1 for b in base_rows if b and not (empty_row is not None and _bag(b) == _bag([empty_row])))
1141
+ rec["compared"] = compared
1142
+ rec["all_match"] = False if False in results else (None if (None in results or not results) else True)
1143
+ if rec["all_match"] is True and rec["items_with_rows"] == 0:
1144
+ rec["all_match"], rec["why"] = None, "no item selected a row: nothing to compare"
1145
+ if rec["all_match"] is True and base_numbers is not None and getattr(sb, "resource_cfg", None):
1146
+ # CPU and memory of the N per-item statements against the batched one(s), interleaved, as a candidate has them
1147
+ from . import resources as resources_mod
1148
+ before = [(plan["cand"]["baseline_sql"], {**others, kp: str(item)}) for item in items]
1149
+ after = [(with_items(marker, ch, typ, dialect), others) for ch in chunks]
1150
+ try:
1151
+ rec["resources"] = resources_mod.many_vs_one(sb, before, after, dict(base_numbers or {}), rec["measurement"])
1152
+ except QueryError as e:
1153
+ rec["resources"] = {"measured": False, "why": "server_error", "error": str(e)[:200]}
1154
+ return rec
1155
+
1156
+
1157
+ def run_plan(sb, plan: dict, runs: int, cfg: dict, log=lambda msg: None, tables: list[dict] | None = None,
1158
+ loaded: set | None = None, profile: dict | None = None) -> dict:
1159
+ """A member on the typical and the heavy run: N statements against the batched statement(s)."""
1160
+ from . import fidelity
1161
+ started = time.monotonic()
1162
+ out = {"id": plan["id"], "pattern": plan["pattern"], "fingerprint": plan["fingerprint"], "site_id": plan["site_id"], "runs": {}, "variants": []}
1163
+ if plan.get("skip"):
1164
+ out["skip"] = plan["skip"]
1165
+ return out
1166
+ bad = [t for t in tables or [] if not t.get("ok") and t["name"] in (plan["cand"].get("tables") or [])]
1167
+ if bad:
1168
+ out["skip"], out["tables_not_built"] = "sandbox_table_not_loaded", [t["name"] for t in bad]
1169
+ return out
1170
+ params = fidelity.params_of(plan["cand"], profile or {})
1171
+ kp = plan["key"]["param"]
1172
+ for name, where in (plan["cand"].get("synthesized") or {}).items():
1173
+ if name == kp or name in params:
1174
+ continue
1175
+ # the value most of the sandbox's rows hold: the statement then selects rows, as a typical run does
1176
+ q = (f"SELECT {where['column']} AS v FROM {where['table']} WHERE {where['column']} IS NOT NULL "
1177
+ f"GROUP BY {where['column']} ORDER BY count(*) DESC LIMIT 1")
1178
+ try:
1179
+ got = sb.rows(q)
1180
+ except QueryError as e:
1181
+ out["skip"], out["error"] = "sandbox_could_not_run", str(e)[:200]
1182
+ return out
1183
+ if not got:
1184
+ out["skip"] = "parameters_match_no_rows"
1185
+ return out
1186
+ params[name] = got[0]["v"]
1187
+ # N from the driver: its own result on the sandbox data, when it is loaded with the member
1188
+ driver_rows, seed = None, None
1189
+ d = plan.get("driver")
1190
+ if d is not None and plan["kind"] in ("n_plus_one", "fan_out") and loaded is not None and set(d.get("tables") or []) <= loaded:
1191
+ try:
1192
+ got = sb.rows(getattr(sb, "frozen", lambda s: s)(d["baseline_sql"]), fidelity.params_of(d, profile or {}))
1193
+ driver_rows = len(got)
1194
+ col = plan["key"]["column"].lower()
1195
+ names = [c for c in (got[0].keys() if got else []) if c.lower() == col or c.lower().endswith("_" + col) or col.endswith("_" + c.lower())]
1196
+ if names:
1197
+ seed = [r.get(names[0]) for r in got if r.get(names[0]) is not None]
1198
+ out["driver"] = {"finding": d.get("finding"), "rows": driver_rows, "values_used": bool(names)}
1199
+ except QueryError as e:
1200
+ out["driver"] = {"finding": d.get("finding"), "error": str(e)[:200]}
1201
+ n, basis = _n_of(plan, cfg, driver_rows)
1202
+ heavy_n = min(max(int(round(n * cfg["heavy_factor"])), n), int(cfg["max_items"]))
1203
+ out["items_basis"] = basis
1204
+ if plan.get("measured_per_driver_run") is not None:
1205
+ out["production_per_driver_run"] = plan["measured_per_driver_run"]
1206
+ for which, count in (("typical", n), ("heavy", heavy_n)):
1207
+ items, how = items_for(sb, plan, params, count, cfg, seed)
1208
+ plist = [{**params, kp: str(v)} for v in items]
1209
+ base = measure_many(sb, plan["cand"]["baseline_sql"], plist)
1210
+ brows = rows_many(sb, plan["cand"]["baseline_sql"], plist) if base.ok else []
1211
+ out["runs"][which] = {"items": len(items), **how, "statements": len(items), "baseline": _numbers(base), "_items": items, "_rows": brows}
1212
+ for i, v in enumerate(plan.get("variants") or []):
1213
+ rec = {"index": i, "rule": v.get("rule"), "source": v.get("source", "mechanical")}
1214
+ said = {}
1215
+ for which in ("typical", "heavy"):
1216
+ r = out["runs"][which]
1217
+ if not r["baseline"].get("ok"):
1218
+ rec[which] = {"measurement": {"ok": False, "error": r["baseline"].get("error", "")}, "all_match": None}
1219
+ said[which] = ("failed", r["baseline"].get("error", ""))
1220
+ continue
1221
+ got = run_variant(sb, plan, v, r["_items"], params, r["_rows"], runs, cfg, base_numbers=r["baseline"] if which == "typical" else None)
1222
+ got["statements_before"], got["statements_after"] = r["statements"], got.get("statements")
1223
+ base_m = Measurement(**{k: r["baseline"][k] for k in ("ok", "read_rows", "read_bytes", "result_rows") if k in r["baseline"]})
1224
+ var_d = got.get("measurement") or {}
1225
+ var_m = Measurement(ok=bool(var_d.get("ok")), read_rows=var_d.get("read_rows", 0), read_bytes=var_d.get("read_bytes", 0),
1226
+ error=var_d.get("error", ""))
1227
+ if var_m.ok:
1228
+ got["reads"] = reads_change(base_m, var_m, getattr(sb, "pages_decide", False), getattr(sb, "floor_bytes", 0), getattr(sb, "floor_rows", 0))
1229
+ rec[which] = got
1230
+ said[which] = _run_verdict(got, var_m)
1231
+ rec["verdict"], rec["reason"] = _combined(said)
1232
+ out["variants"].append(rec)
1233
+ log(f"loop {plan['id']} ({plan.get('symbol') or plan['site_id']}) {v.get('rule')}: {rec['verdict']}: {rec['reason'][:160]}")
1234
+ for which in out["runs"]:
1235
+ out["runs"][which].pop("_items", None)
1236
+ out["runs"][which].pop("_rows", None)
1237
+ out["seconds"] = round(time.monotonic() - started, 1)
1238
+ return out
1239
+
1240
+
1241
+ def _run_verdict(got: dict, var: Measurement) -> tuple[str, str]:
1242
+ if not var.ok:
1243
+ return "failed", var.error[:300]
1244
+ if got.get("all_match") is False:
1245
+ return "rejected", f"{got.get('items_differ')} of {got.get('items_compared')} items got other rows"
1246
+ if got.get("all_match") is None:
1247
+ return "not_shown", got.get("why") or "; ".join(got.get("compared") or {}) or "not compared"
1248
+ r = got.get("reads") or {}
1249
+ if r.get("worse"):
1250
+ return "reads_more", f"reads x{r.get('bytes_ratio')} the bytes (pages), x{r.get('rows_ratio')} the rows"
1251
+ return "same_rows_reads_no_more", f"every item reproduced; reads x{r.get('bytes_ratio')} the bytes, x{r.get('rows_ratio')} the rows"
1252
+
1253
+
1254
+ def _combined(said: dict) -> tuple[str, str]:
1255
+ t, h = said.get("typical", ("not_shown", "")), said.get("heavy", ("not_shown", ""))
1256
+ both = f"typical run: {t[1]}; heavy run: {h[1]}"
1257
+ for bad in ("failed", "rejected"):
1258
+ if bad in (t[0], h[0]):
1259
+ return bad, both
1260
+ if "reads_more" in (t[0], h[0]) and "not_shown" not in (t[0], h[0]):
1261
+ return "reads_more", both
1262
+ if t[0] == "not_shown" and h[0] == "not_shown":
1263
+ return "not_shown", both
1264
+ if "not_shown" in (t[0], h[0]):
1265
+ # sameness shown on one run only: shown when the other run had no row to compare, else not shown
1266
+ shown = h if t[0] == "not_shown" else t
1267
+ other = t if t[0] == "not_shown" else h
1268
+ if "no item selected a row" in other[1]:
1269
+ return shown[0], both
1270
+ return "not_shown", both
1271
+ return t[0] if t[0] == h[0] else ("reads_more" if "reads_more" in (t[0], h[0]) else t[0]), both
1272
+
1273
+
1274
+ def run_all(sb, plans: list[dict], runs: int, cfg: dict, log, tables, loaded, profile, memo: dict | None = None) -> list[dict]:
1275
+ out = []
1276
+ done: dict = memo if memo is not None else {}
1277
+ for plan in plans:
1278
+ # one statement in several loops, with the same N source, the same driver and the same variants, is run once
1279
+ # (otherwise one member of many patterns is benchmarked once per pattern)
1280
+ same = None if plan.get("skip") else json.dumps(
1281
+ [plan["site_id"], plan.get("finding"), plan.get("kind") if plan.get("driver") else "", (plan.get("driver") or {}).get("finding"),
1282
+ plan.get("measured_per_driver_run"), plan.get("measured_driver_rows"), (plan.get("key") or {}).get("param"),
1283
+ [v.get("marker_sql") or v.get("sql") for v in plan.get("variants") or []]], default=str)
1284
+ if same is not None and same in done:
1285
+ out.append({**copy.deepcopy(done[same]), "id": plan["id"], "pattern": plan["pattern"], "fingerprint": plan["fingerprint"],
1286
+ "same_run_as": done[same]["id"]})
1287
+ continue
1288
+ try:
1289
+ out.append(run_plan(sb, plan, runs, cfg, log, tables, loaded, profile))
1290
+ if same is not None:
1291
+ done[same] = out[-1]
1292
+ except SandboxError as e:
1293
+ why = sb.revive() if hasattr(sb, "revive") else ""
1294
+ out.append({"id": plan["id"], "pattern": plan["pattern"], "fingerprint": plan["fingerprint"], "site_id": plan["site_id"],
1295
+ "skip": "sandbox_could_not_run", "error": f"the sandbox stopped ({why or e})"[:300]})
1296
+ except Exception as e: # noqa: BLE001 -- one plan CodeCop could not handle is its own result, not the end of the run
1297
+ out.append({"id": plan["id"], "pattern": plan["pattern"], "fingerprint": plan["fingerprint"], "site_id": plan["site_id"],
1298
+ "skip": "sandbox_could_not_run", "error": f"could not be judged: {type(e).__name__}: {e}"[:300]})
1299
+ return out
1300
+
1301
+
1302
+ class Collector:
1303
+ """The hook bench.run calls per load group (`after_scale`), with the results kept per scale here. It returns None,
1304
+ so the scale's `groups` stay the group benchmark's; cli.py composes the two hooks."""
1305
+
1306
+ def __init__(self, plans: list[dict], runs: int, settings: dict | None = None, log=lambda msg: None):
1307
+ self.plans, self.runs, self.cfg, self.log = plans, runs, settings_of(settings), log
1308
+ self.by_scale: dict[float, list[dict]] = {}
1309
+ self.memo: dict[float, dict] = {}
1310
+
1311
+ def __call__(self, sb, tables, profile, fraction, findings=None):
1312
+ done = self.by_scale.setdefault(fraction, [])
1313
+ seen = {r["id"] for r in done}
1314
+ loaded = {t["name"] for t in tables or [] if t.get("ok")}
1315
+ todo = [p for p in self.plans if p["id"] not in seen and (p.get("skip") or findings is None or p.get("finding") in set(findings)
1316
+ or (p.get("synthesized") and set(p["cand"]["tables"]) <= loaded))]
1317
+ if todo:
1318
+ self.log(f"{sum(1 for p in todo if not p.get('skip'))} loop member(s) benchmarked: N statements against one batched statement")
1319
+ try:
1320
+ done.extend(run_all(sb, todo, self.runs, self.cfg, self.log, tables, loaded, profile, self.memo.setdefault(fraction, {})))
1321
+ except Exception as e: # the loop benchmark never stops the bench
1322
+ for p in todo:
1323
+ done.append({"id": p["id"], "pattern": p["pattern"], "fingerprint": p["fingerprint"], "site_id": p["site_id"],
1324
+ "skip": "sandbox_could_not_run", "error": str(e)[:300]})
1325
+ return None
1326
+
1327
+ def last(self) -> list[dict]:
1328
+ return self.by_scale[max(self.by_scale)] if self.by_scale else []
1329
+
1330
+
1331
+ # --------------------------------------------------------------------------- outcome
1332
+
1333
+ def member_outcome(plan: dict, result: dict | None) -> dict:
1334
+ def done(state, reason, **evidence):
1335
+ return {"state": state, "reason": reason, "next_step": NEXT_STEP[reason], **({"evidence": evidence} if evidence else {})}
1336
+ if plan.get("skip"):
1337
+ o = done("not_judged", plan["skip"])
1338
+ if plan.get("next_step"):
1339
+ o["next_step"] = plan["next_step"]
1340
+ return o
1341
+ if result is None:
1342
+ return done("not_judged", "bench_not_run")
1343
+ if result.get("skip"):
1344
+ return done("not_judged", result["skip"])
1345
+ vs = result.get("variants") or []
1346
+ if not vs:
1347
+ return done("not_judged", "loop_variants_not_asked")
1348
+ wins = [v for v in vs if v["verdict"] == "same_rows_reads_no_more"]
1349
+ if wins:
1350
+ return done("fixed", "batch_verified", variant=wins[0]["index"])
1351
+ if any(v["verdict"] == "rejected" for v in vs):
1352
+ return done("blocked", "loop_item_not_reproduced")
1353
+ if any(v["verdict"] == "reads_more" for v in vs):
1354
+ return done("blocked", "batch_reads_more", tradeoff=True)
1355
+ if all(v["verdict"] == "failed" for v in vs):
1356
+ return done("not_judged", "sandbox_could_not_run")
1357
+ empty = all(((result.get("runs") or {}).get(w) or {}).get("baseline", {}).get("result_rows", 0) == 0 for w in ("typical", "heavy"))
1358
+ return done("not_judged", "parameters_match_no_rows" if empty else "sameness_not_shown")
1359
+
1360
+
1361
+ ORDER = ("loop_item_not_reproduced", "batch_reads_more", "loop_batch_misses_writes", "sandbox_could_not_run", "sameness_not_shown", "parameters_match_no_rows",
1362
+ "loop_variants_not_asked", "loop_key_not_found", "loop_member_not_runnable", "statement_known_at_run_time",
1363
+ "sandbox_table_not_loaded", "bench_not_run",
1364
+ "other_engine_run", "engine_not_benchmarkable", "batch_verified")
1365
+
1366
+
1367
+ def engine_reason(engine_of_pattern: str, bench_engine: str | None) -> str | None:
1368
+ """Why a pattern (or member) on this engine is not this benchmark's to judge: an engine CodeCop has no sandbox for,
1369
+ or another one than the benchmark's. None when it is (or when nothing names its engine)."""
1370
+ from . import engines
1371
+ if not engine_of_pattern or engine_of_pattern == "mixed":
1372
+ return None
1373
+ if engine_of_pattern not in engines.supported():
1374
+ return "engine_not_benchmarkable"
1375
+ if bench_engine and engine_of_pattern != bench_engine:
1376
+ return "other_engine_run"
1377
+ return None
1378
+
1379
+
1380
+ def pattern_outcome(p: dict, members: list[dict], cfg: dict, bench_engine: str | None = None) -> dict:
1381
+ # a pattern on an engine CodeCop has no sandbox for is not judged whatever its loop looks like; one on another engine than
1382
+ # this benchmark's is said by its members (a member may still be a candidate of this one)
1383
+ why_engine = engine_reason(p.get("engine") or "", None)
1384
+ if why_engine:
1385
+ return {"state": "not_judged", "reason": why_engine, "next_step": NEXT_STEP[why_engine], "engine": p.get("engine")}
1386
+ ok, why = qualify(p, cfg)
1387
+ if ok is False:
1388
+ return {"state": "not_judged", "reason": why, "next_step": NEXT_STEP[why]}
1389
+ per = (p.get("measured") or {}).get("executions_per_driver_run")
1390
+ if per is not None and per <= cfg["min_items_per_run_measured"]:
1391
+ return {"state": "nothing_to_gain", "reason": "one_item_per_run", "next_step": "none"}
1392
+ outs = [m["outcome"] for m in members if m.get("outcome")]
1393
+ if not outs:
1394
+ return {"state": "not_judged", "reason": "bench_not_run", "next_step": NEXT_STEP["bench_not_run"]}
1395
+ fixed = sum(1 for o in outs if o["state"] == "fixed")
1396
+ worst = min(outs, key=lambda o: ORDER.index(o["reason"]) if o["reason"] in ORDER else len(ORDER))
1397
+ out = dict(worst)
1398
+ out["evidence"] = {**(worst.get("evidence") or {}), "members_fixed": fixed, "members": len(outs)}
1399
+ return out
1400
+
1401
+
1402
+ # --------------------------------------------------------------------------- loops.json and patterns.json
1403
+
1404
+ def _public_variant(v: dict) -> dict:
1405
+ return {k: v[k] for k in ("rule", "source", "sql", "per_item", "key_expr", "change") if k in v}
1406
+
1407
+
1408
+ def results_doc(patterns_doc: dict, plans: list[dict], results: list[dict], settings: dict | None = None,
1409
+ generated_at: str | None = None, engine: str | None = None) -> dict:
1410
+ """loops.json: per qualifying pattern, its members' plans, results and outcomes. `engine`: the benchmark's (default:
1411
+ the plans')."""
1412
+ cfg = settings_of(settings)
1413
+ engine = engine or next((x.get("engine") for x in plans if x.get("engine")), None)
1414
+ by_id = {r["id"]: r for r in results}
1415
+ out = []
1416
+ for p in patterns_doc.get("patterns") or []:
1417
+ ok, _ = qualify(p, cfg)
1418
+ if ok is None:
1419
+ continue
1420
+ members = []
1421
+ for plan in [x for x in plans if x["fingerprint"] == p["fingerprint"]]:
1422
+ r = by_id.get(plan["id"])
1423
+ m = {"site_id": plan["site_id"], "file": plan.get("file"), "line": plan.get("line"), "symbol": plan.get("symbol"),
1424
+ "tables": plan.get("tables"), "finding": None if plan.get("synthesized") else plan.get("finding"),
1425
+ **({"runnable_by_rule": True} if plan.get("synthesized") else {}), **({"why_not_runnable": plan["why"]} if plan.get("why") else {}),
1426
+ "key": {k: plan["key"][k] for k in ("column", "param", "type", "expr")} if plan.get("key") else None,
1427
+ "key_basis": plan.get("key_basis"), "no_rule": plan.get("no_rule"),
1428
+ **({"sql_from": "agent"} if plan.get("sql_from") == "agent" else {}),
1429
+ **({"path_confirmed": "agent"} if plan.get("path_confirmed") else {}),
1430
+ "variants": [_public_variant(v) for v in plan.get("variants") or []], "result": r}
1431
+ m["outcome"] = member_outcome(plan, r)
1432
+ wrote = sorted(set(p.get("loop_writes") or []) & {re.sub(r'[`"]', "", t).split(".")[-1].lower() for t in plan.get("tables") or []})
1433
+ if m["outcome"]["state"] == "fixed" and wrote:
1434
+ # every item's rows were reproduced with the reads alone; the loop also writes these tables. When each of
1435
+ # those writes changes only the rows of its own item (an UPDATE or DELETE whose WHERE fixes the column the
1436
+ # read takes the item on), an earlier item never writes a row a later item reads, and the batched read
1437
+ # gives each item what its own read gave: the win stands. Otherwise (an INSERT, a write keyed otherwise, a
1438
+ # write CodeCop cannot read) the batch may miss what an earlier item wrote: it needs the writes moved first.
1439
+ m["outcome"] = _with_loop_writes(m["outcome"], p, plan, wrote)
1440
+ members.append(m)
1441
+ entry = {"fingerprint": p["fingerprint"], "id": p.get("id"), "kind": p["kind"], "engine": p.get("engine") or "", "members": members}
1442
+ entry["outcome"] = pattern_outcome(p, members, cfg, engine)
1443
+ out.append(entry)
1444
+ return {"schema_version": SCHEMA_VERSION, "generated_at": generated_at or now(), "settings": cfg, "patterns": out,
1445
+ "outcomes": summarize(out)}
1446
+
1447
+
1448
+ def _with_loop_writes(outcome: dict, p: dict, plan: dict, wrote: list[str]) -> dict:
1449
+ keys = p.get("loop_write_keys")
1450
+ col = str((plan.get("key") or {}).get("column") or "").lower()
1451
+ if keys is None or not col:
1452
+ return {"state": "not_judged", "reason": "loop_writes_rows_it_reads", "next_step": NEXT_STEP["loop_writes_rows_it_reads"],
1453
+ "evidence": {"tables": wrote, "reads_alone": "batch_verified"}}
1454
+ writes_ = [w for t in wrote for w in keys.get(t) or []]
1455
+ unsafe = [w for w in writes_ if w.get("kind") not in ("update", "delete") or col not in (w.get("eq") or [])]
1456
+ ev = {**(outcome.get("evidence") or {}), "tables": wrote, "reads_alone": "batch_verified", "key_column": col,
1457
+ "writes": [{k: w.get(k) for k in ("site_id", "file", "line", "kind", "eq") if w.get(k) is not None} for w in (unsafe or writes_)[:8]]}
1458
+ if writes_ and not unsafe:
1459
+ return {**outcome, "evidence": {**ev, "writes_keyed_per_item": True}}
1460
+ return {"state": "blocked", "reason": "loop_batch_misses_writes", "next_step": NEXT_STEP["loop_batch_misses_writes"], "evidence": ev}
1461
+
1462
+
1463
+ def summarize(entries: list[dict]) -> dict:
1464
+ states = {s: 0 for s in REASONS}
1465
+ reasons: dict[str, int] = {}
1466
+ for e in entries:
1467
+ o = e.get("outcome") or {}
1468
+ if o:
1469
+ states[o["state"]] += 1
1470
+ reasons[o["reason"]] = reasons.get(o["reason"], 0) + 1
1471
+ return {"states": states, "reasons": reasons}
1472
+
1473
+
1474
+ def load(out_dir) -> dict | None:
1475
+ from pathlib import Path
1476
+ f = Path(out_dir) / FILE
1477
+ try:
1478
+ return json.loads(f.read_text()) if f.exists() else None
1479
+ except (OSError, ValueError):
1480
+ return None
1481
+
1482
+
1483
+ def batch_summary(entry: dict | None, p: dict, cfg: dict) -> dict:
1484
+ """The `batch` field a pattern carries in patterns.json: whether it qualifies and, after `codecop bench`, its outcome,
1485
+ the statements and reads before and after (typical and heavy run) and the per-item sameness of each member."""
1486
+ ok, why = qualify(p, cfg)
1487
+ out = {"qualifies": bool(ok), **({"why_not": why} if why else {}), "members_qualifying": len(qualifying_members(p)) if ok else 0}
1488
+ if entry is None:
1489
+ o = pattern_outcome(p, [], cfg) if ok is not None else None
1490
+ if o:
1491
+ out["outcome"] = o
1492
+ return out
1493
+ out["outcome"] = entry.get("outcome")
1494
+ rows = []
1495
+ for m in entry.get("members") or []:
1496
+ r = m.get("result") or {}
1497
+ o = m.get("outcome") or {}
1498
+ row = {"site_id": m["site_id"], "file": m.get("file"), "line": m.get("line"), "symbol": m.get("symbol"),
1499
+ "key": (m.get("key") or {}).get("column"), "key_basis": m.get("key_basis"), "state": o.get("state"),
1500
+ "reason": o.get("reason"), "next_step": o.get("next_step"), "items_basis": r.get("items_basis"),
1501
+ "production_per_driver_run": r.get("production_per_driver_run"), "driver": r.get("driver"),
1502
+ "sql_from": m.get("sql_from"), "path_confirmed": m.get("path_confirmed"), "why_not_runnable": m.get("why_not_runnable")}
1503
+ vi = (o.get("evidence") or {}).get("variant")
1504
+ recs = r.get("variants") or []
1505
+ rec = recs[vi] if vi is not None and vi < len(recs) else (recs[0] if recs else None)
1506
+ if rec:
1507
+ v = (m.get("variants") or [])[rec["index"]] if rec["index"] < len(m.get("variants") or []) else {}
1508
+ row["rule"], row["source"] = rec.get("rule"), rec.get("source")
1509
+ row["sql"] = v.get("sql")
1510
+ row["per_item"] = v.get("per_item")
1511
+ row["verdict"] = rec.get("verdict")
1512
+ for which in ("typical", "heavy"):
1513
+ x = rec.get(which) or {}
1514
+ run = (r.get("runs") or {}).get(which) or {}
1515
+ row[which] = {"items": run.get("items"), "present": run.get("present"), "absent": run.get("absent"), "repeated": run.get("repeated"),
1516
+ "statements_before": x.get("statements_before"), "statements_after": x.get("statements_after"),
1517
+ "read_bytes_before": (run.get("baseline") or {}).get("read_bytes"), "read_rows_before": (run.get("baseline") or {}).get("read_rows"),
1518
+ "read_bytes_after": (x.get("measurement") or {}).get("read_bytes"), "read_rows_after": (x.get("measurement") or {}).get("read_rows"),
1519
+ "items_compared": x.get("items_compared"), "items_reproduced": x.get("items_reproduced"),
1520
+ "items_differ": x.get("items_differ"), "items_with_rows": x.get("items_with_rows"),
1521
+ "same_rows": x.get("all_match"), "reads_worse": (x.get("reads") or {}).get("worse")}
1522
+ elif m.get("variants"):
1523
+ v = m["variants"][0]
1524
+ row["rule"], row["sql"], row["per_item"] = v.get("rule"), v.get("sql"), v.get("per_item")
1525
+ if m.get("no_rule"):
1526
+ row["no_rule"] = m["no_rule"]
1527
+ rows.append({k: v for k, v in row.items() if v is not None})
1528
+ out["members"] = rows
1529
+ return out
1530
+
1531
+
1532
+ def merge(patterns_doc: dict, loops_doc: dict | None, settings: dict | None = None) -> dict:
1533
+ """patterns.json with each loop pattern's `batch` (whether it qualifies; with loops.json, its results), joined by
1534
+ fingerprint. Patterns of other kinds are left as they are."""
1535
+ cfg = settings_of(settings)
1536
+ if loops_doc and (loops_doc.get("agent_paths") or loops_doc.get("agent_statements")):
1537
+ with_agent_statements(patterns_doc, loops_doc) # a path the agent confirmed qualifies the pattern, said as the agent's
1538
+ entries = {e["fingerprint"]: e for e in (loops_doc or {}).get("patterns") or []}
1539
+ for p in patterns_doc.get("patterns") or []:
1540
+ ok, _ = qualify(p, cfg)
1541
+ if ok is None:
1542
+ continue
1543
+ p["batch"] = batch_summary(entries.get(p["fingerprint"]), p, cfg)
1544
+ if p["batch"].get("outcome", {}).get("state") == "fixed" and "batched_query_not_benchmarked" in (p.get("unknowns") or []):
1545
+ p["unknowns"] = [u for u in p["unknowns"] if u != "batched_query_not_benchmarked"]
1546
+ if loops_doc:
1547
+ patterns_doc["batch_outcomes"] = loops_doc.get("outcomes")
1548
+ patterns_doc["batch_generated_at"] = loops_doc.get("generated_at")
1549
+ return patterns_doc
1550
+
1551
+
1552
+ # --------------------------------------------------------------------------- the paid step (never run here)
1553
+
1554
+ ASK_REASONS = ("loop_variants_not_asked", "loop_key_not_found", "loop_item_not_reproduced", "batch_reads_more")
1555
+
1556
+
1557
+ def needs_agent(loops_doc: dict, patterns_doc: dict | None = None) -> list[tuple[dict, dict]]:
1558
+ """(pattern entry, member) pairs the paid step is asked about, one per member call site (one statement in several
1559
+ loops is asked about once): `ask` says what is asked.
1560
+
1561
+ batch the member runs but no rule batched it, the rule's key was not found, its batch lost an item or reads
1562
+ more: the batched statement (and the key)
1563
+ statement the member has no runnable form by rule (an ORM call not translated, a run-time part, a table
1564
+ without a definition): the per-item statement with its key parameter, and the batched statement
1565
+ path the loop's calls were guessed or the item was not traced to the query (`loop_not_traced`): whether
1566
+ the loop reaches the member with the item (yes/no with the chain), and both statements
1567
+ """
1568
+ out, seen = [], set()
1569
+ asked = {str(x) for x in (loops_doc or {}).get("agent_asked_sites") or []}
1570
+ has_batch = set((loops_doc or {}).get("agent_variants") or {})
1571
+
1572
+ def was_asked(sid: str, ask: str) -> bool:
1573
+ # each kind of question once per call site: a site asked about its path that then qualifies, with no batched
1574
+ # statement in that answer, is asked for the batched one (an entry without a kind is an older ledger's)
1575
+ if ask == "batch":
1576
+ return f"{sid}:batch" in asked or sid in has_batch
1577
+ return f"{sid}:{ask}" in asked or sid in asked
1578
+ by_fp = {p.get("fingerprint"): p for p in (patterns_doc or {}).get("patterns") or []}
1579
+ for e0 in (loops_doc or {}).get("patterns") or []:
1580
+ p = by_fp.get(e0.get("fingerprint")) or {}
1581
+ e = {**e0, "loops": e0.get("loops") or p.get("loops"), "driver": e0.get("driver") or p.get("driver")}
1582
+ for m in e.get("members") or []:
1583
+ o = m.get("outcome") or {}
1584
+ if m.get("agent_asked") or m["site_id"] in seen:
1585
+ continue
1586
+ if o.get("reason") in ASK_REASONS and m.get("finding") and not was_asked(m["site_id"], "batch"):
1587
+ out.append((e, {**m, "ask": "batch"}))
1588
+ elif o.get("reason") == "loop_member_not_runnable" and not was_asked(m["site_id"], "statement"):
1589
+ out.append((e, {**m, "ask": "statement"}))
1590
+ else:
1591
+ continue
1592
+ seen.add(m["site_id"])
1593
+ for p in (patterns_doc or {}).get("patterns") or []:
1594
+ ok, why = qualify(p, None)
1595
+ if ok is not False or why != "loop_not_traced" or engine_reason(p.get("engine") or "", None):
1596
+ continue
1597
+ e = {"fingerprint": p["fingerprint"], "id": p.get("id"), "kind": p.get("kind"), "engine": p.get("engine") or "",
1598
+ "loops": p.get("loops"), "driver": p.get("driver")}
1599
+ for m in p.get("members") or []:
1600
+ if m.get("verified") is True and m.get("depends_on_loop_var") is True or m.get("path_confirmed") or m["site_id"] in seen \
1601
+ or was_asked(m["site_id"], "path"):
1602
+ continue
1603
+ if m.get("depends_on_loop_var") is False:
1604
+ continue # traced: the item does not reach this statement
1605
+ out.append((e, {**m, "ask": "path"}))
1606
+ seen.add(m["site_id"])
1607
+ return out
1608
+
1609
+
1610
+ def estimate(loops_doc: dict, settings: dict | None = None, patterns_doc: dict | None = None) -> dict:
1611
+ """What the paid step would ask and its cost at API rates: per member call site, a low and a high figure (settings
1612
+ agent_cost_per_member_usd_low / _high); `calls`: the agent calls it takes (agent_sites_per_call per call)."""
1613
+ cfg = settings_of(settings)
1614
+ todo = needs_agent(loops_doc, patterns_doc)
1615
+ n = len(todo)
1616
+ per = max(int(cfg["agent_sites_per_call"]), 1)
1617
+ asks: dict[str, int] = {}
1618
+ for _, m in todo:
1619
+ asks[m["ask"]] = asks.get(m["ask"], 0) + 1
1620
+ return {"patterns": len({e["fingerprint"] for e, _ in todo}), "members": n, "asks": asks, "calls": -(-n // per) if n else 0,
1621
+ "cost_low_usd": round(n * cfg["agent_cost_per_member_usd_low"], 2), "cost_high_usd": round(n * cfg["agent_cost_per_member_usd_high"], 2),
1622
+ "ids": sorted({e.get("id") or e["fingerprint"] for e, _ in todo})}
1623
+
1624
+
1625
+ def _lines(root, file: str, line: int, before: int, after: int) -> str:
1626
+ from .patterns import Source
1627
+ got = Source(root, 3).lines(file or "") if root else None
1628
+ if not got:
1629
+ return ""
1630
+ lo, hi = max(int(line) - 1 - before, 0), min(int(line) + after, len(got))
1631
+ return "\n".join(f"{i + 1:>5} {got[i]}" for i in range(lo, hi))
1632
+
1633
+
1634
+ def _table_text(inventory: dict | None, rank: dict | None, name: str, max_cols: int) -> str:
1635
+ bare = re.sub(r'[`"]', "", name or "").split(".")[-1].lower()
1636
+ for d in (rank or {}).get("table_definitions") or []:
1637
+ if d["name"].split(".")[-1].lower() == bare:
1638
+ return d.get("create_sql") or ""
1639
+ from .definitions import _schema_tables
1640
+ t = _schema_tables(inventory).get(bare)
1641
+ if not t:
1642
+ return ""
1643
+ cols = ", ".join(f"{c.get('name')} {c.get('type') or '?'}" for c in (t.get("columns") or [])[:max_cols])
1644
+ more = len(t.get("columns") or []) - max_cols
1645
+ return (f"table {t.get('name')} ({cols}{f', ... {more} more' if more > 0 else ''}); primary key {t.get('primary_key') or '?'}; "
1646
+ f"indexes {[ix.get('columns') for ix in t.get('indexes') or []][:8]}; defined at {(t.get('defined_at') or [''])[0]}")
1647
+
1648
+
1649
+ def prompt(loops_doc: dict, rank: dict, engine: str, version: str, settings: dict | None = None, *, patterns_doc: dict | None = None,
1650
+ inventory: dict | None = None, root=None, todo: list | None = None) -> str:
1651
+ cfg = settings_of(settings)
1652
+ by_site = {str(c.get("id")): c for c in (rank or {}).get("candidates") or []}
1653
+ by_finding = {c.get("finding"): c for c in (rank or {}).get("candidates") or []}
1654
+ sites = {s.get("id"): s for s in (inventory or {}).get("call_sites") or []}
1655
+ parts = []
1656
+ for e, m in (todo if todo is not None else needs_agent(loops_doc, patterns_doc)):
1657
+ c = by_finding.get(m.get("finding")) or by_site.get(m["site_id"]) or {}
1658
+ s = sites.get(m["site_id"]) or {}
1659
+ lp = (e.get("loops") or [{}])[0] if e.get("loops") else {}
1660
+ key = m.get("key") or {}
1661
+ ask = m.get("ask", "batch")
1662
+ lines = [f"### site {m['site_id']} · pattern {e.get('id')} ({e.get('kind')}) · ask: {ask}",
1663
+ f"The statement at {m.get('file')}:{m.get('line')} ({m.get('symbol') or ''}) runs once per item of the loop at "
1664
+ f"{lp.get('file')}:{lp.get('line')}" + (f" (over `{lp.get('over')}`, item `{', '.join(lp.get('vars') or [])}`)" if lp.get("over") else "")
1665
+ + (f"; call chain from the loop: {' <- '.join(m.get('path') or [])}" if m.get("path") else "") + "."]
1666
+ if ask == "path":
1667
+ lines.append("CodeCop could not trace this path (a guessed call, a callback, or the item lost on the way). Read the code: say "
1668
+ "whether the loop reaches this statement once per item and whether the item (or a field of it) reaches the "
1669
+ "statement's filter; give the chain of calls you followed.")
1670
+ if (s.get("orm") or {}).get("operation") == "lazy_load":
1671
+ lines.append("This is a lazy load of an ORM relationship: say `reaches` false when the query that loaded these "
1672
+ "instances eager-loads the relationship (joinedload, selectinload, select_related, prefetch_related, "
1673
+ "an eager `lazy=` on the relationship), since then no statement runs per item.")
1674
+ if s.get("orm"):
1675
+ o = s["orm"]
1676
+ lines.append(f"ORM call: `{s.get('expr') or s.get('sink')}` ({o.get('library')} {o.get('operation')} on {o.get('model_or_table')}"
1677
+ + (f"; {o.get('notes')}" if o.get("notes") else "") + ")")
1678
+ if c.get("baseline_sql"):
1679
+ lines.append("The statement as CodeCop runs it:\n```sql\n" + c["baseline_sql"][: cfg["agent_max_sql_chars"]] + "\n```")
1680
+ if key:
1681
+ lines.append(f"The item is parameter `{key.get('param')}` ({key.get('column')}).")
1682
+ elif s.get("sql"):
1683
+ lines.append("CodeCop's reading of it (`«expr»` is a part known only at run time):\n```sql\n" + s["sql"][: cfg["agent_max_sql_chars"]] + "\n```")
1684
+ if m.get("why_not_runnable"):
1685
+ lines.append(f"Why CodeCop could not run it by rule: {m['why_not_runnable']}")
1686
+ if m.get("no_rule"):
1687
+ lines.append(f"No batching rule applies: {m['no_rule']}")
1688
+ code = _lines(root, m.get("file") or "", int(m.get("line") or 0), int(cfg["agent_context_lines"]), int(cfg["agent_context_lines"]))
1689
+ if code:
1690
+ lines.append(f"Code around the statement ({m.get('file')}):\n```\n{code}\n```")
1691
+ if lp.get("file") and (lp.get("file"), lp.get("line")) != (m.get("file"), m.get("line")):
1692
+ loop_code = _lines(root, lp["file"], int(lp.get("line") or 0), 2, int(cfg["agent_context_lines"]))
1693
+ if loop_code:
1694
+ lines.append(f"The loop ({lp['file']}):\n```\n{loop_code}\n```")
1695
+ for t in (m.get("tables") or s.get("tables") or [])[:6]:
1696
+ txt = _table_text(inventory, rank, t, int(cfg["agent_max_columns"]))
1697
+ if txt:
1698
+ lines.append(f"Table `{t}`: {txt[: cfg['agent_max_sql_chars']]}")
1699
+ parts.append("\n".join(lines))
1700
+ from . import engines
1701
+ eng = engines.get(engine).label if engine else engine
1702
+ arr = "`k IN {codecop_items:Array(T)}`" if engine == "clickhouse" else "`k = ANY({codecop_items:T[]})`"
1703
+ return (
1704
+ f"You are reading loops that run a query once per item, for an automated benchmark on {eng} {version}. The repository is "
1705
+ "the current directory; read any file you need. Never connect to a database or run a command against one: CodeCop runs "
1706
+ "everything you write in its own sandbox with generated data.\n\n## For each site below, answer\n"
1707
+ "- `statement` (when the site asks `statement` or `path`, or CodeCop's statement above is not what the code sends): the ONE "
1708
+ "per-item statement the code sends for one item, as a SELECT on the tables named, with every value a parameter "
1709
+ "`{name:Type}` (T a type of this engine); `key_param`: the parameter that takes the item; `params`: for every other "
1710
+ "parameter, the table and column its value is compared with; `tables`: the tables it reads.\n"
1711
+ f"- `sql`: ONE batched statement for all the items (run in chunks), returning every item's rows with a column `codecop_k` "
1712
+ f"holding the item each row belongs to; the items are one bound list: {arr}; keep every other parameter with its name "
1713
+ "and type. `per_item`: `order_by` and `limit` each item's rows had, and `absent`: `no_rows` or `aggregate_over_no_rows`.\n"
1714
+ "- `reaches` and `item_reaches` (when the site asks `path`): true or false, read from the code; `chain`: the calls "
1715
+ "from the loop to the statement, as you followed them. Say false when unsure.\n\n## How it is checked\n"
1716
+ "CodeCop runs the per-item statement once per item and the batched one once per chunk, splits the result by `codecop_k` and "
1717
+ "compares every item's rows (an item with no row and an item listed twice included). A batched statement that changes "
1718
+ "any item's rows is not used; one that reads more is a trade-off, never a win. Your claims are recorded as yours.\n"
1719
+ "- Use only syntax and functions of this engine and version. Skip a site you cannot answer.\n\n## Sites\n\n"
1720
+ + "\n\n".join(parts)
1721
+ + "\n\nReturn JSON: {\"members\": [{\"site_id\", \"statement\", \"key_param\", \"params\": {name: {\"table\", \"column\"}}, "
1722
+ "\"tables\", \"sql\", \"param\", \"change\", \"per_item\": {\"order_by\", \"limit\", \"absent\"}, \"reaches\", \"item_reaches\", \"chain\"}]}.")
1723
+
1724
+
1725
+ AGENT_SCHEMA = {
1726
+ "type": "object", "required": ["members"], "additionalProperties": False,
1727
+ "properties": {"members": {"type": "array", "items": {
1728
+ "type": "object", "required": ["site_id"], "additionalProperties": False,
1729
+ "properties": {"site_id": {"type": "string"}, "param": {"type": "string"}, "sql": {"type": "string"}, "change": {"type": "string"},
1730
+ "statement": {"type": "string"}, "key_param": {"type": "string"},
1731
+ "params": {"type": "object", "additionalProperties": {"type": "object", "additionalProperties": False,
1732
+ "properties": {"table": {"type": "string"}, "column": {"type": "string"}}}},
1733
+ "tables": {"type": "array", "items": {"type": "string"}},
1734
+ "reaches": {"type": "boolean"}, "item_reaches": {"type": "boolean"},
1735
+ "chain": {"type": "array", "items": {"type": "string"}},
1736
+ "per_item": {"type": "object", "additionalProperties": False,
1737
+ "properties": {"order_by": {"type": "string"}, "limit": {"type": "string"},
1738
+ "absent": {"enum": ["no_rows", "aggregate_over_no_rows"]}}}}}}},
1739
+ }
1740
+
1741
+
1742
+ def agent_variant(sql: str, per_item: dict | None) -> dict | None:
1743
+ """An agent's statement in the harness's form: the bound list as the marker the runner fills."""
1744
+ m = re.search(r"IN\s*\{codecop_items\s*:\s*Array\([^{}]*\)\}|=\s*ANY\s*\(\s*\{codecop_items\s*:[^{}]*\}\s*\)", sql or "")
1745
+ if not m:
1746
+ return None
1747
+ marker = sql[:m.start()] + f"IN ({MARKER})" + sql[m.end():]
1748
+ return {"sql": sql, "marker_sql": marker, "marker_unlimited": marker, "per_item": {"order_by": "", "limit": "", "absent": "no_rows",
1749
+ "split": "codecop_k", **(per_item or {})}}
1750
+
1751
+
1752
+ # Bumped when the paid step's instructions change in a way that changes answers: every stored loop answer is asked again.
1753
+ PROMPT_REV = "loops-3"
1754
+ ANSWER_FIELDS = ("agent_variants", "agent_statements", "agent_paths", "agent_asked_sites")
1755
+
1756
+
1757
+ def prompt_version() -> str:
1758
+ from . import verdicts
1759
+ return verdicts.prompt_version(PROMPT_REV, json.dumps(AGENT_SCHEMA, sort_keys=True))
1760
+
1761
+
1762
+ def site_text(site: dict | None, member: dict | None = None) -> str:
1763
+ """What a member's answer depends on in the code: its SQL as discover read it, else its ORM call."""
1764
+ s = site or {}
1765
+ return s.get("sql") or s.get("expr") or s.get("sink") or f"{(member or {}).get('file')}:{(member or {}).get('symbol')}"
1766
+
1767
+
1768
+ def site_answer(loops_doc: dict, sid: str) -> dict:
1769
+ """Everything the paid step answered for one member call site (loops.json keeps it by site)."""
1770
+ paths = {k: v for k, v in (loops_doc.get("agent_paths") or {}).items() if k.endswith(f":{sid}")}
1771
+ return {"variants": list((loops_doc.get("agent_variants") or {}).get(sid) or []),
1772
+ "statement": (loops_doc.get("agent_statements") or {}).get(sid),
1773
+ "paths": paths, "asks": [a for a in loops_doc.get("agent_asked_sites") or [] if a == sid or str(a).startswith(f"{sid}:")]}
1774
+
1775
+
1776
+ def _drop_site(loops_doc: dict, sid: str) -> None:
1777
+ (loops_doc.get("agent_variants") or {}).pop(sid, None)
1778
+ (loops_doc.get("agent_statements") or {}).pop(sid, None)
1779
+ for k in [k for k in (loops_doc.get("agent_paths") or {}) if k.endswith(f":{sid}")]:
1780
+ loops_doc["agent_paths"].pop(k, None)
1781
+ if loops_doc.get("agent_asked_sites"):
1782
+ loops_doc["agent_asked_sites"] = [a for a in loops_doc["agent_asked_sites"] if not (a == sid or str(a).startswith(f"{sid}:"))]
1783
+
1784
+
1785
+ def _restore_site(loops_doc: dict, sid: str, rec: dict) -> None:
1786
+ _drop_site(loops_doc, sid)
1787
+ if rec.get("variants"):
1788
+ loops_doc.setdefault("agent_variants", {})[sid] = list(rec["variants"])
1789
+ if rec.get("statement"):
1790
+ loops_doc.setdefault("agent_statements", {})[sid] = rec["statement"]
1791
+ for k, v in (rec.get("paths") or {}).items():
1792
+ loops_doc.setdefault("agent_paths", {})[k] = v
1793
+ asked = loops_doc.setdefault("agent_asked_sites", [])
1794
+ asked += [a for a in rec.get("asks") or [] if a not in asked]
1795
+
1796
+
1797
+ def member_sites(patterns_doc: dict | None, loops_doc: dict | None) -> dict[str, dict]:
1798
+ """site id -> {tables, file, symbol} of every loop member the patterns or loops.json name."""
1799
+ out: dict[str, dict] = {}
1800
+ for src in ((patterns_doc or {}).get("patterns") or [], (loops_doc or {}).get("patterns") or []):
1801
+ for p in src:
1802
+ for m in p.get("members") or []:
1803
+ if m.get("site_id"):
1804
+ out.setdefault(str(m["site_id"]), {"tables": m.get("tables") or [], "file": m.get("file"), "symbol": m.get("symbol")})
1805
+ return out
1806
+
1807
+
1808
+ def sync_answers(loops_doc: dict, patterns_doc: dict | None, inventory: dict | None, answers, fresh=False) -> dict:
1809
+ """loops.json's answers made to agree with the per-statement answer store (verdicts.Answers): an answer stored for the
1810
+ member as it reads now is put back; an answer given for another text of the statement or another definition of a
1811
+ table it reads is dropped (asked again); an answer loops.json holds that the store does not (an earlier version
1812
+ of CodeCop) is moved into the store once. Returns {restored, dropped, migrated}."""
1813
+ from .verdicts import wants_fresh
1814
+ sites = {s.get("id"): s for s in (inventory or {}).get("call_sites") or []}
1815
+ keys = dict(loops_doc.get("agent_answer_keys") or {})
1816
+ pv = prompt_version()
1817
+ got = {"restored": 0, "dropped": 0, "migrated": 0}
1818
+ for sid, m in member_sites(patterns_doc, loops_doc).items():
1819
+ site = sites.get(sid)
1820
+ k = answers.key("loop", site_text(site, m), m.get("tables") or (site or {}).get("tables") or [], pv)
1821
+ held = site_answer(loops_doc, sid)
1822
+ has = bool(held["variants"] or held["statement"] or held["paths"] or held["asks"])
1823
+ rec = answers.get(k, fresh, ref=sid, file=m.get("file") or "")
1824
+ if rec is not None:
1825
+ _restore_site(loops_doc, sid, rec.get("answer") or {})
1826
+ keys[sid] = k
1827
+ got["restored"] += 1
1828
+ elif has and keys.get(sid) not in (None, k):
1829
+ _drop_site(loops_doc, sid) # answered for another statement text or table definition
1830
+ keys.pop(sid, None)
1831
+ got["dropped"] += 1
1832
+ elif has and wants_fresh(fresh, ref=sid, file=m.get("file") or ""):
1833
+ _drop_site(loops_doc, sid) # `--fresh`: asked again
1834
+ keys.pop(sid, None)
1835
+ elif has:
1836
+ answers.put(k, {"kind": "loop", "id": sid, "answer": held, "migrated_from": "loops.json"}, save=False)
1837
+ keys[sid] = k
1838
+ got["migrated"] += 1
1839
+ loops_doc["agent_answer_keys"] = keys
1840
+ if got["migrated"]:
1841
+ answers.save()
1842
+ return got
1843
+
1844
+
1845
+ def ask_agent(loops_doc: dict, patterns_doc: dict, rank: dict, root, runner, *, engine: str, version: str, model: str | None = None,
1846
+ max_budget_usd: float | None = None, settings: dict | None = None, inventory: dict | None = None,
1847
+ todo: list | None = None, concurrency: int = 1, answers=None) -> dict:
1848
+ """The paid step: agent calls for the loop members rules cannot judge (needs_agent, or `todo`: the ones the run's
1849
+ queue chose), agent_sites_per_call sites per call, `concurrency` calls at a time, until the budget is spent. What it
1850
+ answers is stored by member call site in loops.json for `codecop bench`: `agent_variants` (batched statements),
1851
+ `agent_statements` (per-item statements, `sql_from: agent`), `agent_paths` (whether the loop reaches the member with
1852
+ its item: `path_confirmed` by the agent, said apart from traced), and in the per-statement answer store (`answers`),
1853
+ so a later run pays nothing for an unchanged member. Nothing it says is trusted: the sandbox runs both statements and
1854
+ compares every item's rows. A call the budget or the plan's usage limit stopped leaves its sites not asked
1855
+ (`not_asked_budget`, `not_asked_limit`)."""
1856
+ import threading
1857
+ import time as _time
1858
+ from concurrent.futures import ThreadPoolExecutor
1859
+ from .agent import AgentError, UsageLimitError
1860
+ cfg = settings_of(settings)
1861
+ todo = needs_agent(loops_doc, patterns_doc) if todo is None else list(todo)
1862
+ if not todo:
1863
+ return {"asked": 0, "with_variants": 0, "with_statements": 0, "paths": 0, "cost_usd": 0.0, "calls": 0,
1864
+ "not_asked_budget": 0, "not_asked_limit": 0}
1865
+ per = max(int(cfg["agent_sites_per_call"]), 1)
1866
+ store = loops_doc.setdefault("agent_variants", {})
1867
+ stmts = loops_doc.setdefault("agent_statements", {})
1868
+ paths = loops_doc.setdefault("agent_paths", {})
1869
+ asked = loops_doc.setdefault("agent_asked_sites", [])
1870
+ keys = loops_doc.setdefault("agent_answer_keys", {})
1871
+ ledger = loops_doc.setdefault("agent", {"calls": []})
1872
+ sites = {s.get("id"): s for s in (inventory or {}).get("call_sites") or []}
1873
+ lock = threading.Lock()
1874
+ tot = {"spent": 0.0, "v": 0, "s": 0, "p": 0, "calls": 0, "asked": 0, "budget": 0, "limit": 0}
1875
+ stop = threading.Event()
1876
+ pv = prompt_version()
1877
+ chunks = [todo[i:i + per] for i in range(0, len(todo), per)]
1878
+
1879
+ def one(chunk: list) -> None:
1880
+ if stop.is_set():
1881
+ with lock:
1882
+ tot[tot.get("why") or "budget"] += len(chunk) # not asked: for what stopped the step
1883
+ return
1884
+ with lock:
1885
+ left = None if max_budget_usd is None else round(float(max_budget_usd) - tot["spent"], 4)
1886
+ if left is not None and left <= 0:
1887
+ with lock:
1888
+ tot["budget"] += len(chunk)
1889
+ return
1890
+ if hasattr(runner, "tell"):
1891
+ runner.tell("loops", len(chunk))
1892
+ began = _time.monotonic()
1893
+ text = prompt(loops_doc, rank, engine, version, settings, patterns_doc=patterns_doc, inventory=inventory, root=root, todo=chunk)
1894
+ try:
1895
+ result = runner.run(text, AGENT_SCHEMA, root, model=model, max_budget_usd=left)
1896
+ except UsageLimitError:
1897
+ with lock:
1898
+ tot.setdefault("why", "limit")
1899
+ tot["limit"] += len(chunk)
1900
+ stop.set()
1901
+ return
1902
+ except AgentError as e:
1903
+ if "budget" not in str(e).lower():
1904
+ raise
1905
+ stop.set()
1906
+ with lock:
1907
+ tot["budget"] += len(chunk)
1908
+ return
1909
+ took = round(_time.monotonic() - began, 1)
1910
+ cost = float(getattr(result, "cost_usd", 0) or 0)
1911
+ wanted = {m["site_id"]: (e, m) for e, m in chunk}
1912
+ answered = {"variants": 0, "statements": 0, "paths": 0}
1913
+ with lock:
1914
+ tot["spent"] += cost
1915
+ tot["calls"] += 1
1916
+ for v in (result.output or {}).get("members") or []:
1917
+ sid = v.get("site_id")
1918
+ if sid not in wanted:
1919
+ continue
1920
+ e, m = wanted[sid]
1921
+ av = agent_variant(v.get("sql") or "", v.get("per_item"))
1922
+ if av:
1923
+ store.setdefault(sid, []).append({**av, "site_id": sid, "change": (v.get("change") or "")[:120],
1924
+ **({"param": str(v["param"])[:60]} if v.get("param") else {})})
1925
+ answered["variants"] += 1
1926
+ if (v.get("statement") or "").strip() and v.get("key_param"):
1927
+ stmts[sid] = {"sql": v["statement"], "key_param": v["key_param"], "params": v.get("params") or {},
1928
+ "tables": [str(t) for t in v.get("tables") or m.get("tables") or []][:12], "at": now()}
1929
+ answered["statements"] += 1
1930
+ if m.get("ask") == "path" and isinstance(v.get("reaches"), bool):
1931
+ paths[f"{e['fingerprint']}:{sid}"] = {"reaches": v["reaches"], "item_reaches": bool(v.get("reaches")) and v.get("item_reaches") is True,
1932
+ "chain": [str(x)[:120] for x in v.get("chain") or []][:12], "at": now()}
1933
+ answered["paths"] += 1
1934
+ for sid, (_, m) in wanted.items():
1935
+ if f"{sid}:{m['ask']}" not in asked:
1936
+ asked.append(f"{sid}:{m['ask']}")
1937
+ if answers is not None:
1938
+ site = sites.get(sid)
1939
+ k = answers.key("loop", site_text(site, m), m.get("tables") or (site or {}).get("tables") or [], pv)
1940
+ answers.put(k, {"kind": "loop", "id": sid, "answer": site_answer(loops_doc, sid), "model": getattr(result, "model", "")},
1941
+ save=False)
1942
+ keys[sid] = k
1943
+ tot["asked"] += len(chunk)
1944
+ tot["v"], tot["s"], tot["p"] = tot["v"] + answered["variants"], tot["s"] + answered["statements"], tot["p"] + answered["paths"]
1945
+ ledger["calls"].append({"members": list(wanted), "asks": {a: sum(1 for _, m in chunk if m["ask"] == a) for a in ("batch", "statement", "path")},
1946
+ "answered": answered, "cost_usd": round(cost, 6), "seconds": took, "model": getattr(result, "model", ""), "at": now()})
1947
+ if answers is not None:
1948
+ answers.save()
1949
+
1950
+ workers = max(min(int(concurrency or 1), len(chunks)), 1)
1951
+ if workers == 1:
1952
+ for c in chunks:
1953
+ one(c)
1954
+ else:
1955
+ with ThreadPoolExecutor(max_workers=workers) as pool:
1956
+ for f in [pool.submit(one, c) for c in chunks]:
1957
+ f.result()
1958
+ ledger["cost_total_usd"] = round(sum(x["cost_usd"] for x in ledger["calls"]), 4)
1959
+ return {"asked": tot["asked"], "with_variants": tot["v"], "with_statements": tot["s"], "paths": tot["p"], "cost_usd": round(tot["spent"], 4),
1960
+ "calls": tot["calls"], "not_asked_budget": tot["budget"], "not_asked_limit": tot["limit"]}
1961
+
1962
+
1963
+ def with_agent_statements(patterns_doc: dict, loops_doc: dict | None) -> dict:
1964
+ """patterns.json carrying what the paid step answered, by member call site: whether the loop reaches the member
1965
+ and its item reaches the query (`path_confirmed`, said as the agent's, never as traced), and the per-item
1966
+ statement it wrote for a member with no runnable form (`agent_statement`). Also the batched statements
1967
+ (with_agent_variants)."""
1968
+ paths = (loops_doc or {}).get("agent_paths") or {}
1969
+ stmts = (loops_doc or {}).get("agent_statements") or {}
1970
+ for p in patterns_doc.get("patterns") or []:
1971
+ for m in p.get("members") or []:
1972
+ got = paths.get(f"{p.get('fingerprint')}:{m.get('site_id')}")
1973
+ if got and m.get("verified") is not True:
1974
+ m["path_confirmed"] = {"by": "agent", **{k: got.get(k) for k in ("reaches", "item_reaches", "chain") if k in got}}
1975
+ if stmts.get(m.get("site_id")):
1976
+ m["agent_statement"] = True
1977
+ return with_agent_variants(patterns_doc, loops_doc)
1978
+
1979
+
1980
+ def agent_candidate(site_id: str, st: dict, site: dict | None, definitions: dict[str, dict], engine: str) -> tuple[dict | None, str]:
1981
+ """A loop member's per-item statement as the agent wrote it, as a candidate: every parameter `{name:Type}` names
1982
+ the column its values are read from (`params`), the tables it reads are loaded. (None, why) otherwise."""
1983
+ sql = st.get("sql") or ""
1984
+ if not sql.strip() or not re.match(r"^\s*(?:WITH|SELECT)\b", sql, re.I):
1985
+ return None, "the agent's per-item statement is not a SELECT"
1986
+ names = {m.group(1) for m in PARAM.finditer(sql)}
1987
+ key = st.get("key_param")
1988
+ if not key or key not in names:
1989
+ return None, "the agent's per-item statement does not take the item as a parameter"
1990
+ tables = [t.split(".")[-1].lower().strip('"') for t in st.get("tables") or []]
1991
+ if not tables or any(t not in definitions for t in tables):
1992
+ return None, "a table the agent's statement reads is not loaded in the sandbox"
1993
+ params = {}
1994
+ for name, where in (st.get("params") or {}).items():
1995
+ if name in names and name != key and isinstance(where, dict) and where.get("table") and where.get("column"):
1996
+ t = str(where["table"]).split(".")[-1].lower().strip('"')
1997
+ if t in definitions:
1998
+ params[name] = {"table": definitions[t]["name"], "column": where["column"]}
1999
+ types = {m.group(1): m.group(2).strip() for m in PARAM.finditer(sql)}
2000
+ # a list parameter with no column (`checkpoint_id <> ALL({ids:text[]})`) is run with the empty list
2001
+ fixed = {n: "{}" for n in names - {key} - set(params) if types.get(n, "").endswith("[]")}
2002
+ if names - {key} - set(params) - set(fixed):
2003
+ return None, "a parameter of the agent's statement names no column to read its values from"
2004
+ # the item itself: the loop bench binds it per item, but the statement is also measured on its own (its tables are
2005
+ # loaded through it), where `{key:Type}` left unbound was sent as text and failed as a syntax error:
2006
+ # the column it equals gives it a value there; a list item runs with the empty list
2007
+ eq = [e for e in equalities(sql, _dialect(engine)) or [] if e["param"] == key and e.get("column")]
2008
+ if eq and len(tables) == 1 and key not in params:
2009
+ params[key] = {"table": definitions[tables[0]]["name"], "column": eq[0]["column"]}
2010
+ elif types.get(key, "").endswith("[]"):
2011
+ fixed[key] = "{}"
2012
+ return {"finding": f"LA-{site_id}", "id": site_id, "tables": [definitions[t]["name"] for t in tables], "baseline_sql": sql,
2013
+ "params": dict(fixed), "variants": [], "synthesized": params, "agent_key": key, "sql_from": "agent",
2014
+ "site": {"file": (site or {}).get("file"), "line": (site or {}).get("line")},
2015
+ "assumptions": ["the per-item statement is the agent's reading of the code (sql_from agent): CodeCop runs it as written; "
2016
+ "that it is what the code sends is the agent's claim, not verified"]}, ""
2017
+
2018
+
2019
+ def with_agent_variants(patterns_doc: dict, loops_doc: dict | None) -> dict:
2020
+ """patterns.json carrying the agent's statements for `prepare` (by member call site: one statement in several loops
2021
+ is asked about once and benchmarked in each)."""
2022
+ store = (loops_doc or {}).get("agent_variants") or {}
2023
+ for p in patterns_doc.get("patterns") or []:
2024
+ got = [v for m in p.get("members") or [] for v in store.get(m.get("site_id"), [])]
2025
+ if got:
2026
+ p["agent_batch_variants"] = got
2027
+ return patterns_doc
2028
+
2029
+
2030
+ # --------------------------------------------------------------------------- upload
2031
+
2032
+ UPLOAD_MEMBER = ("site_id", "file", "line", "symbol", "key", "key_basis", "state", "reason", "next_step", "items_basis",
2033
+ "production_per_driver_run", "rule", "source", "verdict", "no_rule", "sql_from", "path_confirmed")
2034
+ UPLOAD_RUN = ("items", "present", "absent", "repeated", "statements_before", "statements_after", "read_bytes_before", "read_rows_before",
2035
+ "read_bytes_after", "read_rows_after", "items_compared", "items_reproduced", "items_differ", "items_with_rows", "same_rows",
2036
+ "reads_worse")
2037
+
2038
+
2039
+ def for_upload(batch: dict | None, with_text: bool = True, databases: set[str] | None = None) -> dict | None:
2040
+ """A pattern's `batch` for the bundle: codes, counts and places; the batched statement only as normalized text
2041
+ (every value ?), and only with `with_text` ([push] observed_text)."""
2042
+ if not isinstance(batch, dict):
2043
+ return None
2044
+ from .observed import strip_databases
2045
+ from .sqlinfo import _normalize_text
2046
+ out = {k: batch[k] for k in ("qualifies", "why_not", "members_qualifying") if k in batch}
2047
+ if batch.get("outcome"):
2048
+ o = batch["outcome"]
2049
+ out["outcome"] = {k: o[k] for k in ("state", "reason", "next_step") if k in o}
2050
+ ev = o.get("evidence") or {}
2051
+ if ev:
2052
+ out["outcome"]["evidence"] = {k: ev[k] for k in ("members_fixed", "members", "tradeoff") if k in ev}
2053
+ rows = []
2054
+ for m in batch.get("members") or []:
2055
+ q = {k: m[k] for k in UPLOAD_MEMBER if k in m}
2056
+ for which in ("typical", "heavy"):
2057
+ if isinstance(m.get(which), dict):
2058
+ q[which] = {k: m[which][k] for k in UPLOAD_RUN if k in m[which]}
2059
+ if isinstance(m.get("per_item"), dict):
2060
+ q["per_item"] = {"absent": m["per_item"].get("absent"), "ordered": bool(m["per_item"].get("order_by")),
2061
+ "limited": bool(m["per_item"].get("limit"))}
2062
+ if with_text and m.get("sql"):
2063
+ text = _normalize_text(re.sub(r"\{\w+\s*:\s*[^{}]+\}", "?", m["sql"]))
2064
+ q["normalized_sql"] = strip_databases(text, databases) if databases else text
2065
+ d = m.get("driver")
2066
+ if isinstance(d, dict):
2067
+ q["driver"] = {k: d[k] for k in ("rows", "values_used") if k in d}
2068
+ rows.append(q)
2069
+ if rows:
2070
+ out["members"] = rows
2071
+ return out