codecop 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (222) hide show
  1. codecop/__init__.py +7 -0
  2. codecop/access.py +140 -0
  3. codecop/access_postgres.py +284 -0
  4. codecop/advisor.py +1512 -0
  5. codecop/advisor_bench.py +493 -0
  6. codecop/advisor_ch.py +2080 -0
  7. codecop/advisor_view.py +381 -0
  8. codecop/advisors.py +184 -0
  9. codecop/agent.py +221 -0
  10. codecop/agentfacts.py +745 -0
  11. codecop/apply/__init__.py +327 -0
  12. codecop/apply/check.py +344 -0
  13. codecop/apply/cli.py +162 -0
  14. codecop/apply/clickhouse.py +379 -0
  15. codecop/apply/common.py +238 -0
  16. codecop/apply/html.py +264 -0
  17. codecop/apply/patch.py +213 -0
  18. codecop/apply/postgres.py +102 -0
  19. codecop/apply/trial.py +166 -0
  20. codecop/assemble.py +104 -0
  21. codecop/baseline.py +1043 -0
  22. codecop/bench.py +2464 -0
  23. codecop/blockers.py +935 -0
  24. codecop/budget.py +980 -0
  25. codecop/catalog_profile.py +525 -0
  26. codecop/changed.py +261 -0
  27. codecop/cicmd.py +1002 -0
  28. codecop/cli.py +5421 -0
  29. codecop/client.py +729 -0
  30. codecop/coverage.py +1067 -0
  31. codecop/coverage_reasons.py +116 -0
  32. codecop/crashlog.py +70 -0
  33. codecop/datagen.py +766 -0
  34. codecop/datagen_postgres.py +630 -0
  35. codecop/datagen_sqlite.py +323 -0
  36. codecop/dbcli.py +885 -0
  37. codecop/definitions.py +457 -0
  38. codecop/discover/__init__.py +702 -0
  39. codecop/discover/arms.py +160 -0
  40. codecop/discover/base.py +234 -0
  41. codecop/discover/dialect.py +296 -0
  42. codecop/discover/elixir.py +64 -0
  43. codecop/discover/engine_go.py +320 -0
  44. codecop/discover/go.py +1947 -0
  45. codecop/discover/java.py +1528 -0
  46. codecop/discover/loops.py +1671 -0
  47. codecop/discover/named_go.py +258 -0
  48. codecop/discover/origins.py +4565 -0
  49. codecop/discover/origins_ts.py +1584 -0
  50. codecop/discover/orm_django.py +2772 -0
  51. codecop/discover/orm_django_models.py +814 -0
  52. codecop/discover/orm_django_sql.py +662 -0
  53. codecop/discover/orm_ent.py +565 -0
  54. codecop/discover/orm_ex_ecto.py +2138 -0
  55. codecop/discover/orm_go.py +2134 -0
  56. codecop/discover/orm_go_bun.py +602 -0
  57. codecop/discover/orm_go_run.py +636 -0
  58. codecop/discover/orm_go_types.py +1082 -0
  59. codecop/discover/orm_java.py +1450 -0
  60. codecop/discover/orm_jdbi.py +743 -0
  61. codecop/discover/orm_jooq.py +806 -0
  62. codecop/discover/orm_jpa.py +1307 -0
  63. codecop/discover/orm_mybatis.py +730 -0
  64. codecop/discover/orm_py.py +557 -0
  65. codecop/discover/orm_py_peewee.py +1266 -0
  66. codecop/discover/orm_py_prisma.py +298 -0
  67. codecop/discover/orm_rb_activerecord.py +1906 -0
  68. codecop/discover/orm_rust.py +1248 -0
  69. codecop/discover/orm_rust_seaorm.py +734 -0
  70. codecop/discover/orm_sqlalchemy.py +2475 -0
  71. codecop/discover/orm_stats.py +307 -0
  72. codecop/discover/orm_tables.py +29 -0
  73. codecop/discover/orm_ts.py +503 -0
  74. codecop/discover/orm_ts_drizzle.py +697 -0
  75. codecop/discover/orm_ts_knex.py +1117 -0
  76. codecop/discover/orm_ts_kysely.py +861 -0
  77. codecop/discover/orm_ts_prisma.py +1045 -0
  78. codecop/discover/orm_ts_schema.py +169 -0
  79. codecop/discover/orm_ts_sequelize.py +1401 -0
  80. codecop/discover/orm_ts_typeorm.py +1067 -0
  81. codecop/discover/probes.py +323 -0
  82. codecop/discover/python.py +595 -0
  83. codecop/discover/ruby.py +793 -0
  84. codecop/discover/rust.py +2378 -0
  85. codecop/discover/schema.py +520 -0
  86. codecop/discover/schema_ent.py +145 -0
  87. codecop/discover/schema_ts.py +420 -0
  88. codecop/discover/tsresolve.py +257 -0
  89. codecop/discover/typescript.py +1728 -0
  90. codecop/discover/xml_mapper.py +526 -0
  91. codecop/engines/__init__.py +515 -0
  92. codecop/engines/base.py +498 -0
  93. codecop/engines/clickhouse.py +1558 -0
  94. codecop/engines/pg_ddl.py +444 -0
  95. codecop/engines/pg_hints.py +137 -0
  96. codecop/engines/postgres.py +1060 -0
  97. codecop/engines/sqlite.py +742 -0
  98. codecop/families/__init__.py +3 -0
  99. codecop/families/build.py +280 -0
  100. codecop/families/cli.py +177 -0
  101. codecop/families/coverage_hook.py +62 -0
  102. codecop/families/driver.py +221 -0
  103. codecop/families/goslice.py +229 -0
  104. codecop/families/goslice_tool/go.mod +3 -0
  105. codecop/families/goslice_tool/main.go +403 -0
  106. codecop/families/holes.py +451 -0
  107. codecop/families/images/Dockerfile.go +5 -0
  108. codecop/families/images/Dockerfile.python +4 -0
  109. codecop/families/images/Dockerfile.rust +4 -0
  110. codecop/families/isolate.py +171 -0
  111. codecop/families/locate.py +270 -0
  112. codecop/families/model.py +301 -0
  113. codecop/families/plangate.py +271 -0
  114. codecop/families/tagpatch.py +174 -0
  115. codecop/fidelity.py +671 -0
  116. codecop/fixgroups.py +130 -0
  117. codecop/formerly.py +91 -0
  118. codecop/grantscript.py +254 -0
  119. codecop/groupbench.py +1375 -0
  120. codecop/groups.py +594 -0
  121. codecop/groups_view.py +186 -0
  122. codecop/heat.py +1405 -0
  123. codecop/heatcli.py +219 -0
  124. codecop/joins.py +1749 -0
  125. codecop/joins_view.py +127 -0
  126. codecop/kinds/__init__.py +507 -0
  127. codecop/kinds/calls/__init__.py +501 -0
  128. codecop/kinds/calls/extract.py +1097 -0
  129. codecop/kinds/calls/harness.py +408 -0
  130. codecop/kinds/calls/measure.py +342 -0
  131. codecop/kinds/calls/rules.py +139 -0
  132. codecop/kinds/calls/runners/RunCalls.java +167 -0
  133. codecop/kinds/calls/runners/run_go.go +141 -0
  134. codecop/kinds/calls/runners/run_node.js +186 -0
  135. codecop/kinds/calls/runners/run_python.py +319 -0
  136. codecop/kinds/calls/runners/run_rust.rs +200 -0
  137. codecop/kinds/calls/standin.py +340 -0
  138. codecop/kinds/pipeline.py +288 -0
  139. codecop/kinds/regex/__init__.py +1167 -0
  140. codecop/kinds/regex/engines/RegexHarness.java +129 -0
  141. codecop/kinds/regex/engines/run_go.go +294 -0
  142. codecop/kinds/regex/engines/run_node.js +99 -0
  143. codecop/kinds/regex/engines/run_python.py +295 -0
  144. codecop/kinds/regex/engines/run_rust.rs +149 -0
  145. codecop/kinds/regex/extract.py +1438 -0
  146. codecop/kinds/regex/harness.py +235 -0
  147. codecop/kinds/regex/measure.py +270 -0
  148. codecop/kinds/regex/shapes.py +418 -0
  149. codecop/kinds/regex/syntax.py +1721 -0
  150. codecop/kinds/testkind.py +107 -0
  151. codecop/kinds/transaction/__init__.py +228 -0
  152. codecop/kinds/transaction/bind.py +355 -0
  153. codecop/kinds/transaction/measure.py +264 -0
  154. codecop/kinds/transaction/plan.py +462 -0
  155. codecop/kinds/transaction/rules.py +540 -0
  156. codecop/kinds/transaction/sandbox.py +94 -0
  157. codecop/kinds/transaction/scenarios.py +520 -0
  158. codecop/kinds/transaction/schedule.py +483 -0
  159. codecop/kinds/transaction/shapes.py +418 -0
  160. codecop/kinds/transaction/verify.py +293 -0
  161. codecop/live.py +237 -0
  162. codecop/loopbench.py +2071 -0
  163. codecop/loopschema.py +591 -0
  164. codecop/mcpserver.py +120 -0
  165. codecop/mechanism.py +214 -0
  166. codecop/members.py +200 -0
  167. codecop/multi.py +443 -0
  168. codecop/observed.py +1868 -0
  169. codecop/parts.py +102 -0
  170. codecop/patterns.py +830 -0
  171. codecop/patterns_view.py +559 -0
  172. codecop/plangate.py +242 -0
  173. codecop/profile.py +439 -0
  174. codecop/prompts/areas.md +19 -0
  175. codecop/prompts/observed_variants.md +20 -0
  176. codecop/prompts/profile.md +60 -0
  177. codecop/prompts/profile_postgres.md +68 -0
  178. codecop/prompts/profile_sizes.md +26 -0
  179. codecop/prompts/profile_sqlite.md +69 -0
  180. codecop/prompts/rank.md +84 -0
  181. codecop/prompts/rank_postgres.md +96 -0
  182. codecop/prompts/rank_sqlite.md +94 -0
  183. codecop/prompts/scenario_variants.md +20 -0
  184. codecop/rank.py +1473 -0
  185. codecop/realdb/__init__.py +688 -0
  186. codecop/realdb/clickhouse.py +1223 -0
  187. codecop/realdb/facts.py +815 -0
  188. codecop/realdb/locality.py +964 -0
  189. codecop/realdb/locks.py +355 -0
  190. codecop/realdb/match.py +531 -0
  191. codecop/realdb/postgres.py +643 -0
  192. codecop/realdb/ratios.py +77 -0
  193. codecop/realdb/sample.py +126 -0
  194. codecop/relations.py +227 -0
  195. codecop/report.py +1854 -0
  196. codecop/resources.py +332 -0
  197. codecop/resources_view.py +266 -0
  198. codecop/rules/entry_points.toml +1013 -0
  199. codecop/rules/sinks.toml +362 -0
  200. codecop/runsonce.py +8 -0
  201. codecop/sandboxschema.py +555 -0
  202. codecop/scenario_agent.py +172 -0
  203. codecop/scenario_bind.py +507 -0
  204. codecop/scenario_sql.py +971 -0
  205. codecop/scenarios.py +675 -0
  206. codecop/scenarios_view.py +274 -0
  207. codecop/schemacli.py +67 -0
  208. codecop/schemas/areas_output.schema.json +21 -0
  209. codecop/schemas/profile_output.schema.json +362 -0
  210. codecop/schemas/rank_output.schema.json +385 -0
  211. codecop/sizes.py +200 -0
  212. codecop/sqlinfo.py +558 -0
  213. codecop/typedparams.py +576 -0
  214. codecop/verdicts.py +212 -0
  215. codecop/writebench.py +720 -0
  216. codecop/writecost.py +440 -0
  217. codecop/writes.py +1208 -0
  218. codecop-0.1.0.dist-info/METADATA +42 -0
  219. codecop-0.1.0.dist-info/RECORD +222 -0
  220. codecop-0.1.0.dist-info/WHEEL +4 -0
  221. codecop-0.1.0.dist-info/entry_points.txt +2 -0
  222. codecop-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,515 @@
1
+ """Engines CodeCop can rank, profile, benchmark and report on.
2
+
3
+ Everything after discover goes through one `Engine` per database: which prompts
4
+ the agent gets, which variant kinds and cause codes it may return, how the
5
+ sandbox is started, how a table's access paths are described, and what the
6
+ report says about the limits of the run. Adding an engine is one subclass here
7
+ plus its adapter module; rank.py, profile.py, bench.py and report.py do not
8
+ name an engine.
9
+
10
+ engines.get("postgres").sandbox("17") # a context manager, see base.py for its methods
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import copy
16
+ import re
17
+
18
+ from .base import Measurement, QueryError, SandboxError, find_runtime, image_ready, list_sandboxes # noqa: F401
19
+
20
+ # Cause codes every engine shares. Each engine adds its own.
21
+ COMMON_CAUSES = ("wide_read", "heavy_columns", "per_row_function", "full_sort", "offset_paging", "leading_wildcard", "in_loop",
22
+ "unbounded_result", "repeated_read", "join_order", "no_partition_pruning", "cross_tenant_scan", "other")
23
+
24
+
25
+ class Engine:
26
+ name = ""
27
+ label = ""
28
+ rank_prompt = "rank"
29
+ profile_prompt = "profile"
30
+ variant_kinds: tuple[str, ...] = ()
31
+ cause_codes: tuple[str, ...] = ()
32
+ delivery: dict[str, str] = {} # variant kind -> how the fix is delivered
33
+ limits: tuple[str, ...] = ()
34
+ evidence = "" # one line: what the numbers are
35
+ # The sandbox image and the versions the sandbox's own SQL works on. `min_version` is the oldest server every
36
+ # statement CodeCop sends is valid on (each engine says which features set it); `tested_version` is the newest one
37
+ # the test suite has run against. A repository may target anything: `resolve_version` picks what is benchmarked.
38
+ image = ""
39
+ default_version = ""
40
+ min_version: tuple[int, ...] = ()
41
+ tested_version: tuple[int, ...] = ()
42
+ min_reason = ""
43
+ in_process = False # True: the sandbox runs in this process (no container runtime, no image)
44
+ auto = True # `codecop scan --engine auto` runs it when it has sites
45
+
46
+ def sandbox(self, version: str, runtime: str | None = None):
47
+ raise NotImplementedError
48
+
49
+ def image_for(self, version: str) -> str:
50
+ return f"{self.image}:{version}" if self.image else ""
51
+
52
+ @property
53
+ def doctor_image(self) -> str:
54
+ """The image `codecop doctor` checks: the one a scan uses when the repository names no version."""
55
+ return self.image_for(self.default_version)
56
+
57
+ def supported_text(self) -> str:
58
+ if not self.min_version:
59
+ return "no sandbox"
60
+ return (f"{'.'.join(map(str, self.min_version))} and newer, tested up to {'.'.join(map(str, self.tested_version))}; "
61
+ f"default {self.default_version}")
62
+
63
+ def resolve_version(self, requested: str | None, source: str = "") -> dict:
64
+ """Which server version the sandbox runs for a repository that targets `requested`.
65
+
66
+ Never raises: an older, unreadable or missing version gets the nearest supported one and a note that says so.
67
+ Returns {engine, requested, source, version, image, changed, reason, note}. `reason` is "" (the requested
68
+ version is used), `older` (below what the sandbox's SQL needs), `unreadable` (no version number in it),
69
+ `none` (nothing was requested) or `newer` (used as asked, but newer than CodeCop was tested with).
70
+ `note` is the sentence the console output, bench.json and the report repeat."""
71
+ asked = (requested or "").strip()
72
+ numbers = version_numbers(asked)
73
+ low = ".".join(map(str, self.min_version))
74
+ out = {"engine": self.name, "requested": asked, "source": source, "version": asked, "image": "", "changed": False,
75
+ "reason": "", "note": ""}
76
+ if not self.min_version:
77
+ return out
78
+ if not asked:
79
+ out.update(version=self.default_version, changed=True, reason="none",
80
+ note=f"no {self.label} version is known for this repository; benchmarked on {self.default_version} (CodeCop's default)")
81
+ elif not numbers:
82
+ out.update(version=self.default_version, changed=True, reason="unreadable",
83
+ note=f"repository targets {self.label} '{asked}', which names no version number; benchmarked on "
84
+ f"{self.default_version} (CodeCop's default)")
85
+ elif numbers[:len(self.min_version)] < self.min_version:
86
+ out.update(version=low, changed=True, reason="older",
87
+ note=f"repository targets {self.label} {asked}; benchmarked on {low}, the oldest version the sandbox "
88
+ f"supports ({self.min_reason}). Plans and available features can differ between the two")
89
+ elif numbers[:len(self.tested_version)] > self.tested_version:
90
+ out.update(reason="newer", note=f"{self.label} {asked} is newer than the newest version CodeCop was tested with "
91
+ f"({'.'.join(map(str, self.tested_version))})")
92
+ out["image"] = self.image_for(out["version"])
93
+ return out
94
+
95
+ def fallback_version(self, resolved: dict, why: str) -> dict:
96
+ """The same record moved to the default version, for when the image of the chosen one can not be had."""
97
+ if not self.min_version or resolved["version"] == self.default_version:
98
+ return resolved
99
+ was = resolved["version"]
100
+ return {**resolved, "version": self.default_version, "image": self.image_for(self.default_version), "changed": True,
101
+ "reason": "no_image",
102
+ "note": (f"repository targets {self.label} {resolved['requested']}; " if resolved["requested"] else "")
103
+ + f"the sandbox image for {was} is not available ({why}); benchmarked on {self.default_version} (CodeCop's default)"}
104
+
105
+ def table_access(self, create_sql: str, name: str, baseline_sql: str, rows_estimate: int | None = None) -> dict:
106
+ raise NotImplementedError
107
+
108
+ def variant_extras(self, variant: dict) -> dict:
109
+ """Fields derived from a variant's setup for the report to draw (the new key, the new index)."""
110
+ return {"new_order_by": []}
111
+
112
+ def skip_reason(self, sql: str) -> str:
113
+ """Why SQL labelled with this engine cannot be a candidate on it, as a coverage reason, or "".
114
+
115
+ other_engine: plainly written for another database, whatever the call site's label says.
116
+ not_a_read: a read the benchmark does not run (a locking read). no_table: only catalog tables."""
117
+ return ""
118
+
119
+ def foreign_sql(self, sql: str) -> bool:
120
+ return bool(self.skip_reason(sql))
121
+
122
+ def site_skip_reason(self, site: dict) -> str:
123
+ """Like skip_reason, from what the call site says beside its SQL: "other_engine" when cheap evidence there
124
+ speaks against this engine although discover labelled the site with it on weak grounds."""
125
+ return ""
126
+
127
+ def canonical_table(self, name: str) -> str:
128
+ """One spelling per table: the sandbox has a single database."""
129
+ name = name.strip().replace("`", "").replace('"', "")
130
+ return name[len("default."):] if name.lower().startswith("default.") else name
131
+
132
+ def merge_scripts(self, best_sql: str, other_sqls: list[str]) -> tuple[str, list[str]]:
133
+ """Fold what other batches' definitions of the same table carry beyond columns into the chosen one.
134
+ Returns the script and short notes on what was added."""
135
+ return best_sql, []
136
+
137
+ def score_bonus(self, site: dict) -> float:
138
+ """Engine-specific shortlist weight for one call site, added to the generic score."""
139
+ return 0.0
140
+
141
+ def prompt_context(self, inventory: dict, names: set[str]) -> str:
142
+ """Extra text for the rank prompt (index statements found in the repo, for example)."""
143
+ return ""
144
+
145
+ def rank_schema(self, schema: dict) -> dict:
146
+ """The rank output schema narrowed to this engine's variant kinds and cause codes."""
147
+ out = copy.deepcopy(schema)
148
+ cand = out["properties"]["candidates"]["items"]["properties"]
149
+ cand["variants"]["items"]["properties"]["kind"]["enum"] = list(self.variant_kinds)
150
+ cand["causes"]["items"]["properties"]["code"]["enum"] = list(self.cause_codes)
151
+ return out
152
+
153
+
154
+ class ClickHouse(Engine):
155
+ name = "clickhouse"
156
+ label = "ClickHouse"
157
+ variant_kinds = ("rewrite", "skip_index", "projection", "ordering_key", "materialized_view", "column_type")
158
+ cause_codes = ("key_not_used", "no_partition_pruning", "final_merge", "wide_read", "heavy_columns", "per_row_function", "full_sort",
159
+ "offset_paging", "leading_wildcard", "in_loop", "unbounded_result", "repeated_read", "join_order",
160
+ "skip_index_ineffective", "cross_tenant_scan", "other")
161
+ delivery = {"rewrite": "code patch", "skip_index": "migration", "projection": "migration + storage cost",
162
+ "ordering_key": "migration plan, manual", "materialized_view": "migration + code patch", "column_type": "migration"}
163
+ limits = (
164
+ "Single ClickHouse server: Distributed, Replicated and Shared engines were replaced by plain local tables.",
165
+ "Measured right after loading in several batches, without forcing a merge.",
166
+ "Data is generated from the profile, so results show how a query scales, not an absolute production speedup.",
167
+ )
168
+ evidence = "rows and bytes read are the evidence"
169
+
170
+ image = "docker.io/clickhouse/clickhouse-server"
171
+ default_version = "25.8"
172
+ # 24.8: the table setting deduplicate_merge_projection_mode (a projection on a ReplacingMergeTree) and the JSON
173
+ # column type (behind allow_experimental_json_type there, which the sandbox turns on when a definition needs it).
174
+ # Run end to end on 24.8, 25.3, 25.8 and 26.3.
175
+ min_version = (24, 8)
176
+ tested_version = (26, 6)
177
+ min_reason = "a projection on a deduplicating table needs deduplicate_merge_projection_mode, which 24.8 added"
178
+
179
+ def sandbox(self, version: str, runtime: str | None = None):
180
+ from .clickhouse import ClickHouseSandbox
181
+ return ClickHouseSandbox(version, runtime=runtime)
182
+
183
+ def table_access(self, create_sql, name, baseline_sql, rows_estimate=None):
184
+ from ..access import table_access
185
+ return table_access(create_sql, name, baseline_sql, rows_estimate)
186
+
187
+ def variant_extras(self, variant: dict) -> dict:
188
+ from ..access import new_order_by
189
+ return {"new_order_by": new_order_by(variant.get("setup_sql") or []) if variant["kind"] in ("ordering_key", "projection") else []}
190
+
191
+
192
+ class Postgres(Engine):
193
+ name = "postgres"
194
+ label = "PostgreSQL"
195
+ rank_prompt = "rank_postgres"
196
+ profile_prompt = "profile_postgres"
197
+ variant_kinds = ("rewrite", "index", "materialized_view", "column_type", "partitioning")
198
+ cause_codes = ("seq_scan", "non_sargable", "missing_join_index", "partial_index_match", "not_covering", "or_conditions",
199
+ "count_scan", "correlated_subquery", "no_gin_index") + COMMON_CAUSES
200
+ delivery = {"rewrite": "code patch", "index": "migration", "materialized_view": "migration + code patch", "column_type": "migration",
201
+ "partitioning": "migration plan, manual"}
202
+ limits = (
203
+ "Single bare PostgreSQL server with default planner settings; production settings (work_mem, random_page_cost) can change a plan.",
204
+ "Measured with parallel query and JIT off, right after VACUUM ANALYZE: no bloat, no dead rows, a complete visibility map.",
205
+ "Parameters are sent as typed literals, so the planner sees each value; a prepared statement on a generic plan can differ.",
206
+ "Extensions the image does not ship, foreign keys, CHECK constraints, triggers and row-level security are left out of the sandbox tables.",
207
+ "Data is generated from the profile, so results show how a query scales, not an absolute production speedup.",
208
+ )
209
+ evidence = "rows scanned and buffers touched are the evidence"
210
+ # tokens that only ClickHouse SQL has: discover labels a few such files postgres when the driver cannot be told apart
211
+ _NOT_POSTGRES = re.compile(
212
+ r"\bFINAL\b|\bPREWHERE\b|\bFORMAT\s+(?:JSON\w*|TSV\w*|CSV\w*|Null)\b|\b(?:toUInt\d+|toInt\d+|toDate(?:Time(?:64)?)?|toStartOf\w+|"
213
+ r"arrayJoin|countIf|sumIf|uniq(?:Exact)?|argMax|argMin|JSONExtract\w*|toString|notEmpty|multiIf|groupArray)\s*\(|"
214
+ r"\{\w+:(?:U?Int\d+|String|DateTime\w*|Array\(|UUID|Date)\b|"
215
+ # and SQLite's own: its catalog, pragmas, conflict clauses and autoincrement keyword
216
+ r"\bsqlite_(?:master|schema|sequence)\b|^\s*PRAGMA\b|\bINSERT\s+OR\s+(?:REPLACE|IGNORE|ABORT|FAIL|ROLLBACK)\b|\bAUTOINCREMENT\b", re.I)
217
+ # labels that rest on the project's default or a package's other files, not on the statement or its handle
218
+ _WEAK_BASES = ("project_choice", "inferred", "default", "package", "")
219
+
220
+ def sandbox(self, version: str, runtime: str | None = None):
221
+ from .postgres import PostgresSandbox
222
+ return PostgresSandbox(version, runtime=runtime)
223
+
224
+ def table_access(self, create_sql, name, baseline_sql, rows_estimate=None):
225
+ from ..access_postgres import table_access
226
+ return table_access(create_sql, name, baseline_sql, rows_estimate)
227
+
228
+ def variant_extras(self, variant: dict) -> dict:
229
+ """`new_order_by` carries the new index's columns, so a console that draws "key before -> after" draws the index."""
230
+ from ..access_postgres import new_index, new_partition_by
231
+ setup = variant.get("setup_sql") or []
232
+ out: dict = {"new_order_by": []}
233
+ ix = new_index(setup) if variant["kind"] in ("index", "materialized_view", "partitioning", "column_type") else None
234
+ if ix:
235
+ out["new_index"] = ix
236
+ if variant["kind"] == "index":
237
+ out["new_order_by"] = ix["columns"]
238
+ if variant["kind"] == "partitioning":
239
+ out["new_partition_by"] = new_partition_by(setup)
240
+ return out
241
+
242
+ # a locking read is part of a write path, and catalog queries are not application data
243
+ _NOT_A_CANDIDATE = re.compile(r"\bpg_catalog\.|\bpg_(?:class|namespace|locks|stat_\w+|advisory\w*)\b", re.I)
244
+ _WHERE = re.compile(r"\bWHERE\b(.*)", re.I | re.S)
245
+ _SIGNALS = (
246
+ # a function or cast around a column in a predicate: the classic way to lose an index
247
+ (re.compile(r"\b(?:lower|upper|date|date_trunc|coalesce|btrim|trim|to_char)\s*\(\s*[\w.]+[^)]*\)\s*(?:=|<|>|LIKE|ILIKE|IN\b|BETWEEN\b)", re.I), 1.5),
248
+ (re.compile(r"[\w.\"]+::(?:text|varchar|date)\s*(?:=|LIKE|ILIKE|IN\b)", re.I), 1.5),
249
+ (re.compile(r"->>?\s*'[^']+'\s*\)?\s*(?:=|<|>|LIKE|ILIKE|IN\b|IS\b)", re.I), 1.0), # filter on a jsonb field
250
+ (re.compile(r"\bILIKE\b", re.I), 1.0),
251
+ (re.compile(r"\bNOT\s+IN\s*\(\s*SELECT\b|\bNOT\s+EXISTS\b", re.I), 0.5),
252
+ (re.compile(r"\bOR\b", re.I), 0.5),
253
+ )
254
+
255
+ image = "docker.io/library/postgres"
256
+ default_version = "17"
257
+ # 12: pg_attribute.attgenerated and pg_partition_tree() (12); hashint8extended, sha512() and the jit setting (11);
258
+ # attidentity and extended statistics (10); max_parallel_workers_per_gather (9.6).
259
+ min_version = (12,)
260
+ tested_version = (18,)
261
+ min_reason = "its catalog queries need pg_attribute.attgenerated and pg_partition_tree, both from 12"
262
+ _LOCKING = re.compile(r"\bFOR\s+(?:NO\s+KEY\s+)?(?:UPDATE|SHARE)\b", re.I)
263
+
264
+ def skip_reason(self, sql: str) -> str:
265
+ sql = sql or ""
266
+ if self._NOT_POSTGRES.search(sql):
267
+ return "other_engine"
268
+ if self._LOCKING.search(sql):
269
+ return "not_a_read"
270
+ return "no_table" if self._NOT_A_CANDIDATE.search(sql) else ""
271
+
272
+ def site_skip_reason(self, site: dict) -> str:
273
+ """A Go call whose statement takes `?` placeholders, labelled PostgreSQL only on the project's or the
274
+ package's word: no database/sql driver for PostgreSQL accepts `?` (discover records `binds` when no library
275
+ of the package rewrites them: discover.engine_go.qmark_binds)."""
276
+ if site.get("binds") == "qmark" and site.get("engine_basis", "") in self._WEAK_BASES:
277
+ return "other_engine"
278
+ return ""
279
+
280
+ def canonical_table(self, name: str) -> str:
281
+ """`public.t` and `t` are the same table on the sandbox's default search path; other schemas are kept."""
282
+ name = name.strip().replace('"', "")
283
+ return name[len("public."):] if name.lower().startswith("public.") else name
284
+
285
+ def merge_scripts(self, best_sql: str, other_sqls: list[str]) -> tuple[str, list[str]]:
286
+ """A Postgres definition is a script. Batches that ran side by side can each know a different subset of a
287
+ table's indexes and enum types: add the CREATE INDEX and CREATE TYPE statements only the others have.
288
+ Indexes are matched by name, then by what they index; a missing index would let a variant "win" by re-adding it."""
289
+ from .pg_ddl import parse_index, split_statements, statement_kind
290
+
291
+ def index_key(stmt: str):
292
+ ix = parse_index(stmt)
293
+ return (ix.name, (ix.method, tuple(c.text for c in ix.columns), tuple(ix.include), ix.where)) if ix else (stmt, stmt)
294
+
295
+ have = split_statements(best_sql)
296
+ names = {index_key(s)[0] for s in have if statement_kind(s) in ("index", "unique_index")}
297
+ shapes = {index_key(s)[1] for s in have if statement_kind(s) in ("index", "unique_index")}
298
+ types = {" ".join(s.split()[:3]).lower() for s in have if statement_kind(s) == "type"}
299
+ add_types, add_indexes = [], []
300
+ for other in other_sqls:
301
+ for stmt in split_statements(other):
302
+ kind = statement_kind(stmt)
303
+ if kind in ("index", "unique_index"):
304
+ name, shape = index_key(stmt)
305
+ if name not in names and shape not in shapes:
306
+ names.add(name)
307
+ shapes.add(shape)
308
+ add_indexes.append(stmt)
309
+ elif kind == "type":
310
+ head = " ".join(stmt.split()[:3]).lower()
311
+ if head not in types:
312
+ types.add(head)
313
+ add_types.append(stmt)
314
+ if not add_types and not add_indexes:
315
+ return best_sql, []
316
+ script = ";\n".join(add_types + [s for s in have] + add_indexes)
317
+ notes = ([f"{len(add_indexes)} index{'es' if len(add_indexes) > 1 else ''} added"] if add_indexes else []) + \
318
+ ([f"{len(add_types)} type{'s' if len(add_types) > 1 else ''} added"] if add_types else [])
319
+ return script, notes
320
+
321
+ def score_bonus(self, site: dict) -> float:
322
+ """Favour reads whose shape tends to defeat indexes, and reads the agent can actually make runnable."""
323
+ sql = site.get("sql") or ""
324
+ where = self._WHERE.search(sql)
325
+ tail = where.group(1) if where else ""
326
+ s = sum(weight for pattern, weight in self._SIGNALS if pattern.search(tail))
327
+ if re.search(r"\bORDER\s+BY\b", sql, re.I) and re.search(r"\bLIMIT\b", sql, re.I):
328
+ s += 1.0 # top-N: needs an index in sort order
329
+ if re.search(r"\bcount\s*\(\s*(?:\*|DISTINCT\b)", sql, re.I):
330
+ s += 0.5
331
+ if re.search(r"\(\s*SELECT\b[^()]*\bWHERE\b[^()]*=\s*\w+\.\w+", sql, re.I):
332
+ s += 0.5 # a subquery that refers to the outer row
333
+ # every run-time fragment is something the agent has to reconstruct; a query made of them rarely becomes runnable
334
+ s -= min(sql.count("«") * 0.75, 4.0)
335
+ s -= 3.0 if len(site.get("tables") or []) > 10 else 0.0
336
+ s -= 2.0 if len(sql) > 6000 else 0.0
337
+ return s
338
+
339
+ def prompt_context(self, inventory: dict, names: set[str]) -> str:
340
+ from .pg_hints import index_hints
341
+ root = (inventory.get("repo") or {}).get("root") or ""
342
+ return index_hints(root, names) if root else "(repository root unknown: search for CREATE INDEX yourself)"
343
+
344
+
345
+ class Sqlite(Engine):
346
+ """SQLite inside the application's process. The sandbox is a database file in this process (engines/sqlite.py): no
347
+ container and no image; the version is the SQLite library this Python runs on."""
348
+ name = "sqlite"
349
+ label = "SQLite"
350
+ rank_prompt = "rank_sqlite"
351
+ profile_prompt = "profile_sqlite"
352
+ in_process = True
353
+ auto = False # `codecop scan --engine auto` runs it only when no server engine has sites (multi.pick)
354
+ variant_kinds = ("rewrite", "index", "column_type")
355
+ cause_codes = ("full_scan", "no_usable_index", "temp_btree_sort", "automatic_index", "non_sargable", "or_conditions",
356
+ "not_covering", "count_scan", "correlated_subquery") + COMMON_CAUSES
357
+ delivery = {"rewrite": "code patch", "index": "migration", "column_type": "migration"}
358
+ limits = (
359
+ "SQLite in this process, on the library Python links; the application's own SQLite build, version, page size and pragmas "
360
+ "(cache_size, mmap_size, journal mode) can differ, and so can its plans.",
361
+ "No ANALYZE was run: like most applications, the planner has no sqlite_stat1 and uses its own estimates. An application "
362
+ "that runs ANALYZE or PRAGMA optimize can get other plans.",
363
+ "Pages are the pages a statement asked the pager for (cache hits plus misses) times the page size; 'rows' are rows a "
364
+ "full table scan stepped over, so a statement that only searches indexes reads 0 such rows. Pages decide.",
365
+ "A statement costs no network round trip in SQLite: batching N statements into one saves their per-statement work "
366
+ "(prepare, bind, step), not network time.",
367
+ "Foreign keys, CHECK constraints and triggers are left out of the sandbox tables.",
368
+ "Data is generated from the profile, so results show how a query scales, not an absolute production speedup.",
369
+ )
370
+ evidence = "pages asked of the pager and full-scan rows are the evidence"
371
+ # in-process: there is no image, and every version runs on the library at hand
372
+ image = ""
373
+ default_version = ""
374
+ min_version = ()
375
+ tested_version = ()
376
+ work_dir: str | None = None # where the sandbox's database file is made; cli bench sets the run's out dir
377
+ _NOT_SQLITE = re.compile(
378
+ r"\bFINAL\b|\bPREWHERE\b|\{\w+:(?:U?Int\d+|String|DateTime\w*|Array\(|UUID|Date)\b|\b(?:toUInt\d+|toDateTime|arrayJoin|countIf|argMax)\s*\(|"
379
+ r"\bILIKE\b|::\s*[a-z]|\bpg_catalog\.|\bjsonb_\w+\s*\(|\bDISTINCT\s+ON\b|\bFOR\s+(?:NO\s+KEY\s+)?(?:UPDATE|SHARE)\b", re.I)
380
+ _CATALOG = re.compile(r"\bsqlite_(?:master|schema|sequence|stat\d)\b|^\s*PRAGMA\b", re.I)
381
+
382
+ def sandbox(self, version: str, runtime: str | None = None):
383
+ from .sqlite import SqliteSandbox
384
+ return SqliteSandbox(version, runtime=runtime, work_dir=self.work_dir)
385
+
386
+ def supported_text(self) -> str:
387
+ import sqlite3
388
+ return f"in-process, on the SQLite library this Python links ({sqlite3.sqlite_version})"
389
+
390
+ def resolve_version(self, requested: str | None, source: str = "") -> dict:
391
+ import sqlite3
392
+ asked = (requested or "").strip()
393
+ have = sqlite3.sqlite_version
394
+ note = (f"the repository targets SQLite {asked}; benchmarked in-process on the SQLite library this Python links, {have}"
395
+ if asked and version_numbers(asked)[:2] != version_numbers(have)[:2] else "")
396
+ return {"engine": self.name, "requested": asked, "source": source, "version": have, "image": "", "changed": bool(note),
397
+ "reason": "library" if note else "", "note": note}
398
+
399
+ def fallback_version(self, resolved: dict, why: str) -> dict:
400
+ return resolved
401
+
402
+ def table_access(self, create_sql, name, baseline_sql, rows_estimate=None):
403
+ from ..access_postgres import table_access
404
+ from .sqlite import normalize_ddl
405
+ out = table_access(normalize_ddl(create_sql or ""), name, baseline_sql, rows_estimate)
406
+ out["engine"] = "sqlite"
407
+ return out
408
+
409
+ def variant_extras(self, variant: dict) -> dict:
410
+ from ..access_postgres import new_index
411
+ from .sqlite import normalize_ddl
412
+ out: dict = {"new_order_by": []}
413
+ ix = new_index([normalize_ddl(s) for s in variant.get("setup_sql") or []]) if variant["kind"] == "index" else None
414
+ if ix:
415
+ out["new_index"] = ix
416
+ out["new_order_by"] = ix["columns"]
417
+ return out
418
+
419
+ def skip_reason(self, sql: str) -> str:
420
+ sql = sql or ""
421
+ if self._NOT_SQLITE.search(sql):
422
+ return "other_engine"
423
+ return "no_table" if self._CATALOG.search(sql) else ""
424
+
425
+ def canonical_table(self, name: str) -> str:
426
+ """`main.t` and `t` are the same table; quoting does not matter."""
427
+ name = name.strip().replace('"', "").replace("`", "").replace("[", "").replace("]", "")
428
+ return name.split(".", 1)[1] if name.lower().startswith(("main.", "temp.")) else name
429
+
430
+ def score_bonus(self, site: dict) -> float:
431
+ """Reads SQLite tends to run as a full scan, and the per-row reads of a loop (the main cost in-process)."""
432
+ sql = site.get("sql") or ""
433
+ where = re.search(r"\bWHERE\b(.*)", sql, re.I | re.S)
434
+ tail = where.group(1) if where else ""
435
+ s = 0.0
436
+ if re.search(r"\b(?:lower|upper|substr|trim|date|datetime|strftime|json_extract|coalesce|ifnull)\s*\(\s*[\w.]+", tail, re.I):
437
+ s += 1.5
438
+ if re.search(r"\bLIKE\s+'%|\bLIKE\s+\?\s*\|\|", tail, re.I) or re.search(r"'%'\s*\|\|", tail):
439
+ s += 1.0
440
+ if re.search(r"\bORDER\s+BY\b", sql, re.I) and re.search(r"\bLIMIT\b", sql, re.I):
441
+ s += 1.0
442
+ if re.search(r"\bOR\b", tail, re.I):
443
+ s += 0.5
444
+ if site.get("in_loop") or site.get("loop_context"):
445
+ s += 1.0
446
+ s -= min(sql.count("«") * 0.75, 4.0)
447
+ return s
448
+
449
+ def prompt_context(self, inventory: dict, names: set[str]) -> str:
450
+ from .pg_hints import index_hints
451
+ root = (inventory.get("repo") or {}).get("root") or ""
452
+ return index_hints(root, names) if root else "(repository root unknown: search for CREATE INDEX yourself)"
453
+
454
+
455
+ def sql_dialect(engine: str) -> str:
456
+ """The sqlglot dialect CodeCop reads an engine's statements with (ClickHouse when nothing better is known)."""
457
+ return engine if engine in ("clickhouse", "postgres", "sqlite") else "clickhouse"
458
+
459
+
460
+ def version_numbers(text: str) -> tuple[int, ...]:
461
+ """'15.6' -> (15, 6); '16-alpine' -> (16,); '26.3.62.3' -> (26, 3, 62, 3); 'latest' -> ()."""
462
+ m = re.match(r"\s*v?(\d+(?:\.\d+)*)", text or "")
463
+ return tuple(int(x) for x in m.group(1).split(".")) if m else ()
464
+
465
+
466
+ def sandbox_plan(engine_name: str, requested: str | None, source: str = "", *, runtime: str | None = None, pull: bool = True,
467
+ log=lambda msg: None) -> dict:
468
+ """The version a run will be benchmarked on, with its image checked: `resolve_version` plus `image_ok`, `image_state`.
469
+
470
+ When the image of the chosen version can not be had (a version that was never published), the engine's default
471
+ is tried, and the note says so. Raises SandboxError when there is no container runtime; `image_ok` False means
472
+ nothing can be benchmarked on this machine as it is."""
473
+ eng = get(engine_name)
474
+ plan = eng.resolve_version(requested, source)
475
+ if getattr(eng, "in_process", False):
476
+ return {**plan, "image_ok": True, "image_state": "in-process", "runtime": "in-process"}
477
+ if not eng.min_version:
478
+ return {**plan, "image_ok": False, "image_state": f"no sandbox adapter for engine '{engine_name}'", "runtime": ""}
479
+ rt = runtime or find_runtime()
480
+ ok, state = image_ready(plan["image"], rt, pull, log)
481
+ if not ok and plan["version"] != eng.default_version:
482
+ second = eng.fallback_version(plan, state)
483
+ ok2, state2 = image_ready(second["image"], rt, pull, log)
484
+ if ok2:
485
+ plan, ok, state = second, ok2, state2
486
+ return {**plan, "image_ok": ok, "image_state": state, "runtime": rt}
487
+
488
+
489
+ ENGINES: dict[str, Engine] = {"clickhouse": ClickHouse(), "postgres": Postgres(), "sqlite": Sqlite()}
490
+ ALIASES = {"postgresql": "postgres", "pg": "postgres", "ch": "clickhouse", "sqlite3": "sqlite"}
491
+
492
+
493
+ class Unsupported(Engine):
494
+ """An engine discover can label but nothing can benchmark yet. rank still builds a prompt for it, as it always did."""
495
+ variant_kinds = ClickHouse.variant_kinds
496
+ cause_codes = ClickHouse.cause_codes
497
+ evidence = ClickHouse.evidence
498
+
499
+ def __init__(self, name: str):
500
+ self.name = self.label = name
501
+
502
+ def sandbox(self, version: str, runtime: str | None = None):
503
+ raise SandboxError(f"No sandbox adapter for engine '{self.name}'. Supported: {', '.join(ENGINES)}.")
504
+
505
+ def table_access(self, create_sql, name, baseline_sql, rows_estimate=None):
506
+ return {"table": name, "engine": "", "order_by": [], "partition_by": "", "rows_estimate": rows_estimate, "filters": []}
507
+
508
+
509
+ def get(name: str) -> Engine:
510
+ key = ALIASES.get((name or "").lower(), (name or "").lower())
511
+ return ENGINES.get(key) or Unsupported(name or "")
512
+
513
+
514
+ def supported() -> list[str]:
515
+ return list(ENGINES)