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,1060 @@
1
+ """Postgres sandbox adapter: a throwaway server in a container, driven through psql inside it.
2
+
3
+ No port is published and no driver is needed: every statement goes through
4
+ `<runtime> exec -i <container> psql`. This module never connects to anything but
5
+ the container it started.
6
+
7
+ What is measured
8
+ ----------------
9
+ `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)` of the query, one warm-up and then
10
+ `runs` timed executions. From the plan of the fastest timed run:
11
+
12
+ read_rows rows the scan nodes fetched: rows returned plus rows removed by a
13
+ filter or an index recheck, times the node's loops. A sequential
14
+ scan of a 2M-row table that keeps 40 rows reads 2M.
15
+ read_bytes shared buffers touched during execution (hit + read) x block size.
16
+ The analogue of ClickHouse's bytes read. Hit and read are added
17
+ because which of the two a page counts as depends only on what
18
+ happens to be cached.
19
+ result_rows rows the top node returned.
20
+
21
+ These two are the primary evidence: they depend on the plan and the data, not on
22
+ the machine, and repeat exactly from run to run. Execution and planning time are
23
+ recorded and secondary. Also kept: rows removed by filters, temp blocks (a sort or
24
+ hash that spilled), every scan node with its relation, index and conditions, and
25
+ an order-insensitive hash of the result for the same-results check.
26
+
27
+ Measurement settings: parallel query off and JIT off, so buffers and rows are not
28
+ split across workers and timings do not include compilation. Parameters written
29
+ `{name:type}` are sent as typed literals, so the planner sees the value (a custom
30
+ plan), as it does for the first executions of a prepared statement.
31
+
32
+ What the sandbox cannot honour is stripped and reported, never silently dropped:
33
+ extensions the image does not ship (their types become text, their indexes are
34
+ left out), foreign keys, CHECK and EXCLUDE constraints, triggers, policies,
35
+ grants, tablespaces.
36
+ """
37
+
38
+ from __future__ import annotations
39
+
40
+ import hashlib
41
+ import json
42
+ import re
43
+ import subprocess
44
+ import time
45
+ import uuid
46
+ from dataclasses import dataclass, field
47
+
48
+ from .base import Measurement, QueryError, SandboxError, find_runtime, outside_quotes
49
+ from .pg_ddl import check_constraints, check_domain, parse_table, split_statements, statement_kind, strip_constraints, unquote
50
+
51
+ IMAGE = "docker.io/library/postgres"
52
+ MARK = "@@codecop@@"
53
+ MAX_QUERY_SECONDS = 180 # the same limit as the ClickHouse sandbox
54
+ PARAM = re.compile(r"\{(\w+)(?::([^{}]+))?\}")
55
+ SCAN_NODES = ("Seq Scan", "Index Scan", "Index Only Scan", "Bitmap Heap Scan", "Tid Scan", "Tid Range Scan", "Sample Scan", "Foreign Scan")
56
+ # a type or function that comes from an extension -> the extension to try
57
+ TYPE_EXTENSION = {"citext": "citext", "vector": "vector", "halfvec": "vector", "sparsevec": "vector", "ltree": "ltree", "lquery": "ltree",
58
+ "hstore": "hstore", "geometry": "postgis", "geography": "postgis", "cube": "cube", "isn": "isn"}
59
+ FUNCTION_EXTENSION = {"uuid_generate_v4": "uuid-ossp", "uuid_generate_v1": "uuid-ossp", "uuid_generate_v1mc": "uuid-ossp",
60
+ "gen_random_bytes": "pgcrypto", "crypt": "pgcrypto", "digest": "pgcrypto", "similarity": "pg_trgm",
61
+ "unaccent": "unaccent", "uuid_generate_v7": "pg_uuidv7"}
62
+ OPCLASS_EXTENSION = {"gin_trgm_ops": "pg_trgm", "gist_trgm_ops": "pg_trgm", "vector_cosine_ops": "vector", "vector_l2_ops": "vector",
63
+ "vector_ip_ops": "vector", "gist_ltree_ops": "ltree"}
64
+
65
+
66
+ CLOCK_CALL = re.compile(r"\b(?:now|transaction_timestamp|statement_timestamp|clock_timestamp)\s*\(\s*\)|\bCURRENT_TIMESTAMP\b(?:\s*\(\s*\d+\s*\))?", re.I)
67
+
68
+
69
+ def quoted(name: str) -> str:
70
+ """A table or column name exactly as given, quoted: Event -> "Event", audit.Log -> "audit"."Log"."""
71
+ return ".".join('"' + p.replace('"', '""') + '"' for p in name.split("."))
72
+
73
+
74
+ @dataclass
75
+ class PgMeasurement(Measurement):
76
+ shared_hit_blocks: int = 0
77
+ shared_read_blocks: int = 0
78
+ temp_blocks: int = 0 # temp blocks read + written: a sort or hash that spilled to disk
79
+ rows_removed: int = 0 # rows fetched and then thrown away by a filter or recheck
80
+ planning_ms: float = 0.0
81
+ execution_ms: float = 0.0
82
+ node_types: list[str] = field(default_factory=list) # distinct scan node types, e.g. ["Index Only Scan", "Seq Scan"]
83
+ scans: list[dict] = field(default_factory=list) # every scan node: node, relation, index, rows, removed, loops, cond, filter
84
+ block_size: int = 8192
85
+
86
+
87
+ _DOLLAR_TAG = re.compile(r"\$([A-Za-z_]\w*)?\$")
88
+
89
+
90
+ def open_quote(script: str) -> bool:
91
+ """Whether the SQL text ends inside a quoted string, a quoted identifier, a dollar-quoted body or a block comment
92
+ (what psql would wait on for more input). Line comments and psql's backslash lines outside quotes are skipped."""
93
+ i, n = 0, len(script or "")
94
+ s = script or ""
95
+ while i < n:
96
+ c = s[i]
97
+ if c == "-" and s.startswith("--", i):
98
+ j = s.find("\n", i)
99
+ i = n if j < 0 else j + 1
100
+ elif c == "/" and s.startswith("/*", i):
101
+ depth, i = 1, i + 2
102
+ while i < n and depth:
103
+ if s.startswith("/*", i):
104
+ depth, i = depth + 1, i + 2
105
+ elif s.startswith("*/", i):
106
+ depth, i = depth - 1, i + 2
107
+ else:
108
+ i += 1
109
+ if depth:
110
+ return True
111
+ elif c in ("'", '"'):
112
+ j = i + 1
113
+ while True:
114
+ j = s.find(c, j)
115
+ if j < 0:
116
+ return True
117
+ if s.startswith(c * 2, j):
118
+ j += 2
119
+ continue
120
+ break
121
+ i = j + 1
122
+ elif c == "$":
123
+ m = _DOLLAR_TAG.match(s, i)
124
+ if m and (i == 0 or not (s[i - 1].isalnum() or s[i - 1] == "_")):
125
+ j = s.find(m.group(0), m.end())
126
+ if j < 0:
127
+ return True
128
+ i = j + len(m.group(0))
129
+ else:
130
+ i += 1
131
+ else:
132
+ nxt = _SPECIAL.search(s, i + 1)
133
+ i = nxt.start() if nxt else n
134
+ return False
135
+
136
+
137
+ _SPECIAL = re.compile(r"[-/'\"$]")
138
+
139
+
140
+ def render_params(sql: str, params: dict | None) -> str:
141
+ """{name:type} -> CAST('value' AS type). A parameter with no value is left as written, so the server names it in its error."""
142
+ params = params or {}
143
+
144
+ def one(m: re.Match) -> str:
145
+ name, typ = m.group(1), m.group(2)
146
+ if name not in params:
147
+ return m.group(0)
148
+ value = params[name]
149
+ if value is None or str(value).upper() == "NULL":
150
+ return f"CAST(NULL AS {typ})" if typ else "NULL"
151
+ lit = "'" + str(value).replace("'", "''") + "'"
152
+ return f"CAST({lit} AS {typ.strip()})" if typ else lit
153
+ return PARAM.sub(one, sql)
154
+
155
+
156
+ def _total(node: dict, key: str) -> float:
157
+ return float(node.get(key) or 0) * float(node.get("Actual Loops") or 0)
158
+
159
+
160
+ def walk_plan(node: dict, scans: list[dict], extra: dict) -> None:
161
+ kind = node.get("Node Type", "")
162
+ if kind in SCAN_NODES:
163
+ returned = _total(node, "Actual Rows")
164
+ removed = _total(node, "Rows Removed by Filter") + _total(node, "Rows Removed by Index Recheck")
165
+ scans.append({
166
+ "node": kind, "relation": node.get("Relation Name", ""), "index": node.get("Index Name", ""),
167
+ "rows": int(round(returned + removed)), "returned": int(round(returned)), "removed": int(round(removed)),
168
+ "loops": int(node.get("Actual Loops") or 0), "heap_fetches": int(_total(node, "Heap Fetches")),
169
+ "cond": str(node.get("Index Cond") or node.get("Recheck Cond") or "")[:200], "filter": str(node.get("Filter") or "")[:200],
170
+ })
171
+ if kind == "Bitmap Index Scan":
172
+ extra.setdefault("bitmap_indexes", []).append(node.get("Index Name", ""))
173
+ # sort and hash memory of the plan nodes (Hash, HashAggregate, Memoize: Peak Memory Usage; a Sort in memory; PostgreSQL
174
+ # 17's WindowAgg, Material and CTE Scan: Maximum Storage in memory). What went to disk is counted apart (spill_kb).
175
+ extra["memory_kb"] = extra.get("memory_kb", 0) + int(node.get("Peak Memory Usage") or 0) + (
176
+ int(node.get("Sort Space Used") or 0) if node.get("Sort Space Type") == "Memory" else 0) + (
177
+ int(node.get("Maximum Storage") or 0) if node.get("Storage Type") == "Memory" else 0)
178
+ extra["spill_kb"] = extra.get("spill_kb", 0) + int(node.get("Disk Usage") or 0) + (
179
+ int(node.get("Sort Space Used") or 0) if node.get("Sort Space Type") == "Disk" else 0) + (
180
+ int(node.get("Maximum Storage") or 0) if node.get("Storage Type") == "Disk" else 0)
181
+ for child in node.get("Plans") or []:
182
+ walk_plan(child, scans, extra)
183
+
184
+
185
+ def plan_text(node: dict, depth: int = 0) -> str:
186
+ """A compact, stable text plan: one line per node with what it read."""
187
+ bits = [node.get("Node Type", "?")]
188
+ if node.get("Index Name"):
189
+ bits.append(f"using {node['Index Name']}")
190
+ if node.get("Relation Name"):
191
+ bits.append(f"on {node['Relation Name']}")
192
+ loops = int(node.get("Actual Loops") or 0)
193
+ facts = [f"rows={float(node.get('Actual Rows') or 0):g}" + (f" x{loops}" if loops != 1 else "")]
194
+ for key, label in (("Rows Removed by Filter", "removed"), ("Rows Removed by Index Recheck", "rechecked"), ("Heap Fetches", "heap fetches")):
195
+ if node.get(key):
196
+ facts.append(f"{label}={float(node[key]):g}")
197
+ buffers = int(node.get("Shared Hit Blocks") or 0) + int(node.get("Shared Read Blocks") or 0)
198
+ if buffers:
199
+ facts.append(f"buffers={buffers}")
200
+ if node.get("Sort Method"):
201
+ facts.append(f"{node['Sort Method']} {node.get('Sort Space Used', 0)}kB {str(node.get('Sort Space Type', '')).lower()}")
202
+ line = " " * depth + ("-> " if depth else "") + " ".join(bits) + " (" + ", ".join(facts) + ")"
203
+ for key in ("Index Cond", "Recheck Cond", "Filter", "Join Filter", "Hash Cond", "Merge Cond", "Sort Key", "Group Key"):
204
+ if node.get(key):
205
+ value = node[key] if isinstance(node[key], str) else ", ".join(map(str, node[key]))
206
+ line += "\n" + " " * (depth + 2) + f"{key}: {value[:240]}"
207
+ return "\n".join([line] + [plan_text(c, depth + 1) for c in node.get("Plans") or []])
208
+
209
+
210
+ VACUUM_RE = re.compile(r"^\s*VACUUM\b", re.I | re.M)
211
+
212
+
213
+ class PostgresSandbox:
214
+ engine = "postgres"
215
+ label = "PostgreSQL"
216
+ copy_kinds = ("column_type", "partitioning") # variants that copy the whole table once
217
+
218
+ @property
219
+ def activity(self):
220
+ """Seconds of this sandbox's scripts by kind (engines/base.Activity), for bench.json `timing.statements`."""
221
+ from .base import Activity
222
+ got = self.__dict__.get("_activity")
223
+ if got is None:
224
+ got = self.__dict__["_activity"] = Activity()
225
+ return got
226
+ # A baseline that touches no more than this is already cheap: one index descent is 3 to 5 pages,
227
+ # so "reads 60% of the bytes" down there is noise. Both must hold for the floor to apply.
228
+ floor_bytes = 16 * 8192
229
+ pages_decide = True # buffer pages touched are the cost; rows scanned are stated beside them (bench.verdict)
230
+ floor_rows = 200
231
+
232
+ def __init__(self, version: str, name: str | None = None, runtime: str | None = None):
233
+ self.version = version
234
+ self.runtime = runtime or find_runtime()
235
+ self.name = name or f"codecop-pg-{uuid.uuid4().hex[:8]}"
236
+ self.database = "postgres"
237
+ self.stripped: list[str] = [] # everything left out, as "<table>: <what>"
238
+ self._deferred: dict[str, list[str]] = {} # table -> index statements to run after the load
239
+ self._notes: dict[str, list[str]] = {}
240
+ self._meta: dict[str, dict[str, dict]] = {}
241
+ self._before: set[tuple[str, str]] | None = None
242
+ self._tried: set[str] = set()
243
+ self.block_size = 8192
244
+ self._real: dict[str, str] = {} # a table's name without quotes, lower case -> its name as created
245
+ self._checks: dict[str, list[str]] = {} # table -> the CHECK expressions its definition declares
246
+ self._load_notes: dict[str, list[str]] = {} # table -> what the generator changed to respect the definition
247
+ self._maps: dict[tuple, dict] = {} # a parent's key and shared columns -> its lookup tables
248
+ self.clock: str | None = None # the instant now() stands for in measured queries (freeze_clock)
249
+ self.max_relation_parents = 5_000_000 # setting bench.max_relation_parents: parent keys a relation chooses among
250
+
251
+ # ---- lifecycle ------------------------------------------------------
252
+ def start(self, timeout_s: int = 120) -> None:
253
+ import os as _os
254
+ # a busy host (disk wait) can take longer to start a server: CODECOP_SANDBOX_START_TIMEOUT_S raises the wait
255
+ timeout_s = int(_os.environ.get("CODECOP_SANDBOX_START_TIMEOUT_S") or timeout_s)
256
+ image = f"{IMAGE}:{self.version}"
257
+ from .base import reap_orphans, sandbox_run_args, start_container
258
+ self.reaped = reap_orphans(self.runtime) # sandboxes of runs that were killed: their disk comes back first
259
+ cmd = [self.runtime, "run", "-d", "--name", self.name, *sandbox_run_args(self.runtime, self.name, "/var/lib/postgresql/data", image),
260
+ "--shm-size", "1g",
261
+ "-e", "POSTGRES_HOST_AUTH_METHOD=trust", image,
262
+ # durability off: the data is disposable and loads are several times faster. None of these change a plan.
263
+ # max_wal_size: the log a load leaves behind is disk the tables can not use. A large one beside a table
264
+ # sized to the free disk can fill the disk; with fsync off a checkpoint every 2GB costs little.
265
+ "-c", "fsync=off", "-c", "synchronous_commit=off", "-c", "full_page_writes=off", "-c", "max_wal_size=2GB",
266
+ "-c", "checkpoint_timeout=30min", "-c", "shared_buffers=512MB", "-c", "maintenance_work_mem=512MB",
267
+ "-c", "listen_addresses=localhost", "-c", "autovacuum=off"]
268
+ proc = start_container(cmd) # with the caps (engines/base.limit_args); without an I/O cap the runtime refuses
269
+ if proc.returncode != 0:
270
+ self.stop()
271
+ raise SandboxError(f"Could not start {image}: {proc.stderr.strip()[:400]}")
272
+ deadline = time.monotonic() + timeout_s
273
+ while time.monotonic() < deadline:
274
+ # the image first runs a temporary server on the socket only; TCP on localhost answers once the real one is up
275
+ ready = subprocess.run([self.runtime, "exec", self.name, "pg_isready", "-h", "127.0.0.1", "-U", "postgres"], capture_output=True)
276
+ if ready.returncode == 0:
277
+ try:
278
+ if self._psql("SELECT 1").strip() == "1":
279
+ self.block_size = int(self._psql("SHOW block_size").strip() or 8192)
280
+ return
281
+ except SandboxError:
282
+ pass
283
+ time.sleep(0.5)
284
+ logs = subprocess.run([self.runtime, "logs", "--tail", "5", self.name], capture_output=True, text=True)
285
+ self.stop()
286
+ raise SandboxError(f"Postgres {self.version} did not become ready in {timeout_s}s. {(logs.stderr or logs.stdout).strip()[-300:]}")
287
+
288
+ def stop(self) -> None:
289
+ from .base import remove_sandbox
290
+ self._session_close()
291
+ remove_sandbox(self.runtime, self.name) # the container, its anonymous volumes and its data volume
292
+
293
+ def _answers(self) -> bool:
294
+ try:
295
+ return self._psql("SELECT 1", timeout=10).strip() == "1"
296
+ except SandboxError:
297
+ return False
298
+
299
+ def revive(self, timeout_s: int = 90) -> str:
300
+ """After a lost connection: wait out crash recovery, or start the container again if it stopped. The data is still there.
301
+
302
+ Returns why it had stopped ('' when it was still running). Raises SandboxError when it does not come back.
303
+ A backend killed for memory makes the postmaster restart itself, so the container is usually still up
304
+ and only needs a few seconds; a stopped container is started again with the same data volume."""
305
+ if self._answers():
306
+ return ""
307
+ state = subprocess.run([self.runtime, "inspect", "-f", "{{.State.Running}} {{.State.ExitCode}} {{.State.OOMKilled}}", self.name],
308
+ capture_output=True, text=True).stdout.split()
309
+ running = state[:1] == ["true"]
310
+ if running:
311
+ why = "a server process crashed and the server recovered"
312
+ else:
313
+ why = "out of memory" if state[2:] == ["true"] or state[1:2] == ["137"] else f"exit code {state[1]}" if len(state) > 1 else "unknown"
314
+ subprocess.run([self.runtime, "start", self.name], capture_output=True)
315
+ deadline = time.monotonic() + timeout_s
316
+ while time.monotonic() < deadline:
317
+ if self._answers():
318
+ return why
319
+ time.sleep(0.5)
320
+ raise SandboxError(f"The sandbox server stopped ({why}) and did not start again.")
321
+
322
+ def __enter__(self) -> "PostgresSandbox":
323
+ from .base import StopOnSignal
324
+ self._signals = StopOnSignal().__enter__() # SIGTERM ends the run through __exit__, not around it
325
+ try:
326
+ self.start()
327
+ except BaseException:
328
+ self.stop()
329
+ self._signals.__exit__()
330
+ raise
331
+ return self
332
+
333
+ def __exit__(self, *exc) -> None:
334
+ try:
335
+ self.stop()
336
+ finally:
337
+ if getattr(self, "_signals", None):
338
+ self._signals.__exit__()
339
+
340
+ # ---- statements -----------------------------------------------------
341
+ def _psql(self, script: str, timeout: int = 1800) -> str:
342
+ return self._psql_both(script, timeout)[0]
343
+
344
+ # One psql process kept open for the run (`[bench] pg_persistent_session`, default on): a `podman exec` costs a noticeable
345
+ # fraction of a second, and a bench sends thousands of scripts: on a large repository most of its time.
346
+ # Each script still behaves as in a session of its own: the script stops at its first error (ON_ERROR_STOP, which ends
347
+ # the process; the next script starts a new one), and after it every setting, temporary table and prepared statement
348
+ # is discarded (DISCARD ALL) and the output reset. What is measured is the server's own figures (EXPLAIN ANALYZE,
349
+ # log_statement_stats, the WAL position): the client round trip it saves was never part of them.
350
+ persistent: bool = True
351
+
352
+ def _session_start(self):
353
+ import queue
354
+ import threading
355
+ cmd = [self.runtime, "exec", "-i", self.name, "psql", "-X", "-q", "-At", "-v", "ON_ERROR_STOP=1", "-U", "postgres", "-d", self.database]
356
+ proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1)
357
+ qo: queue.Queue = queue.Queue()
358
+ qe: queue.Queue = queue.Queue()
359
+
360
+ def pump(stream, q):
361
+ for line in stream:
362
+ q.put(line)
363
+ q.put(None)
364
+ threading.Thread(target=pump, args=(proc.stdout, qo), daemon=True).start()
365
+ threading.Thread(target=pump, args=(proc.stderr, qe), daemon=True).start()
366
+ self._sess = (proc, qo, qe)
367
+ return self._sess
368
+
369
+ def _session_close(self) -> None:
370
+ sess, self._sess = getattr(self, "_sess", None), None
371
+ if sess is not None:
372
+ try:
373
+ sess[0].stdin.close()
374
+ except Exception: # noqa: BLE001
375
+ pass
376
+ try:
377
+ sess[0].kill()
378
+ sess[0].wait(5)
379
+ except Exception: # noqa: BLE001
380
+ pass
381
+
382
+ def _session_run(self, script: str, timeout: int) -> tuple[str, str]:
383
+ import queue
384
+ lock = getattr(self, "_sess_lock", None)
385
+ if lock is None:
386
+ import threading
387
+ lock = self._sess_lock = threading.Lock()
388
+ with lock:
389
+ sess = getattr(self, "_sess", None)
390
+ if sess is None or sess[0].poll() is not None:
391
+ sess = self._session_start()
392
+ proc, qo, qe = sess
393
+ token = f"codecop-end-{uuid.uuid4().hex}"
394
+ # `;` first: a script whose last statement has no semicolon runs it, as psql does at the end of its input
395
+ tail = (f"\n;\n\\set ON_ERROR_STOP 0\nROLLBACK;\nDISCARD ALL;\n\\set ON_ERROR_STOP 1\n\\o\n\\echo {token}\n\\warn {token}\n")
396
+ try:
397
+ proc.stdin.write(script.rstrip("\n") + tail)
398
+ proc.stdin.flush()
399
+ except (BrokenPipeError, OSError):
400
+ self._session_close() # the server or the container went away between scripts: a new session
401
+ proc, qo, qe = self._session_start()
402
+ proc.stdin.write(script.rstrip("\n") + tail)
403
+ proc.stdin.flush()
404
+ deadline = time.monotonic() + timeout
405
+ out: list[str] = []
406
+ err: list[str] = []
407
+ ended = False
408
+ try:
409
+ for q, acc in ((qo, out), (qe, err)):
410
+ while True:
411
+ line = q.get(timeout=max(deadline - time.monotonic(), 0.01))
412
+ if line is None:
413
+ ended = True
414
+ break
415
+ if line.strip() == token:
416
+ break
417
+ acc.append(line)
418
+ if ended:
419
+ break
420
+ except queue.Empty:
421
+ self._session_close()
422
+ raise QueryError(f"statement did not finish within {timeout}s")
423
+ if ended:
424
+ # the script stopped at an error (psql exits on it) or the connection was lost: as a session of its own did
425
+ while True:
426
+ try:
427
+ line = qe.get(timeout=5)
428
+ except queue.Empty:
429
+ break
430
+ if line is None:
431
+ break
432
+ if line.strip() != token:
433
+ err.append(line)
434
+ try:
435
+ code = proc.wait(10)
436
+ except subprocess.TimeoutExpired:
437
+ code = -1
438
+ self._session_close()
439
+ message = re.sub(r"^psql:<stdin>:\d+:\s*", "", "".join(err).strip(), flags=re.M)
440
+ if code == 3 or "ERROR:" in message:
441
+ raise QueryError(message[:1500])
442
+ raise SandboxError(f"Sandbox not reachable: {message[:400]}")
443
+ text = "".join(err)
444
+ text = re.sub(r"^(?:psql:<stdin>:\d+:\s*)?WARNING:\s+there is no transaction in progress\n?", "", text, flags=re.M)
445
+ return "".join(out), text
446
+
447
+ def _psql_both(self, script: str, timeout: int = 1800) -> tuple[str, str]:
448
+ """(stdout, stderr) of one psql session. The server's LOG messages (log_statement_stats) arrive on stderr."""
449
+ if VACUUM_RE.search(script) and not script.lstrip().upper().startswith("CHECKPOINT"):
450
+ # A VACUUM right after the rows were written marked their pages all-visible or not by luck: with
451
+ # synchronous_commit and fsync off, the commits are not yet flushed and VACUUM may not set the hint bits
452
+ # it needs (measured: 0, 616 or all of 1,870 pages for the same table and script; a CHECKPOINT first, all of
453
+ # them every time). The visibility map decides index-only scans (heap fetches) and plans: verdicts of index
454
+ # variants flipped between runs. A CHECKPOINT first makes it the same every run.
455
+ script = "CHECKPOINT;\n" + script
456
+ from .base import statement_kind
457
+ began = time.monotonic()
458
+ out = self._psql_run(script, timeout)
459
+ self.activity.add(statement_kind(script), began, time.monotonic())
460
+ return out
461
+
462
+ def _psql_run(self, script: str, timeout: int) -> tuple[str, str]:
463
+ if self.persistent and not open_quote(script):
464
+ # (a script that leaves a quote open would swallow the session's end marker: psql waits for the rest of the
465
+ # string until the timeout, 30 minutes. Run on its own, psql reaches the end of its input and says so.)
466
+ return self._session_run(script, timeout)
467
+ cmd = [self.runtime, "exec", "-i", self.name, "psql", "-X", "-q", "-At", "-v", "ON_ERROR_STOP=1", "-U", "postgres", "-d", self.database]
468
+ try:
469
+ proc = subprocess.run(cmd, input=script, capture_output=True, text=True, timeout=timeout)
470
+ except subprocess.TimeoutExpired as e:
471
+ raise QueryError(f"statement did not finish within {timeout}s") from e
472
+ if proc.returncode != 0:
473
+ message = re.sub(r"^psql:<stdin>:\d+:\s*", "", proc.stderr.strip(), flags=re.M)
474
+ if proc.returncode == 3 or "ERROR:" in message:
475
+ raise QueryError(message[:1500])
476
+ raise SandboxError(f"Sandbox not reachable: {message[:400]}")
477
+ return proc.stdout, proc.stderr
478
+
479
+ def execute(self, sql: str, params: dict | None = None, settings: dict | None = None) -> str:
480
+ prefix = "".join(f"SET {k} = {v};\n" for k, v in (settings or {}).items())
481
+ return self._psql(prefix + render_params(sql.strip().rstrip(";"), params) + ";")
482
+
483
+ def rows(self, sql: str, params: dict | None = None) -> list[dict]:
484
+ text = self._psql(f"SELECT coalesce(json_agg(t), '[]'::json) FROM ({render_params(sql.strip().rstrip(';'), params)}) t;")
485
+ return json.loads(text) if text.strip() else []
486
+
487
+ def server_version(self) -> str:
488
+ return self._psql("SHOW server_version").strip().split()[0]
489
+
490
+ def _try(self, sql: str) -> str:
491
+ """Run a statement; return the server's error text, or "" when it worked."""
492
+ try:
493
+ self._psql(sql.strip().rstrip(";") + ";")
494
+ return ""
495
+ except QueryError as e:
496
+ return str(e)
497
+
498
+ def _extension(self, name: str) -> bool:
499
+ return not self._try(f'CREATE EXTENSION IF NOT EXISTS "{name}" CASCADE')
500
+
501
+ def _note(self, table: str, text: str) -> None:
502
+ self._notes.setdefault(table, [])
503
+ if text not in self._notes[table]:
504
+ self._notes[table].append(text)
505
+ self.stripped.append(f"{table}: {text}")
506
+
507
+ # ---- tables ---------------------------------------------------------
508
+ def _repair(self, stmt: str, error: str, table: str) -> str | None:
509
+ """One fix for a statement the bare server rejected, or None when there is nothing to try.
510
+
511
+ Installs the extension when the image ships it; otherwise rewrites the statement and records what was lost."""
512
+ m = re.search(r'type "?([\w.]+)"? does not exist', error)
513
+ if m:
514
+ typ = m.group(1).split(".")[-1]
515
+ ext = TYPE_EXTENSION.get(typ.lower())
516
+ if ext and self._extension(ext):
517
+ return stmt
518
+ new = re.sub(rf'(?<![\w.])(?:\w+\.)?"?{re.escape(typ)}"?(?:\s*\([^)]*\))?(?=\s*(?:\[\]|,|\)|\s|$))', "text", stmt, flags=re.I)
519
+ if new != stmt:
520
+ self._note(table, f"type {typ} not available{' (extension ' + ext + ' not installed)' if ext else ''}: stored as text")
521
+ return new
522
+ return None
523
+ m = re.search(r"function ([\w.]+)\(.*?\) does not exist", error)
524
+ if m:
525
+ fn = m.group(1).split(".")[-1]
526
+ ext = FUNCTION_EXTENSION.get(fn.lower())
527
+ if ext and self._extension(ext):
528
+ return stmt
529
+ new = re.sub(rf"\s+DEFAULT\s+\(?(?:\w+\.)?{re.escape(fn)}\s*\([^)]*\)\)?(?:::\w+)?", "", stmt, flags=re.I)
530
+ if new != stmt:
531
+ self._note(table, f"default {fn}() not available{' (extension ' + ext + ' not installed)' if ext else ''}: default left out")
532
+ return new
533
+ return None
534
+ m = re.search(r'operator class "([\w.]+)" does not exist', error)
535
+ if m:
536
+ ext = OPCLASS_EXTENSION.get(m.group(1).lower())
537
+ return stmt if ext and self._extension(ext) else None
538
+ if re.search(r"has no default operator class for access method \"gin\"", error):
539
+ if "btree_gin" in self._tried:
540
+ return None
541
+ self._tried.add("btree_gin")
542
+ return stmt if self._extension("btree_gin") else None
543
+ m = re.search(r'relation "([\w.]+)" does not exist', error)
544
+ if m and re.search(r"nextval\(", stmt, re.I):
545
+ new = re.sub(r"\s+DEFAULT\s+nextval\([^)]*\)(?:::\w+)?", "", stmt, flags=re.I)
546
+ if new != stmt:
547
+ self._note(table, f"sequence {m.group(1)} not defined: default left out")
548
+ return new
549
+ m = re.search(r'collation "([^"]+)"', error)
550
+ if m:
551
+ new = re.sub(r'\s+COLLATE\s+(?:"[^"]+"|\S+)', "", stmt, flags=re.I)
552
+ if new != stmt:
553
+ self._note(table, f"collation {m.group(1)} not available: default collation used")
554
+ return new
555
+ m = re.search(r'tablespace "([^"]+)" does not exist', error)
556
+ if m:
557
+ new = re.sub(r"\s+(?:USING\s+INDEX\s+)?TABLESPACE\s+\S+", "", stmt, flags=re.I)
558
+ return new if new != stmt else None
559
+ m = re.search(r'schema "([^"]+)" does not exist', error)
560
+ if m and not self._try(f'CREATE SCHEMA IF NOT EXISTS "{m.group(1)}"'):
561
+ return stmt
562
+ return None
563
+
564
+ def _run_ddl(self, stmt: str, table: str) -> str:
565
+ """Run one DDL statement, repairing it while a repair exists. Returns "" or the last error."""
566
+ for _ in range(12):
567
+ error = self._try(stmt)
568
+ if not error:
569
+ return ""
570
+ fixed = self._repair(stmt, error, table)
571
+ if fixed is None:
572
+ return error
573
+ stmt = fixed
574
+ return error
575
+
576
+ def create_table(self, definition: dict | str) -> list[str]:
577
+ """Drop and rebuild one table from the agent's definition: CREATE TABLE plus its indexes, `;`-separated.
578
+
579
+ Unique indexes are built now (they deduplicate the load); the others are kept for finish_table, after the data is in.
580
+ Returns what was stripped."""
581
+ if isinstance(definition, str):
582
+ definition = {"name": parse_table(split_statements(definition)[0]).name, "create_sql": definition}
583
+ name = self._register(definition)
584
+ self._notes[name], self._deferred[name] = [], []
585
+ self._checks[name] = [c["expr"] for c in check_constraints(definition["create_sql"])
586
+ if c["table"].split(".")[-1].lower() == name.split(".")[-1].lower()]
587
+ if "." in name:
588
+ self._psql(f'CREATE SCHEMA IF NOT EXISTS "{name.split(".")[0]}";')
589
+ self._psql(f"DROP TABLE IF EXISTS {self._q(name)} CASCADE;")
590
+ created = False
591
+ for stmt in split_statements(definition["create_sql"]):
592
+ kind = statement_kind(stmt)
593
+ head = re.sub(r"\s+", " ", stmt[:70])
594
+ if kind == "comment":
595
+ continue
596
+ if kind == "extension":
597
+ ext = re.search(r'EXTENSION\s+(?:IF\s+NOT\s+EXISTS\s+)?"?([\w-]+)"?', stmt, re.I)
598
+ if ext and not self._extension(ext.group(1)):
599
+ self._note(name, f"extension {ext.group(1)} not installed in the sandbox image")
600
+ elif kind in ("schema", "type", "sequence", "function"): # a function: a LANGUAGE sql one of the repository (definitions.complete)
601
+ error = self._try(stmt)
602
+ if error and "already exists" not in error:
603
+ self._note(name, f"could not run `{head}`: {error.splitlines()[0][:160]}")
604
+ elif kind == "table":
605
+ stmt, notes = strip_constraints(stmt)
606
+ for n in notes:
607
+ self._note(name, n)
608
+ stmt = re.sub(r"^(\s*CREATE\s+)(?:UNLOGGED\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?", r"\1TABLE IF NOT EXISTS ", stmt, count=1, flags=re.I)
609
+ error = self._run_ddl(stmt, name)
610
+ if error:
611
+ raise QueryError(error)
612
+ created = True
613
+ elif kind == "unique_index":
614
+ error = self._run_ddl(re.sub(r"\bCONCURRENTLY\s+", "", stmt, count=1, flags=re.I), name)
615
+ if error:
616
+ self._note(name, f"index left out (`{head}`): {error.splitlines()[0][:160]}")
617
+ elif kind == "index":
618
+ self._deferred[name].append(re.sub(r"\bCONCURRENTLY\s+", "", stmt, count=1, flags=re.I))
619
+ elif kind == "alter":
620
+ if re.search(r"\bFOREIGN\s+KEY\b|\bCHECK\s*\(|\bROW\s+LEVEL\s+SECURITY\b|\bOWNER\s+TO\b|\bVALIDATE\s+CONSTRAINT\b", stmt, re.I):
621
+ self._note(name, f"left out `{head}`")
622
+ elif (error := self._run_ddl(stmt, name)):
623
+ self._note(name, f"could not run `{head}`: {error.splitlines()[0][:160]}")
624
+ else:
625
+ self._note(name, f"left out `{head}` (not a table, index or type)")
626
+ if not created:
627
+ raise QueryError(f"no CREATE TABLE statement for {name} in its definition")
628
+ # a partitioned table with no partition rejects every row
629
+ partitioned = self._psql(
630
+ f"SELECT c.relkind = 'p' AND NOT EXISTS (SELECT 1 FROM pg_inherits i WHERE i.inhparent = c.oid) "
631
+ f"FROM pg_class c WHERE c.oid = '{self._q(name)}'::regclass;").strip()
632
+ if partitioned == "t":
633
+ self._psql(f"CREATE TABLE {quoted(name + '_codecop_default')} PARTITION OF {self._q(name)} DEFAULT;")
634
+ self._note(name, "no partitions defined: one DEFAULT partition holds all rows, so partition pruning cannot show")
635
+ return list(self._notes[name])
636
+
637
+ # ---- names ----------------------------------------------------------
638
+ # A definition's name reaches the sandbox without its quotes ("Event" arrives as Event), and Postgres folds an
639
+ # unquoted name to lower case. The name as the CREATE TABLE statement wrote it is the table's name: it is read
640
+ # from the definition once and used, quoted, in every statement the sandbox writes.
641
+ def _register(self, definition: dict) -> str:
642
+ given = definition["name"].replace('"', "")
643
+ want = given.split(".")[-1].lower()
644
+ real = None
645
+ for stmt in split_statements(definition.get("create_sql") or ""):
646
+ if statement_kind(stmt) == "table":
647
+ t = parse_table(stmt)
648
+ if t and not t.partition_of and t.name.split(".")[-1].lower() == want:
649
+ real = t.name
650
+ break
651
+ real = real or unquote(definition["name"])
652
+ if real.startswith("public."):
653
+ real = real[len("public."):] if "." not in given else real
654
+ for key in {given.lower(), real.lower(), real.split(".")[-1].lower(), "public." + real.split(".")[-1].lower()}:
655
+ self._real[key] = real
656
+ return real
657
+
658
+ def _name(self, name: str) -> str:
659
+ """The table's name as it was created (see _register); a name the sandbox was never given is read as SQL writes it."""
660
+ return self._real.get(name.replace('"', "").lower()) or unquote(name)
661
+
662
+ def _q(self, name: str) -> str:
663
+ return quoted(self._name(name))
664
+
665
+ def column_types(self, name: str) -> dict[str, str]:
666
+ name = self._name(name)
667
+ cols = self.rows(
668
+ "SELECT a.attname AS name, format_type(a.atttypid, a.atttypmod) AS type, a.attnotnull AS notnull, a.atthasdef AS has_default, "
669
+ "a.attidentity <> '' AS identity, a.attgenerated <> '' AS generated, "
670
+ "(SELECT pg_get_expr(d.adbin, d.adrelid) FROM pg_attrdef d WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum) AS default, "
671
+ "EXISTS (SELECT 1 FROM pg_index i WHERE i.indrelid = a.attrelid AND i.indisunique AND i.indnkeyatts = 1 AND i.indkey[0] = a.attnum "
672
+ "AND i.indpred IS NULL AND i.indexprs IS NULL) AS unique_alone, "
673
+ "(SELECT json_agg(e.enumlabel ORDER BY e.enumsortorder) FROM pg_enum e WHERE e.enumtypid = a.atttypid) AS enum "
674
+ f"FROM pg_attribute a WHERE a.attrelid = '{self._q(name)}'::regclass AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum")
675
+ self._meta[name] = {c["name"]: c for c in cols}
676
+ return {c["name"]: c["type"] for c in cols}
677
+
678
+ def insert_statements(self, name: str, rows: int, columns: list[dict], types: dict[str, str], *,
679
+ fixtures: list[dict] | None = None, placed: dict | None = None,
680
+ relations: list[dict] | None = None) -> list[str]:
681
+ from ..datagen_postgres import insert_statements
682
+ name = self._name(name)
683
+ from ..datagen import REALISM
684
+ domains: dict[str, list[dict]] = {}
685
+ for expr in self._checks.get(name) or []:
686
+ d = check_domain(expr)
687
+ if d and d["column"] in types:
688
+ domains.setdefault(d["column"], []).append(d)
689
+ notes: list[str] = []
690
+ out = insert_statements(name, rows, columns, types, fixtures=fixtures, placed=placed, meta=self._meta.get(name),
691
+ realism=tuple(getattr(self, "realism", REALISM)), relations=relations, domains=domains, notes=notes)
692
+ self._load_notes[name] = notes
693
+ return out
694
+
695
+ def load(self, name: str, statements: list[str]) -> None:
696
+ """Run a table's generated INSERTs. A profile expression that calls an integer function with the row number
697
+ (a bigint: `repeat(md5(...), number % 4)`) is given the overload it needs and the statement is run again."""
698
+ name = self._name(name)
699
+ for stmt in statements:
700
+ for _ in range(8):
701
+ try:
702
+ self._psql(stmt.strip().rstrip(";") + ";")
703
+ break
704
+ except QueryError as e:
705
+ if not self._overload(str(e), name):
706
+ raise
707
+
708
+ def _overload(self, error: str, table: str) -> bool:
709
+ """`function f(text, bigint) does not exist`: when pg_catalog has f(text, integer), make public.f(text, bigint)
710
+ that casts and calls it. True when a function was made. `number` is a bigint so that products of it do not
711
+ overflow, and the built-in text functions (repeat, lpad, left, substr, chr) take an integer."""
712
+ m = re.search(r"function ((?:\w+\.)?\w+)\(([^)]*)\) does not exist", error)
713
+ if not m or "bigint" not in m.group(2):
714
+ return False
715
+ fn = m.group(1).split(".")[-1]
716
+ args = [a.strip() for a in m.group(2).split(",")]
717
+ if f"{fn}({', '.join(args)})" in self._tried:
718
+ return False
719
+ self._tried.add(f"{fn}({', '.join(args)})")
720
+ found = self.rows(
721
+ "SELECT oidvectortypes(p.proargtypes) AS args, pg_get_function_result(p.oid) AS result FROM pg_proc p "
722
+ f"WHERE p.proname = '{fn}' AND p.pronamespace = 'pg_catalog'::regnamespace AND p.pronargs = {len(args)} "
723
+ "AND p.prokind = 'f' AND NOT p.proretset")
724
+ for cand in found:
725
+ theirs = [a.strip() for a in cand["args"].split(",")]
726
+ if all(a == b or (a == "bigint" and b == "integer") or a == "unknown" for a, b in zip(args, theirs)):
727
+ mine = [b if a == "unknown" else a for a, b in zip(args, theirs)]
728
+ call = ", ".join(f"${i + 1}::integer" if a == "bigint" and b == "integer" else f"${i + 1}"
729
+ for i, (a, b) in enumerate(zip(args, theirs)))
730
+ if self._try(f"CREATE OR REPLACE FUNCTION public.{fn}({', '.join(mine)}) RETURNS {cand['result']} LANGUAGE sql IMMUTABLE "
731
+ f"AS $codecop$ SELECT pg_catalog.{fn}({call}) $codecop$"):
732
+ return False
733
+ self._note(table, f"{fn}({', '.join(args)}): the profile passes the row number (a bigint) where {fn} takes an integer; "
734
+ "the sandbox casts it")
735
+ return True
736
+ return False
737
+
738
+ # ---- relations (relations.py) ---------------------------------------
739
+ def relation_maps(self, name: str, relations: list[dict]) -> list[dict]:
740
+ """Prepare this table's relations against its loaded parents: one lookup table of the parent's keys per relation.
741
+
742
+ Returns the relations as datagen_postgres wants them ({column, group, same, map, counts, total, skewed}) with
743
+ the relation itself under `relation`. A relation whose parent holds no rows is returned with `total` 0 and is
744
+ not applied."""
745
+ out = []
746
+ for rel in relations:
747
+ parent, key = self._name(rel["parent"]), rel["parent_column"]
748
+ shared = [s["parent_column"] for s in rel.get("same_as_parent") or []]
749
+ mark = (parent, key, tuple(shared))
750
+ if mark not in self._maps:
751
+ n = len(self._maps) + 1
752
+ table = f"codecop_rel_{n}"
753
+ extra = "".join(f", ({quoted(c)})::text AS {'x' if i == 0 else f'd{i}'}" for i, c in enumerate(shared))
754
+ names = "".join(f", {'x' if i == 0 else f'd{i}'}" for i in range(len(shared)))
755
+ group = "x" if shared else "NULL::text"
756
+ self._psql(
757
+ f"DROP TABLE IF EXISTS {table}, {table}_n;\n"
758
+ f"CREATE UNLOGGED TABLE {table} AS SELECT (row_number() OVER (ORDER BY k)) - 1 AS rn, k{names}, "
759
+ f"(row_number() OVER (PARTITION BY {group} ORDER BY k)) - 1 AS grn FROM ("
760
+ f"SELECT DISTINCT ON (({quoted(key)})::text) ({quoted(key)})::text AS k{extra} FROM {quoted(parent)} "
761
+ f"WHERE {quoted(key)} IS NOT NULL ORDER BY ({quoted(key)})::text LIMIT {int(self.max_relation_parents)}) s;\n"
762
+ f"CREATE INDEX ON {table} (rn);\nCREATE UNIQUE INDEX ON {table} (k);\n"
763
+ + (f"CREATE INDEX ON {table} (x, grn);\nCREATE UNLOGGED TABLE {table}_n AS SELECT x, count(*) AS n FROM {table} "
764
+ f"WHERE x IS NOT NULL GROUP BY x;\nCREATE UNIQUE INDEX ON {table}_n (x);\nANALYZE {table}_n;\n" if shared else "")
765
+ + f"ANALYZE {table};")
766
+ total = int(self._psql(f"SELECT count(*) FROM {table};").strip() or 0)
767
+ self._maps[mark] = {"map": table, "counts": f"{table}_n" if shared else "", "total": total}
768
+ m = self._maps[mark]
769
+ same = [(s["column"], "x" if i == 0 else f"d{i}") for i, s in enumerate(rel.get("same_as_parent") or [])]
770
+ out.append({"relation": rel, "column": rel["column"], "group": same[0][0] if same else None, "same": same,
771
+ "skewed": rel.get("distribution") == "skewed", **m})
772
+ return out
773
+
774
+ def relation_check(self, name: str, prepared: list[dict]) -> list[dict]:
775
+ """Count, in the loaded table, the rows that break each relation: a key with no parent row, a shared column
776
+ that differs from the parent's. Both are 0 when the relation was applied."""
777
+ out = []
778
+ for p in prepared:
779
+ fk = quoted(p["column"])
780
+ differs = " OR ".join(f"(c.{quoted(col)})::text IS DISTINCT FROM m.{mc}" for col, mc in p["same"]) or "false"
781
+ row = self.rows(f"SELECT count(*) FILTER (WHERE m.k IS NULL) AS orphans, count(*) FILTER (WHERE m.k IS NOT NULL AND ({differs})) "
782
+ f"AS mismatched, count(*) AS checked FROM {self._q(name)} c LEFT JOIN {p['map']} m ON m.k = (c.{fk})::text "
783
+ f"WHERE c.{fk} IS NOT NULL")[0]
784
+ out.append({"orphans": int(row["orphans"]), "mismatched": int(row["mismatched"]), "checked": int(row["checked"]),
785
+ "parents": p["total"]})
786
+ return out
787
+
788
+ def drop_relation_maps(self) -> None:
789
+ for m in self._maps.values():
790
+ self._try(f"DROP TABLE IF EXISTS {m['map']}, {m['map']}_n")
791
+ self._maps = {}
792
+
793
+ def check_violations(self, name: str) -> list[dict]:
794
+ """Every CHECK the definition declares, with the number of loaded rows that break it. The constraints are not
795
+ on the sandbox table (a row that broke one would fail the whole load); this says how far the data respects them."""
796
+ out = []
797
+ for expr in self._checks.get(self._name(name)) or []:
798
+ rec = {"check": expr[:300], "generated_for": bool(check_domain(expr))}
799
+ try:
800
+ rec["violations"] = int(self._psql(f"SELECT count(*) FROM {self._q(name)} WHERE NOT ({expr});").strip() or 0)
801
+ except QueryError as e:
802
+ rec["error"] = str(e).splitlines()[0][:200]
803
+ out.append(rec)
804
+ return out
805
+
806
+ def finish_table(self, definition: dict) -> dict:
807
+ """After the load: build the remaining indexes, then VACUUM ANALYZE so plans see real statistics and a visibility map."""
808
+ name = self._name(definition["name"])
809
+ built = 0
810
+ for stmt in self._deferred.pop(name, []):
811
+ error = self._run_ddl(stmt, name)
812
+ if error:
813
+ head = re.sub(r"\s+", " ", stmt[:70])
814
+ self._note(name, f"index left out (`{head}`): {error.splitlines()[0][:160]}")
815
+ else:
816
+ built += 1
817
+ self._psql(f"VACUUM (ANALYZE) {self._q(name)};")
818
+ # The sandbox runs without fsync and with asynchronous commit. A checkpoint puts the loaded
819
+ # table on disk, so a server that a later query takes down comes back with its data.
820
+ self._psql("CHECKPOINT;")
821
+ out: dict = {"indexes_built_after_load": built}
822
+ if self._notes.get(name):
823
+ out["stripped"] = list(self._notes[name])
824
+ # an index the definition has and the sandbox table does not: a variant that adds it back would "win"
825
+ missing = [n for n in self._notes.get(name) or [] if n.startswith("index left out")]
826
+ if missing:
827
+ out["indexes_left_out"] = missing
828
+ if self._load_notes.get(name):
829
+ out["generator_notes"] = list(self._load_notes[name])
830
+ checks = self.check_violations(name)
831
+ if checks:
832
+ out["checks"] = checks
833
+ return out
834
+
835
+ def table_stats(self, table: str) -> dict:
836
+ q = self._q(table)
837
+ # a partitioned parent has no storage of its own: add up the tree. A plain table is its own tree.
838
+ tree = f"(SELECT '{q}'::regclass AS relid UNION SELECT relid FROM pg_partition_tree('{q}'::regclass)) parts"
839
+ r = self.rows(
840
+ f"SELECT (SELECT count(*) FROM {q}) AS rows, "
841
+ f"(SELECT coalesce(sum(pg_total_relation_size(relid)), 0) FROM {tree}) AS bytes_on_disk, "
842
+ f"(SELECT coalesce(sum(pg_table_size(relid)), 0) FROM {tree}) AS heap_bytes, "
843
+ f"(SELECT coalesce(sum(pg_indexes_size(relid)), 0) FROM {tree}) AS index_bytes, "
844
+ # counted by the table's oid: building a name from pg_indexes and casting it folds "Event" to event
845
+ f"(SELECT count(*) FROM pg_index WHERE indrelid = '{q}'::regclass) AS indexes")
846
+ return {k: int(v) for k, v in r[0].items()} if r else {}
847
+
848
+ def free_bytes(self) -> int:
849
+ df = subprocess.run([self.runtime, "exec", self.name, "df", "-Pk", "/var/lib/postgresql"], capture_output=True, text=True)
850
+ try:
851
+ return int(df.stdout.strip().splitlines()[-1].split()[3]) * 1024
852
+ except (IndexError, ValueError):
853
+ return 0
854
+
855
+ # ---- variants -------------------------------------------------------
856
+ def _relations(self) -> set[tuple[str, str]]:
857
+ text = self._psql(
858
+ "SELECT c.relkind::text || '|' || c.oid::regclass::text FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace "
859
+ "WHERE n.nspname NOT IN ('pg_catalog', 'information_schema') AND n.nspname NOT LIKE 'pg_toast%' "
860
+ "AND c.relkind IN ('r', 'p', 'm', 'v', 'i', 'I', 'S') "
861
+ "UNION ALL SELECT 'X|' || s.stxnamespace::regnamespace::text || '.' || quote_ident(s.stxname) FROM pg_statistic_ext s;")
862
+ return {tuple(line.split("|", 1)) for line in text.splitlines() if "|" in line}
863
+
864
+ def storage_bytes(self, tables: list[str], setup_sql: list[str]) -> int:
865
+ return int(self._psql("SELECT pg_database_size(current_database());").strip() or 0)
866
+
867
+ def apply_setup(self, statements: list[str]) -> None:
868
+ """Run a variant's setup, then refresh statistics on what it touched. Whatever it creates is found by diffing the catalog."""
869
+ self._before = self._relations()
870
+ if not statements:
871
+ return
872
+ for script in statements:
873
+ for stmt in split_statements(script):
874
+ kind = statement_kind(stmt)
875
+ stmt = re.sub(r"\bCONCURRENTLY\s+", "", stmt, count=1, flags=re.I)
876
+ if kind == "extension":
877
+ ext = re.search(r'EXTENSION\s+(?:IF\s+NOT\s+EXISTS\s+)?"?([\w-]+)"?', stmt, re.I)
878
+ if ext and not self._extension(ext.group(1)):
879
+ raise QueryError(f"extension {ext.group(1)} is not installed in the sandbox image")
880
+ continue
881
+ error = self._run_ddl(stmt, "variant") if kind in ("table", "index", "unique_index", "type") else self._try(stmt)
882
+ if error:
883
+ raise QueryError(error)
884
+ new = self._relations() - self._before
885
+ fresh = [n for k, n in new if k in ("r", "m")]
886
+ # tables that got a new index or new statistics need ANALYZE (expression statistics), new tables a visibility map too
887
+ touched = self._psql(
888
+ "SELECT DISTINCT i.indrelid::regclass::text FROM pg_index i WHERE i.indexrelid::regclass::text = ANY(%s) "
889
+ "UNION SELECT DISTINCT s.stxrelid::regclass::text FROM pg_statistic_ext s;" % self._array([n for k, n in new if k in ("i", "I")])
890
+ ).split("\n") if new else []
891
+ script = "".join(f"VACUUM (ANALYZE) {n};\n" for n in sorted(fresh))
892
+ script += "".join(f"ANALYZE {n};\n" for n in sorted(set(t for t in touched if t.strip()) - set(fresh)))
893
+ script += "".join(f"ANALYZE {n};\n" for k, n in sorted(new) if k == "p")
894
+ if script:
895
+ self._psql(script)
896
+
897
+ @staticmethod
898
+ def _array(names: list[str]) -> str:
899
+ return "ARRAY[" + ", ".join("'" + n.replace("'", "''") + "'" for n in names) + "]::text[]"
900
+
901
+ def undo_setup(self, statements: list[str]) -> None:
902
+ """Drop everything that exists now and did not before the setup."""
903
+ if self._before is None:
904
+ return
905
+ new = self._relations() - self._before
906
+ self._before = None
907
+ word = {"v": "VIEW", "m": "MATERIALIZED VIEW", "i": "INDEX", "I": "INDEX", "r": "TABLE", "p": "TABLE", "S": "SEQUENCE", "X": "STATISTICS"}
908
+ order = {"X": 0, "v": 1, "m": 2, "i": 3, "I": 3, "p": 4, "r": 5, "S": 6}
909
+ for kind, name in sorted(new, key=lambda kn: order.get(kn[0], 9)):
910
+ self._try(f"DROP {word[kind]} IF EXISTS {name}" + ("" if kind == "X" else " CASCADE"))
911
+
912
+ # ---- measurement ----------------------------------------------------
913
+ # statement_timeout is the query time limit: a measured query that runs longer on sandbox-sized data is recorded
914
+ # as failed with the server's own message. Memory is bounded by work_mem per sort or hash; what still takes the
915
+ # server down is handled by revive().
916
+ statement_timeout_s: float = MAX_QUERY_SECONDS # `[bench] statement_timeout_s` (set_statement_timeout)
917
+
918
+ # `[bench] pg_work_mem` / `pg_hash_mem_multiplier`, or production's (pg.check.settings): sorts and hashes get the memory
919
+ # production gives them, so the sandbox spills where production does and not where it does not. None: the server's.
920
+ work_mem: str | None = None
921
+ hash_mem_multiplier: float | None = None
922
+ resource_min_cpu_ms: float = 5.0 # `[bench] resource_min_cpu_ms`: a statement under this is repeated in one session and divided
923
+ resource_max_repeats: int = 50 # `[bench] resource_max_repeats`: ... at most this many times
924
+
925
+ @property
926
+ def SESSION(self) -> str:
927
+ return (f"SET max_parallel_workers_per_gather = 0;\nSET jit = off;\nSET statement_timeout = '{int(self.statement_timeout_s * 1000)}ms';\n"
928
+ "SET extra_float_digits = 0;\n"
929
+ + (f"SET work_mem = '{self.work_mem}';\n" if self.work_mem else "")
930
+ + (f"SET hash_mem_multiplier = {float(self.hash_mem_multiplier):g};\n" if self.hash_mem_multiplier else ""))
931
+
932
+ def set_work_mem(self, work_mem: str | int | None, hash_mem_multiplier: float | None = None) -> None:
933
+ """Sorts and hashes of every measured statement get this work_mem (a number of kB, or text such as '64MB')."""
934
+ if work_mem:
935
+ text = f"{int(work_mem)}kB" if isinstance(work_mem, (int, float)) or str(work_mem).isdigit() else str(work_mem)
936
+ if re.fullmatch(r"\d+\s*(kB|MB|GB)?", text.strip()):
937
+ self.work_mem = text.replace(" ", "")
938
+ if hash_mem_multiplier:
939
+ self.hash_mem_multiplier = float(hash_mem_multiplier)
940
+
941
+ # ---- CPU of a statement --------------------------------------------------------------------------------------
942
+ # log_statement_stats = on makes the server report getrusage() of the backend for each statement (user and system
943
+ # CPU, elapsed); client_min_messages = log sends that report to this session (stderr of psql). The plain statement
944
+ # runs, output discarded inside the container (\o /dev/null): EXPLAIN ANALYZE's instrumentation would inflate CPU.
945
+ # One backend (parallel query off), so one process's figures are the statement's. Verified on 15, 16 and 17.
946
+ STATS = re.compile(r"!\s*([\d.]+) s user, ([\d.]+) s system, ([\d.]+) s elapsed")
947
+
948
+ def _cpu_runs(self, statements: list[str]) -> list[tuple[float, float, float]]:
949
+ """(user ms, system ms, elapsed ms) of each statement, in order, from one session."""
950
+ body = "".join(f"{s};\n" for s in statements)
951
+ _, err = self._psql_both(self.SESSION + "SET client_min_messages = log;\n\\o /dev/null\nSET log_statement_stats = on;\n" + body
952
+ + "SET log_statement_stats = off;\n")
953
+ found = [(float(u) * 1000, float(sy) * 1000, float(el) * 1000) for u, sy, el in self.STATS.findall(err)]
954
+ # a statement is reported when the setting was on as it started: not the SET that switches it on, but the SET that
955
+ # switches it off (the last block). Measured on 15.6 and 17: n statements give n + 1 blocks.
956
+ return found[:len(statements)] if len(found) >= len(statements) else []
957
+
958
+ def sample(self, statements: list[tuple[str, dict | None]]) -> list[dict]:
959
+ """Run each statement once, in the order given, and return each run's CPU and time (user + system from the server's
960
+ statement statistics). A statement whose CPU is under resource_min_cpu_ms is repeated in the same session until
961
+ its total passes it (at most resource_max_repeats times) and divided. Memory is not here: on PostgreSQL it is the
962
+ plan's sort and hash memory, which only EXPLAIN reports (measure)."""
963
+ texts = [self.frozen(render_params(sql.strip().rstrip(";"), params)) for sql, params in statements]
964
+ reps: dict[str, int] = {}
965
+ for text in dict.fromkeys(texts):
966
+ probe = self._cpu_runs([text])
967
+ cpu = (probe[0][0] + probe[0][1]) if probe else 0.0
968
+ reps[text] = max(1, min(int(self.resource_max_repeats), int(self.resource_min_cpu_ms / cpu) + 1 if cpu > 0 else int(self.resource_max_repeats)))
969
+ if cpu >= self.resource_min_cpu_ms:
970
+ reps[text] = 1
971
+ order = [t for t in texts for _ in range(reps[t])]
972
+ got = self._cpu_runs(order)
973
+ if len(got) != len(order):
974
+ return [{} for _ in statements]
975
+ out, i = [], 0
976
+ for t in texts:
977
+ chunk = got[i:i + reps[t]]
978
+ i += reps[t]
979
+ user, system, elapsed = (sum(x[k] for x in chunk) / len(chunk) for k in range(3))
980
+ out.append({"cpu_ms": round(user + system, 3), "cpu_user_ms": round(user, 3), "cpu_system_ms": round(system, 3),
981
+ "duration_ms": round(elapsed, 3), "repeats": reps[t]})
982
+ return out
983
+
984
+ def set_statement_timeout(self, seconds: float) -> None:
985
+ """The longest a measured statement may run before the server cancels it (`[bench] statement_timeout_s`)."""
986
+ self.statement_timeout_s = max(float(seconds), 0.001)
987
+
988
+ def freeze_clock(self) -> str:
989
+ """Fix the instant `now()` stands for in every measured query from here on, and return it.
990
+
991
+ A baseline and its variant run seconds apart. A query with `created_at >= now() - interval '1 day'` then
992
+ sees a window that has moved, a few rows fall out of it, and an index that can not change a result is
993
+ reported as changing it. The data is generated relative to the load's own now(), so the instant is taken
994
+ after the load."""
995
+ self.clock = self._psql("SELECT now()::text;").strip()
996
+ return self.clock
997
+
998
+ def frozen(self, sql: str) -> str:
999
+ """The statement with every reading of the clock replaced by the frozen instant (see freeze_clock)."""
1000
+ if not self.clock:
1001
+ return sql
1002
+ ts = f"'{self.clock}'::timestamptz"
1003
+
1004
+ def change(text: str) -> str:
1005
+ text = CLOCK_CALL.sub(f"({ts})", text)
1006
+ text = re.sub(r"\bCURRENT_DATE\b", f"(({ts})::date)", text, flags=re.I)
1007
+ text = re.sub(r"\bLOCALTIMESTAMP\b(?:\s*\(\s*\d+\s*\))?", f"(({ts})::timestamp)", text, flags=re.I)
1008
+ text = re.sub(r"\bCURRENT_TIME\b(?:\s*\(\s*\d+\s*\))?", f"(({ts})::timetz)", text, flags=re.I)
1009
+ return re.sub(r"\bLOCALTIME\b(?:\s*\(\s*\d+\s*\))?", f"(({ts})::time)", text, flags=re.I)
1010
+ return outside_quotes(sql, change)
1011
+
1012
+ def measure(self, sql: str, params: dict | None = None, runs: int = 3) -> PgMeasurement:
1013
+ """Run a SELECT under EXPLAIN (ANALYZE, BUFFERS) and report what it read. The first run is a warm-up and is not timed."""
1014
+ sql = self.frozen(render_params(sql.strip().rstrip(";"), params))
1015
+ m = PgMeasurement(ok=False, block_size=self.block_size)
1016
+ script = self.SESSION + "".join(
1017
+ f"\\echo {MARK}\nEXPLAIN (ANALYZE, BUFFERS, TIMING OFF, FORMAT JSON) {sql};\n" for _ in range(runs + 1))
1018
+ try:
1019
+ chunks = [c.strip() for c in self._psql(script).split(MARK)[1:]]
1020
+ plans = [json.loads(c)[0] for c in chunks if c]
1021
+ if not plans:
1022
+ m.error = "EXPLAIN returned no plan"
1023
+ return m
1024
+ timed = plans[1:] or plans
1025
+ best = min(timed, key=lambda p: float(p.get("Execution Time") or 0))
1026
+ root = best["Plan"]
1027
+ scans: list[dict] = []
1028
+ extra: dict = {}
1029
+ walk_plan(root, scans, extra)
1030
+ m.scans = scans
1031
+ m.node_types = sorted({s["node"] for s in scans})
1032
+ m.read_rows = sum(s["rows"] for s in scans)
1033
+ m.rows_removed = sum(s["removed"] for s in scans)
1034
+ m.shared_hit_blocks = int(root.get("Shared Hit Blocks") or 0)
1035
+ m.shared_read_blocks = int(root.get("Shared Read Blocks") or 0)
1036
+ m.temp_blocks = int(root.get("Temp Read Blocks") or 0) + int(root.get("Temp Written Blocks") or 0)
1037
+ m.read_bytes = (m.shared_hit_blocks + m.shared_read_blocks) * self.block_size
1038
+ m.result_rows = int(round(_total(root, "Actual Rows")))
1039
+ m.memory_bytes = int(extra.get("memory_kb", 0)) * 1024
1040
+ m.execution_ms = float(best.get("Execution Time") or 0)
1041
+ m.planning_ms = float(best.get("Planning Time") or 0)
1042
+ m.duration_ms = m.execution_ms
1043
+ m.runs = [float(p.get("Execution Time") or 0) for p in timed]
1044
+ m.explain = plan_text(root)
1045
+ m.result_hash = self.result_hash(sql)
1046
+ m.ok = True
1047
+ m.memory_kind = "plan_nodes"
1048
+ m.spill_bytes = int(root.get("Temp Written Blocks") or 0) * self.block_size
1049
+ m.runs_detail = {"cpu_ms": [None] * len(timed), "memory_bytes": [m.memory_bytes] * len(timed), "duration_ms": list(m.runs)}
1050
+ except QueryError as e:
1051
+ m.error = str(e)
1052
+ except (json.JSONDecodeError, KeyError, IndexError) as e:
1053
+ m.error = f"could not read the EXPLAIN output: {e}"
1054
+ return m
1055
+
1056
+ def result_hash(self, sql: str, params: dict | None = None) -> str:
1057
+ """Hash of the result ignoring row order: the row count plus a sum of per-row hashes."""
1058
+ sql = self.frozen(render_params(sql.strip().rstrip(";"), params))
1059
+ text = self._psql(self.SESSION + f"SELECT count(*), coalesce(sum(hashtextextended(codecop_row::text, 0)), 0) FROM ({sql}) codecop_row;").strip()
1060
+ return hashlib.sha1(text.encode()).hexdigest()[:16]