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/blockers.py ADDED
@@ -0,0 +1,935 @@
1
+ """Why a ranked query did not end with a verified improvement: one state, one reason code, and the numbers behind it.
2
+
3
+ Every query the agent was shown ends in exactly one of four states:
4
+
5
+ fixed a variant read meaningfully less and was shown to return the same rows (verdict `win`)
6
+ blocked measured, and no query-level change with the same results reads less. `blockers[]` says what in a
7
+ table stands in the way, only where the engine's own output shows it (EXPLAIN granules or the plan's
8
+ scan nodes, read against the table's rows, and the key or indexes from the definition)
9
+ not_judged could not be judged: CodeCop could not see or run it (SQL assembled at run time, a table the sandbox
10
+ could not load, a baseline the server refused, parameters that match no rows, sameness not shown)
11
+ nothing_to_gain the agent judged it not worth a benchmark (small table, already cheap, same as another, one-off,
12
+ behind a cache), or the sandbox measured it at the engine's floor
13
+
14
+ "Blocked" and "could not be judged" are kept apart because different people remove them: a table change against
15
+ setting CodeCop up. A reason is a code from the fixed vocabulary below, never prose; what proves it is in `evidence`
16
+ as numbers and codes. Where the stored data can not say why, the code says so (`rejected_other`, `agent_no_answer`).
17
+
18
+ Computed from the stage files only, so `codecop report` recomputes it for an out dir of any age. No agent, no network.
19
+ Thresholds are settings under `[blockers]` in codecop.toml (DEFAULTS).
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import re
25
+ from collections import Counter
26
+
27
+ SCHEMA_VERSION = 1
28
+ STATES = ("fixed", "blocked", "not_judged", "nothing_to_gain")
29
+ REASONS = {
30
+ "fixed": ("verified",),
31
+ "blocked": ("no_variant_reads_less", "fix_changes_results", "fix_results_differ", "no_variant_proposed", "heavy_by_count",
32
+ "fix_costs_inserts", "insert_cost_near_limit", "fix_costs_memory", "fix_costs_cpu", "resource_cost_near_limit"),
33
+ "not_judged": ("assembled_needs_pull", "assembled_not_seen", "assembled_shape_rejected", "sql_from_outside_code",
34
+ "sql_too_long_for_agent", "variants_not_asked", "other_engine", "agent_no_answer", "agent_failed", "budget_reached", "bench_not_run",
35
+ "sandbox_table_not_loaded", "sandbox_could_not_run", "sandbox_lost", "parameters_match_no_rows", "sameness_not_shown",
36
+ "sandbox_unlike_production", "insert_cost_not_measured", "evidence_only", "not_a_candidate", "join_not_asked",
37
+ "engine_not_benchmarkable", "definition_incomplete", "baseline_timed_out"),
38
+ "nothing_to_gain": ("small_table", "already_cheap", "same_as_another", "one_off", "cached", "already_cheap_measured", "rejected_other"),
39
+ }
40
+ BLOCKERS = ("key_not_usable", "join_side_unfiltered", "dedup_read_required", "full_partition_range_read", "heavy_by_count", "no_fix_found")
41
+ # what removes each kind of blocker, for grouping; never a suggestion of a specific change
42
+ REMOVED_BY = {"key_not_usable": ["table_key", "projection", "index"], "join_side_unfiltered": ["table_key", "projection", "index", "query"],
43
+ "dedup_read_required": ["schema", "application"], "full_partition_range_read": ["partition_key", "query"],
44
+ "heavy_by_count": ["application"], "no_fix_found": []}
45
+ # the agent's rejection codes (prompts/rank.md)
46
+ REJECTION = {"small_table": ("nothing_to_gain", "small_table"), "already_cheap": ("nothing_to_gain", "already_cheap"),
47
+ "duplicate": ("nothing_to_gain", "same_as_another"), "one_off": ("nothing_to_gain", "one_off"),
48
+ "cached": ("nothing_to_gain", "cached"), "unresolved_sql": ("not_judged", "assembled_needs_pull"),
49
+ "other_engine": ("not_judged", "other_engine")}
50
+ # `sql_assembled_at_run_time` (one code for every SQL the agent could not resolve) is split by what the run knows about the
51
+ # statement. Each reason names one next step, as a code (the console words it):
52
+ ASSEMBLED = ("assembled_needs_pull", "assembled_not_seen", "assembled_shape_rejected", "sql_from_outside_code", "sql_too_long_for_agent")
53
+ LEGACY_ASSEMBLED = "sql_assembled_at_run_time" # what outcomes stored before the split say; read, never written
54
+ NEXT_STEP = {
55
+ "assembled_needs_pull": "connect_read_only_pull", # the statement is then read from the query log
56
+ "assembled_not_seen": "longer_window_or_add_tag", # it did not run in the window, or runs as a shape CodeCop can not tie to it
57
+ "assembled_shape_rejected": "none_codecop_side", # the observed shape could not be made runnable: CodeCop's defect to count
58
+ "sql_from_outside_code": "nothing_at_this_site", # a generic executor, a console, stored SQL
59
+ "sql_too_long_for_agent": "raise_rank_max_sql_chars", # the prompt cut the statement: rank.max_sql_chars
60
+ }
61
+ # A statement production ran, benchmarked as it ran (observed.py): nobody has been asked for a faster variant of it yet.
62
+ # Its next step is the paid one: `codecop rank --observed-variants`.
63
+ VARIANTS_NEXT_STEP = "ask_agent_for_variants"
64
+ # A join statement CodeCop flagged (joins.py) that no candidate carries: CodeCop wrote no variant it could prove, and no agent has
65
+ # been asked about its join yet. Its next step is the paid one: `codecop rank --focus join`.
66
+ JOIN_NEXT_STEP = "ask_agent_for_join_variants"
67
+ # Where a candidate's SQL comes from (observed.SQL_FROM): a verified win on SQL nobody saw running is counted apart and never
68
+ # as production load saved.
69
+ ASSEMBLED_SQL = ("code_variants", "agent")
70
+ # What a SQL text of a call site is made of (inventory `resolution`) when it does not come from the code at all.
71
+ OUTSIDE_CODE = ("parameter",)
72
+ # rejected as cheap by the agent, but the measured load says otherwise: these become `heavy_by_count`
73
+ CHEAP_CODES = ("small_table", "already_cheap")
74
+
75
+ DEFAULTS = {
76
+ # a table counts as read whole when a query reads at least this share of its granules (ClickHouse) or rows
77
+ # (PostgreSQL) in the sandbox
78
+ "full_read_share": 0.5,
79
+ # a read that reads at most this many rows per row it returns (and a few rows over) is at its floor: no access path
80
+ # returns those rows reading fewer. "Nothing to gain, measured", not "needs another fix"
81
+ "read_per_returned_floor": 2.0,
82
+ "read_floor_slack_rows": 64,
83
+ # a query the agent called cheap whose measured share of all bytes read in the workload window is at least this
84
+ # is "cheap per run, heavy in total"
85
+ "heavy_share_of_read_bytes": 0.01,
86
+ # the agent's "nothing to gain" (small table, already cheap, one-off) is confirmed by the real catalog when every table
87
+ # the query reads has at most this many rows there (basis `catalog`); otherwise it stands on the agent's word alone
88
+ # (basis `agent`), counted apart in the roll-up
89
+ "confirm_small_table_max_rows": 10_000,
90
+ # ... and a small_table claim is disputed when a table it reads has at least this many rows in the real catalog
91
+ "dispute_small_table_min_rows": 1_000_000,
92
+ }
93
+
94
+ DEDUPLICATING = re.compile(r"(Replacing|Collapsing|VersionedCollapsing|Coalescing|Aggregating|Summing)MergeTree", re.I)
95
+ CH_ERROR = re.compile(r"Code:\s*(\d+)")
96
+ CH_NAME = re.compile(r"\(([A-Z][A-Z0-9_]{2,})\)")
97
+ QUOTED = re.compile(r"\"[^\"]*\"|'[^']*'|`[^`]*`")
98
+ SERVER_STOPPED = "the sandbox server stopped"
99
+ # a table that was not built for a reason of CodeCop's own, not the server's
100
+ BUILD_CLASSES = (("no data profile", "no_data_profile"), ("the load produced no rows", "load_produced_no_rows"),
101
+ ("the load kept", "unique_key_kept_few_rows"), ("not built", "not_built"))
102
+
103
+
104
+ def settings_of(config: dict | None) -> dict:
105
+ """The `[blockers]` table of codecop.toml over the defaults. Values that are not numbers are ignored."""
106
+ out = dict(DEFAULTS)
107
+ for k, v in (config or {}).items():
108
+ if k in DEFAULTS and isinstance(v, (int, float)) and not isinstance(v, bool):
109
+ out[k] = float(v)
110
+ return out
111
+
112
+
113
+ def short(name: str) -> str:
114
+ return str(name or "").replace('"', "").replace("`", "").split(".")[-1].lower()
115
+
116
+
117
+ def error_class(text: str, engine: str = "") -> str:
118
+ """A short class for an error, with no names or values in it, so identical failures group as one line.
119
+
120
+ ClickHouse: `clickhouse:<code>` and the exception name when the message carries it. PostgreSQL: the first line
121
+ after ERROR:, quoted names and numbers replaced. CodeCop's own build failures have codes of their own."""
122
+ text = str(text or "")
123
+ low = text.lower()
124
+ if SERVER_STOPPED in low:
125
+ return "server_stopped"
126
+ for marker, code in BUILD_CLASSES:
127
+ if low.startswith(marker):
128
+ return code
129
+ m = CH_ERROR.search(text)
130
+ if m:
131
+ name = CH_NAME.search(text[m.end():])
132
+ return f"clickhouse:{m.group(1)}" + (f":{name.group(1)}" if name else "")
133
+ if "ERROR:" in text:
134
+ first = text.split("ERROR:", 1)[1].strip().splitlines()[0] if text.split("ERROR:", 1)[1].strip() else ""
135
+ first = re.sub(r"\d+", "N", QUOTED.sub("?", first))
136
+ return "postgres:" + " ".join(first.split())[:80]
137
+ if "did not finish within" in low:
138
+ return "timeout"
139
+ return "unknown"
140
+
141
+
142
+ def _ratio(var, base) -> float | None:
143
+ """var / base, rounded; None when there is no finite ratio (a zero baseline)."""
144
+ var, base = float(var or 0), float(base or 0)
145
+ if base > 0:
146
+ return round(var / base, 4)
147
+ return 1.0 if var <= 0 else None
148
+
149
+
150
+ def _mem(m: dict | None) -> int:
151
+ return int((m or {}).get("memory_bytes") or 0)
152
+
153
+
154
+ def _compared_code(compared: str, base_rows: int) -> str:
155
+ """Why sameness was not decided, as a code (bench.Comparison's sentences)."""
156
+ c = (compared or "").lower()
157
+ if base_rows == 0:
158
+ return "baseline_returned_nothing"
159
+ for needle, code in (("changes results by design", "by_design"), ("returned different rows when it was run a second time", "baseline_not_repeatable"),
160
+ ("only adds an index or projection", "plan_dependent"), ("two order by clauses differ", "order_differs")):
161
+ if needle in c:
162
+ return code
163
+ return "not_compared"
164
+
165
+
166
+ def outcome(state: str, reason: str, source: str, evidence: dict | None = None, blockers: list[dict] | None = None) -> dict:
167
+ """`from`: who decided: `agent` (its rejection code), `sandbox` (a sandbox measurement), `measured` (the real
168
+ workload's measured load), `run` (what the run did or did not do)."""
169
+ out = {"state": state, "reason": reason, "from": source, "evidence": evidence or {}}
170
+ if state == "blocked":
171
+ out["blockers"] = blockers or []
172
+ return out
173
+
174
+
175
+ # ---- reading the engine's own output ------------------------------------------------------------------------------
176
+
177
+ def ch_reads(explain: str) -> dict[str, dict]:
178
+ """From ClickHouse `EXPLAIN indexes = 1`: per table, granules and parts selected against the total.
179
+
180
+ table -> {granules: [selected, total], parts: [selected, total], partition_parts: [selected, total] | None}. The
181
+ total is the first index step's denominator (before any pruning), the selected count the last step's numerator
182
+ (what is read). A table read twice (a self-join, a UNION) adds up. A table with no index steps is left out."""
183
+ reads: list[dict] = []
184
+ current: dict | None = None
185
+ indent = -1
186
+ for line in (explain or "").splitlines():
187
+ stripped = line.strip()
188
+ depth = len(line) - len(line.lstrip())
189
+ m = re.match(r"ReadFromMergeTree\s*\(([^)]*)\)", stripped)
190
+ if m:
191
+ current = {"table": short(m.group(1)), "steps": []}
192
+ indent = depth
193
+ reads.append(current)
194
+ continue
195
+ if current is None or not stripped:
196
+ continue
197
+ if stripped == "Indexes:": # printed at the read's own depth by some versions
198
+ continue
199
+ if depth <= indent: # the next plan step: this read's block is over
200
+ current = None
201
+ continue
202
+ if stripped in ("MinMax", "Partition", "PrimaryKey", "Skip"):
203
+ current["steps"].append({"name": stripped})
204
+ continue
205
+ got = re.match(r"(Parts|Granules):\s*(\d+)/(\d+)", stripped)
206
+ if got and current["steps"]:
207
+ current["steps"][-1][got.group(1).lower()] = [int(got.group(2)), int(got.group(3))]
208
+ tables: dict[str, dict] = {}
209
+ for read in reads:
210
+ steps = [s for s in read["steps"] if "granules" in s]
211
+ if not steps:
212
+ continue
213
+ t = tables.setdefault(read["table"], {"granules": [0, 0], "parts": [0, 0], "partition_parts": None})
214
+ t["granules"][0] += steps[-1]["granules"][0]
215
+ t["granules"][1] += steps[0]["granules"][1]
216
+ if "parts" in steps[-1] and "parts" in steps[0]:
217
+ t["parts"][0] += steps[-1]["parts"][0]
218
+ t["parts"][1] += steps[0]["parts"][1]
219
+ part = next((s for s in read["steps"] if s["name"] == "Partition" and "parts" in s), None) \
220
+ or next((s for s in read["steps"] if s["name"] == "MinMax" and "parts" in s), None)
221
+ if part:
222
+ prev = t["partition_parts"] or [0, 0]
223
+ t["partition_parts"] = [prev[0] + part["parts"][0], prev[1] + part["parts"][1]]
224
+ return tables
225
+
226
+
227
+ def pg_reads(scans: list[dict] | None) -> dict[str, dict]:
228
+ """From the PostgreSQL plan's scan nodes: per relation, rows fetched (kept and removed by filters) and node types."""
229
+ out: dict[str, dict] = {}
230
+ for n in scans or []:
231
+ if not n.get("loops"):
232
+ continue # a node that never ran read nothing
233
+ t = out.setdefault(short(n.get("relation")), {"rows_fetched": 0, "nodes": []})
234
+ t["rows_fetched"] += int(n.get("rows") or 0)
235
+ if n.get("node") not in t["nodes"]:
236
+ t["nodes"].append(n.get("node"))
237
+ return out
238
+
239
+
240
+ def _read_share(engine: str, table: str, baseline: dict, table_rows: dict[str, int], single: bool) -> dict | None:
241
+ """What one run of the baseline read of one table, as the engine reported it: {share, ...the counts}. None when
242
+ the stored output can not say (no EXPLAIN for the table, no rows known)."""
243
+ if engine == "clickhouse":
244
+ reads = ch_reads(baseline.get("explain") or "")
245
+ r = reads.get(short(table))
246
+ if r and r["granules"][1]:
247
+ out = {"granules_read": r["granules"][0], "granules_total": r["granules"][1],
248
+ "share": round(r["granules"][0] / r["granules"][1], 4)}
249
+ if r.get("partition_parts"):
250
+ out["partition_parts_read"], out["partition_parts_total"] = r["partition_parts"]
251
+ return out
252
+ rows = table_rows.get(short(table))
253
+ if single and rows: # one table: everything the query read came from it
254
+ return {"rows_read": int(baseline.get("read_rows") or 0), "table_rows": rows,
255
+ "share": round(int(baseline.get("read_rows") or 0) / rows, 4)}
256
+ return None
257
+ reads = pg_reads(baseline.get("scans"))
258
+ r = reads.get(short(table))
259
+ rows = table_rows.get(short(table))
260
+ if r and rows:
261
+ return {"rows_fetched": r["rows_fetched"], "table_rows": rows, "share": round(r["rows_fetched"] / rows, 4), "nodes": r["nodes"]}
262
+ return None
263
+
264
+
265
+ def _final_on(sql: str, table: str) -> bool:
266
+ """The query reads `table` with FINAL (`t FINAL`, `t AS x FINAL`, `db.t x FINAL`)."""
267
+ name = re.escape(short(table))
268
+ return bool(re.search(rf"[`\"]?\b{name}\b[`\"]?\s+(?:AS\s+)?(?:(?!FINAL\b|WHERE\b|PREWHERE\b|JOIN\b|ON\b|GROUP\b|ORDER\b|LIMIT\b)\w+\s+)?FINAL\b",
269
+ sql or "", re.I))
270
+
271
+
272
+ def _wanted_prefix(filters: list[dict]) -> list[str]:
273
+ """Equality (and IN) columns, then the first range column: a key prefix that would serve these filters."""
274
+ eq = [f["column"] for f in filters if f.get("op") in ("eq", "in")]
275
+ rng = [f["column"] for f in filters if f.get("op") == "range" and f["column"] not in eq]
276
+ return eq + rng[:1]
277
+
278
+
279
+ def table_blockers(engine: str, cand: dict, access: list[dict], baseline: dict, table_rows: dict[str, int],
280
+ variants: list[dict], definitions: dict[str, dict], settings: dict) -> list[dict]:
281
+ """The table-level evidence for a blocked query. Each entry: {code, table, columns?, ..., read{...}, from, definition}.
282
+
283
+ Only what the stored output proves: the access analysis (computed from the definition and the SQL) says the key or
284
+ no index can serve the filters, and the engine's own count says the read covered at least `full_read_share` of
285
+ the table. `definition` says where the definition came from: an assembled one makes the claim only as right as it."""
286
+ out: list[dict] = []
287
+ full = settings["full_read_share"]
288
+ tables = cand.get("tables") or []
289
+ for a in access:
290
+ name = a.get("table") or ""
291
+ d = definitions.get(short(name)) or {}
292
+ source = "real catalog" if d.get("source") == "real catalog" else "assembled" if d.get("inferred") else "repository"
293
+ read = _read_share(engine, name, baseline, table_rows, len(tables) == 1)
294
+ if read is None:
295
+ continue
296
+ whole = read["share"] >= full
297
+ filters = [f for f in a.get("filters") or [] if f.get("op") != "join"]
298
+ base = {"table": name, "read": read, "from": "computed", "definition": source}
299
+ if filters and whole and not any(f.get("key") == "used" for f in filters):
300
+ entry = {"code": "key_not_usable", **base, "columns": [f["column"] for f in filters],
301
+ "filter_keys": {f["column"]: f.get("key") for f in filters}, "wanted_key_prefix": _wanted_prefix(filters)}
302
+ if engine == "clickhouse":
303
+ entry["key"] = list(a.get("order_by") or [])
304
+ else:
305
+ entry["indexes"] = [ix.get("name") for ix in a.get("indexes") or []]
306
+ out.append(entry)
307
+ elif not filters and whole and len(tables) > 1:
308
+ out.append({"code": "join_side_unfiltered", **base})
309
+ if engine == "clickhouse":
310
+ if whole and DEDUPLICATING.search(a.get("engine") or "") and _final_on(cand.get("baseline_sql") or "", name):
311
+ # confirmed when a variant that reads the table without FINAL returned other rows
312
+ confirmed = any(v.get("results_match") is False and v.get("sql") and not _final_on(v["sql"], name) for v in variants)
313
+ out.append({"code": "dedup_read_required", **base, "engine": a.get("engine"), "confirmed": confirmed})
314
+ parts = (read.get("partition_parts_read"), read.get("partition_parts_total"))
315
+ if a.get("partition_by") and parts[1] and parts[1] > 1 and parts[0] == parts[1]:
316
+ out.append({"code": "full_partition_range_read", **base, "partition_by": a["partition_by"]})
317
+ for b in out:
318
+ b["removed_by"] = REMOVED_BY[b["code"]]
319
+ return out
320
+
321
+
322
+ # ---- one candidate --------------------------------------------------------------------------------------------------
323
+
324
+ def candidate_outcome(engine: str, cand: dict, record: dict | None, variants: list[dict], access: list[dict],
325
+ table_rows: dict[str, int], definitions: dict[str, dict], settings: dict,
326
+ floors: tuple[int, int] = (0, 0), load: dict | None = None, benched: bool = True) -> dict:
327
+ if record is not None and record.get("timed_out") and not record.get("judged_at"):
328
+ # the baseline hit the time limit at every scale it was run at: a fact, with the rows it timed out at
329
+ out = outcome("not_judged", "baseline_timed_out", "sandbox", {"timed_out": record["timed_out"]})
330
+ elif isinstance(cand.get("write"), dict):
331
+ from . import writes # a write statement: its own floor and the same-final-state rule (writes.outcome)
332
+ out = writes.outcome(engine, cand, record, variants, settings, floors, benched)
333
+ else:
334
+ out = _candidate_outcome(engine, cand, record, variants, access, table_rows, definitions, settings, floors, load, benched)
335
+ if record is not None and record.get("timed_out"):
336
+ # judged where the baseline finished; that it timed out at the largest scale is part of the outcome
337
+ out.setdefault("evidence", {})["timed_out"] = record["timed_out"]
338
+ out["evidence"]["judged_at"] = record.get("judged_at")
339
+ if cand.get("sql_from"):
340
+ out["sql_from"] = cand["sql_from"]
341
+ return out
342
+
343
+
344
+ def _candidate_outcome(engine: str, cand: dict, record: dict | None, variants: list[dict], access: list[dict],
345
+ table_rows: dict[str, int], definitions: dict[str, dict], settings: dict,
346
+ floors: tuple[int, int] = (0, 0), load: dict | None = None, benched: bool = True) -> dict:
347
+ """The outcome of one benchmarked candidate.
348
+
349
+ `record`: the bench record at the largest scale ({baseline, variants, not_benchmarked, fidelity, ...}); None when
350
+ the candidate is not in bench.json. `variants`: normalized, one per proposed variant:
351
+ {kind, verdict, same_results, results_match, compared, sql, reason, var}. `floors`: the engine's (bytes, rows) below
352
+ which a baseline is already cheap (bench.verdict). `load`: the measured production load of the call site, if any."""
353
+ if not benched or record is None:
354
+ return outcome("not_judged", "bench_not_run", "run")
355
+ nb = record.get("not_benchmarked")
356
+ if nb and nb.get("reason") == "sandbox_lost":
357
+ return outcome("not_judged", "sandbox_lost", "sandbox", {"detail": nb.get("detail", "")[:300]})
358
+ if nb and nb.get("reason") == RUNTIME_TEXT:
359
+ return outcome("not_judged", RUNTIME_TEXT, "run", {"detail": nb.get("detail", "")[:400]})
360
+ if nb and nb.get("reason") == "definition_incomplete":
361
+ return outcome("not_judged", "definition_incomplete", "run", {"detail": nb.get("detail", "")[:400]})
362
+ if nb:
363
+ return outcome("not_judged", "sandbox_table_not_loaded", "sandbox",
364
+ {"tables": [{"table": t.get("table"), "error_class": error_class(t.get("error"), engine)} for t in nb.get("tables") or []]})
365
+ base = record.get("baseline") or {}
366
+ if not base.get("ok"):
367
+ return outcome("not_judged", "sandbox_could_not_run", "sandbox",
368
+ {"stage": "baseline", "error_class": "server_stopped" if record.get("sandbox_restarted") else error_class(base.get("error"), engine)})
369
+ measured = {"read_rows": int(base.get("read_rows") or 0), "read_bytes": int(base.get("read_bytes") or 0),
370
+ "result_rows": int(base.get("result_rows") or 0), "memory_bytes": _mem(base)}
371
+ fid = record.get("fidelity") or {}
372
+ if fid.get("grade"):
373
+ measured["fidelity"] = fid["grade"]
374
+ # read no row: nothing was measured. An aggregate over nothing still returns its one row (`count(*)` = 0) and on
375
+ # PostgreSQL an index probe that finds nothing still touches a page or two, so neither the bytes nor the rows
376
+ # returned say otherwise: a count whose values matched no generated row was "already cheap" before
377
+ # SQLite counts no rows read, only pages (they decide there): a statement that read pages read something
378
+ read_nothing = measured["read_rows"] == 0 and not (engine == "sqlite" and int(base.get("pages") or 0) > 0)
379
+ if read_nothing and not [t for t in cand.get("tables") or [] if t]:
380
+ # reads no table of the application (pg_advisory_lock(...), system.tables): it ran, and there is no data to read
381
+ return outcome("nothing_to_gain", "already_cheap_measured", "sandbox", {**measured, "reads_no_table": True})
382
+ if read_nothing:
383
+ return outcome("not_judged", "parameters_match_no_rows", "sandbox", measured)
384
+ if record.get("parameters_match_no_rows"):
385
+ # rows were read, none matched, and production's typical run returns rows: no verdict on the query can come from it
386
+ return outcome("not_judged", "parameters_match_no_rows", "sandbox", {**measured, **record["parameters_match_no_rows"]})
387
+ wins = [v for v in variants if v["verdict"] == "win"]
388
+ if wins:
389
+ ok, costly, unmeasured = insert_cost_rule(wins, settings, engine)
390
+ fine, heavy_on = resource_cost_rule(ok)
391
+ if ok and not fine:
392
+ # read less and verified, but holds or burns more than a limit (resources.judge): a trade-off, never fixed
393
+ best = _best(heavy_on, measured)
394
+ judged = (best.get("resources") or {}).get("judged") or {}
395
+ reason = "fix_costs_memory" if judged.get("memory") == "over" else "fix_costs_cpu" if judged.get("cpu") == "over" \
396
+ else "resource_cost_near_limit"
397
+ return outcome("blocked", reason, "sandbox", {**measured, "kind": best["kind"], **_ratios(best, measured), **_insert_evidence(best),
398
+ **_resource_evidence(best), "trade_off": True},
399
+ [{"code": "no_fix_found", "table": None, "read": {k: measured[k] for k in ("read_rows", "result_rows")},
400
+ "from": "computed", "removed_by": REMOVED_BY["no_fix_found"]}])
401
+ ok = fine
402
+ if ok:
403
+ best = _best(ok, measured)
404
+ return outcome("fixed", "verified", "sandbox", {**measured, "kind": best["kind"], **_ratios(best, measured), **_insert_evidence(best),
405
+ **_other_run(best), **unlike_production(record)})
406
+ if costly:
407
+ best = _best(costly, measured)
408
+ near = bool((best.get("insert_cost") or {}).get("near_limit"))
409
+ return outcome("blocked", "insert_cost_near_limit" if near else "fix_costs_inserts", "sandbox", {**measured, "kind": best["kind"], **_ratios(best, measured),
410
+ **_insert_evidence(best), "trade_off": True},
411
+ [{"code": "no_fix_found", "table": None, "read": {k: measured[k] for k in ("read_rows", "result_rows")},
412
+ "from": "computed", "removed_by": REMOVED_BY["no_fix_found"]}])
413
+ best = _best(unmeasured, measured)
414
+ return outcome("not_judged", "insert_cost_not_measured", "sandbox", {**measured, "kind": best["kind"], **_ratios(best, measured),
415
+ **_insert_evidence(best)})
416
+ heavy = _heavy(load, settings)
417
+ floor_bytes, floor_rows = floors
418
+ marks = int(base.get("selected_marks") or 0)
419
+ cheap = None
420
+ if floor_bytes and measured["read_bytes"] <= floor_bytes and measured["read_rows"] <= floor_rows:
421
+ cheap = {**measured, "floor_bytes": floor_bytes, "floor_rows": floor_rows}
422
+ elif engine != "sqlite" and measured["result_rows"] > 0 and 0 < measured["read_rows"] <= measured["result_rows"] * float(
423
+ (settings or {}).get("read_per_returned_floor", DEFAULTS["read_per_returned_floor"])) + float(
424
+ (settings or {}).get("read_floor_slack_rows", DEFAULTS["read_floor_slack_rows"])):
425
+ # reads about what it returns (151 read for 151 returned): no index or key returns those rows reading fewer
426
+ cheap = {**measured, "reads_what_it_returns": True}
427
+ elif engine == "clickhouse" and 0 < marks <= max(len(cand.get("tables") or []), 1):
428
+ # ClickHouse reads whole granules: one granule of each table is the least any query can read of it
429
+ # (SelectedMarks of the run, from the server's query log)
430
+ cheap = {**measured, "selected_marks": marks, "total_marks": int(base.get("total_marks") or 0),
431
+ "tables_read": len(cand.get("tables") or [])}
432
+ if cheap is not None:
433
+ if heavy:
434
+ return outcome("blocked", "heavy_by_count", "measured", {**cheap, **heavy},
435
+ [{"code": "heavy_by_count", "table": None, "read": heavy, "from": "measured", "removed_by": REMOVED_BY["heavy_by_count"]}])
436
+ if fid.get("grade") == "off":
437
+ return outcome("not_judged", "sandbox_unlike_production", "sandbox", {**cheap, "ratios": fid.get("ratios") or {}})
438
+ return outcome("nothing_to_gain", "already_cheap_measured", "sandbox", cheap)
439
+ tally = dict(Counter(v["verdict"] for v in variants))
440
+ evidence = {**measured, "variants": len(variants), "verdicts": tally}
441
+ # read less, and were not shown to return the same rows: whether a fix exists is not known
442
+ undecided = [v for v in variants if v["verdict"] == "mixed" and v.get("same_results", True) and _reads_less(engine, v, measured)
443
+ and (v.get("results_match") is None or measured["result_rows"] == 0)]
444
+ if undecided:
445
+ v = undecided[0]
446
+ return outcome("not_judged", "sameness_not_shown", "sandbox",
447
+ {**evidence, "kind": v["kind"], "why": _compared_code(v.get("compared") or "", measured["result_rows"]), **_ratios(v, measured)})
448
+ measured_variants = [v for v in variants if v["verdict"] not in ("failed", "untested")]
449
+ if variants and not measured_variants:
450
+ failed = [v for v in variants if v["verdict"] == "failed"]
451
+ stage = "variant_setup" if failed and all(str(v.get("reason") or "").startswith("setup failed") for v in failed) else "variant"
452
+ return outcome("not_judged", "sandbox_could_not_run", "sandbox",
453
+ {**evidence, "stage": stage, "error_classes": sorted({error_class(_variant_error(v), engine) for v in failed})})
454
+ blockers = None
455
+
456
+ def blocked(reason: str, more: dict) -> dict:
457
+ nonlocal blockers
458
+ if blockers is None:
459
+ blockers = table_blockers(engine, cand, access, base, table_rows, variants, definitions, settings) or [
460
+ {"code": "no_fix_found", "table": None, "read": {k: measured[k] for k in ("read_rows", "result_rows")}, "from": "computed",
461
+ "removed_by": REMOVED_BY["no_fix_found"]}]
462
+ return outcome("blocked", reason, "sandbox", {**evidence, **more}, blockers)
463
+
464
+ by_design = [v for v in variants if v["verdict"] == "mixed" and not v.get("same_results", True) and _reads_less(engine, v, measured)]
465
+ if by_design:
466
+ v = _best(by_design, measured)
467
+ return blocked("fix_changes_results", {"kind": v["kind"], **_ratios(v, measured)})
468
+ differ = [v for v in variants if v["verdict"] == "rejected"]
469
+ if differ:
470
+ v = differ[0]
471
+ return blocked("fix_results_differ", {"kind": v["kind"], "compared": "row_count" if str(v.get("compared") or "").startswith("row count")
472
+ else "rows", "variant_result_rows": int((v["var"] or {}).get("result_rows") or 0),
473
+ **_ratios(v, measured)})
474
+ if not variants and cand.get("sql_from") == "query_log" and not cand.get("variants_asked"):
475
+ # production's statement, measured as it ran: no agent has been asked for a variant of it (that step is paid)
476
+ return outcome("not_judged", "variants_not_asked", "run", {**measured, "next_step": VARIANTS_NEXT_STEP})
477
+ if not variants:
478
+ return blocked("no_variant_proposed", {})
479
+ best = _best(measured_variants, measured)
480
+ return blocked("no_variant_reads_less", {"kind": best["kind"], **_ratios(best, measured), **_thresholds()})
481
+
482
+
483
+ TABLE_LEVEL = ("skip_index", "projection", "ordering_key", "index", "partitioning")
484
+
485
+
486
+ def insert_cost_rule(wins: list[dict], settings: dict, engine: str = "clickhouse") -> tuple[list[dict], list[dict], list[dict]]:
487
+ """The rule for a table-level variant (an index, a projection, a new sorting key) that reads less: it costs every
488
+ insert, so the read verdict alone does not make it Fixed. Split the winning variants into (ok, costly, unmeasured):
489
+
490
+ (a PostgreSQL `index` is table-level too: its insert side is measured on PostgreSQL as well, writecost.measure_postgres)
491
+ ok a query-level variant; or a table-level one whose insert side was measured (writecost.py) within the
492
+ thresholds `[bench] insert_cost_max_time_ratio` and `insert_cost_max_storage_ratio`; or one from a bench
493
+ that did not measure insert sides at all (an older bench.json, or `[bench] insert_cost = false`): then
494
+ `insert_cost` says `not_measured` beside the verdict and the finding says so.
495
+ costly measured above a threshold: a trade-off, shown as Needs another fix (`fix_costs_inserts`), never Fixed.
496
+ unmeasured the bench measured insert sides and this one's measurement failed: Could not be judged
497
+ (`insert_cost_not_measured`, shown as "read side verified, insert side not measured"). On PostgreSQL
498
+ a table-level variant with no insert measurement at all is here too: this build's PostgreSQL bench does
499
+ not measure insert sides, so a read-verified index there is never Fixed on its read side alone."""
500
+ ok, costly, unmeasured = [], [], []
501
+ for v in wins:
502
+ if v.get("kind") not in TABLE_LEVEL:
503
+ ok.append(v)
504
+ continue
505
+ ic = v.get("insert_cost")
506
+ if ic is None and engine == "postgres":
507
+ unmeasured.append(v) # the PostgreSQL bench measures no insert side: read side verified, insert side not measured
508
+ elif ic is None:
509
+ ok.append(v) # no measurement was attempted (older bench, or the setting is off): stated, not judged here
510
+ elif not ic.get("measured"):
511
+ unmeasured.append(v)
512
+ elif ic.get("within") is False:
513
+ costly.append(v)
514
+ else:
515
+ ok.append(v)
516
+ return ok, costly, unmeasured
517
+
518
+
519
+ def resource_cost_rule(wins: list[dict]) -> tuple[list[dict], list[dict]]:
520
+ """Split read-side wins into (fine, costly) by their measured CPU and memory (bench resources.judge): costly when the
521
+ memory or the CPU is over its limit, or a limit lies inside the range of the runs (near_limit). A variant without a
522
+ resource judgement (an older bench.json, the profile off, a measure not judged) is fine: CPU and memory never make or
523
+ keep a win by themselves, they can only take one away."""
524
+ fine, costly = [], []
525
+ for v in wins:
526
+ judged = (v.get("resources") or {}).get("judged") or {}
527
+ (costly if any(judged.get(k) in ("over", "near_limit") for k in ("memory", "cpu")) else fine).append(v)
528
+ return fine, costly
529
+
530
+
531
+ def _resource_evidence(v: dict) -> dict:
532
+ """The resource judgement behind a trade-off: per measure its state and the ratio with the range of the runs, and the
533
+ thresholds ([bench] memory_trade_off_ratio, memory_trade_off_min_bytes, cpu_trade_off_ratio, cpu_trade_off_min_ms)."""
534
+ res = v.get("resources") or {}
535
+ judged = res.get("judged") or {}
536
+ out = {"resource_cost": {k: judged[k] for k in ("memory", "cpu") if k in judged}}
537
+ for k in ("memory", "cpu"):
538
+ m = res.get(k) or {}
539
+ if m.get("ratio") is not None:
540
+ out["resource_cost"][f"{k}_range"] = [m.get("low"), m.get("high")]
541
+ if judged.get("thresholds"):
542
+ out["thresholds"] = judged["thresholds"]
543
+ return out
544
+
545
+
546
+ def _insert_evidence(v: dict) -> dict:
547
+ ic = v.get("insert_cost")
548
+ if v.get("kind") not in TABLE_LEVEL:
549
+ return {}
550
+ if ic is None:
551
+ return {"insert_cost": {"measured": False, "reason": "not_measured"}}
552
+ keep = ("measured", "reason", "rows", "blocks", "insert_time_ratio", "written_bytes_ratio", "storage_ratio", "parts_ratio", "within", "thresholds",
553
+ "wal_bytes_ratio", "index_bytes", "wal_from", "rounds", "insert_time_ratios", "insert_time_ratio_range", "near_limit")
554
+ return {"insert_cost": {k: ic[k] for k in keep if k in ic}}
555
+
556
+
557
+ def _thresholds() -> dict:
558
+ from .bench import WIN_RATIO, WORSE_RATIO
559
+ return {"win_ratio": WIN_RATIO, "worse_ratio": WORSE_RATIO}
560
+
561
+
562
+ def _best(variants: list[dict], measured: dict) -> dict:
563
+ """The variant that read the least, by the smaller of its two ratios (an unmeasured one last)."""
564
+ def key(v: dict) -> float:
565
+ r = _ratios(v, measured)
566
+ got = [x for x in (r.get("rows_ratio"), r.get("bytes_ratio")) if x is not None]
567
+ return min(got) if got else float("inf")
568
+ return min(variants, key=key)
569
+
570
+
571
+ def _reads_less(engine: str, v: dict, measured: dict) -> bool:
572
+ """What bench.verdict calls reading less: at most WIN_RATIO on the deciding measure, and on ClickHouse no more than
573
+ WORSE_RATIO on the other (on PostgreSQL the pages decide)."""
574
+ from .bench import WIN_RATIO, WORSE_RATIO
575
+ r = _ratios(v, measured)
576
+ rows, size = r.get("rows_ratio"), r.get("bytes_ratio")
577
+ if engine in ("postgres", "sqlite"): # pages decide
578
+ return size is not None and size <= WIN_RATIO
579
+ got = [x for x in (rows, size) if x is not None]
580
+ return len(got) == 2 and min(got) <= WIN_RATIO and max(got) <= WORSE_RATIO
581
+
582
+
583
+ def _variant_error(v: dict) -> str:
584
+ reason = str(v.get("reason") or "")
585
+ return (v.get("var") or {}).get("error") or reason.removeprefix("setup failed: ")
586
+
587
+
588
+ def _ratios(v: dict, measured: dict) -> dict:
589
+ var = v.get("var") or {}
590
+ if not var.get("ok"):
591
+ return {}
592
+ out = {"rows_ratio": _ratio(var.get("read_rows"), measured["read_rows"]), "bytes_ratio": _ratio(var.get("read_bytes"), measured["read_bytes"]),
593
+ "memory_ratio": _ratio(var.get("memory_bytes"), measured["memory_bytes"]) if measured.get("memory_bytes") else None}
594
+ # CPU (user + system): the median ratio of the interleaved runs (resources.py) when they were taken; absent otherwise
595
+ mem = (v.get("resources") or {}).get("memory") or {}
596
+ if mem.get("ratio") is not None:
597
+ out["memory_ratio"] = mem["ratio"] # the median ratio of the resource runs (resources.py) over one measurement's
598
+ cpu = (v.get("resources") or {}).get("cpu") or {}
599
+ if cpu.get("ratio") is not None and (v.get("resources") or {}).get("cpu_kind") == "rusage":
600
+ out["cpu_ratio"] = cpu["ratio"]
601
+ return out
602
+
603
+
604
+ def unlike_production(record: dict | None) -> dict:
605
+ """The qualifier of a Fixed outcome measured on data that does not resemble production: {data_unlike_production: {...}}
606
+ when the baseline's fidelity grade is `off`, else {}.
607
+
608
+ The rule: a variant that read meaningfully less and was shown to return the same rows stays Fixed whatever the data
609
+ (the sameness and the read are real measurements of the variant against the baseline), but the size of the gain was
610
+ measured on data that reads unlike production, so it is labelled so ("measured on data that does not resemble
611
+ production") and counted apart in the roll-up (`fixed_on_unlike_data`), never as production load saved. Which tables'
612
+ data came from the catalog alone (no agent profile) is said with it: those are the usual cause."""
613
+ fid = (record or {}).get("fidelity") or {}
614
+ if fid.get("grade") != "off":
615
+ return {}
616
+ basis = (record or {}).get("profile_basis") or {}
617
+ return {"data_unlike_production": {"fidelity": "off", "ratios": {k: v for k, v in (fid.get("ratios") or {}).items() if v is not None},
618
+ "catalog_only_tables": sorted(t for t, b in basis.items() if b == "catalog only"),
619
+ "label": UNLIKE_PRODUCTION_LABEL}}
620
+
621
+
622
+ UNLIKE_PRODUCTION_LABEL = "measured on data that does not resemble production"
623
+
624
+
625
+ def _other_run(v: dict) -> dict:
626
+ """For a variant judged on two runs (the typical run returns nothing, sameness shown on a run with rows): what it
627
+ read on that other run, so a probe that skips an empty read and reads more when rows exist says so."""
628
+ other = v.get("heavy")
629
+ if not other or not isinstance(other, dict):
630
+ return {}
631
+ return {"other_run": {k: other.get(k) for k in ("verdict", "reason", "results_match") if other.get(k) is not None}}
632
+
633
+
634
+ def _heavy(load: dict | None, settings: dict) -> dict | None:
635
+ """The measured load when it makes a cheap query heavy in total; None otherwise or when nothing was measured."""
636
+ if not load or load.get("match") not in ("exact", "template", "tag"):
637
+ return None
638
+ share = float(load.get("share_of_read_bytes") or 0)
639
+ if share < settings["heavy_share_of_read_bytes"]:
640
+ return None
641
+ return {"share_of_read_bytes": round(share, 6), "read_bytes": int(load.get("read_bytes") or 0),
642
+ "executions": int(load.get("executions") or 0), "threshold": settings["heavy_share_of_read_bytes"]}
643
+
644
+
645
+ def has_fragments(sql: str) -> bool:
646
+ """The call site's SQL has parts only known at run time («expr» from discover, a template action in a .sql file)."""
647
+ return bool(re.search(r"«[^»]*»|…|\{\{.*?\}\}|\{%.*?%\}", sql or "", re.S))
648
+
649
+
650
+ RUNTIME_TEXT = "statement_known_at_run_time"
651
+ RUNTIME_WORDS = "could not be judged: part of the statement is only known at run time"
652
+ _LITERAL = re.compile(r"'(?:[^']|'')*'")
653
+ _PLACEHOLDER = re.compile(r"\{(\w+)(?:\s*:\s*[^{}]+?)?\}")
654
+ _TEMPLATE = re.compile(r"«[^»]*»|\{\{.*?\}\}|\{%.*?%\}", re.S)
655
+
656
+
657
+ def unbound_parts(sql: str, bound=()) -> list[str]:
658
+ """What of a statement is still only known at run time once `bound` parameters have their values: a `{name:Type}`
659
+ placeholder no value is given for, a «expr» discover left, a template tag. Text inside quoted literals is not read
660
+ (`'{a}'` is an array literal). Sent to a server as it is, each fails as a syntax error; it is classed before any
661
+ sandbox run instead (RUNTIME_TEXT)."""
662
+ text = _LITERAL.sub("''", sql or "")
663
+ names = set(bound or ())
664
+ out: list[str] = []
665
+ for m in _PLACEHOLDER.finditer(text):
666
+ if m.group(1) not in names and m.group(0) not in out:
667
+ out.append(m.group(0))
668
+ for m in _TEMPLATE.finditer(text):
669
+ if m.group(0) not in out:
670
+ out.append(m.group(0))
671
+ return out
672
+
673
+
674
+ def runtime_detail(parts: list[str]) -> str:
675
+ return f"{RUNTIME_WORDS}: " + ", ".join(p[:60] for p in parts[:4])
676
+
677
+
678
+ def assembled_reason(site: dict | None, *, sql_cut: int, pulled: bool, gate: dict | None = None, window_hours=None,
679
+ unlocated: dict | None = None, likely: int = 0) -> tuple[str, dict]:
680
+ """Which of ASSEMBLED an `unresolved_sql` rejection is, and the evidence: (reason, evidence).
681
+
682
+ In order: an observed statement was found and could not be made runnable (`gate`: the shape gate's output);
683
+ the call site's SQL is a parameter of a generic executor; the SQL is fixed text longer than the prompt showed
684
+ (`sql_cut`, rank.json `max_sql_chars`); a pull exists and no statement in its window matched (`unlocated`: the
685
+ shapes with no call site on the tables this site reads, {shapes, read_bytes}); no pull."""
686
+ sql = ((site or {}).get("sql") or "").strip()
687
+ if gate:
688
+ return "assembled_shape_rejected", {"gate": gate}
689
+ if site and site.get("resolution") in OUTSIDE_CODE:
690
+ return "sql_from_outside_code", {"resolution": site.get("resolution")}
691
+ if site and sql and len(sql) > sql_cut and not has_fragments(sql):
692
+ return "sql_too_long_for_agent", {"sql_chars": len(sql), "cut_at": sql_cut}
693
+ if pulled:
694
+ ev = {"window_hours": window_hours} if window_hours else {}
695
+ if unlocated:
696
+ ev["unlocated_on_its_tables"] = unlocated
697
+ if likely:
698
+ ev["likely_matches"] = likely
699
+ if site and sql and len(sql) > sql_cut:
700
+ ev.update(sql_chars=len(sql), cut_at=sql_cut)
701
+ return "assembled_not_seen", ev
702
+ return "assembled_needs_pull", ({"sql_chars": len(sql), "cut_at": sql_cut} if site and len(sql) > sql_cut else {})
703
+
704
+
705
+ def catalog_basis(code: str, site: dict | None, facts, engine: str, settings: dict) -> dict:
706
+ """What a pulled catalog says about the agent's "nothing to gain": {basis: catalog} when every table the query reads
707
+ is in the real catalog with at most `confirm_small_table_max_rows` rows, else {basis: agent}; with the largest real
708
+ row count (`catalog_max_rows`) when every table is known, and `disputed` when a small_table claim meets a table of
709
+ at least `dispute_small_table_min_rows` rows. Never changes the state: the counts say how much stands on the word."""
710
+ tables = [t for t in (site or {}).get("tables") or [] if t and "«" not in t]
711
+ if not facts or not tables:
712
+ return {"basis": "agent"}
713
+ from .rank import _catalog_table
714
+ try:
715
+ real = facts.tables(engine)
716
+ except Exception:
717
+ return {"basis": "agent"}
718
+ rows = []
719
+ for t in tables:
720
+ entry = _catalog_table(real, t, engine)
721
+ if entry is None or entry.get("rows") is None:
722
+ return {"basis": "agent"}
723
+ rows.append(int(entry["rows"]))
724
+ top = max(rows)
725
+ out = {"basis": "catalog" if top <= settings["confirm_small_table_max_rows"] else "agent", "catalog_max_rows": top}
726
+ if code == "small_table" and top >= settings["dispute_small_table_min_rows"]:
727
+ out["disputed"] = True
728
+ return out
729
+
730
+
731
+ def rejection_outcome(r: dict, load: dict | None, settings: dict, disputed: bool = False,
732
+ assembled: tuple[str, dict] | None = None) -> dict:
733
+ """The outcome of a query the agent examined and rejected, from its code. `other` (and a code CodeCop does not know)
734
+ says only that the agent gave no code: the detail it wrote is in `rejected_by_agent[].detail`. `assembled`: for
735
+ `unresolved_sql`, which of ASSEMBLED it is (assembled_reason); without it, `assembled_needs_pull`."""
736
+ code = r.get("code") or "other"
737
+ state, reason = REJECTION.get(code, ("nothing_to_gain", "rejected_other"))
738
+ evidence: dict = {"agent_code": code}
739
+ if code == "unresolved_sql":
740
+ reason, more = assembled or ("assembled_needs_pull", {})
741
+ evidence.update({"next_step": NEXT_STEP[reason], **more}) # a more precise next step of the evidence wins
742
+ if disputed:
743
+ evidence["disputed"] = True # the computed access analysis speaks against `already_cheap` (rank.audit_rejections)
744
+ heavy = _heavy(load, settings) if code in CHEAP_CODES else None
745
+ if heavy:
746
+ return outcome("blocked", "heavy_by_count", "measured", {**evidence, **heavy},
747
+ [{"code": "heavy_by_count", "table": None, "read": heavy, "from": "measured", "removed_by": REMOVED_BY["heavy_by_count"]}])
748
+ return outcome(state, reason, "agent", evidence)
749
+
750
+
751
+ # ---- inputs from the stage files ------------------------------------------------------------------------------------
752
+
753
+ def engine_floors(engine: str, bench: dict | None = None) -> tuple[int, int]:
754
+ """(bytes, rows) at or under which a baseline is already cheap on this engine: what bench.json recorded, else the
755
+ sandbox adapter's own (an older bench.json does not record them)."""
756
+ got = (bench or {}).get("floors") or {}
757
+ if "bytes" in got and "rows" in got:
758
+ return int(got["bytes"] or 0), int(got["rows"] or 0)
759
+ try:
760
+ if engine == "postgres":
761
+ from .engines.postgres import PostgresSandbox as cls
762
+ elif engine == "sqlite":
763
+ from .engines.sqlite import SqliteSandbox as cls
764
+ else:
765
+ from .engines.clickhouse import ClickHouseSandbox as cls
766
+ return int(getattr(cls, "floor_bytes", 0) or 0), int(getattr(cls, "floor_rows", 0) or 0)
767
+ except Exception:
768
+ return 0, 0
769
+
770
+
771
+ def table_rows_of(scale: dict | None) -> dict[str, int]:
772
+ """Rows loaded per table at one scale, by short lower-case name."""
773
+ return {short(t["name"]): int(t.get("rows") or 0) for t in (scale or {}).get("tables") or [] if t.get("ok") and t.get("rows")}
774
+
775
+
776
+ def variants_from_bench(record: dict, proposed: list[dict]) -> list[dict]:
777
+ """The normalized variants of one bench record at the largest scale, with what each claimed (rank.json)."""
778
+ out = []
779
+ for i, rec in enumerate((record or {}).get("variants") or []):
780
+ v = proposed[i] if i < len(proposed) else {}
781
+ out.append({"kind": rec.get("kind") or v.get("kind"), "verdict": rec.get("verdict") or "untested", "same_results": v.get("same_results", True),
782
+ "results_match": rec.get("results_match"), "compared": rec.get("compared") or "", "sql": v.get("sql") or "",
783
+ "reason": rec.get("reason") or "", "var": rec.get("measurement"),
784
+ **({"insert_cost": rec["insert_cost"]} if rec.get("insert_cost") else {}),
785
+ **({"resources": rec["resources"]} if isinstance(rec.get("resources"), dict) else {}),
786
+ **({"heavy": {k: rec["heavy"].get(k) for k in ("verdict", "reason", "results_match")}} if isinstance(rec.get("heavy"), dict) else {})})
787
+ return out
788
+
789
+
790
+ def variants_from_findings(variants: list[dict]) -> list[dict]:
791
+ """The normalized variants of a findings.json finding: the verdict at the largest scale and its measurement."""
792
+ out = []
793
+ for v in variants or []:
794
+ last = (v.get("scales") or [None])[-1] if v.get("verdict") != "untested" else None
795
+ out.append({"kind": v.get("kind"), "verdict": v.get("verdict") or "untested", "same_results": v.get("same_results", True),
796
+ "results_match": v.get("results_match"), "compared": v.get("compared") or "", "sql": v.get("sql") or "",
797
+ "reason": v.get("reason") or "", "var": (last or {}).get("variant"),
798
+ **({"insert_cost": v["insert_cost"]} if v.get("insert_cost") else {}),
799
+ **({"resources": v["resources"]} if isinstance(v.get("resources"), dict) else {}),
800
+ **({"heavy": {k: v["heavy"].get(k) for k in ("verdict", "reason", "results_match")}} if isinstance(v.get("heavy"), dict) else {})})
801
+ return out
802
+
803
+
804
+ def for_bench(rank: dict, result: dict, settings: dict | None = None) -> dict[str, dict]: # noqa: C901
805
+ """finding -> outcome for every candidate of a bench result, as bench.json records it. No production load is
806
+ known here (that is the report's), so `heavy_by_count` comes only from the report."""
807
+ from . import engines
808
+ settings = settings_of(settings)
809
+ engine = rank.get("engine") or result.get("engine") or ""
810
+ scales = result.get("scales") or []
811
+ largest = scales[-1] if scales else {}
812
+ records = {f["finding"]: f for f in largest.get("findings") or []}
813
+ definitions = {short(d["name"]): d for d in rank.get("table_definitions") or []}
814
+ rows = table_rows_of(largest)
815
+ floors = engine_floors(engine, result)
816
+ out = {}
817
+ for c in rank.get("candidates") or []:
818
+ access = []
819
+ for t in c.get("tables") or []:
820
+ d = definitions.get(short(t))
821
+ if not d or not d.get("create_sql"):
822
+ continue
823
+ try:
824
+ access.append(engines.get(engine).table_access(d["create_sql"], d["name"], c["baseline_sql"], None))
825
+ except Exception: # a definition the access analysis can not read is no evidence either way
826
+ continue
827
+ rec = records.get(c["finding"])
828
+ used_rows, reduced = rows, None
829
+ if not _baseline_ran(rec):
830
+ # ClickHouse reduced-scale baseline: the full-scale load was too heavy for this candidate's tables (memory, disk,
831
+ # time) or its run failed there, while a smaller scale ran it. The outcome is taken where it ran, and says so.
832
+ for sc in reversed(scales[:-1]):
833
+ r2 = next((f for f in sc.get("findings") or [] if f.get("finding") == c["finding"]), None)
834
+ if _baseline_ran(r2):
835
+ rec, used_rows, reduced = r2, table_rows_of(sc), sc.get("fraction")
836
+ break
837
+ out[c["finding"]] = candidate_outcome(engine, c, rec, variants_from_bench(rec or {}, c.get("variants") or []), access, used_rows,
838
+ definitions, settings, floors, benched=bool(scales))
839
+ if reduced is not None:
840
+ ev = out[c["finding"]].setdefault("evidence", {})
841
+ ev["baseline_scale"] = reduced
842
+ ev["reduced_scale"] = f"baseline at reduced scale ({reduced:g} of the full-scale rows): the full-scale run did not finish"
843
+ return out
844
+
845
+
846
+ def _baseline_ran(rec: dict | None) -> bool:
847
+ return bool(rec) and not rec.get("not_benchmarked") and bool((rec.get("baseline") or {}).get("ok"))
848
+
849
+
850
+ # ---- the roll-up ----------------------------------------------------------------------------------------------------
851
+
852
+ def _ntg_basis(queries: list[dict]) -> dict:
853
+ out = {"measured": 0, "catalog": 0, "agent": 0, "disputed": 0}
854
+ for q in queries:
855
+ o = q.get("outcome") or {}
856
+ if o.get("state") != "nothing_to_gain":
857
+ continue
858
+ ev = o.get("evidence") or {}
859
+ if o.get("from") in ("sandbox", "measured"):
860
+ out["measured"] += 1
861
+ elif ev.get("basis") == "catalog":
862
+ out["catalog"] += 1
863
+ else:
864
+ out["agent"] += 1
865
+ out["disputed"] += bool(ev.get("disputed"))
866
+ return out
867
+
868
+
869
+ def rollup(queries: list[dict], settings: dict, window_hours=None) -> dict:
870
+ """Counts per state and per reason, blocker codes, and tables ranked by the load that waits on them.
871
+
872
+ `queries`: [{id, finding, sites, outcome, tables, load_read_bytes, sandbox_read_bytes}]. A table's weight is the
873
+ measured bytes read in the workload window by its blocked queries with a costed match (exact or template); a table
874
+ with measured load ranks above one without, then by call sites, then findings. A query's whole load counts towards
875
+ each table that blocks it. Sandbox bytes are reported beside it, never multiplied into it."""
876
+ states = {s: 0 for s in STATES}
877
+ sites = {s: 0 for s in STATES}
878
+ reasons: dict[tuple[str, str], dict] = {}
879
+ codes: Counter = Counter()
880
+ tables: dict[str, dict] = {}
881
+ unknown = 0
882
+ for q in queries:
883
+ o = q.get("outcome") or {}
884
+ state = o.get("state")
885
+ if state not in states:
886
+ unknown += 1
887
+ continue
888
+ states[state] += 1
889
+ sites[state] += q.get("sites") or 1
890
+ row = reasons.setdefault((state, o.get("reason") or "unknown"), {"state": state, "reason": o.get("reason") or "unknown", "queries": 0, "sites": 0})
891
+ row["queries"] += 1
892
+ row["sites"] += q.get("sites") or 1
893
+ for b in o.get("blockers") or []:
894
+ codes[b["code"]] += 1
895
+ for name in sorted({b["table"] for b in o.get("blockers") or [] if b.get("table")}):
896
+ t = tables.setdefault(name, {"table": name, "queries": 0, "sites": 0, "codes": Counter(), "findings": [],
897
+ "measured_queries": 0, "measured_read_bytes": 0, "sandbox_read_bytes": 0, "definition": ""})
898
+ t["queries"] += 1
899
+ t["sites"] += q.get("sites") or 1
900
+ for b in o["blockers"]:
901
+ if b.get("table") == name:
902
+ t["codes"][b["code"]] += 1
903
+ t["definition"] = t["definition"] or b.get("definition") or ""
904
+ if q.get("finding"):
905
+ t["findings"].append(q["finding"])
906
+ if q.get("load_read_bytes") is not None:
907
+ t["measured_queries"] += 1
908
+ t["measured_read_bytes"] += int(q["load_read_bytes"])
909
+ t["sandbox_read_bytes"] += int(q.get("sandbox_read_bytes") or 0)
910
+ ranked = sorted(tables.values(), key=lambda t: (-(t["measured_queries"] > 0), -t["measured_read_bytes"], -t["sites"], -t["queries"],
911
+ -t["sandbox_read_bytes"], t["table"]))
912
+ order = {s: i for i, s in enumerate(STATES)}
913
+ fixed = [q for q in queries if (q.get("outcome") or {}).get("state") == "fixed"]
914
+ return {
915
+ "schema_version": SCHEMA_VERSION,
916
+ "ranked": len(queries), "unknown": unknown,
917
+ "states": states, "sites": sites,
918
+ # fixed, by where the SQL text comes from: a win on a statement assembled from code or written by the agent is shown
919
+ # under fixed with its origin, and counted here apart from statements written in code or observed in production
920
+ "fixed_by_sql_from": dict(Counter(q.get("sql_from") or "code" for q in fixed).most_common()),
921
+ "fixed_not_seen_in_production": sum(1 for q in fixed if q.get("sql_from") in ASSEMBLED_SQL),
922
+ # fixed, but measured on data that reads unlike production (fidelity off): counted apart (unlike_production)
923
+ "fixed_on_unlike_data": sum(1 for q in fixed if ((q.get("outcome") or {}).get("evidence") or {}).get("data_unlike_production")),
924
+ # nothing to gain, by what it stands on: measured (the sandbox at the engine's floor, or the real load by rule),
925
+ # the real catalog's row counts, or the agent's word alone (catalog_basis)
926
+ "nothing_to_gain_basis": _ntg_basis(queries),
927
+ "reasons": sorted(reasons.values(), key=lambda r: (order[r["state"]], -r["queries"], r["reason"])),
928
+ "blockers": [{"code": c, "queries": n} for c, n in codes.most_common()],
929
+ "blocked_without_table": sum(1 for q in queries if (q.get("outcome") or {}).get("state") == "blocked"
930
+ and not any(b.get("table") for b in (q["outcome"].get("blockers") or []))),
931
+ "tables": [{**t, "codes": dict(t["codes"].most_common()), "measured_read_bytes": t["measured_read_bytes"] if t["measured_queries"] else None}
932
+ for t in ranked],
933
+ "window_hours": window_hours,
934
+ "settings": dict(settings),
935
+ }