codecop 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (222) hide show
  1. codecop/__init__.py +7 -0
  2. codecop/access.py +140 -0
  3. codecop/access_postgres.py +284 -0
  4. codecop/advisor.py +1512 -0
  5. codecop/advisor_bench.py +493 -0
  6. codecop/advisor_ch.py +2080 -0
  7. codecop/advisor_view.py +381 -0
  8. codecop/advisors.py +184 -0
  9. codecop/agent.py +221 -0
  10. codecop/agentfacts.py +745 -0
  11. codecop/apply/__init__.py +327 -0
  12. codecop/apply/check.py +344 -0
  13. codecop/apply/cli.py +162 -0
  14. codecop/apply/clickhouse.py +379 -0
  15. codecop/apply/common.py +238 -0
  16. codecop/apply/html.py +264 -0
  17. codecop/apply/patch.py +213 -0
  18. codecop/apply/postgres.py +102 -0
  19. codecop/apply/trial.py +166 -0
  20. codecop/assemble.py +104 -0
  21. codecop/baseline.py +1043 -0
  22. codecop/bench.py +2464 -0
  23. codecop/blockers.py +935 -0
  24. codecop/budget.py +980 -0
  25. codecop/catalog_profile.py +525 -0
  26. codecop/changed.py +261 -0
  27. codecop/cicmd.py +1002 -0
  28. codecop/cli.py +5421 -0
  29. codecop/client.py +729 -0
  30. codecop/coverage.py +1067 -0
  31. codecop/coverage_reasons.py +116 -0
  32. codecop/crashlog.py +70 -0
  33. codecop/datagen.py +766 -0
  34. codecop/datagen_postgres.py +630 -0
  35. codecop/datagen_sqlite.py +323 -0
  36. codecop/dbcli.py +885 -0
  37. codecop/definitions.py +457 -0
  38. codecop/discover/__init__.py +702 -0
  39. codecop/discover/arms.py +160 -0
  40. codecop/discover/base.py +234 -0
  41. codecop/discover/dialect.py +296 -0
  42. codecop/discover/elixir.py +64 -0
  43. codecop/discover/engine_go.py +320 -0
  44. codecop/discover/go.py +1947 -0
  45. codecop/discover/java.py +1528 -0
  46. codecop/discover/loops.py +1671 -0
  47. codecop/discover/named_go.py +258 -0
  48. codecop/discover/origins.py +4565 -0
  49. codecop/discover/origins_ts.py +1584 -0
  50. codecop/discover/orm_django.py +2772 -0
  51. codecop/discover/orm_django_models.py +814 -0
  52. codecop/discover/orm_django_sql.py +662 -0
  53. codecop/discover/orm_ent.py +565 -0
  54. codecop/discover/orm_ex_ecto.py +2138 -0
  55. codecop/discover/orm_go.py +2134 -0
  56. codecop/discover/orm_go_bun.py +602 -0
  57. codecop/discover/orm_go_run.py +636 -0
  58. codecop/discover/orm_go_types.py +1082 -0
  59. codecop/discover/orm_java.py +1450 -0
  60. codecop/discover/orm_jdbi.py +743 -0
  61. codecop/discover/orm_jooq.py +806 -0
  62. codecop/discover/orm_jpa.py +1307 -0
  63. codecop/discover/orm_mybatis.py +730 -0
  64. codecop/discover/orm_py.py +557 -0
  65. codecop/discover/orm_py_peewee.py +1266 -0
  66. codecop/discover/orm_py_prisma.py +298 -0
  67. codecop/discover/orm_rb_activerecord.py +1906 -0
  68. codecop/discover/orm_rust.py +1248 -0
  69. codecop/discover/orm_rust_seaorm.py +734 -0
  70. codecop/discover/orm_sqlalchemy.py +2475 -0
  71. codecop/discover/orm_stats.py +307 -0
  72. codecop/discover/orm_tables.py +29 -0
  73. codecop/discover/orm_ts.py +503 -0
  74. codecop/discover/orm_ts_drizzle.py +697 -0
  75. codecop/discover/orm_ts_knex.py +1117 -0
  76. codecop/discover/orm_ts_kysely.py +861 -0
  77. codecop/discover/orm_ts_prisma.py +1045 -0
  78. codecop/discover/orm_ts_schema.py +169 -0
  79. codecop/discover/orm_ts_sequelize.py +1401 -0
  80. codecop/discover/orm_ts_typeorm.py +1067 -0
  81. codecop/discover/probes.py +323 -0
  82. codecop/discover/python.py +595 -0
  83. codecop/discover/ruby.py +793 -0
  84. codecop/discover/rust.py +2378 -0
  85. codecop/discover/schema.py +520 -0
  86. codecop/discover/schema_ent.py +145 -0
  87. codecop/discover/schema_ts.py +420 -0
  88. codecop/discover/tsresolve.py +257 -0
  89. codecop/discover/typescript.py +1728 -0
  90. codecop/discover/xml_mapper.py +526 -0
  91. codecop/engines/__init__.py +515 -0
  92. codecop/engines/base.py +498 -0
  93. codecop/engines/clickhouse.py +1558 -0
  94. codecop/engines/pg_ddl.py +444 -0
  95. codecop/engines/pg_hints.py +137 -0
  96. codecop/engines/postgres.py +1060 -0
  97. codecop/engines/sqlite.py +742 -0
  98. codecop/families/__init__.py +3 -0
  99. codecop/families/build.py +280 -0
  100. codecop/families/cli.py +177 -0
  101. codecop/families/coverage_hook.py +62 -0
  102. codecop/families/driver.py +221 -0
  103. codecop/families/goslice.py +229 -0
  104. codecop/families/goslice_tool/go.mod +3 -0
  105. codecop/families/goslice_tool/main.go +403 -0
  106. codecop/families/holes.py +451 -0
  107. codecop/families/images/Dockerfile.go +5 -0
  108. codecop/families/images/Dockerfile.python +4 -0
  109. codecop/families/images/Dockerfile.rust +4 -0
  110. codecop/families/isolate.py +171 -0
  111. codecop/families/locate.py +270 -0
  112. codecop/families/model.py +301 -0
  113. codecop/families/plangate.py +271 -0
  114. codecop/families/tagpatch.py +174 -0
  115. codecop/fidelity.py +671 -0
  116. codecop/fixgroups.py +130 -0
  117. codecop/formerly.py +91 -0
  118. codecop/grantscript.py +254 -0
  119. codecop/groupbench.py +1375 -0
  120. codecop/groups.py +594 -0
  121. codecop/groups_view.py +186 -0
  122. codecop/heat.py +1405 -0
  123. codecop/heatcli.py +219 -0
  124. codecop/joins.py +1749 -0
  125. codecop/joins_view.py +127 -0
  126. codecop/kinds/__init__.py +507 -0
  127. codecop/kinds/calls/__init__.py +501 -0
  128. codecop/kinds/calls/extract.py +1097 -0
  129. codecop/kinds/calls/harness.py +408 -0
  130. codecop/kinds/calls/measure.py +342 -0
  131. codecop/kinds/calls/rules.py +139 -0
  132. codecop/kinds/calls/runners/RunCalls.java +167 -0
  133. codecop/kinds/calls/runners/run_go.go +141 -0
  134. codecop/kinds/calls/runners/run_node.js +186 -0
  135. codecop/kinds/calls/runners/run_python.py +319 -0
  136. codecop/kinds/calls/runners/run_rust.rs +200 -0
  137. codecop/kinds/calls/standin.py +340 -0
  138. codecop/kinds/pipeline.py +288 -0
  139. codecop/kinds/regex/__init__.py +1167 -0
  140. codecop/kinds/regex/engines/RegexHarness.java +129 -0
  141. codecop/kinds/regex/engines/run_go.go +294 -0
  142. codecop/kinds/regex/engines/run_node.js +99 -0
  143. codecop/kinds/regex/engines/run_python.py +295 -0
  144. codecop/kinds/regex/engines/run_rust.rs +149 -0
  145. codecop/kinds/regex/extract.py +1438 -0
  146. codecop/kinds/regex/harness.py +235 -0
  147. codecop/kinds/regex/measure.py +270 -0
  148. codecop/kinds/regex/shapes.py +418 -0
  149. codecop/kinds/regex/syntax.py +1721 -0
  150. codecop/kinds/testkind.py +107 -0
  151. codecop/kinds/transaction/__init__.py +228 -0
  152. codecop/kinds/transaction/bind.py +355 -0
  153. codecop/kinds/transaction/measure.py +264 -0
  154. codecop/kinds/transaction/plan.py +462 -0
  155. codecop/kinds/transaction/rules.py +540 -0
  156. codecop/kinds/transaction/sandbox.py +94 -0
  157. codecop/kinds/transaction/scenarios.py +520 -0
  158. codecop/kinds/transaction/schedule.py +483 -0
  159. codecop/kinds/transaction/shapes.py +418 -0
  160. codecop/kinds/transaction/verify.py +293 -0
  161. codecop/live.py +237 -0
  162. codecop/loopbench.py +2071 -0
  163. codecop/loopschema.py +591 -0
  164. codecop/mcpserver.py +120 -0
  165. codecop/mechanism.py +214 -0
  166. codecop/members.py +200 -0
  167. codecop/multi.py +443 -0
  168. codecop/observed.py +1868 -0
  169. codecop/parts.py +102 -0
  170. codecop/patterns.py +830 -0
  171. codecop/patterns_view.py +559 -0
  172. codecop/plangate.py +242 -0
  173. codecop/profile.py +439 -0
  174. codecop/prompts/areas.md +19 -0
  175. codecop/prompts/observed_variants.md +20 -0
  176. codecop/prompts/profile.md +60 -0
  177. codecop/prompts/profile_postgres.md +68 -0
  178. codecop/prompts/profile_sizes.md +26 -0
  179. codecop/prompts/profile_sqlite.md +69 -0
  180. codecop/prompts/rank.md +84 -0
  181. codecop/prompts/rank_postgres.md +96 -0
  182. codecop/prompts/rank_sqlite.md +94 -0
  183. codecop/prompts/scenario_variants.md +20 -0
  184. codecop/rank.py +1473 -0
  185. codecop/realdb/__init__.py +688 -0
  186. codecop/realdb/clickhouse.py +1223 -0
  187. codecop/realdb/facts.py +815 -0
  188. codecop/realdb/locality.py +964 -0
  189. codecop/realdb/locks.py +355 -0
  190. codecop/realdb/match.py +531 -0
  191. codecop/realdb/postgres.py +643 -0
  192. codecop/realdb/ratios.py +77 -0
  193. codecop/realdb/sample.py +126 -0
  194. codecop/relations.py +227 -0
  195. codecop/report.py +1854 -0
  196. codecop/resources.py +332 -0
  197. codecop/resources_view.py +266 -0
  198. codecop/rules/entry_points.toml +1013 -0
  199. codecop/rules/sinks.toml +362 -0
  200. codecop/runsonce.py +8 -0
  201. codecop/sandboxschema.py +555 -0
  202. codecop/scenario_agent.py +172 -0
  203. codecop/scenario_bind.py +507 -0
  204. codecop/scenario_sql.py +971 -0
  205. codecop/scenarios.py +675 -0
  206. codecop/scenarios_view.py +274 -0
  207. codecop/schemacli.py +67 -0
  208. codecop/schemas/areas_output.schema.json +21 -0
  209. codecop/schemas/profile_output.schema.json +362 -0
  210. codecop/schemas/rank_output.schema.json +385 -0
  211. codecop/sizes.py +200 -0
  212. codecop/sqlinfo.py +558 -0
  213. codecop/typedparams.py +576 -0
  214. codecop/verdicts.py +212 -0
  215. codecop/writebench.py +720 -0
  216. codecop/writecost.py +440 -0
  217. codecop/writes.py +1208 -0
  218. codecop-0.1.0.dist-info/METADATA +42 -0
  219. codecop-0.1.0.dist-info/RECORD +222 -0
  220. codecop-0.1.0.dist-info/WHEEL +4 -0
  221. codecop-0.1.0.dist-info/entry_points.txt +2 -0
  222. codecop-0.1.0.dist-info/licenses/LICENSE +21 -0
codecop/bench.py ADDED
@@ -0,0 +1,2464 @@
1
+ """Stages 4 and 5, sandbox and benchmark.
2
+
3
+ Build a throwaway server (ClickHouse or Postgres, see engines/), load generated
4
+ data at each scale, then run every candidate's baseline and variants and record
5
+ what each one read. Rows and bytes read lead; wall-clock time on a laptop is
6
+ secondary. On Postgres "bytes read" is shared buffers touched x 8 kB.
7
+
8
+ A variant is a win only when it reads meaningfully less and, if it promised the
9
+ same results, returns the same rows. Everything else is recorded as what it is:
10
+ no change, slower, different results, or failed with the server's own message.
11
+
12
+ Realism (`realism`, all on by default):
13
+ sizes columns have the sizes the profile states (sizes.py): wide rows make small granules
14
+ content lengths vary and text has the shape of its content kind, so it compresses like real payloads
15
+ physical a deduplicating table holds duplicate row versions, parts stay as loaded, a variant's copy keeps the part layout
16
+ fit with a real workload: each matched baseline is compared with production and the fixtures are corrected (fidelity.py)
17
+ Every baseline that production knows gets a fidelity grade either way.
18
+
19
+ Statements production ran (observed.py, catalog_profile.py): at each scale their fixtures get the share of the sandbox
20
+ table that holds production's median rows read inside the run's time window (target_shares), and after the load their
21
+ time window ends where the loaded data ends (anchor_times). A run whose values match no row where production's typical
22
+ run returns rows is measured and not judged (`parameters_match_no_rows`).
23
+
24
+ Groups. Candidates that share no table (nor a relation) are loaded and measured group by group, largest first; the
25
+ tables of a group are dropped before the next one is loaded. Groups are joined while the peak memory the groups so far
26
+ needed per planned byte says they fit in `group_memory_share` of the server's memory limit (plan_groups, take_group);
27
+ each scale records its groups with their peak memory (`scales[].groups`).
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import copy
33
+ import json
34
+ import math
35
+ import re
36
+ import time
37
+ from datetime import datetime, timezone
38
+
39
+ from . import __version__
40
+ from . import blockers as blockers_mod, datagen, engines, fidelity, parts as parts_mod, relations as relations_mod, sizes
41
+ from . import resources as resources_mod
42
+ from .access import query_filters
43
+ from .datagen import REALISM, ProfileError, base_type, place_fixtures
44
+ from .engines.base import Measurement, QueryError, SandboxError, split_limit
45
+ from .engines.clickhouse import quote_ident, quote_table, undo_statements # noqa: F401 (ClickHouse's undo, kept importable from here)
46
+ from .writecost import settings_of as writecost_settings
47
+
48
+ WIN_RATIO = 0.8 # a win reads at most 80% of the baseline's bytes or rows
49
+ WORSE_RATIO = 1.15
50
+ # Above this a share stops being printed as a percentage: "reads 9000000% of the bytes" is a baseline that read
51
+ # two pages, not a measurement. The sentence then gives both absolute figures.
52
+ MAX_SHARE_SHOWN = 10.0
53
+ LIMIT_NO_ORDER = re.compile(r"\bLIMIT\b", re.I)
54
+ # A setup made only of these adds a way to reach rows and can not change which rows a query returns.
55
+ ACCESS_PATH_ONLY = re.compile(
56
+ r"^\s*(?:CREATE\s+(?:UNIQUE\s+)?INDEX\b|CREATE\s+STATISTICS\b|ANALYZE\b|VACUUM\b|"
57
+ r"ALTER\s+TABLE\s+\S+\s+(?:ADD|MATERIALIZE)\s+(?:INDEX|PROJECTION)\b)", re.I)
58
+
59
+
60
+ MIN_TABLE_ROWS = 1000 # a scaled-down table keeps at least this many rows (setting min_table_rows under [bench])
61
+
62
+ # Columns no statement reads (`[bench] fill_unread_columns`, ClickHouse): a wide text column that no statement, variant,
63
+ # index, projection, key or relation of the run names gets filler of the same length per row (datagen.shaped_text). The
64
+ # row keeps its width, so granules, parts and every byte a statement reads are the same; what is saved is making and
65
+ # compressing text nobody looks at (on a table of very wide rows, most of its load). Only columns at least this wide on
66
+ # average (`[bench] fill_unread_min_bytes`) are filled: narrow ones cost nothing to make.
67
+ FILL_UNREAD_MIN_BYTES = 256
68
+ RANGED_LOAD = "direct" # `[bench] ranged_load`: how parts cut by time are built (ClickHouse): "direct" or "copy" (as before)
69
+ IDENT_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
70
+ # a statement that reads every column: SELECT *, t.*, a column list by regular expression
71
+ STAR_RE = re.compile(r"(?:\bSELECT\s+(?:DISTINCT\s+)?|,\s*|\.)\*(?![\w*])|\bCOLUMNS\s*\(", re.I)
72
+ COPY_RE = re.compile(r"\s*(?:INSERT\s+INTO|CREATE\s+(?:OR\s+REPLACE\s+)?TABLE)\s+[`\"\w.]+(?:\s*\([^)]*\))?(?:\s+ENGINE\s*=.*?)?\s+(?:AS\s+)?SELECT\s+\*\s+FROM\s+[`\"\w.]+\s*;?\s*$", re.I | re.S)
73
+ # fields of a candidate or plan that are words for people, not statements (their column names do not keep a column);
74
+ # the table definitions name every column
75
+ PROSE_KEYS = {"table_definitions", "title", "causes", "assumptions", "reason", "why", "note", "notes", "description",
76
+ "explanation", "summary", "label", "rationale", "evidence"}
77
+
78
+
79
+ def statement_texts(*docs) -> list[str]:
80
+ """Every string inside these documents (candidates, variants, plans): the statements the run may send."""
81
+ out: list[str] = []
82
+
83
+ def walk(x) -> None:
84
+ if isinstance(x, str):
85
+ if len(x) > 2:
86
+ out.append(x)
87
+ elif isinstance(x, dict):
88
+ for k, v in x.items():
89
+ if k not in PROSE_KEYS:
90
+ walk(v)
91
+ elif isinstance(x, (list, tuple)):
92
+ for v in x:
93
+ walk(v)
94
+ for d in docs:
95
+ walk(d)
96
+ return out
97
+
98
+
99
+ def advisor_statements(doc: dict | None) -> dict | None:
100
+ """What the advisor may send to the sandbox: its runnable statements and the suggestions it can measure (their DDL,
101
+ their rewrites). A suggestion the advisor already found no runnable statement for (`claimed_not_measured`) is left out,
102
+ and so is the advisor's description of each table's workload: neither is run. A statement that still names a filled
103
+ column is caught when it runs (ClickHouseSandbox.filled_reads)."""
104
+ if not doc:
105
+ return None
106
+ return {"runnable": doc.get("runnable"),
107
+ "table_suggestions": [s for s in doc.get("table_suggestions") or []
108
+ if ((s.get("outcome") or {}).get("reason") or "") != "claimed_not_measured"]}
109
+
110
+
111
+ class ReadColumns:
112
+ """Which columns the run's statements may read: every identifier any of its statements names (case-insensitive), and
113
+ whether a statement that names a table reads all of its columns (SELECT *). Over-inclusive on purpose: a word that
114
+ only looks like a column keeps the column."""
115
+
116
+ def __init__(self, texts: list[str], min_bytes: int = FILL_UNREAD_MIN_BYTES):
117
+ self.texts = [t for t in texts if t]
118
+ self.tokens = {m.lower() for t in self.texts for m in IDENT_RE.findall(t)}
119
+ self.min_bytes = int(min_bytes)
120
+ self._star: dict[str, bool] = {}
121
+
122
+ def reads_all(self, table: str) -> bool:
123
+ short = table.split(".")[-1].strip('`"').lower()
124
+ if short not in self._star:
125
+ pat = re.compile(rf"\b{re.escape(short)}\b", re.I)
126
+ # a copy of the table (a variant's INSERT ... SELECT * or CREATE ... AS SELECT *) moves the filler with
127
+ # the rows; the statements then read the copy by the same column names
128
+ self._star[short] = any(pat.search(t) and STAR_RE.search(t) and not COPY_RE.match(t) for t in self.texts)
129
+ return self._star[short]
130
+
131
+ def unread(self, sb, name: str, columns: list[dict], fixtures: list[dict] | None, relations: list[dict]) -> list[str]:
132
+ """The wide text columns of `name` to fill: none when a statement reads the whole table."""
133
+ if self.reads_all(name):
134
+ return []
135
+ keep = {c.lower() for c in self.tokens}
136
+ # what the table itself reads: its keys, version and TTL (engine_full), skip indexes, projections, constraints,
137
+ # and the expressions of the columns it computes (a MATERIALIZED length(text) keeps the text)
138
+ try:
139
+ facts = sb.rows("SELECT sorting_key, partition_key, primary_key, sampling_key, engine_full, create_table_query FROM system.tables "
140
+ "WHERE database = {d:String} AND name = {t:String}",
141
+ {"t": name.split(".")[-1], "d": name.split(".")[0] if "." in name else sb.database})
142
+ defaults = sb.rows("SELECT name, default_expression FROM system.columns WHERE database = {d:String} AND table = {t:String}",
143
+ {"t": name.split(".")[-1], "d": name.split(".")[0] if "." in name else sb.database})
144
+ indexes = sb.rows("SELECT expr FROM system.data_skipping_indices WHERE database = {d:String} AND table = {t:String}",
145
+ {"t": name.split(".")[-1], "d": name.split(".")[0] if "." in name else sb.database})
146
+ except QueryError:
147
+ return []
148
+ for f in facts:
149
+ for k in ("sorting_key", "partition_key", "primary_key", "sampling_key", "engine_full"):
150
+ keep |= {m.lower() for m in IDENT_RE.findall(str(f.get(k) or ""))}
151
+ q = str(f.get("create_table_query") or "")
152
+ tail = re.search(r"\b(?:PROJECTION|CONSTRAINT|INDEX)\b", q)
153
+ if tail:
154
+ keep |= {m.lower() for m in IDENT_RE.findall(q[tail.start():])}
155
+ for ix in indexes:
156
+ keep |= {m.lower() for m in IDENT_RE.findall(str(ix.get("expr") or ""))}
157
+ keep |= {str(v.get("column") or "").lower() for f in fixtures or [] for v in f.get("values") or []}
158
+ keep |= {str(s.get("column") or "").lower() for f in fixtures or [] for s in f.get("size_factors") or []}
159
+ for r in relations:
160
+ if r.get("table") == name:
161
+ keep |= {str(r.get("column") or "").lower()} | {str(s.get("column") or "").lower() for s in r.get("same_as_parent") or []}
162
+ if r.get("parent") == name:
163
+ keep |= {str(r.get("parent_column") or "").lower()} | {str(s.get("parent_column") or "").lower() for s in r.get("same_as_parent") or []}
164
+ computed = {str(d["name"]).lower(): {m.lower() for m in IDENT_RE.findall(str(d.get("default_expression") or ""))} for d in defaults}
165
+ changed = True
166
+ while changed:
167
+ more = set().union(*(computed.get(c, set()) for c in keep)) - keep if keep else set()
168
+ changed = bool(more)
169
+ keep |= more
170
+ out = []
171
+ for c in columns:
172
+ if c.get("kind") != "text" or c["name"].lower() in keep:
173
+ continue
174
+ if (sizes.mean_bytes(c) or float(c.get("avg_len") or 0)) >= self.min_bytes:
175
+ out.append(c["name"])
176
+ return sorted(out)
177
+
178
+
179
+ def sandbox_rows(real_rows: int, max_rows: int, fraction: float, least: int = MIN_TABLE_ROWS) -> int:
180
+ """Rows to generate: the real count up to `max_rows`, times the scale; at least `least`, so a small scale still has
181
+ rows to filter, but never more than the real table holds. A configuration table of a few rows stays that small: as 1,000 it
182
+ would make a query that reads it whole read far more than production reads."""
183
+ real = max(int(real_rows or 0), 1)
184
+ return max(int(min(real, max_rows) * fraction), min(int(least), real), 1)
185
+
186
+
187
+ def scaled_columns(columns: list[dict], rows: int, real_rows: int) -> list[dict]:
188
+ """Shrink key cardinalities with the table, so rows per key stay roughly as in production.
189
+
190
+ A key with more distinct values than a tenth of the real table (user ids, hashes) scales
191
+ down with the data. A small dimension (a few thousand tenants) keeps its real size."""
192
+ out = []
193
+ ratio = rows / max(real_rows, 1)
194
+ for c in columns:
195
+ c = dict(c)
196
+ if c.get("kind") == "key" and c.get("distinct"):
197
+ d = int(c["distinct"])
198
+ if d > max(real_rows, 1) / 10:
199
+ d = max(int(d * ratio), 1)
200
+ c["distinct"] = max(min(d, rows), 1)
201
+ out.append(c)
202
+ return out
203
+
204
+
205
+ def estimated_row_bytes(columns: list[dict], realism: tuple = (), fixtures: list[dict] | None = None) -> int:
206
+ """Rough bytes on disk per generated row. Random text does not compress, so it dominates; shaped content
207
+ (realism "content") compresses by about its kind's ratio. A fixture's heavier rows count by their share."""
208
+ total = 0.0
209
+ for c in columns:
210
+ if c.get("kind") == "text":
211
+ stated = sizes.mean_bytes(c) if "sizes" in realism else None
212
+ size = stated or float(c.get("avg_len") or 40)
213
+ if stated and "content" in realism:
214
+ size /= sizes.compress_ratio(c)
215
+ for f in fixtures or []:
216
+ factor = next((float(x.get("factor") or 1) for x in f.get("size_factors") or [] if x.get("column") == c["name"]), 1.0)
217
+ size *= 1 + min(max(float(f.get("share") or 0), 0.0), 0.5) * max(factor - 1, 0)
218
+ total += size
219
+ elif c.get("kind") == "expr":
220
+ total += 200
221
+ else:
222
+ total += 16
223
+ return max(int(total), 16)
224
+
225
+
226
+ def fit_rows(rows: int, columns: list[dict], free_bytes: int, copies: int, realism: tuple = (), fixtures: list[dict] | None = None,
227
+ per_row: float | None = None) -> int:
228
+ """Shrink a table so that it and the variant copies built from it fit in the sandbox's free disk.
229
+
230
+ `per_row`: the bytes a row of this table took on disk at a smaller scale, indexes included. It replaces the
231
+ estimate, which knows nothing of the table's indexes: a table with ten of them took four times its estimate."""
232
+ budget = free_bytes * 0.6
233
+ need = rows * (per_row or estimated_row_bytes(columns, realism, fixtures)) * copies
234
+ return rows if need <= budget or budget <= 0 else max(int(rows * budget / need), min(MIN_TABLE_ROWS, rows))
235
+
236
+
237
+ DISK_SHARE = 0.4 # of the sandbox's free disk, for all tables of one scale together: loading and merging need room on top
238
+
239
+
240
+ def share_disk(needs: dict[str, int], free_bytes: int, share: float = DISK_SHARE) -> dict[str, float]:
241
+ """How much of its wanted rows each table gets so that all of them together fit: table name -> factor (1.0 = all).
242
+
243
+ `needs` is each table's estimated bytes, copies included. Small tables are left whole; the large ones shrink by one
244
+ common factor. Without this each table was fitted against the free disk on its own, and several large tables
245
+ (or one very wide one) filled the disk between them."""
246
+ budget = free_bytes * share
247
+ total = sum(needs.values())
248
+ if budget <= 0 or total <= budget:
249
+ return dict.fromkeys(needs, 1.0)
250
+ small = {n for n, v in needs.items() if v <= budget * 0.05}
251
+ large_total = total - sum(needs[n] for n in small)
252
+ factor = max((budget - sum(needs[n] for n in small)) / large_total, 0.0) if large_total else 1.0
253
+ return {n: 1.0 if n in small else min(factor, 1.0) for n in needs}
254
+
255
+
256
+ DEDUPLICATING_ENGINE = re.compile(r"\bENGINE\s*=\s*(?:Replicated|Shared)?(?:Replacing|Coalescing|Collapsing|VersionedCollapsing|Aggregating|Summing)MergeTree\b", re.I)
257
+
258
+
259
+ def sorting_key(create_sql: str) -> list[str]:
260
+ """The bare column names of a table's ORDER BY, in order; [] when the key holds an expression or there is none."""
261
+ from .access import key_parts
262
+ from .apply.clickhouse import clause
263
+ span = clause(create_sql or "", r"ORDER\s+BY")
264
+ if not span:
265
+ return []
266
+ parts = [p.strip().strip("`\"") for p in key_parts(create_sql[span[0]:span[1]])]
267
+ return parts if parts and all(re.fullmatch(r"\w+", p) for p in parts) else []
268
+
269
+
270
+ def unique_key_pins(definition: dict, columns: list[dict], fixtures: list[dict]) -> tuple[list[dict], list[str]]:
271
+ """The columns to generate, without the pinned values that would make other rows versions of a fixture's row.
272
+
273
+ A deduplicating table (ReplacingMergeTree and the like) keeps one row per sorting key under FINAL and after a
274
+ merge. A fixture that sets every column of that key is then one row, and when the profile pins the same value on
275
+ other rows of a key column, those rows hold the same key: FINAL keeps whichever was inserted last, so the fixture's
276
+ other values (the tenant a row belongs to) were there or gone by the order of the generated rows. Those pins
277
+ are left out on this table; returns the columns and a note per value left out."""
278
+ if not DEDUPLICATING_ENGINE.search(definition.get("create_sql") or ""):
279
+ return columns, []
280
+ key = sorting_key(definition.get("create_sql") or "")
281
+ taken: dict[str, set[str]] = {}
282
+ for f in fixtures or []:
283
+ values = {v.get("column"): str(v.get("value")) for v in f.get("values") or [] if v.get("column")}
284
+ if key and all(k in values for k in key):
285
+ for k in key:
286
+ taken.setdefault(k, set()).add(values[k])
287
+ if not taken:
288
+ return columns, []
289
+ out, notes = [], []
290
+ for c in columns:
291
+ pins = c.get("pinned") or []
292
+ kept = [p for p in pins if str(p.get("value")) not in taken.get(c["name"], set())]
293
+ if len(kept) != len(pins):
294
+ notes.append(f"{c['name']}: a value a fixture sets on the whole sorting key is not also pinned on other rows "
295
+ "(on a deduplicating table those rows would be versions of the fixture's row)")
296
+ c = {**c, "pinned": kept}
297
+ out.append(c)
298
+ return out, notes
299
+
300
+
301
+ def copies_of(sb, rank: dict, name: str) -> int:
302
+ """1, or 2 when a variant re-keys, re-types or partitions the table: it copies it once."""
303
+ return 1 + any(v["kind"] in sb.copy_kinds and name in c["tables"] for c in rank["candidates"] for v in c["variants"])
304
+
305
+
306
+ def held_bytes(sb, names: list[str]) -> dict[str, int]:
307
+ """Bytes on disk the sandbox holds now for each of these tables (0 for one not built yet). ClickHouse only."""
308
+ if getattr(sb, "engine", "") != "clickhouse" or not hasattr(sb, "table_stats"):
309
+ return {}
310
+ out = {}
311
+ for n in names:
312
+ try:
313
+ out[n] = int(sb.table_stats(n).get("bytes_on_disk") or 0)
314
+ except (QueryError, SandboxError, AttributeError):
315
+ out[n] = 0
316
+ return out
317
+
318
+
319
+ def released_bytes(sb, names: list[str]) -> int:
320
+ """Bytes on disk of tables kept loaded after their group (keep_released_tables), either engine."""
321
+ total = 0
322
+ for n in names:
323
+ try:
324
+ total += int(sb.table_stats(n).get("bytes_on_disk") or 0)
325
+ except (QueryError, SandboxError, AttributeError):
326
+ pass
327
+ return total
328
+
329
+
330
+ def drop_released(sb, names: list[str]) -> None:
331
+ """Drop tables kept after their group: a later load needs their disk (or the run is not kept)."""
332
+ if not names:
333
+ return
334
+ if hasattr(sb, "release"):
335
+ sb.release(list(names))
336
+ else:
337
+ for n in names:
338
+ try:
339
+ sb.execute(f"DROP TABLE IF EXISTS {n}")
340
+ except QueryError:
341
+ pass
342
+ for n in names:
343
+ if isinstance(getattr(sb, "loaded", None), dict):
344
+ sb.loaded.pop(n, None)
345
+ sb.releasable = set(getattr(sb, "releasable", None) or ()) - set(names)
346
+
347
+
348
+ def sizing(sb, rank: dict, by_name: dict, max_rows: int, fraction: float, least: int, row_bytes: dict, realism: tuple,
349
+ free: int) -> tuple[dict[str, float], dict[str, int]]:
350
+ """(factor per table from share_disk, rows per table as planned) for a scale, against `free` bytes of disk."""
351
+ wanted = {d["name"]: sandbox_rows(by_name[d["name"]]["rows"], max_rows, fraction, least) for d in rank["table_definitions"] if d["name"] in by_name}
352
+ needs = {n: w * (row_bytes.get(n) or estimated_row_bytes(by_name[n]["columns"], realism, by_name[n].get("fixtures"))) * copies_of(sb, rank, n)
353
+ for n, w in wanted.items()}
354
+ factors = share_disk(needs, free) if needs else {}
355
+ rows = {n: fit_rows(max(int(w * factors.get(n, 1.0)), min(w, 1000)), by_name[n]["columns"], free, copies_of(sb, rank, n), realism,
356
+ by_name[n].get("fixtures"), row_bytes.get(n)) for n, w in wanted.items()}
357
+ return factors, rows
358
+
359
+
360
+ def target_shares(profile: dict, rows: dict[str, int], reach: dict[tuple[str, str], float] | None = None) -> tuple[dict, list[dict]]:
361
+ """Shares of the sandbox tables for the fixtures that state how many rows a run reads (`target_rows`, the statements
362
+ production ran: catalog_profile.fixture_for), for this scale's table sizes. Returns a copy of the profile and one
363
+ record per fixture.
364
+
365
+ The fixture holds production's median rows read per run inside the run's time window: share = target rows over the
366
+ table's rows times the share of them inside the window (datagen.window_share for a generated time; `reach`,
367
+ (table, fixture id) -> the share measured on the loaded table, for a time the profile writes as an expression). The
368
+ share is at most fidelity.MAX_SHARE; a fixture that would need more says so (`capped`): its runs read fewer rows than
369
+ production's because the sandbox table is smaller, and the grade says `scale_bound`. The share is the ceiling the fit
370
+ may lower (`share_estimated`), as any profile's estimate is."""
371
+ out = copy.deepcopy(profile)
372
+ notes = []
373
+ for t in out.get("tables") or []:
374
+ n = int(rows.get(t["name"]) or 0)
375
+ if n <= 0:
376
+ continue
377
+ cols = {c["name"]: c for c in t.get("columns") or []}
378
+ for f in t.get("fixtures") or []:
379
+ if f.get("target_rows") is None:
380
+ continue
381
+ win = f.get("window") or {}
382
+ hours = float(win.get("hours") or 24)
383
+ known = [datagen.window_share(cols[c], hours) for c in win.get("columns") or [] if c in cols]
384
+ measured = (reach or {}).get((t["name"], str(f.get("id"))))
385
+ inside = measured if measured is not None else min([k for k in known if k], default=None)
386
+ basis = ("measured on the loaded table" if measured is not None else "the generated spread of the time column" if inside is not None
387
+ else "no time window on this table" if not win.get("columns") else "unknown (the time column is an expression): the whole table")
388
+ inside = inside if inside and inside > 0 else 1.0
389
+ want = float(f["target_rows"]) / (n * inside)
390
+ share = min(max(want, fidelity.MIN_SHARE), fidelity.MAX_SHARE)
391
+ f["share"] = round(share, 7)
392
+ f["share_estimated"] = f["share"]
393
+ notes.append({"table": t["name"], "fixture": f.get("id"), "target_rows": int(f["target_rows"]), "table_rows": n,
394
+ "inside_window": round(inside, 6), "inside_basis": basis, "share": f["share"], "capped": want > fidelity.MAX_SHARE})
395
+ return out, notes
396
+
397
+
398
+ def time_columns_newest(sb, cand: dict, types_of) -> tuple[datetime | None, str]:
399
+ """The newest time the candidate's time-bounded columns hold in the loaded tables, and which column it was."""
400
+ o = cand.get("observed") or {}
401
+ wanted = {p["column"]: p.get("epoch_unit") for p in (o.get("params") or {}).values() if p.get("time") and p.get("column")}
402
+ best, basis = None, ""
403
+ if getattr(sb, "engine", "") != "clickhouse":
404
+ return best, basis
405
+ for table in cand.get("tables") or []:
406
+ types = types_of(table)
407
+ for col, unit in wanted.items():
408
+ if col not in types:
409
+ continue
410
+ try:
411
+ got = sb.rows(f"SELECT toString(max({quote_ident(col)})) AS v FROM {quote_table(table)}")[0]["v"]
412
+ except (QueryError, IndexError, KeyError):
413
+ continue
414
+ when = _as_time(got, unit)
415
+ if when and (best is None or when > best):
416
+ best, basis = when, f"the newest {table}.{col} in the sandbox"
417
+ return best, basis
418
+
419
+
420
+ def _as_time(text, unit: str | None) -> datetime | None:
421
+ s = str(text or "").strip()
422
+ if not s:
423
+ return None
424
+ if unit and re.fullmatch(r"\d+", s):
425
+ from .observed import EPOCH_SCALE
426
+ v = int(s) / EPOCH_SCALE.get(unit, 1)
427
+ return datetime.fromtimestamp(v, tz=timezone.utc) if v > 86_400 else None
428
+ try:
429
+ when = datetime.fromisoformat(s.replace(" ", "T")[:26])
430
+ except ValueError:
431
+ return None
432
+ when = when if when.tzinfo else when.replace(tzinfo=timezone.utc)
433
+ return when if when.year > 1971 else None
434
+
435
+
436
+ def anchor_times(sb, candidates: list[dict], clock: str | None) -> list[dict]:
437
+ """Put each observed statement's time window where the sandbox's data is: it ends at the newest time its bounded
438
+ columns hold (the data of an agent's profile often ends days before today), else at the benchmark's clock. The
439
+ parameters are changed in place; one record per candidate: {finding, end, hours, basis}."""
440
+ from .observed import time_value
441
+ cache: dict[str, dict] = {}
442
+
443
+ def types_of(table: str) -> dict:
444
+ if table not in cache:
445
+ try:
446
+ cache[table] = sb.column_types(table)
447
+ except (QueryError, SandboxError):
448
+ cache[table] = {}
449
+ return cache[table]
450
+
451
+ fallback = _as_time(clock, None) if clock else None
452
+ out = []
453
+ for c in candidates:
454
+ o = c.get("observed") or {}
455
+ specs = {n: p["time"] for n, p in (o.get("params") or {}).items() if p.get("time") and n in (c.get("params") or {})}
456
+ if not specs:
457
+ continue
458
+ hours = float(o.get("time_window_hours") or 24)
459
+ end, basis = time_columns_newest(sb, c, types_of)
460
+ if end is None:
461
+ end, basis = fallback, "the benchmark's clock"
462
+ if end is None:
463
+ continue
464
+ for name, spec in specs.items():
465
+ c["params"][name] = time_value(spec, end, hours)
466
+ c["time_window"] = {"end": end.strftime("%Y-%m-%d %H:%M:%S"), "hours": hours, "basis": basis}
467
+ out.append({"finding": c["finding"], **c["time_window"]})
468
+ return out
469
+
470
+
471
+ def measured_reach(sb, rank: dict, profile: dict) -> dict[tuple[str, str], float]:
472
+ """(table, fixture id) -> the share of the loaded table's rows inside the candidate's window, for the fixtures whose
473
+ window column the profile writes as an expression (window_share can not say). Read on the loaded table, with the
474
+ window the candidate runs with (anchor_times)."""
475
+ by_finding = {c["finding"]: c for c in rank["candidates"]}
476
+ out: dict[tuple[str, str], float] = {}
477
+ if getattr(sb, "engine", "") != "clickhouse":
478
+ return out
479
+ for t in profile.get("tables") or []:
480
+ cols = {c["name"]: c for c in t.get("columns") or []}
481
+ for f in t.get("fixtures") or []:
482
+ win = f.get("window") or {}
483
+ fid = str(f.get("id") or "").split("~")[0]
484
+ cand = by_finding.get(fid)
485
+ todo = [c for c in win.get("columns") or [] if c in cols and datagen.window_share(cols[c], float(win.get("hours") or 24)) is None]
486
+ if f.get("target_rows") is None or not todo or not cand or not cand.get("time_window"):
487
+ continue
488
+ end = cand["time_window"]["end"]
489
+ hours = float(cand["time_window"]["hours"])
490
+ col = todo[0]
491
+ try:
492
+ r = sb.rows(f"SELECT countIf({quote_ident(col)} >= toDateTime({{e:String}}, 'UTC') - toIntervalSecond({int(hours * 3600)}) "
493
+ f"AND {quote_ident(col)} <= toDateTime({{e:String}}, 'UTC')) / greatest(count(), 1) AS r FROM {quote_table(t['name'])}",
494
+ {"e": end})
495
+ out[(t["name"], str(f.get("id")))] = max(float(r[0]["r"] or 0), 1e-6)
496
+ except (QueryError, IndexError, KeyError, ValueError):
497
+ continue
498
+ return out
499
+
500
+
501
+ MIN_SCALE_GROWTH = 2.0 # a scale whose tables can not grow by this factor over the previous one is skipped (setting min_scale_growth)
502
+
503
+
504
+ def scale_growth(sb, rank: dict, profile: dict, max_rows: int, fraction: float, previous: dict[str, int], row_bytes: dict,
505
+ min_table_rows: int | None = None) -> tuple[float, dict[str, int]]:
506
+ """(the most any table grows over `previous`, rows per table as planned) for the next scale, before anything is loaded.
507
+
508
+ The plan counts the disk the previous scale's tables hold as free (they are dropped first), so it is the most the
509
+ scale can load: when even that is not `min_scale_growth` times the previous, loading it measures the same thing again."""
510
+ by_name = {t["name"]: t for t in profile["tables"]}
511
+ names = [d["name"] for d in rank["table_definitions"] if d["name"] in by_name]
512
+ least = MIN_TABLE_ROWS if min_table_rows is None else max(int(min_table_rows), 1)
513
+ _, rows = sizing(sb, rank, by_name, max_rows, fraction, least, row_bytes, tuple(getattr(sb, "realism", ())),
514
+ sb.free_bytes() + sum(held_bytes(sb, names).values()))
515
+ grows = [rows[n] / previous[n] for n in rows if previous.get(n)]
516
+ return (max(grows) if grows else math.inf), rows
517
+
518
+
519
+ def load_tables(sb, rank: dict, profile: dict, max_rows: int, fraction: float, log,
520
+ on_event=lambda name, label, counts: None, only: set[str] | None = None, keep_rows: dict[str, int] | None = None,
521
+ real_tables: dict[str, dict] | None = None, relations: dict | None = None,
522
+ row_bytes: dict[str, float] | None = None, min_kept_share: float | None = None,
523
+ min_table_rows: int | None = None, part_size_ratio: float | None = None,
524
+ row_factor: float | None = None, memory_retries: int | None = None, _retried: bool = False) -> list[dict]:
525
+ """`row_factor`: the load group's tables do not fit the memory budget together at their planned rows (take_group):
526
+ each gets this share of them, and says so (`memory_scaled`). `memory_retries`: how many times a table whose load
527
+ passed the server's memory limit (code 241) is loaded again, each time with less (MEMORY_RETRIES).
528
+
529
+ `only`: rebuild just these tables (a fit round) and the tables that follow them. `keep_rows`: table -> the row
530
+ count it was first loaded with, so a rebuilt table is the same size. `real_tables`: table -> the real catalog's
531
+ sizes, for the table's fidelity grade. `relations`: relations.resolve(rank, profile), worked out here when not given.
532
+ `row_bytes`: table -> bytes a row took on disk at a smaller scale; sizes the tables instead of the estimate.
533
+
534
+ Every entry says whether the table was built (`ok`) and, when not, why (`error`). A table that holds no rows
535
+ after its load is not built: a query on it measures nothing."""
536
+ loaded = []
537
+ by_name = {t["name"]: t for t in profile["tables"]}
538
+ placed = place_fixtures(profile["tables"])
539
+ realism = tuple(getattr(sb, "realism", ()))
540
+ # Invariants between tables (relations.py): parents are loaded first, and a child's rows follow its parents' rows.
541
+ if relations is None:
542
+ relations = relations_mod.resolve({**rank, "engine": rank.get("engine") or getattr(sb, "engine", "")}, profile)
543
+ following: dict[str, list[dict]] = {}
544
+ for rel in relations["relations"]:
545
+ following.setdefault(rel["table"], []).append(rel)
546
+ unenforced: dict[str, list[dict]] = {}
547
+ for rel in relations["skipped"]:
548
+ unenforced.setdefault(rel["table"], []).append(rel)
549
+ if only is not None:
550
+ only = relations_mod.descendants(relations["relations"], set(only))
551
+ position = {d["name"]: i for i, d in enumerate(rank["table_definitions"])}
552
+ definitions = {d["name"]: d for d in rank["table_definitions"]}
553
+ not_built: dict[str, str] = {}
554
+
555
+ row_bytes = row_bytes or {}
556
+ min_kept_share = MIN_KEPT_SHARE if min_kept_share is None else float(min_kept_share)
557
+ least = MIN_TABLE_ROWS if min_table_rows is None else max(int(min_table_rows), 1)
558
+ order = [n for n in relations["order"] if n in definitions] + [n for n in definitions if n not in relations["order"]]
559
+ order = [n for n in order if only is None or n in only]
560
+ # the tables of the previous scale (or the copy a fit round rebuilds) are dropped before their new rows are written:
561
+ # the disk they hold is free for this load. Counted as used, it made a larger scale barely larger than the smaller one
562
+ old = held_bytes(sb, order)
563
+ if hasattr(sb, "bound_memory"):
564
+ sb.bound_memory("before the load") # a server at its limit refuses even the disk query below
565
+ # tables an earlier group left loaded for a later bench of the run (keep_released_tables): their disk counts as free
566
+ # for the sizing, so every table gets the rows it would get were they dropped, and they are dropped when this load
567
+ # needs that disk
568
+ if getattr(sb, "releasable", None):
569
+ sb.releasable = set(sb.releasable) - set(order) # loaded again now: no longer kept for later
570
+ spare_names = [n for n in sorted(getattr(sb, "releasable", None) or ()) if n not in order]
571
+ spare = released_bytes(sb, spare_names)
572
+ factors, planned_now = sizing(sb, rank, by_name, max_rows, fraction, least, row_bytes, realism, sb.free_bytes() + sum(old.values()) + spare)
573
+ if spare_names:
574
+ need = sum(r * (row_bytes.get(n) or estimated_row_bytes(by_name[n]["columns"], realism, by_name[n].get("fixtures"))) * copies_of(sb, rank, n)
575
+ for n, r in planned_now.items() if n in order)
576
+ if need > DISK_SHARE * (sb.free_bytes() + sum(old.values())):
577
+ drop_released(sb, spare_names)
578
+ log(f"{len(spare_names)} table(s) kept from earlier groups dropped: this load needs their disk")
579
+ spare = 0
580
+ cache = getattr(sb, "loaded", None) # a kept sandbox (keep_sandbox): what is loaded from an earlier run
581
+ for at, name in enumerate(order):
582
+ definition = definitions[name]
583
+ short = name.split(".")[-1]
584
+ entry = {"name": name, "inferred": bool(definition.get("inferred")), "source": definition.get("source", ""), "ok": False, "error": ""}
585
+ key = None
586
+ reader = getattr(sb, "unread_reader", None)
587
+ if isinstance(cache, dict) and by_name.get(name) is not None:
588
+ p0 = by_name[name]
589
+ # which of its columns the run's statements name decides which are filled: part of what the table depends on
590
+ named = None if reader is None else [reader.reads_all(name)] + sorted(c["name"] for c in p0.get("columns") or []
591
+ if c["name"].lower() in reader.tokens)
592
+ key = load_key(definition, p0, sandbox_rows(p0["rows"], max_rows, fraction, least), factors.get(name, 1.0), row_factor,
593
+ part_size_ratio, realism, (keep_rows or {}).get(name), (real_tables or {}).get(name),
594
+ [(cache.get(r["parent"]) or ("",))[0] for r in following.get(name) or []], named)
595
+ held = cache.get(name)
596
+ if only is None and held is not None and held[0] == key and held[1].get("ok"):
597
+ # loaded by an earlier bench of this run with the same definition, profile and rows: measured as it is
598
+ entry = {**copy.deepcopy(held[1]), "reused_from_earlier_run": True}
599
+ sb.stripped = list(getattr(sb, "stripped", []) or []) + [f"{name}: {x}" for x in entry.get("stripped") or []]
600
+ log(f"{name}: still loaded from the earlier bench of this run (same definition, profile and rows): not loaded again")
601
+ loaded.append(entry)
602
+ on_event("table_loaded", f"{name}: {entry.get('rows', 0):,} rows (loaded before)",
603
+ {"fraction": fraction, "table": name, "ok": True, "rows": entry.get("rows", 0), "bytes_on_disk": entry.get("bytes_on_disk", 0),
604
+ "reduced": "reduced_from" in entry, "done": len(loaded), "total": len(rank["table_definitions"]), "reused": True})
605
+ continue
606
+ try:
607
+ real_rpm = ((real_tables or {}).get(name) or {}).get("rows_per_mark")
608
+ if hasattr(sb, "scale_granularity") and real_rpm and (by_name.get(name) or {}).get("rows"):
609
+ # granules scaled to production's, so re-keys and projections select as many marks as there
610
+ planned = sandbox_rows(by_name[name]["rows"], max_rows, fraction, least) * min(factors.get(name, 1.0), 1.0)
611
+ definition = sb.scale_granularity(definition, real_rpm, planned / max(by_name[name]["rows"], 1))
612
+ stripped = sb.create_table(definition)
613
+ if getattr(sb, "granularity_plan", {}).get(name):
614
+ entry["granularity"] = sb.granularity_plan[name]
615
+ if stripped:
616
+ entry["stripped"] = stripped
617
+ prof = by_name.get(name)
618
+ if prof is None:
619
+ # no profile describes it (a table only a later candidate reads, or one no agent was asked about): a
620
+ # schema-only profile from its definition, so its statements read rows instead of an empty table
621
+ try:
622
+ from .loopschema import DEFAULTS as LS_DEFAULTS, schema_profile
623
+ real = int(definition.get("rows") or 0)
624
+ prof = schema_profile(definition, {}, sb.engine, {**LS_DEFAULTS, "schema_rows": real or LS_DEFAULTS["schema_rows"]})
625
+ prof = prof if prof.get("columns") else None
626
+ except Exception: # noqa: BLE001 - left empty, as before
627
+ prof = None
628
+ if prof is not None:
629
+ by_name[name] = prof
630
+ entry["profile_basis"] = "schema only (no data profile for this table)"
631
+ if prof is None:
632
+ entry["error"] = "no data profile for this table: left empty"
633
+ not_built[name] = entry["error"]
634
+ loaded.append(entry)
635
+ continue
636
+ types = sb.column_types(name)
637
+ wanted = sandbox_rows(prof["rows"], max_rows, fraction, least)
638
+ copies = copies_of(sb, rank, name)
639
+ shared = max(int(wanted * factors.get(name, 1.0)), min(wanted, 1000))
640
+ free = sb.free_bytes() + sum(old.get(n, 0) for n in order[at + 1:]) + spare
641
+ rows = fit_rows(shared, prof["columns"], free, copies, realism, prof.get("fixtures"), row_bytes.get(name))
642
+ if keep_rows and keep_rows.get(name):
643
+ rows = min(keep_rows[name], rows) if only is None else keep_rows[name]
644
+ if rows < wanted:
645
+ entry["reduced_from"] = wanted
646
+ log(f"[yellow]{name}: {wanted:,} rows would not fit in the sandbox's free disk; generating {rows:,}[/yellow]")
647
+ planned_here = rows
648
+ if row_factor and row_factor < 1 and only is None and not (keep_rows and keep_rows.get(name)):
649
+ rows = max(int(rows * row_factor), min(least, rows), 1)
650
+ if hasattr(sb, "bound_memory"):
651
+ # memory the server kept from the loads before (it does not give it back by itself): a restart when it is high
652
+ event = sb.bound_memory(f"before {name}")
653
+ if event:
654
+ entry.setdefault("server_restarts", []).append(event)
655
+ log(f"[yellow]server restarted before loading {name}: {event['why']}; RSS {event['resident_before'] / 1e6:,.0f} -> "
656
+ f"{event['resident_after'] / 1e6:,.0f} MB[/yellow]")
657
+ started = time.monotonic()
658
+ if hasattr(sb, "plan_time_ranges"):
659
+ # parts that each hold one range of the table's time column, as real parts do (parts.py)
660
+ shape = prof.get("part_shape") or {}
661
+ filtered = set()
662
+ for c in rank["candidates"]:
663
+ if name in c.get("tables", []) or short in c.get("tables", []):
664
+ filtered |= set(query_filters(c.get("baseline_sql") or "", name, set(types)))
665
+ sb.plan_time_ranges(definition, types, filtered,
666
+ shape.get("ratio") if shape.get("ratio") is not None else part_size_ratio or parts_mod.DEFAULT_RATIO,
667
+ shape.get("basis") or ("profile" if shape.get("ratio") is not None else "setting" if part_size_ratio else "default"),
668
+ prof.get("duplicate_share"))
669
+ if hasattr(sb, "plan_parts"):
670
+ real = (real_tables or {}).get(name) or {}
671
+ # the real layout by age when the pull has parts per partition, else the real average, else the default
672
+ sb.plan_parts(definition, real["parts"] / real["partitions"] if real.get("parts") and real.get("partitions") else None,
673
+ prof.get("duplicate_share"), **({"layout": real["layout"]} if real.get("layout") else {}))
674
+ mine = relations_mod.row_order(following.get(name) or [])
675
+ usable = [r for r in mine if r["parent"] not in not_built and hasattr(sb, "relation_maps")]
676
+ shape = {c["name"]: c for c in prof["columns"]}
677
+ prepared = sb.relation_maps(name, [{**r, "distribution": (shape.get(r["column"]) or {}).get("distribution")}
678
+ for r in usable]) if usable else []
679
+ applied = [p for p in prepared if p["total"] > 0]
680
+ more = {"relations": applied} if applied else {}
681
+ columns, left_out = unique_key_pins(definition, prof["columns"], prof.get("fixtures") or [])
682
+ if left_out:
683
+ entry["pins_left_out"] = left_out
684
+ run_all = getattr(sb, "load", None) or (lambda _name, stmts: [sb.execute(x) for x in stmts])
685
+ statements: list[str] = []
686
+ # wide text columns no statement of the run reads: filler of the same length (ReadColumns, datagen.shaped_text)
687
+ filled = reader.unread(sb, name, columns, prof.get("fixtures"), relations["relations"]) \
688
+ if reader is not None and hasattr(sb, "full_width_sample") and {"sizes", "content"} <= set(realism) else []
689
+ fill = {"filler": set(filled)} if filled else {}
690
+
691
+ def build(n: int) -> list[str]:
692
+ statements[:] = sb.insert_statements(name, n, scaled_columns(columns, n, prof["rows"]), types,
693
+ fixtures=prof.get("fixtures"), placed=placed, **more, **fill)
694
+ return statements
695
+
696
+ rows, attempts = _load_within_memory(sb, definition, name, rows, least, run_all, log, build,
697
+ MEMORY_RETRIES if memory_retries is None else max(int(memory_retries), 0))
698
+ if attempts:
699
+ entry["memory_retries"] = attempts
700
+ if filled:
701
+ # what an insert costs is measured on rows of full content (writecost.measure): a sample of them, made apart
702
+ width = estimated_row_bytes([c for c in columns if c["name"] in filled], ("sizes",))
703
+ ws = writecost_settings(getattr(sb, "insert_settings", None))
704
+ n_sample = max(min(rows, int(ws["insert_rows"]), int(ws["insert_sample_bytes"] / max(estimated_row_bytes(columns, ("sizes",)), 1))), 1)
705
+ try:
706
+ sb.full_width_sample(name, sb.insert_statements(name, n_sample, scaled_columns(columns, rows, prof["rows"]), types,
707
+ fixtures=prof.get("fixtures"), placed=placed, **more))
708
+ sample_note = f"a sample of {n_sample:,} rows with full content is kept for the insert-side measurements"
709
+ except QueryError as e:
710
+ sample_note = f"no sample with full content could be made ({str(e)[:120]}): an insert side is measured on the filled rows"
711
+ entry["filled_columns"] = {"columns": filled, "bytes_per_row": width,
712
+ "basis": "no statement, variant, index, projection, key or relation of this run names them: "
713
+ "each row holds filler of the length the profile gives it, so the row is as wide "
714
+ "and every statement reads the same rows and bytes", "insert_sample": sample_note}
715
+ log(f"{name}: {len(filled)} column(s) no statement reads ({', '.join(filled[:6])}{', …' if len(filled) > 6 else ''}; "
716
+ f"about {width:,} bytes a row) hold filler of their length; {sample_note}")
717
+ sb.filled_columns[name] = set(filled) # a measured statement that names one is recorded (filled_reads)
718
+ if rows < planned_here:
719
+ # the rows this table was measured at, and why: the memory, not the disk
720
+ entry["memory_scaled"] = {"rows_planned": planned_here, "rows_loaded": rows,
721
+ "basis": "the server's memory limit (code 241) on the load"
722
+ if any(a["action"] == "fewer_rows" for a in attempts) else "the load group's planned memory"}
723
+ log(f"[yellow]{name}: measured at {rows:,} rows instead of {planned_here:,}: memory[/yellow]")
724
+ if hasattr(sb, "add_versions"):
725
+ entry.update(sb.add_versions(definition, prof.get("duplicate_share")))
726
+ entry.update(sb.finish_table(definition))
727
+ stats = sb.table_stats(name)
728
+ if real_tables and real_tables.get(name):
729
+ entry["fidelity"] = fidelity.check_table(stats, real_tables[name])
730
+ entry.update(ok=True, target_rows=rows, real_rows=prof["rows"], load_s=round(time.monotonic() - started, 1), **stats,
731
+ missing_columns=[c["name"] for c in prof["columns"] if c["name"] not in types])
732
+ # what the generated rows were made to agree with, and how many rows break it (0 when it was applied)
733
+ kept = []
734
+ checks = sb.relation_check(name, applied) if applied else []
735
+ for p, counted in zip(applied, checks):
736
+ kept.append({**_public(p["relation"]), "enforced": True, **counted})
737
+ kept += [{**_public(p["relation"]), "enforced": False, "reason": f"{p['relation']['parent']} holds no rows to follow"}
738
+ for p in prepared if p["total"] <= 0]
739
+ kept += [{**_public(r), "enforced": False, "reason": f"{r['parent']} could not be built: {not_built[r['parent']][:160]}"}
740
+ for r in mine if r["parent"] in not_built]
741
+ kept += [{**_public(r), "enforced": False, "reason": "this sandbox adapter does not apply relations"}
742
+ for r in mine if r["parent"] not in not_built and not hasattr(sb, "relation_maps")]
743
+ kept += [{**_public(r), "enforced": False, "reason": r["reason"]} for r in unenforced.get(name) or []]
744
+ if kept:
745
+ entry["relations"] = kept
746
+ if not stats.get("rows"):
747
+ # an empty table is not a table to measure on: every query that reads it would "read nothing"
748
+ # what is known, not a guess at why: the statements ran without an error and the table reports no rows
749
+ entry.update(ok=False, statements_run=len(statements),
750
+ error=f"the load produced no rows: {len(statements)} generating statement(s) for "
751
+ f"{rows:,} rows ran without an error from the server, and the server's row count of "
752
+ f"{name} is 0")
753
+ log(f"[red]could not build {name}:[/red] {entry['error']}")
754
+ elif stats["rows"] < rows * min_kept_share:
755
+ # a handful of rows where the profile asked for a table: what a query reads there says nothing about it
756
+ entry.update(ok=False, rows_lost=rows - stats["rows"],
757
+ error=f"the load kept {stats['rows']:,} of {rows:,} generated rows: a unique constraint rejected the rest "
758
+ "(the profile does not make the columns of a unique key distinct)")
759
+ log(f"[red]could not build {name}:[/red] {entry['error']}")
760
+ else:
761
+ log(f"loaded {name}: {stats.get('rows', 0):,} rows, {stats.get('bytes_on_disk', 0) / 1e6:.0f} MB"
762
+ + (f", {stats['parts']} parts" if "parts" in stats else "")
763
+ + (f", {sum(1 for k in kept if k['enforced'])} relation(s) kept" if any(k["enforced"] for k in kept) else "")
764
+ + (f", {(getattr(sb, 'uncut', None) or {})[name]:,} partitions loaded in one insert, not cut into parts "
765
+ "([bench] max_cut_partitions)" if name in (getattr(sb, "uncut", None) or {}) else ""))
766
+ if name in (getattr(sb, "uncut", None) or {}):
767
+ entry["uncut_partitions"] = sb.uncut[name]
768
+ if stats["rows"] < rows * LOST_ROWS_NOTE:
769
+ entry["rows_lost"] = rows - stats["rows"]
770
+ log(f"[yellow]{name}: {rows - stats['rows']:,} of {rows:,} generated rows were dropped by a unique constraint[/yellow]")
771
+ except (QueryError, ProfileError) as e:
772
+ entry["error"] = str(e)[:600]
773
+ log(f"[red]could not build {name}:[/red] {entry['error'][:200]}")
774
+ except SandboxError as e:
775
+ why = ""
776
+ try:
777
+ why = sb.revive() if hasattr(sb, "revive") else ""
778
+ except SandboxError as again:
779
+ raise again from e
780
+ entry["error"] = f"the sandbox server stopped while loading this table ({why or e}); it was started again"
781
+ entry["sandbox_restarted"] = True
782
+ oom = "out of memory" in (why or "") or memory_error(e)
783
+ tries = max(int(MEMORY_RETRIES if memory_retries is None else memory_retries), 1)
784
+ if int(_retried) < (tries if oom else 1):
785
+ # once more, alone: the host's memory may have come back (another container ended its load); when the server
786
+ # ran out of memory, with half the rows each time (a table of wide text columns at the largest scale)
787
+ factor = (row_factor or 1.0) * 0.5 if oom else row_factor # halved again on each retry
788
+ log(f"[yellow]{name}: the sandbox server stopped during the load ({why or e}); loading it once more"
789
+ + (f" with {factor:.0%} of its rows" if oom else "") + "[/yellow]")
790
+ again = load_tables(sb, {**rank, "table_definitions": [definition]}, profile, max_rows, fraction, log, on_event,
791
+ only={name} if only is not None else None, keep_rows=None if oom else keep_rows, real_tables=real_tables,
792
+ relations=relations, row_bytes=row_bytes, min_kept_share=min_kept_share, min_table_rows=least,
793
+ part_size_ratio=part_size_ratio, row_factor=factor, memory_retries=memory_retries,
794
+ _retried=int(_retried) + 1)
795
+ if again and again[0].get("ok"):
796
+ entry = {**again[0], "sandbox_restarted": True}
797
+ if oom:
798
+ ms = entry.get("memory_scaled") or {}
799
+ entry["memory_scaled"] = {**ms, "basis": "the server ran out of memory loading it: loaded again with fewer rows",
800
+ "row_factor": round(min(float(factor or 1.0), float(ms.get("row_factor") or 1.0)), 4)}
801
+ if not entry.get("ok"):
802
+ log(f"[red]could not build {name}:[/red] {entry['error'][:200]}")
803
+ if not entry["ok"]:
804
+ not_built[name] = entry["error"]
805
+ if isinstance(cache, dict):
806
+ if entry.get("ok") and key is not None:
807
+ cache[name] = (key, copy.deepcopy(entry))
808
+ else:
809
+ cache.pop(name, None)
810
+ loaded.append(entry)
811
+ on_event("table_loaded", f"{name}: {entry.get('rows', 0):,} rows" if entry["ok"] else f"{name}: not loaded",
812
+ {"fraction": fraction, "table": name, "ok": entry["ok"], "rows": entry.get("rows", 0),
813
+ "bytes_on_disk": entry.get("bytes_on_disk", 0), "reduced": "reduced_from" in entry,
814
+ "done": len(loaded), "total": len(rank["table_definitions"])})
815
+ if hasattr(sb, "drop_relation_maps"):
816
+ sb.drop_relation_maps()
817
+ loaded.sort(key=lambda t: position.get(t["name"], len(position))) # reported in the order the definitions are listed
818
+ return loaded
819
+
820
+
821
+ MIN_FREE_DISK_BYTES = 4_000_000_000 # setting min_free_disk_bytes under [bench]: below it the run says the disk is low
822
+
823
+
824
+ def disk_check(sb, settings: dict, log) -> dict:
825
+ """The disk the sandbox has before anything is loaded, and what was left behind by earlier runs: the sandboxes of
826
+ killed runs removed on start (engines/base.reap_orphans), and the volumes no container uses (anyone's: counted, not
827
+ removed). A disk below `min_free_disk_bytes` is said plainly: every table is then cut to what fits."""
828
+ out = {"free_bytes": 0, "reaped": dict(getattr(sb, "reaped", {}) or {}), "dangling_volumes": 0}
829
+ try:
830
+ out["free_bytes"] = int(sb.free_bytes()) if hasattr(sb, "free_bytes") else 0
831
+ except (QueryError, SandboxError):
832
+ pass
833
+ if getattr(sb, "runtime", None):
834
+ try:
835
+ from .engines.base import dangling_volumes
836
+ out["dangling_volumes"] = dangling_volumes(sb.runtime)
837
+ except (OSError, SandboxError):
838
+ pass
839
+ gone = out["reaped"]
840
+ if gone.get("containers") or gone.get("volumes"):
841
+ log(f"removed what killed runs left behind: {gone.get('containers', 0)} sandbox container(s), {gone.get('volumes', 0)} data volume(s)")
842
+ floor = int(settings.get("min_free_disk_bytes") or MIN_FREE_DISK_BYTES)
843
+ if out["free_bytes"] and out["free_bytes"] < floor:
844
+ out["low"] = True
845
+ log(f"[yellow]the sandbox's disk is low: {out['free_bytes'] / 1e9:.1f} GB free (under {floor / 1e9:.1f} GB); tables are cut to what fits"
846
+ + (f". {out['dangling_volumes']} volume(s) on the host belong to no container (`{sb.runtime} volume ls -f dangling=true`; "
847
+ "removing the ones that are yours frees their disk)" if out["dangling_volumes"] else "") + "[/yellow]")
848
+ return out
849
+
850
+
851
+ MEMORY_RETRIES = 4 # setting memory_retries under [bench]: loads again after code 241 (restart, smaller blocks, then half the rows)
852
+
853
+
854
+ def memory_error(e: Exception) -> bool:
855
+ text = str(e).lower()
856
+ return "memory limit" in text or "memory_limit_exceeded" in text or "code: 241" in text
857
+
858
+
859
+ def _load_within_memory(sb, definition: dict, name: str, rows: int, least: int, run_all, log, build, retries: int) -> tuple[int, list[dict]]:
860
+ """Load `rows` generated rows of a table; when the load passes the server's memory limit (code 241), load it again
861
+ with less: first after the server gave back what it held (bound_memory: a restart), then with blocks a quarter the
862
+ size and one cut at a time, then with half the rows each time, down to `least`. Returns (rows loaded, attempts)."""
863
+ attempts: list[dict] = []
864
+ saved = {k: getattr(sb, k) for k in ("insert_block_bytes", "copy_block_bytes", "load_workers") if hasattr(sb, k)}
865
+ try:
866
+ while True:
867
+ try:
868
+ run_all(name, build(rows))
869
+ return rows, attempts
870
+ except QueryError as e:
871
+ if not memory_error(e) or len(attempts) >= retries or not hasattr(sb, "wait_idle"):
872
+ raise
873
+ n = len(attempts)
874
+ if hasattr(sb, "wait_idle"):
875
+ sb.wait_idle()
876
+ if hasattr(sb, "wait_for_memory"):
877
+ sb.wait_for_memory() # on a shared host the limit follows the host's free memory: wait for some back
878
+ # every attempt starts on a server that gave back what the failed one left allocated (a failed load can
879
+ # leave RSS at the limit, far above what the server tracks, and the next attempt then fails too)
880
+ event = sb.bound_memory(f"{name}: code 241 on the load", force=True) if hasattr(sb, "bound_memory") else None
881
+ if n == 0 and hasattr(sb, "bound_memory"):
882
+ attempts.append({"action": "restart", "rows": rows, **({"restart": event} if event else {})})
883
+ elif n <= 1 and saved:
884
+ for k in ("insert_block_bytes", "copy_block_bytes"):
885
+ if k in saved:
886
+ setattr(sb, k, max(int(getattr(sb, k)) // 4, 1_000_000))
887
+ if "load_workers" in saved:
888
+ sb.load_workers = 1
889
+ attempts.append({"action": "smaller_blocks", "rows": rows, "insert_block_bytes": getattr(sb, "insert_block_bytes", None)})
890
+ else:
891
+ if rows <= least:
892
+ raise
893
+ rows = max(rows // 2, least)
894
+ attempts.append({"action": "fewer_rows", "rows": rows})
895
+ log(f"[yellow]{name}: the load passed the server's memory limit; loading it again ({attempts[-1]['action'].replace('_', ' ')}, "
896
+ f"{rows:,} rows)[/yellow]")
897
+ sb.create_table(definition)
898
+ finally:
899
+ for k, v in saved.items():
900
+ setattr(sb, k, v)
901
+
902
+
903
+ LOST_ROWS_NOTE = 0.9 # a table that keeps less than this share of its generated rows says how many it lost
904
+ # A table that keeps less than this share is not the table the profile describes, and is not built: a unique key
905
+ # whose columns the profile left constant keeps a row per key. Setting `min_kept_share` under [bench] in codecop.toml.
906
+ MIN_KEPT_SHARE = 0.05
907
+
908
+
909
+ def _public(rel: dict) -> dict:
910
+ return {k: rel.get(k) for k in ("column", "parent", "parent_column", "same_as_parent", "source", "basis")}
911
+
912
+
913
+ def pct(ratio: float) -> str:
914
+ """A share for a sentence: 0.3% stays 0.3%, never rounds to 0%."""
915
+ value = ratio * 100
916
+ if value == 0 or value >= 10:
917
+ return f"{value:.0f}%"
918
+ return f"{value:.1f}%" if value >= 0.1 else "under 0.1%"
919
+
920
+
921
+ def _count(n: float) -> str:
922
+ for unit, size in (("B", 1e9), ("M", 1e6), ("K", 1e3)):
923
+ if abs(n) >= size:
924
+ return f"{n / size:.1f}{unit}"
925
+ return f"{n:.0f}"
926
+
927
+
928
+ def _size(n: float) -> str:
929
+ for unit, size in (("GB", 1e9), ("MB", 1e6), ("kB", 1e3)):
930
+ if abs(n) >= size:
931
+ return f"{n / size:.1f} {unit}"
932
+ return f"{n:.0f} B"
933
+
934
+
935
+ def read_ratio(variant: float, baseline: float) -> float:
936
+ """variant / baseline. A baseline of zero has no ratio: the same (1.0) when the variant is zero too, else worse without bound."""
937
+ if baseline > 0:
938
+ return variant / baseline
939
+ return 1.0 if variant <= 0 else math.inf
940
+
941
+
942
+ def reads_text(base: Measurement, var: Measurement, floor_bytes: int = 0, floor_rows: int = 0, joiner: str = "and") -> str:
943
+ """What the variant read against the baseline, as one clause.
944
+
945
+ Shares ("17% of the rows and 23% of the bytes") only when both baselines are large enough for a share to mean
946
+ something: above zero, above the engine's noise floor, and the share itself no more than MAX_SHARE_SHOWN. Otherwise
947
+ the absolute figures of both, so a baseline that read nothing or two pages never yields a percentage."""
948
+ rows, size = read_ratio(var.read_rows, base.read_rows), read_ratio(var.read_bytes, base.read_bytes)
949
+ small = base.read_rows <= max(floor_rows, 0) or base.read_bytes <= max(floor_bytes, 0)
950
+ if small or max(rows, size) > MAX_SHARE_SHOWN:
951
+ return (f"reads {_count(var.read_rows)} rows {joiner} {_size(var.read_bytes)}; the baseline read "
952
+ f"{_count(base.read_rows)} rows and {_size(base.read_bytes)}")
953
+ return f"reads {pct(rows)} of the rows {joiner} {pct(size)} of the bytes"
954
+
955
+
956
+ def verdict(base: Measurement, var: Measurement, same_results: bool, compare_rows_only: bool = False,
957
+ floor_bytes: int = 0, floor_rows: int = 0, *, match: bool | None | str = "unset", why: str = "",
958
+ pages_decide: bool = False, empty_shown: bool = False, typical_empty: bool = False) -> tuple[str, str]:
959
+ """`floor_*`: a baseline that reads no more than both is already cheap, so a smaller read is noise, not a win.
960
+
961
+ `pages_decide`: on PostgreSQL the bytes are buffer pages touched, which is what a query pays for; rows scanned
962
+ are a count of tuples the executor looked at and can rise while the work falls (a join order that visits more
963
+ rows through an index instead of a few through repeated scans). There the pages decide and the rows are stated.
964
+
965
+ `match`: whether the variant was shown to return the baseline's rows: True, False, or None when that could not be
966
+ decided (`why` says why). Left out, it is read from the two measurements: the row counts when `compare_rows_only`,
967
+ else the result hashes. A variant whose sameness was not shown is never a win and never rejected.
968
+
969
+ `empty_shown`: this baseline returned no rows, and the variant was shown to return the same rows on another run of
970
+ the same query that returns some (the heavy run, see combined_verdict); `match` is then that run's."""
971
+ if not var.ok:
972
+ return "failed", var.error[:300]
973
+ if match == "unset":
974
+ match = (var.result_rows == base.result_rows if compare_rows_only else var.result_hash == base.result_hash) if same_results else None
975
+ if same_results and match is False:
976
+ return "rejected", why or (f"row count differs: {base.result_rows} vs {var.result_rows}" if compare_rows_only
977
+ else "results differ from the baseline")
978
+ if base.read_bytes == 0 and base.read_rows == 0 and var.read_bytes == 0 and var.read_rows == 0:
979
+ return "no_change", "neither the baseline nor the variant read anything: the parameters match no rows"
980
+ bytes_ratio = read_ratio(var.read_bytes, base.read_bytes)
981
+ rows_ratio = read_ratio(var.read_rows, base.read_rows)
982
+ best, worst = min(bytes_ratio, rows_ratio), max(bytes_ratio, rows_ratio)
983
+ reads = reads_text(base, var, floor_bytes, floor_rows)
984
+ if pages_decide:
985
+ if rows_ratio > WORSE_RATIO and bytes_ratio <= WIN_RATIO and " of the rows and " in reads:
986
+ reads = f"touches {pct(bytes_ratio)} of the pages, while scanning {pct(rows_ratio)} of the rows"
987
+ best = worst = bytes_ratio
988
+ if best <= WIN_RATIO and base.read_bytes <= floor_bytes and base.read_rows <= floor_rows:
989
+ return "no_change", f"the baseline already reads little: {base.read_rows} rows, {base.read_bytes // 1024} kB"
990
+ if best <= WIN_RATIO and worst <= WORSE_RATIO:
991
+ # Reading less only counts as a win when the results were shown to be the same.
992
+ less = reads.split(" and ")[0] if " of the rows and " in reads else reads
993
+ if not same_results:
994
+ return "mixed", f"{less}, but changes the results by design: not verified"
995
+ if match is None:
996
+ return "mixed", f"{less}, but it was not shown to return the same rows: {why or 'not compared'}"
997
+ if (base.result_rows == 0 or typical_empty) and not empty_shown:
998
+ return "mixed", f"{less}, but the baseline {'returned' if base.result_rows == 0 else 'found'} no rows: sameness not shown"
999
+ return "win", reads
1000
+ # worse on both measures; or nothing reads less and one measure is more than ten times the baseline's
1001
+ # (a baseline of zero that became something is worse without bound)
1002
+ if best >= WORSE_RATIO or (best > WIN_RATIO and worst > MAX_SHARE_SHOWN):
1003
+ return "slower", reads
1004
+ if best <= WIN_RATIO:
1005
+ return "mixed", reads_text(base, var, floor_bytes, floor_rows, joiner="but")
1006
+ return "no_change", reads
1007
+
1008
+
1009
+ def combined_verdict(typical: tuple[str, str], heavy: tuple[str, str] | None) -> tuple[str, str]:
1010
+ """The verdict of a variant measured on the typical run and on the heavy run of its query.
1011
+
1012
+ Used when the typical run returns nothing (as production's typical run does): its sameness is shown on the heavy
1013
+ run, and each run says what was read. A run that fails or returns other rows decides; a variant that reads less on
1014
+ one run and more on the other is mixed; reading less on either run, and no more on the other, is a win."""
1015
+ if heavy is None:
1016
+ return typical
1017
+ (tv, tr), (hv, hr) = typical, heavy
1018
+ both = f"typical run: {tr}; heavy run: {hr}"
1019
+ for bad in ("failed", "rejected"):
1020
+ if bad in (tv, hv):
1021
+ return bad, f"heavy run: {hr}" if hv == bad else f"typical run: {tr}"
1022
+ verdicts = {tv, hv}
1023
+ if verdicts == {"slower"}:
1024
+ return "slower", both
1025
+ if "slower" in verdicts:
1026
+ return ("mixed", both) if verdicts & {"win", "mixed"} else ("slower", both)
1027
+ if "mixed" in verdicts:
1028
+ return "mixed", both
1029
+ if "win" in verdicts:
1030
+ return "win", both
1031
+ return "no_change", both
1032
+
1033
+
1034
+ GRADE_ORDER = {"close": 0, "near": 1, "off": 2, "unchecked": 3}
1035
+ SPREAD_CAP = 1000.0 # a ratio further than this counts as this far in the fit's sum (an infinite one would hide every other)
1036
+
1037
+
1038
+ def judge(before: dict[str, dict], after: dict[str, dict]) -> tuple[bool, str]:
1039
+ """Whether a fit round is kept: (kept, why).
1040
+
1041
+ Undone when any run's grade got worse. Kept when a grade got better and none worse; with the same grades, kept when
1042
+ the ratios together moved towards production (the sum of how far each is from 1, on a log scale, fell). The
1043
+ worst single ratio used to decide, and that is often one no round can move (a heavy run production reads more rows
1044
+ for than the sandbox table holds): every round then stood or fell by the noise of that one measure."""
1045
+ worse = sorted(f for f in after if GRADE_ORDER.get(after[f]["grade"], 3) > GRADE_ORDER.get((before.get(f) or {}).get("grade"), 3))
1046
+ if worse:
1047
+ return False, f"grade worse for {', '.join(worse)}"
1048
+ better = sorted(f for f in after if GRADE_ORDER.get(after[f]["grade"], 3) < GRADE_ORDER.get((before.get(f) or {}).get("grade"), 3))
1049
+ if better:
1050
+ return True, f"grade better for {', '.join(better)}"
1051
+
1052
+ def total(checks: dict[str, dict]) -> float:
1053
+ return sum(math.log(min(fidelity.spread(r), SPREAD_CAP)) for ch in checks.values() for r in ch["ratios"].values() if r is not None)
1054
+
1055
+ b, a = total(before), total(after)
1056
+ return (a < b), f"same grades; distance to production {b:.2f} -> {a:.2f} (sum of log ratios)"
1057
+
1058
+
1059
+ def fit_to_production(sb, rank: dict, profile: dict, production: dict[str, dict], reload, log, rounds: int,
1060
+ heavy: dict | None = None) -> tuple[dict, list[dict]]:
1061
+ """Measure each baseline production knows, correct the fixtures, rebuild the tables that changed; up to `rounds` times.
1062
+
1063
+ Returns the profile as corrected and the record of every round. A round whose correction makes the worst ratio
1064
+ worse is undone and the fitting stops: the profile before it stays.
1065
+ `heavy`: fidelity.heavy_runs' second result. Its heavy runs are fitted beside the typical ones, each towards its own
1066
+ target (the 99th percentile), and appear in the record under `<finding>~heavy`."""
1067
+ history: list[dict] = []
1068
+ production = {**production, **((heavy or {}).get("production") or {})}
1069
+ known = [c for c in list(rank["candidates"]) + list((heavy or {}).get("candidates") or []) if c["finding"] in production
1070
+ and not isinstance(c.get("write"), dict)] # a write is never run outside its rolled-back transaction
1071
+ if not known:
1072
+ return profile, history
1073
+
1074
+ def measure_all(using: dict) -> dict[str, dict]:
1075
+ return {c["finding"]: sb.measure(c["baseline_sql"], fidelity.params_of(c, using), 1).to_dict() for c in known}
1076
+
1077
+ def moved(before: dict, after: dict, changes: list[dict]) -> set[str]:
1078
+ """Tables to rebuild: the changed ones, and every table holding a fixture whose rows moved (fixtures share the
1079
+ row numbers of a table between them, so changing one's share shifts the next one's slice)."""
1080
+ names = {ch["table"] for ch in changes}
1081
+ old, new = place_fixtures(before["tables"]), place_fixtures(after["tables"])
1082
+ shifted = {fid for fid in set(old) | set(new) if old.get(fid) != new.get(fid)}
1083
+ return names | {t["name"] for t in after["tables"] if any(str(f.get("id")) in shifted for f in t.get("fixtures") or [])}
1084
+
1085
+ current = measure_all(profile)
1086
+ # Two levers, one per round: the fixtures (shares, sizes, own values), then the shape of time-ranged parts. A round
1087
+ # that moves both and is undone would lose the good one with the bad one; a round of one lever that is undone
1088
+ # leaves the next lever to try, and the fitting stops when no lever is left.
1089
+ levers = ["fixtures", "parts"]
1090
+ for n in range(rounds):
1091
+ grades = {f: fidelity.check(m, production[f])["grade"] for f, m in current.items()}
1092
+ if all(g == "close" for g in grades.values()):
1093
+ break
1094
+ changes: list[dict] = []
1095
+ while levers and not changes:
1096
+ corrected, changes = fidelity.corrections(known, current, production, profile, lever=levers[0])
1097
+ if not changes:
1098
+ levers.pop(0)
1099
+ if not changes:
1100
+ break
1101
+ lever = levers[0]
1102
+ started = time.monotonic()
1103
+ rebuilt = moved(profile, corrected, changes)
1104
+ failed = reload(corrected, rebuilt)
1105
+ if failed:
1106
+ # the reload could not rebuild a table (memory on a shared host): the round is undone and the fitting stops,
1107
+ # so the table is measured as it was before the round, not left unbuilt
1108
+ history.append({"round": n + 1, "lever": lever, "changes": changes, "kept": False,
1109
+ "judged": f"could not rebuild {', '.join(sorted(failed))}", "seconds": round(time.monotonic() - started, 1)})
1110
+ log(f"fit round {n + 1} ({lever}): undone: could not rebuild {', '.join(sorted(failed))}; the fitting stops")
1111
+ reload(profile, rebuilt)
1112
+ break
1113
+ after = measure_all(corrected)
1114
+ before_checks = {f: fidelity.check(m, production[f]) for f, m in current.items()}
1115
+ after_checks = {f: fidelity.check(m, production[f]) for f, m in after.items()}
1116
+ better, why = judge(before_checks, after_checks)
1117
+ history.append({"round": n + 1, "lever": lever, "changes": changes, "kept": better, "judged": why,
1118
+ "seconds": round(time.monotonic() - started, 1), "before": before_checks, "after": after_checks})
1119
+ log(f"fit round {n + 1} ({lever}): {len(changes)} change(s), " + ", ".join(
1120
+ f"{f} {history[-1]['before'][f]['grade']} -> {history[-1]['after'][f]['grade']}" for f in after) + ("" if better else f" (undone: {why})"))
1121
+ if not better:
1122
+ reload(profile, rebuilt)
1123
+ levers.pop(0) # this lever made a grade worse: the next one, if any, gets the next round
1124
+ continue
1125
+ profile, current = corrected, after
1126
+ return profile, history
1127
+
1128
+
1129
+ BY_DESIGN = "not compared: variant changes results by design"
1130
+ ROWS_ONLY = "row count only (LIMIT without ORDER BY)"
1131
+ ROWS = "rows, ignoring order"
1132
+ TIES = ("rows before LIMIT, and the row count (the ORDER BY has ties, so which of the tied rows LIMIT keeps is not determined; "
1133
+ "an index changes which, not what the query means)")
1134
+ NOT_REPEATABLE = ("not compared: the baseline returned different rows when it was run a second time, so its result is not "
1135
+ "determined (a LIMIT, DISTINCT ON or any() without a total order inside the query, or a function that changes between runs)")
1136
+ PLAN_DEPENDENT = ("not compared: the query text is the baseline's and the setup only adds an index or projection, which can not "
1137
+ "change what a query returns; the rows differ, so the result depends on the plan (a LIMIT, DISTINCT ON or "
1138
+ "any() without a total order inside the query)")
1139
+ ORDER_DIFFERS = "rows before LIMIT and the row count match; the two ORDER BY clauses differ, so the rows LIMIT keeps were not compared"
1140
+
1141
+
1142
+ def same_text(a: str, b: str) -> bool:
1143
+ return " ".join(a.split()).rstrip(";").strip() == " ".join(b.split()).rstrip(";").strip()
1144
+
1145
+
1146
+ def access_path_only(setup_sql: list[str]) -> bool:
1147
+ """True when every setup statement only adds an index, a projection or statistics."""
1148
+ statements = [s for script in setup_sql for s in re.split(r";\s*(?=\S)", script.strip().rstrip(";")) if s.strip()]
1149
+ return bool(statements) and all(ACCESS_PATH_ONLY.match(s) for s in statements)
1150
+
1151
+
1152
+ class Comparison:
1153
+ """Whether a variant returns the baseline's rows, for one candidate. Keeps what it learned about the baseline.
1154
+
1155
+ Decided in two steps, because the variant's own statements need its setup and the baseline's need it gone:
1156
+ `with_setup` right after the variant was measured, `settle` after its setup was undone.
1157
+
1158
+ equal hashes the same rows
1159
+ LIMIT without ORDER BY only the row count can be compared (any rows may come back)
1160
+ ORDER BY ... LIMIT, hashes differ the ordering may have ties: compare the rows before the LIMIT (the
1161
+ statement without its outermost ORDER BY / LIMIT / OFFSET) and the row
1162
+ count. Equal and the same ORDER BY: the same rows up to ties.
1163
+ still different run the baseline again. If it disagrees with itself, nothing can be
1164
+ compared. If the variant's text is the baseline's and its setup only adds
1165
+ an access path, the data did not change, so "results differ" is not said.
1166
+ Otherwise the results differ."""
1167
+
1168
+ def __init__(self, sb, cand: dict, base: Measurement, params: dict):
1169
+ self.sb, self.cand, self.base, self.params = sb, cand, base, params
1170
+ self.baseline_sql = cand["baseline_sql"]
1171
+ self.limit = split_limit(self.baseline_sql)
1172
+ # no ORDER BY at all and a LIMIT anywhere, or an outermost LIMIT that nothing orders: any rows may come back
1173
+ self.rows_only = (bool(LIMIT_NO_ORDER.search(self.baseline_sql)) and not re.search(r"\bORDER\s+BY\b", self.baseline_sql, re.I)) \
1174
+ or (bool(self.limit) and not self.limit["has_order"])
1175
+ self.full: str | None | bool = False # hash of the baseline before its LIMIT; False = not asked yet
1176
+ self.repeatable: bool | None = None
1177
+
1178
+ def _hash(self, sql: str) -> str | None:
1179
+ try:
1180
+ return self.sb.result_hash(sql, self.params)
1181
+ except QueryError:
1182
+ return None
1183
+
1184
+ def with_setup(self, variant: dict, m: Measurement) -> dict:
1185
+ """What has to be read while the variant's setup is still in place."""
1186
+ pending: dict = {}
1187
+ if not m.ok or not variant.get("same_results", True) or self.rows_only or m.result_hash == self.base.result_hash:
1188
+ return pending
1189
+ theirs = split_limit(variant.get("sql") or "")
1190
+ if self.limit and theirs and self.limit["has_order"] and m.result_rows == self.base.result_rows:
1191
+ pending["theirs"] = theirs
1192
+ pending["full"] = self._hash(theirs["sql"])
1193
+ return pending
1194
+
1195
+ def settle(self, variant: dict, m: Measurement, pending: dict) -> tuple[bool | None, str]:
1196
+ """(match, compared): match is None when sameness could not be decided, and `compared` says why."""
1197
+ if not variant.get("same_results", True):
1198
+ return None, BY_DESIGN
1199
+ if not m.ok:
1200
+ return None, ""
1201
+ if self.rows_only:
1202
+ return m.result_rows == self.base.result_rows, ROWS_ONLY
1203
+ if m.result_hash == self.base.result_hash:
1204
+ return True, ROWS
1205
+ if pending.get("full"):
1206
+ if self.full is False:
1207
+ self.full = self._hash(self.limit["sql"])
1208
+ if self.full and self.full == pending["full"]:
1209
+ return (True, TIES) if pending["theirs"]["order_by"] == self.limit["order_by"] else (None, ORDER_DIFFERS)
1210
+ if self.repeatable is None:
1211
+ again = self._hash(self.baseline_sql)
1212
+ self.repeatable = again is None or again == self.base.result_hash
1213
+ if not self.repeatable:
1214
+ return None, NOT_REPEATABLE
1215
+ if same_text(variant.get("sql") or "", self.baseline_sql) and access_path_only(variant.get("setup_sql") or []):
1216
+ return None, PLAN_DEPENDENT
1217
+ return False, ROWS
1218
+
1219
+
1220
+ def bench_candidate(sb, cand: dict, runs: int, log, on_event=lambda name, label, counts: None, production: dict | None = None,
1221
+ table_rows: int = 0, heavy: dict | None = None, typical_empty: bool = False) -> dict:
1222
+ """`heavy`: {params, production} for this query's heavy run (the 99th percentile of production's runs), or
1223
+ {built: False, reason}. The heavy run is the baseline with other parameter values, measured once and graded on its
1224
+ own. The verdicts of the variants are those of the typical run, except when the typical run returns nothing (as
1225
+ production's typical run of the query does, fidelity.empty_runs): each variant is then measured on the heavy run as
1226
+ well, its sameness is shown there, and the verdict covers both runs (combined_verdict, `heavy` in the record)."""
1227
+ if isinstance(cand.get("write"), dict):
1228
+ # a write statement (writes.py): run inside a rolled-back transaction, its final state compared (writebench.py)
1229
+ from . import writebench
1230
+ return writebench.bench_write(sb, cand, runs, log, on_event, cand["write"].get("settings"),
1231
+ (getattr(sb, "floor_bytes", 0), getattr(sb, "floor_rows", 0)))
1232
+ params = cand.get("params") or {}
1233
+ if getattr(sb, "resource_cfg", None) and hasattr(sb, "thread_override"):
1234
+ # production's threads for this shape: memory and wall time follow the thread count
1235
+ sb.thread_override = max(int(round(float((production or {}).get("threads_avg") or 0))), 0) or None
1236
+ base = sb.measure(cand["baseline_sql"], params, runs)
1237
+ out = {"finding": cand["finding"], "baseline": base.to_dict(), "variants": []}
1238
+ if getattr(sb, "thread_override", None):
1239
+ out["threads_from"] = "production"
1240
+ compare = Comparison(sb, cand, base, params)
1241
+ heavy_base: Measurement | None = None
1242
+ if production:
1243
+ out["fidelity"] = fidelity.check(out["baseline"], production, table_rows)
1244
+ if base.ok:
1245
+ zero = out["fidelity"].get("zero_targets") or {}
1246
+ log(f"{cand['finding']} against production's {out['fidelity'].get('graded_against', 'mean')} run: {out['fidelity']['grade']} ("
1247
+ + ", ".join([f"{k} x{v:g}" for k, v in out["fidelity"]["ratios"].items() if v is not None]
1248
+ + [f"{k}: production 0, sandbox {z['sandbox']:,}" for k, z in zero.items()]) + ")")
1249
+ if base.ok and heavy and heavy.get("params"):
1250
+ heavy_base = sb.measure(cand["baseline_sql"], heavy["params"], 1)
1251
+ m = heavy_base.to_dict()
1252
+ graded = fidelity.check(m, heavy["production"], table_rows)
1253
+ out["fidelity"]["heavy"] = {"built": True, "ok": bool(m.get("ok")), "grade": graded["grade"], "ratios": graded["ratios"],
1254
+ "production": graded["production"], "graded_against": heavy.get("basis") or "p99",
1255
+ "measured": {k: m.get(k) for k in ("read_rows", "read_bytes", "result_rows", "selected_parts", "selected_marks",
1256
+ "memory_bytes", "cpu_ms", "memory_kind")},
1257
+ **({"scale_bound": True} if graded.get("scale_bound") else {})}
1258
+ log(f"{cand['finding']} heavy run against production's 99th percentile: {graded['grade']} ("
1259
+ + ", ".join(f"{k} x{v:g}" for k, v in graded["ratios"].items() if v is not None) + ")")
1260
+ elif heavy and heavy.get("built") is False:
1261
+ out["fidelity"]["heavy"] = {"built": False, "reason": heavy.get("reason", "")}
1262
+ on_event("baseline", f"{cand['finding']} baseline {'measured' if base.ok else 'failed'}",
1263
+ {"finding": cand["finding"], "ok": base.ok, "read_rows": base.read_rows, "read_bytes": base.read_bytes,
1264
+ "duration_ms": round(base.duration_ms, 1), "variants": len(cand["variants"])})
1265
+ if not base.ok:
1266
+ log(f"{cand['finding']}: [red]baseline failed[/red] {base.error[:160]}")
1267
+ return out
1268
+ # the typical run returns nothing (or, an aggregate's one row, was made a run that finds nothing: fidelity.empty_runs):
1269
+ # sameness can only be shown on the heavy run, so every variant is measured there too
1270
+ empty = base.result_rows == 0 or typical_empty
1271
+ two_runs = empty and heavy_base is not None and heavy_base.ok and heavy_base.result_rows > 0
1272
+ heavy_params = (heavy or {}).get("params") or {}
1273
+ heavy_compare = Comparison(sb, cand, heavy_base, heavy_params) if two_runs else None
1274
+ if two_runs:
1275
+ out["variants_on"] = "typical and heavy run"
1276
+ # production's typical run returns rows and this one none, and no heavy run shows anything: the chosen values match no
1277
+ # row, so what any variant does here says nothing about the query (`parameters_match_no_rows`, blockers.py)
1278
+ wanted = (fidelity.target(production).get("rows_returned_per_run") or 0) if production else 0
1279
+ no_rows = base.result_rows == 0 and not typical_empty and wanted > 0 and not two_runs
1280
+ if no_rows:
1281
+ out["parameters_match_no_rows"] = {"production_rows_returned": wanted, "sandbox_rows_returned": 0, "read_rows": base.read_rows}
1282
+ log(f"{cand['finding']}: [yellow]could not be judged[/yellow]: the parameters match no rows (production's typical run returns "
1283
+ f"{wanted:,.0f})")
1284
+ pages = getattr(sb, "pages_decide", False)
1285
+ res_cfg = getattr(sb, "resource_cfg", None) if base.ok and not no_rows else None
1286
+ pooled: list[dict] = [] # every resource run the baseline had beside its variants
1287
+ cap_s = float(getattr(sb, "max_candidate_s", 0) or 0) # `[bench] max_candidate_s`: 0 is no cap
1288
+ began_cand = time.monotonic()
1289
+
1290
+ def lost_on_reads(m: Measurement, h: Measurement | None) -> bool:
1291
+ """The variant reads no less than its baseline (typical run, and the heavy one when measured), whatever its rows:
1292
+ its CPU and memory runs could not change a verdict, so they are not taken."""
1293
+ said = verdict(base, m, True, compare.rows_only, sb.floor_bytes, sb.floor_rows, match=True, pages_decide=pages)[0]
1294
+ if said in ("win", "mixed"):
1295
+ return False
1296
+ if h is not None and heavy_base is not None and heavy_base.ok:
1297
+ return verdict(heavy_base, h, True, compare.rows_only, sb.floor_bytes, sb.floor_rows, match=True,
1298
+ pages_decide=pages)[0] not in ("win", "mixed")
1299
+ return True
1300
+ for i, v in enumerate(cand["variants"]):
1301
+ rec = {"index": i, "kind": v["kind"], "setup_error": "", "storage_delta_bytes": 0, "setup_s": 0.0,
1302
+ # a scenario's rule variant keeps its tags (scenario_bind.align reads the record against it)
1303
+ **{k: v[k] for k in ("scenario", "change", "rule") if v.get("scenario") and v.get(k)}}
1304
+ if cap_s and time.monotonic() - began_cand > cap_s:
1305
+ # the candidate used its time (`[bench] max_candidate_s`): the variants after it are not run, and said
1306
+ rec.update(verdict="untested", reason=f"not run: the candidate passed its time cap of {cap_s:g} s ([bench] max_candidate_s)",
1307
+ measurement=None, cut="max_candidate_s")
1308
+ out["variants"].append(rec)
1309
+ out.setdefault("cut", {"setting": "max_candidate_s", "limit_s": cap_s, "variants_not_run": 0})["variants_not_run"] += 1
1310
+ log(f"{cand['finding']} variant {i + 1} ({v['kind']}): not run (time cap {cap_s:g} s, setting max_candidate_s in the bench table of codecop.toml)")
1311
+ continue
1312
+ before = sb.storage_bytes(cand["tables"], [])
1313
+ started = time.monotonic()
1314
+ notes: list[str] = []
1315
+ try:
1316
+ done = sb.apply_setup(v.get("setup_sql") or []) if not v.get("held_back") else []
1317
+ notes = list(done) if isinstance(done, list) else []
1318
+ except QueryError as e:
1319
+ rec["setup_error"] = str(e)[:500]
1320
+ rec["setup_s"] = round(time.monotonic() - started, 1)
1321
+ if notes:
1322
+ rec["setup_notes"] = notes # what the sandbox had to add for the setup to run (a table setting)
1323
+ m = hm = None
1324
+ pending: dict = {}
1325
+ heavy_pending: dict = {}
1326
+ res_runs: dict = {} # the resource runs of this variant (resources.py): taken while its setup is there
1327
+ if v.get("held_back"):
1328
+ # found before the sandbox was built (definitions.complete): it reads a column no definition has
1329
+ rec.update(verdict="failed", reason=f"not run: {v['held_back'].get('detail', '')[:300]}", measurement=None,
1330
+ held_back=v["held_back"].get("reason"))
1331
+ elif rec["setup_error"]:
1332
+ rec.update(verdict="failed", reason=f"setup failed: {rec['setup_error'][:240]}", measurement=None)
1333
+ else:
1334
+ m = sb.measure(v["sql"], params, runs)
1335
+ rec["storage_delta_bytes"] = sb.storage_bytes(cand["tables"], v.get("setup_sql") or []) - before
1336
+ pending = compare.with_setup(v, m)
1337
+ if heavy_compare is not None:
1338
+ hm = sb.measure(v["sql"], heavy_params, 1)
1339
+ heavy_pending = heavy_compare.with_setup(v, hm)
1340
+ if res_cfg and m.ok and lost_on_reads(m, hm):
1341
+ rec["resources"] = {"skipped": "reads_no_less", "detail": "reads no less than its baseline: CPU and memory runs not taken"}
1342
+ elif res_cfg and m.ok and v.get("setup_sql"):
1343
+ # the baseline must not see the setup: the variant's runs now, the baseline's right after the undo
1344
+ res_runs = _resource_runs_with_setup(sb, v, m, base, params, heavy_base, heavy_params, res_cfg, log, cand["finding"])
1345
+ note = ""
1346
+ if m is not None and m.ok and v.get("kind") == "projection" and hasattr(sb, "projection_note"):
1347
+ try:
1348
+ note = sb.projection_note(m, v.get("setup_sql") or []) # read while the projection is still there
1349
+ except (QueryError, SandboxError):
1350
+ note = ""
1351
+ sb.undo_setup(v.get("setup_sql") or [])
1352
+ if m is not None:
1353
+ match, compared = compare.settle(v, m, pending)
1354
+ why = compared.removeprefix("not compared: ") if match is None else ""
1355
+ if heavy_compare is not None and hm is not None:
1356
+ hmatch, hcompared = heavy_compare.settle(v, hm, heavy_pending)
1357
+ hwhy = hcompared.removeprefix("not compared: ") if hmatch is None else ""
1358
+ heavy_said = verdict(heavy_base, hm, v.get("same_results", True), heavy_compare.rows_only, sb.floor_bytes, sb.floor_rows,
1359
+ match=hmatch, why=hwhy, pages_decide=pages)
1360
+ # the typical run returned nothing, so it shows no sameness of its own: the heavy run's stands for it,
1361
+ # unless the typical run already returned other rows
1362
+ shown = hmatch if match is not False else False
1363
+ typical_said = verdict(base, m, v.get("same_results", True), compare.rows_only, sb.floor_bytes, sb.floor_rows,
1364
+ match=shown, why=hwhy if shown is None else why, pages_decide=pages, empty_shown=shown is True,
1365
+ typical_empty=typical_empty)
1366
+ rec["typical"] = {"verdict": typical_said[0], "reason": typical_said[1]}
1367
+ rec["heavy"] = {"verdict": heavy_said[0], "reason": heavy_said[1], "compared": hcompared,
1368
+ "results_match": hmatch if hm.ok else None, "measurement": hm.to_dict()}
1369
+ rec["verdict"], rec["reason"] = combined_verdict(typical_said, heavy_said)
1370
+ if match is not False:
1371
+ match, compared = hmatch, f"on the heavy run: {hcompared}"
1372
+ else:
1373
+ rec["verdict"], rec["reason"] = verdict(base, m, v.get("same_results", True), compare.rows_only, sb.floor_bytes, sb.floor_rows,
1374
+ match=match, why=why, pages_decide=pages, typical_empty=typical_empty)
1375
+ if no_rows and rec["verdict"] != "failed":
1376
+ # measured, and said, but not a verdict on the query: its run here finds nothing that production's finds
1377
+ rec["measured_verdict"] = rec["verdict"]
1378
+ rec["verdict"] = "untested"
1379
+ rec["reason"] = (f"could not be judged: the parameters match no rows (production's typical run returns {wanted:,.0f}, this "
1380
+ f"one none); measured: {rec['reason']}")
1381
+ if note:
1382
+ rec["projection_note"] = note
1383
+ if rec["verdict"] in ("slower", "no_change", "mixed"):
1384
+ rec["reason"] = f"{rec['reason']} ({note})"
1385
+ rec["compared"] = compared
1386
+ # what was measured, as opposed to `same_results`, which is what the variant claims
1387
+ rec["results_match"] = match if m.ok else None
1388
+ rec["measurement"] = m.to_dict()
1389
+ if res_cfg and m.ok and not (rec.get("resources") or {}).get("skipped"):
1390
+ _resource_profile(sb, cand, v, rec, base, hm, params, heavy_base, heavy_params, res_cfg, res_runs, pooled, log)
1391
+ out["variants"].append(rec)
1392
+ log(f"{cand['finding']} variant {i + 1} ({v['kind']}): {rec['verdict']}: {rec['reason'][:240]}")
1393
+ m = rec.get("measurement") or {}
1394
+ on_event("variant", f"{cand['finding']} {v['kind']}: {rec['verdict']}",
1395
+ {"finding": cand["finding"], "index": i, "kind": v["kind"], "verdict": rec["verdict"],
1396
+ "read_rows": m.get("read_rows"), "read_bytes": m.get("read_bytes")})
1397
+ if pooled:
1398
+ out["baseline"].update(resources_mod.baseline_fields(pooled, out["baseline"].get("cpu_kind") or ""))
1399
+ out["baseline"]["noisy"] = resources_mod.noisy(sb)
1400
+ return out
1401
+
1402
+
1403
+ def _resource_runs_with_setup(sb, v: dict, m: Measurement, base: Measurement, params: dict, heavy_base: Measurement | None,
1404
+ heavy_params: dict, cfg: dict, log, finding: str) -> dict:
1405
+ """The variant's resource runs while its setup is in place (the typical run, and the heavy one when it was built)."""
1406
+ try:
1407
+ n = resources_mod.runs_for(cfg, base.duration_ms, m.duration_ms)
1408
+ got = {"n": n, "var": resources_mod.alone(sb, v["sql"], params, n)}
1409
+ if heavy_base is not None and heavy_base.ok and heavy_params:
1410
+ got["heavy_var"] = resources_mod.alone(sb, v["sql"], heavy_params, n)
1411
+ return got
1412
+ except QueryError as e:
1413
+ log(f"{finding} {v['kind']}: resource runs failed: {str(e)[:160]}")
1414
+ return {"error": str(e)[:300]}
1415
+
1416
+
1417
+ def _resource_profile(sb, cand: dict, v: dict, rec: dict, base: Measurement, hm: Measurement | None, params: dict,
1418
+ heavy_base: Measurement | None, heavy_params: dict, cfg: dict, runs: dict, pooled: list[dict], log) -> None:
1419
+ """rec["resources"]: the variant's CPU, memory, time, spill and result size against its baseline (resources.py), on the
1420
+ typical run and, when it was built, the heavy run, and whether either takes a read-side win away (`judged`)."""
1421
+ if runs.get("error"):
1422
+ rec["resources"] = {"error": runs["error"]}
1423
+ return
1424
+ is_noisy = resources_mod.noisy(sb)
1425
+ m = rec["measurement"]
1426
+ try:
1427
+ heavy_ok = heavy_base is not None and heavy_base.ok and bool(heavy_params)
1428
+ if v.get("setup_sql"):
1429
+ n = runs["n"]
1430
+ base_runs, var_runs = resources_mod.alone(sb, cand["baseline_sql"], params, n), runs["var"]
1431
+ heavy_pair = (resources_mod.alone(sb, cand["baseline_sql"], heavy_params, n), runs.get("heavy_var") or []) if heavy_ok else None
1432
+ else:
1433
+ n = resources_mod.runs_for(cfg, base.duration_ms, float(m.get("duration_ms") or 0))
1434
+ base_runs, var_runs = resources_mod.interleaved(sb, cand["baseline_sql"], v["sql"], params, n)
1435
+ heavy_pair = resources_mod.interleaved(sb, cand["baseline_sql"], v["sql"], heavy_params, n) if heavy_ok else None
1436
+ except QueryError as e:
1437
+ log(f"{cand['finding']} {v['kind']}: resource runs failed: {str(e)[:160]}")
1438
+ rec["resources"] = {"error": str(e)[:300]}
1439
+ return
1440
+ pooled.extend(base_runs)
1441
+ interleave = not v.get("setup_sql")
1442
+ res = resources_mod.profile(base_runs, var_runs, base.to_dict(), m, interleave=interleave, is_noisy=is_noisy)
1443
+ if heavy_pair is not None:
1444
+ res["heavy"] = resources_mod.profile(heavy_pair[0], heavy_pair[1], heavy_base.to_dict(), hm.to_dict() if hm is not None else {},
1445
+ interleave=interleave, is_noisy=is_noisy)
1446
+ res["judged"] = resources_mod.judge(res, cfg)
1447
+ said = resources_mod.fact(res, cfg) if rec.get("verdict") == "no_change" else ""
1448
+ if said:
1449
+ res["fact"] = said
1450
+ rec["resources"] = res
1451
+ m.update(resources_mod.baseline_fields(var_runs, m.get("cpu_kind") or ""))
1452
+ m["noisy"] = is_noisy
1453
+ cpu, mem = res.get("cpu") or {}, res.get("memory") or {}
1454
+ log(f"{cand['finding']} {v['kind']}: resources over {res['runs']} {'interleaved ' if interleave else ''}runs: "
1455
+ + ", ".join(f"{k} x{r['ratio']:g} (x{r['low']:g} to x{r['high']:g})" for k, r in (("cpu", cpu), ("memory", mem))
1456
+ if r and r.get("ratio") is not None)
1457
+ + (" (beside other containers: CPU not judged)" if is_noisy else ""))
1458
+
1459
+
1460
+ def run(rank: dict, profile: dict, *, max_rows: int = 2_000_000, scales: tuple[float, ...] = (0.1, 1.0), runs: int = 3,
1461
+ runtime: str | None = None, log=lambda msg: None, on_event=lambda name, label, counts: None,
1462
+ realism: tuple = REALISM, production: dict[str, dict] | None = None, real_tables: dict[str, dict] | None = None,
1463
+ fit_rounds: int = 1, sandbox: dict | None = None, settings: dict | None = None, blocker_settings: dict | None = None,
1464
+ after_scale=None, on_checkpoint=None, production_settings: dict | None = None, statement_docs: list | None = None,
1465
+ before_load=None) -> dict:
1466
+ """`on_checkpoint(partial)`: called after each load group with the result so far (`partial: true`), so a run lost
1467
+ later keeps what it measured (the CLI writes it to bench.json).
1468
+
1469
+ `on_event(name, label, counts)` reports each table, baseline and verdict as it lands (labels and numbers only).
1470
+
1471
+ `production`: finding -> what the real query log says per run (rows_read_per_run, bytes_read_per_run,
1472
+ rows_returned_per_run), for the fidelity grade and the fit. `real_tables`: table -> real catalog sizes.
1473
+ `sandbox`: the version to run, as engines.sandbox_plan or Engine.resolve_version returns it. Left out, the
1474
+ version rank.json names is resolved here: a repository that targets a server older than the sandbox's own SQL
1475
+ supports is benchmarked on the nearest supported one, and the result says so (`engine_version_note`).
1476
+ `settings`: the `[bench]` table of codecop.toml (max_relation_parents). `blocker_settings`: its `[blockers]` table.
1477
+ `after_scale(sb, tables, profile, fraction, findings=...)`: the group benchmark (groupbench.py), called for each
1478
+ load group of each scale once its candidates ran, while that group's tables are still loaded (`tables`: those
1479
+ tables; `findings`: the candidates of that load group); the lists it returns are joined as the scale's `groups`.
1480
+ The load groups themselves are recorded as the scale's `load_groups` when there is more than one.
1481
+ `statement_docs`: what else the run sends besides the candidates (the plans of groups, loops and the advisor): the
1482
+ columns they name are read too (ReadColumns, `[bench] fill_unread_columns`).
1483
+
1484
+ The result's `summary` counts, at the largest scale, the candidates whose baseline ran (`benchmarked`), those
1485
+ whose tables could not be built (`not_benchmarked`) and those whose baseline the server refused (`baseline_failed`).
1486
+ A candidate one of whose tables was not built is never measured: it is recorded with `not_benchmarked` and the
1487
+ build error, so an empty table can not pass for "the baseline read nothing"."""
1488
+ started = time.monotonic()
1489
+ timer = PhaseTimer()
1490
+ production = production or {}
1491
+ settings = settings or {}
1492
+ engine = engines.get(rank["engine"])
1493
+ plan = sandbox or engine.resolve_version(rank.get("engine_version_requested") or rank.get("engine_version"),
1494
+ rank.get("engine_version_source") or "")
1495
+ version = plan.get("version") or rank["engine_version"]
1496
+ result = {
1497
+ "schema_version": 1, "tool_version": __version__,
1498
+ "generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
1499
+ "engine": rank["engine"], "engine_version": version,
1500
+ # what the repository targets, where that came from, and why another version ran (empty when the same one did)
1501
+ "engine_version_requested": plan.get("requested") or "", "engine_version_source": plan.get("source") or "",
1502
+ "engine_version_note": plan.get("note") or "", "sandbox_image": plan.get("image") or "",
1503
+ "evidence_tier": "profile-based synthetic",
1504
+ "max_rows": max_rows, "runs": runs, "scales": [],
1505
+ "limits": list(engine.limits),
1506
+ "realism": list(realism),
1507
+ }
1508
+ if plan.get("note"):
1509
+ if sandbox is None: # a caller that resolved the version has said it already
1510
+ log(f"[yellow]{plan['note']}[/yellow]")
1511
+ result["limits"].insert(0, plan["note"][0].upper() + plan["note"][1:] + ".")
1512
+ if "physical" in realism and rank["engine"] == "clickhouse":
1513
+ result["limits"] = [x for x in result["limits"] if not x.startswith("Measured right after loading")] + [
1514
+ "Tables are merged to the real number of parts per partition: by the partition's age when the real catalog has parts per "
1515
+ "partition (many small parts in the newest partitions), else the table's average (4 without a real catalog), at most "
1516
+ f"{int(settings.get('max_parts_per_partition') or 12)} in one partition, and then kept as they are; "
1517
+ "a deduplicating table gets duplicate versions for the profile's share of its rows (10% when the profile does not say).",
1518
+ "When a table's partition key (or its sorting key and a query's filter) depends on a time column, each part holds one contiguous "
1519
+ "range of that column, as parts written over time do: the oldest part of a partition covers the most time and each newer one "
1520
+ f"{float(settings.get('part_size_ratio') or parts_mod.DEFAULT_RATIO):g} times the one before (a stated shape: the real rows per part are "
1521
+ "not pulled), and a newer version of a row is in the next newer part. The fit may change that ratio towards production's parts selected."]
1522
+ heavy: dict | None = None
1523
+ if "fit" in realism and production and fit_rounds > 0:
1524
+ # a query whose 99th-percentile run is far from its median run gets a second run with rows of its own (fidelity.py)
1525
+ profile, heavy = fidelity.heavy_runs(rank["candidates"], production, profile)
1526
+ result["heavy_runs"] = heavy["notes"]
1527
+ built = [n["finding"] for n in heavy["notes"] if n["built"]]
1528
+ if built:
1529
+ log(f"{len(built)} baseline(s) get a heavy run beside the typical one (production's 99th percentile): {', '.join(built)}")
1530
+ related = relations_mod.resolve(rank, profile)
1531
+ measured_row_bytes: dict[str, float] = {}
1532
+ from .engines import base as engines_base
1533
+ engines_base.set_limits(settings.get("sandbox_cpus"), settings.get("sandbox_memory"), settings.get("sandbox_blkio_weight"),
1534
+ settings.get("sandbox_write_bps"))
1535
+ t_sb = time.monotonic()
1536
+ with sandbox_of(engine, version, runtime) as sb:
1537
+ timer.add("sandbox_start", time.monotonic() - t_sb)
1538
+ sb.__dict__.pop("_activity", None) # a kept sandbox: this run's statements only (timing.statements)
1539
+ sb.__dict__.pop("filled_reads", None)
1540
+ sb.stripped = [] # what this run's tables left out (a kept sandbox carried the last run's)
1541
+ sb.realism = tuple(realism)
1542
+ if settings.get("max_relation_parents") and hasattr(sb, "max_relation_parents"):
1543
+ sb.max_relation_parents = int(settings["max_relation_parents"])
1544
+ if settings.get("max_parts_per_partition") and hasattr(sb, "max_parts_per_partition"):
1545
+ sb.max_parts_per_partition = max(int(settings["max_parts_per_partition"]), 1)
1546
+ if settings.get("min_index_granularity") and hasattr(sb, "min_granularity"):
1547
+ sb.min_granularity = max(int(settings["min_index_granularity"]), 1) # scaled granules
1548
+ if settings.get("insert_block_bytes") and hasattr(sb, "insert_block_bytes"):
1549
+ sb.insert_block_bytes = max(int(settings["insert_block_bytes"]), 1_000_000)
1550
+ if settings.get("load_memory_share") and hasattr(sb, "load_memory_share"):
1551
+ sb.load_memory_share = min(max(float(settings["load_memory_share"]), 0.05), 0.95)
1552
+ if settings.get("copy_block_bytes") and hasattr(sb, "copy_block_bytes"):
1553
+ sb.copy_block_bytes = max(int(settings["copy_block_bytes"]), 1_000_000)
1554
+ if hasattr(sb, "persistent"):
1555
+ # PostgreSQL: one psql process for the run instead of one `podman exec` per script (`[bench] pg_persistent_session`)
1556
+ sb.persistent = settings.get("pg_persistent_session") is not False
1557
+ if settings.get("max_cut_partitions") is not None and hasattr(sb, "max_cut_partitions"):
1558
+ sb.max_cut_partitions = max(int(settings["max_cut_partitions"]), 0) # 0: always cut
1559
+ if settings.get("load_workers") and hasattr(sb, "load_workers"):
1560
+ sb.load_workers = max(int(settings["load_workers"]), 1)
1561
+ if hasattr(sb, "time_plan"):
1562
+ # ClickHouse, parts cut by time: "copy" (generate to a table sorted by time, copy each range out) or "direct"
1563
+ # (each range generated from its row numbers; the same rows, no copy; engines/clickhouse._load_time_ranged_direct)
1564
+ sb.ranged_load = str(settings.get("ranged_load") or RANGED_LOAD)
1565
+ if settings.get("restart_rss_share") is not None and hasattr(sb, "restart_rss_share"):
1566
+ sb.restart_rss_share = min(max(float(settings["restart_rss_share"]), 0.05), 1.0)
1567
+ if settings.get("restart_rss_growth_bytes") is not None and hasattr(sb, "restart_rss_growth"):
1568
+ sb.restart_rss_growth = max(int(settings["restart_rss_growth_bytes"]), 0)
1569
+ if settings.get("wait_for_memory_s") is not None and hasattr(sb, "wait_memory_s"):
1570
+ sb.wait_memory_s = max(float(settings["wait_for_memory_s"]), 0.0)
1571
+ if settings.get("wait_for_memory_bytes") is not None and hasattr(sb, "wait_memory_bytes"):
1572
+ sb.wait_memory_bytes = max(int(settings["wait_for_memory_bytes"]), 0)
1573
+ # one candidate's baseline and variants get at most this long; the variants after it are not run and said
1574
+ # (`[bench] max_candidate_s`, 0 for no cap)
1575
+ sb.max_candidate_s = float(settings["max_candidate_s"]) if settings.get("max_candidate_s") is not None else MAX_CANDIDATE_S
1576
+ # wide columns no statement of the run reads hold filler of their length (ReadColumns; ClickHouse, default on)
1577
+ sb.insert_settings = settings
1578
+ sb.unread_reader = ReadColumns(statement_texts(rank.get("candidates"), (heavy or {}).get("candidates"), profile.get("param_overrides"),
1579
+ statement_docs),
1580
+ int(settings.get("fill_unread_min_bytes") or FILL_UNREAD_MIN_BYTES)) \
1581
+ if settings.get("fill_unread_columns") is not False and hasattr(sb, "full_width_sample") else None
1582
+ if sb.unread_reader is not None:
1583
+ result["filled_columns_rule"] = (
1584
+ "Wide text columns that no statement, variant, index, projection, key or relation of the run names hold filler "
1585
+ "of the length the profile gives each row (setting fill_unread_columns): rows are as wide, so granules, parts, "
1586
+ "rows and bytes read are the same; disk use is smaller and insert sides are measured on a sample with full content.")
1587
+ result["memory"] = {"fresh_resident_bytes": int(getattr(sb, "fresh_resident", 0) or 0), "neighbours": []}
1588
+ result["disk"] = disk_check(sb, settings, log)
1589
+ if settings.get("statement_timeout_s") and hasattr(sb, "set_statement_timeout"):
1590
+ sb.set_statement_timeout(float(settings["statement_timeout_s"]))
1591
+ result["statement_timeout_s"] = float(getattr(sb, "statement_timeout_s", 0) or 0)
1592
+ # the resource profile of every variant against its baseline (resources.py): threads pinned, work_mem as production's
1593
+ res_cfg = resources_mod.settings_of(settings)
1594
+ if res_cfg["resources"] and hasattr(sb, "sample"):
1595
+ sb.resource_cfg = res_cfg
1596
+ result["resources"] = {**resources_mod.configure(sb, res_cfg, production_settings),
1597
+ "limits": {k: res_cfg[k] for k in ("memory_trade_off_ratio", "memory_trade_off_min_bytes",
1598
+ "cpu_trade_off_ratio", "cpu_trade_off_min_ms")}}
1599
+ else:
1600
+ sb.resource_cfg = None
1601
+ if hasattr(sb, "resource_threads") and not res_cfg["resources"]:
1602
+ sb.resource_threads = None # off: the runs keep the server's own thread count, as before
1603
+ ratio_setting = float(settings["part_size_ratio"]) if settings.get("part_size_ratio") is not None else None
1604
+ growth = float(settings.get("min_scale_growth") or MIN_SCALE_GROWTH)
1605
+ previous_rows: dict[str, int] = {}
1606
+ fit_extra: dict[str, int] = {} # finding -> scales its load group skipped: fit rounds it gets at the largest
1607
+ empties_done: set[str] = set() # findings whose typical run was made to return nothing where production's does
1608
+ result["scales_skipped"] = []
1609
+ result["server_version"] = sb.server_version()
1610
+ result["runtime"] = sb.runtime
1611
+ # at or under both, a baseline is already cheap: a smaller read is noise (verdict), and blockers.py says so
1612
+ result["floors"] = {"bytes": int(getattr(sb, "floor_bytes", 0) or 0), "rows": int(getattr(sb, "floor_rows", 0) or 0)}
1613
+ if before_load is not None:
1614
+ # the plan gate (plangate.py): every statement planned on the empty schema first; what does not plan is not loaded for
1615
+ t_gate = time.monotonic()
1616
+ rank, result["plan_gate"] = before_load(sb, rank)
1617
+ timer.add("plan_gate", time.monotonic() - t_gate)
1618
+ on_event("sandbox_ready", f"{engine.label} {result['server_version']}",
1619
+ {"server_version": result["server_version"], "scales": list(scales), "candidates": len(rank["candidates"]),
1620
+ "engine_version_requested": result["engine_version_requested"], "engine_version": version})
1621
+ for n, fraction in enumerate(scales):
1622
+ if previous_rows and growth > 1:
1623
+ most, planned = scale_growth(sb, rank, profile, max_rows, fraction, previous_rows, measured_row_bytes,
1624
+ settings.get("min_table_rows"))
1625
+ if most < growth:
1626
+ # the disk (or the real row counts) bounds every table near the size it already had: the same measurement again
1627
+ skipped = {"fraction": fraction, "most_growth": round(most, 2), "min_scale_growth": growth,
1628
+ "reason": f"no table could grow by x{growth:g} over the previous scale (at most x{most:.2f}): the sandbox's disk "
1629
+ "or the real row counts bound them; loading this scale would measure the same thing again",
1630
+ "tables": {t: {"rows_previous": previous_rows.get(t), "rows_planned": r} for t, r in planned.items()}}
1631
+ result["scales_skipped"].append(skipped)
1632
+ log(f"[yellow]scale {fraction:g} skipped: {skipped['reason']}[/yellow]")
1633
+ on_event("scale_skipped", f"Scale {fraction:g} skipped", {"scale": n, "fraction": fraction, "most_growth": skipped["most_growth"]})
1634
+ continue
1635
+ log(f"scale {fraction:g}: loading data")
1636
+ scale_began = time.monotonic()
1637
+ if hasattr(sb, "neighbours"):
1638
+ # on a shared host what other containers hold is memory this server's limit does not have (it follows the
1639
+ # host's free memory), so a run beside them is said, not left to fail with code 241
1640
+ near = {**sb.neighbours(), **({"memory_state": sb.memory_state()} if hasattr(sb, "memory_state") else {}), "fraction": fraction}
1641
+ result["memory"]["neighbours"].append(near)
1642
+ if near.get("containers"):
1643
+ log(f"[yellow]the sandbox is not alone on its host: {near['containers']} other container(s) hold "
1644
+ f"{near['memory_bytes'] / 1e6:,.0f} MB; the server's memory limit is {(near.get('memory_state') or {}).get('limit', 0) / 1e6:,.0f} MB "
1645
+ "now and follows the host's free memory, so memory figures and fits are measured beside them[/yellow]")
1646
+
1647
+ def at_scale(name: str, label: str, counts: dict, fraction=fraction, n=n) -> None:
1648
+ on_event(name, label, {"scale": n, "fraction": fraction, **counts})
1649
+
1650
+ at_scale("scale_started", f"Scale {fraction:g}: loading data", {"tables": len(rank["table_definitions"])})
1651
+ # the fixtures that say how many rows a run reads (the statements production ran) get their share of this
1652
+ # scale's tables (target_shares), before anything is placed
1653
+ by_name_now = {t["name"]: t for t in profile["tables"]}
1654
+ least_now = MIN_TABLE_ROWS if settings.get("min_table_rows") is None else max(int(settings["min_table_rows"]), 1)
1655
+ if hasattr(sb, "free_bytes"):
1656
+ _, planned_rows = sizing(sb, rank, by_name_now, max_rows, fraction, least_now, measured_row_bytes, tuple(realism),
1657
+ sb.free_bytes() + sum(held_bytes(sb, list(by_name_now)).values()))
1658
+ else:
1659
+ planned_rows = {n: sandbox_rows(t["rows"], max_rows, fraction, least_now) for n, t in by_name_now.items()}
1660
+ profile, share_notes = target_shares(profile, planned_rows)
1661
+ groups = plan_groups(rank, related, planned_rows, by_name_now, measured_row_bytes, tuple(realism), settings,
1662
+ together=getattr(after_scale, "together", None)) if len(rank["candidates"]) else \
1663
+ [{"findings": set(), "tables": {d["name"] for d in rank["table_definitions"]}, "units": []}]
1664
+ # (no candidate: a follow-up proof of a loop member made runnable by rule needs only its tables. The empty
1665
+ # list that stood here made take_group fail: "list indices must be integers or slices, not str")
1666
+ if n < len(scales) - 1 and settings.get("skip_scales_that_add_nothing") is not False and groups and groups != [[]]:
1667
+ # a load group whose every table the largest scale loads at the size it has here (it cannot grow), or at the
1668
+ # real catalog's row count, is measured there only: this scale would measure the same rows, or a cut-down copy
1669
+ # of a table whose real size is known. Its fit gets this scale's round at the largest scale instead.
1670
+ keep_g = []
1671
+ for g in groups:
1672
+ why = settled_why(g, by_name_now, planned_rows, real_tables, max_rows, scales[-1], least_now, growth)
1673
+ if why:
1674
+ result.setdefault("scales_skipped_groups", []).append({"fraction": fraction, "findings": sorted(g["findings"]),
1675
+ "tables": sorted(g["tables"]), "reason": why})
1676
+ for f in g["findings"]:
1677
+ fit_extra[f] = fit_extra.get(f, 0) + 1
1678
+ else:
1679
+ keep_g.append(g)
1680
+ if len(keep_g) < len(groups):
1681
+ log(f"scale {fraction:g}: {len(groups) - len(keep_g)} of {len(groups)} load group(s) measured at the largest scale only "
1682
+ "(their tables have the same rows there, or the real catalog's; setting skip_scales_that_add_nothing in the bench table of codecop.toml)")
1683
+ groups = keep_g
1684
+ if len(groups) > 1:
1685
+ log(f"scale {fraction:g}: {len(groups)} groups of tables that no candidate reads together, loaded and measured one after "
1686
+ "another (memory; setting group_loads in the bench table of codecop.toml)")
1687
+ tables: list[dict] = []
1688
+ findings: list[dict] = []
1689
+ fit_history: list[dict] = []
1690
+ group_records: list[dict] = []
1691
+ grouped: list[dict] | None = None
1692
+ insert_measured = 0
1693
+ clock = None
1694
+ ratio_seen: float | None = None
1695
+ pending = list(groups)
1696
+ g_index = 0
1697
+ kept: dict[str, dict] = {} # tables of the previous group the next one reads too: left loaded
1698
+ fresh = int(getattr(sb, "fresh_resident", 0) or 0)
1699
+ while pending:
1700
+ group, pending, budget = take_group(pending, ratio_seen, sb, planned_rows, by_name_now, measured_row_bytes, tuple(realism), settings)
1701
+ g_index += 1
1702
+ for g_attempt in (1, 2):
1703
+ try:
1704
+ g_rank = {**rank, "candidates": [c for c in rank["candidates"] if c["finding"] in group["findings"]],
1705
+ "table_definitions": [d for d in rank["table_definitions"] if d["name"] in group["tables"]]}
1706
+ restarts_before = len(getattr(sb, "restarts", []) or [])
1707
+ if group.get("split") and len(groups) >= 1:
1708
+ log(f"group {g_index}: split to fit the memory budget: {len(group['findings'])} candidate(s) of a group of tables that "
1709
+ "do not fit together; the rest follow, reusing the tables they share")
1710
+ g_heavy = None if heavy is None else {**heavy, "candidates": [h for h in heavy["candidates"] if h.get("heavy_of") in group["findings"]]}
1711
+ if len(groups) > 1:
1712
+ log(f"group {g_index}: {len(g_rank['candidates'])} candidate(s) on {', '.join(sorted(group['tables']))}")
1713
+ started_at = sb.server_now() if hasattr(sb, "server_now") else None
1714
+ if hasattr(sb, "clock"):
1715
+ sb.clock = None
1716
+ reuse = [kept[d["name"]] for d in g_rank["table_definitions"] if d["name"] in kept]
1717
+ to_load = {**g_rank, "table_definitions": [d for d in g_rank["table_definitions"] if d["name"] not in kept]}
1718
+ if reuse:
1719
+ log(f"group {g_index}: {len(reuse)} table(s) still loaded from the group before: {', '.join(t['name'] for t in reuse)}")
1720
+ with timer.time("load", len(to_load["table_definitions"])):
1721
+ g_tables = reuse + load_tables(sb, to_load, profile, max_rows, fraction, log, at_scale, real_tables=real_tables, relations=related,
1722
+ row_bytes=measured_row_bytes, min_kept_share=settings.get("min_kept_share"),
1723
+ min_table_rows=settings.get("min_table_rows"), part_size_ratio=ratio_setting,
1724
+ row_factor=group.get("row_factor"), memory_retries=settings.get("memory_retries"))
1725
+ # a table whose parts were cut by time carries the shape it was cut to, so the fit can change it (parts.py)
1726
+ shapes = {t["name"]: t["part_layout"] for t in g_tables if (t.get("part_layout") or {}).get("parts_hold") == "time ranges"}
1727
+ if shapes:
1728
+ profile = {**profile, "tables": [{**pt, "part_shape": {**(pt.get("part_shape") or {}), "ratio": shapes[pt["name"]]["part_size_ratio"],
1729
+ "basis": shapes[pt["name"]]["part_size_basis"]}}
1730
+ if pt["name"] in shapes else pt for pt in profile["tables"]]}
1731
+ first_seen = [c for c in g_rank["candidates"] if c["finding"] not in empties_done]
1732
+ empties_done.update(c["finding"] for c in g_rank["candidates"])
1733
+ if first_seen and "fit" in realism and production and fit_rounds > 0:
1734
+ # a query whose typical production run returns nothing gets a typical run that returns nothing (fidelity.py);
1735
+ # at the first scale its load group is measured at
1736
+ strings = {t["name"]: {c for c, ty in sb.column_types(t["name"]).items() if base_type(ty) == "String"}
1737
+ for t in g_tables if t.get("ok")} if hasattr(sb, "column_types") else None
1738
+ keys = {d["name"]: sorting_key(d.get("create_sql") or "") for d in g_rank["table_definitions"]}
1739
+ profile, empties = fidelity.empty_runs(first_seen, production, profile, strings, keys)
1740
+ result.setdefault("empty_runs", []).extend(empties)
1741
+ made = [e["finding"] for e in empties if e["empty"]]
1742
+ if made:
1743
+ log(f"{len(made)} typical run(s) return nothing, as production's median run does: {', '.join(made)} "
1744
+ "(parameter values no row holds; the variants are also measured on the heavy run)")
1745
+ # what a row really took, indexes included: the next, larger scale is sized by it
1746
+ measured_row_bytes.update({t["name"]: t["bytes_on_disk"] / t["rows"] for t in g_tables
1747
+ if t.get("ok") and t.get("rows") and t.get("bytes_on_disk")})
1748
+ # one instant for every measured query of this group, taken after the data (generated up to "now") is in
1749
+ g_clock = sb.freeze_clock() if hasattr(sb, "freeze_clock") else None
1750
+ clock = clock or g_clock
1751
+ sizes_loaded = {t["name"]: t["target_rows"] for t in g_tables if t.get("ok") and t.get("target_rows")}
1752
+
1753
+ def reload(changed_profile: dict, names: set[str], g_rank=g_rank, g_tables=g_tables, sizes_loaded=sizes_loaded) -> set[str]:
1754
+ """Rebuild these tables (a fit round): the names that were built before and could not be rebuilt."""
1755
+ was_ok = {t["name"] for t in g_tables if t.get("ok")}
1756
+ again = load_tables(sb, g_rank, changed_profile, max_rows, fraction, log, only=names,
1757
+ keep_rows=sizes_loaded, real_tables=real_tables, min_kept_share=settings.get("min_kept_share"),
1758
+ min_table_rows=settings.get("min_table_rows"), part_size_ratio=ratio_setting,
1759
+ memory_retries=settings.get("memory_retries"))
1760
+ for entry in again:
1761
+ at = next((i for i, t in enumerate(g_tables) if t["name"] == entry["name"]), None)
1762
+ if at is None:
1763
+ g_tables.append(entry)
1764
+ else:
1765
+ g_tables[at] = entry
1766
+ return {e["name"] for e in again if not e.get("ok") and e["name"] in was_ok}
1767
+
1768
+ # the statements production ran: their time window ends where the sandbox's data ends (anchor_times)
1769
+ anchored = anchor_times(sb, g_rank["candidates"], g_clock)
1770
+ if anchored:
1771
+ result.setdefault("time_windows", []).extend({**a, "fraction": fraction} for a in anchored)
1772
+ reach = measured_reach(sb, g_rank, profile)
1773
+ if reach:
1774
+ # a window on a time the profile writes as an expression: the share inside it is read on the loaded table,
1775
+ # and the fixtures are given the share that holds the rows a run reads there
1776
+ profile, again_notes = target_shares(profile, {t["name"]: t.get("target_rows") or planned_rows.get(t["name"]) for t in g_tables}, reach)
1777
+ share_notes = [s for s in share_notes if (s["table"], str(s["fixture"])) not in reach] + [s for s in again_notes if (s["table"], str(s["fixture"])) in reach]
1778
+ changed = {t for t, _ in reach}
1779
+ with timer.time("reload_time_window", len(changed)):
1780
+ reload(profile, changed)
1781
+ log(f"rows inside the time window measured on {', '.join(sorted(changed))}: shares set from them and reloaded")
1782
+ if "fit" in realism and production and fit_rounds > 0:
1783
+ try:
1784
+ with timer.time("fit"):
1785
+ extra = max((fit_extra.get(c["finding"], 0) for c in g_rank["candidates"]), default=0)
1786
+ profile, g_fit = fit_to_production(sb, g_rank, profile, production, reload, log, fit_rounds + extra, g_heavy)
1787
+ except SandboxError as e:
1788
+ # the server stopped in the fit (memory): the group is measured on what it has, unfitted, and said
1789
+ why = sb.revive() if hasattr(sb, "revive") else ""
1790
+ log(f"[yellow]group {g_index}: the sandbox stopped during the fit ({why or e}); measured without the fit[/yellow]")
1791
+ result.setdefault("fit_stopped", []).append({"group": g_index, "fraction": fraction, "why": why or str(e)[:200]})
1792
+ g_fit = []
1793
+ fit_history += [{**h, "group": g_index} for h in g_fit] if len(groups) > 1 else g_fit
1794
+ with timer.time("measure", len(g_rank["candidates"])):
1795
+ g_findings = measure_group(sb, g_rank, g_tables, profile, production, heavy, runs, log, at_scale, result,
1796
+ [c["finding"] for c in rank["candidates"]])
1797
+ if n == len(scales) - 1:
1798
+ # the write side of every table-level variant that read less, beside its read verdict (writecost.py);
1799
+ # measured per group, while the group's tables are still loaded
1800
+ from . import writecost
1801
+ t_ic = time.monotonic()
1802
+ got_ic = writecost.measure_findings(sb, g_rank, g_findings, settings, log)
1803
+ insert_measured += got_ic
1804
+ timer.add("insert_cost", time.monotonic() - t_ic, got_ic)
1805
+ peak = sb.memory_peak_since(started_at) if started_at and hasattr(sb, "memory_peak_since") else None
1806
+ planned_bytes = group_bytes(group["tables"], planned_rows, by_name_now, measured_row_bytes, tuple(realism))
1807
+ if peak and planned_bytes:
1808
+ # what the group needed above a fresh server, per planned byte: the next groups are planned by it
1809
+ ratio_seen = max(ratio_seen or 0.0, max(peak - fresh, 0) / planned_bytes)
1810
+ g_restarts = (getattr(sb, "restarts", []) or [])[restarts_before:]
1811
+ group_records.append({"group": g_index, "tables": sorted(group["tables"]), "findings": sorted(group["findings"]),
1812
+ "planned_bytes": planned_bytes, "peak_memory_bytes": peak, "memory_budget_bytes": budget,
1813
+ **({"split": True} if group.get("split") else {}),
1814
+ **({"row_factor": round(group["row_factor"], 4)} if group.get("row_factor") else {}),
1815
+ **({"reused_tables": [t["name"] for t in reuse]} if reuse else {}),
1816
+ **({"server_restarts": g_restarts} if g_restarts else {}),
1817
+ **({"clock": g_clock} if g_clock else {})})
1818
+ if len(groups) > 1:
1819
+ log(f"group {g_index}: peak memory {(peak or 0) / 1e6:,.0f} MB for {planned_bytes / 1e6:,.0f} MB of tables planned"
1820
+ + (f" (budget {budget / 1e6:,.0f} MB)" if budget else "")
1821
+ + (f"; the server was restarted {len(g_restarts)} time(s) to give back memory it held" if g_restarts else ""))
1822
+ if after_scale is not None:
1823
+ # the group benchmark, on this load group's tables while they are loaded: a scan group's members
1824
+ # share its table, so they are in one load group (plan_groups); the hook runs the groups whose
1825
+ # members are all among this group's findings
1826
+ try:
1827
+ with timer.time("groups_loops_advisor"):
1828
+ part = after_scale(sb, g_tables, profile, fraction, findings=set(group["findings"]))
1829
+ except SandboxError as e:
1830
+ sb.revive()
1831
+ part = [{"skip": "sandbox_could_not_run", "error": str(e)[:300]}]
1832
+ except Exception as e: # noqa: BLE001 -- the groups, loops and advisor of this load group: said, the run goes on
1833
+ log(f"[red]group {g_index}: the groups, loops and advisor could not finish: {type(e).__name__}: {e}[/red]")
1834
+ result.setdefault("could_not_finish", []).append(
1835
+ {"step": "groups, loops and advisor", "group": g_index, "fraction": fraction,
1836
+ "reason": f"{type(e).__name__}: {e}"[:300]})
1837
+ part = None
1838
+ if part is not None:
1839
+ grouped = (grouped or []) + list(part)
1840
+ if getattr(sb, "engine", "") == "postgres":
1841
+ from . import writecost
1842
+ writecost.release_sources(sb) # the rows the insert-side measurements of this group shared
1843
+ # live progress: the sandbox time so far and what is left, projected from the candidates done
1844
+ units_total = max(len(rank["candidates"]) * len(scales), 1)
1845
+ units_done = n * len(rank["candidates"]) + len({f["finding"] for f in findings} | set(group["findings"]))
1846
+ spent_s = time.monotonic() - started
1847
+ left_s = spent_s * max(units_total - units_done, 0) / max(units_done, 1)
1848
+ log(f"progress: scale {fraction:g}, load group {g_index}: {spent_s / 60:.0f} min of sandbox time so far, "
1849
+ f"about {left_s / 60:.0f} min left ({units_done} of {units_total} candidate-scales)")
1850
+ on_event("progress", f"{spent_s / 60:.0f} min so far, about {left_s / 60:.0f} min left",
1851
+ {"elapsed_s": round(spent_s), "left_s": round(left_s), "done": units_done, "total": units_total})
1852
+ seen = {t["name"] for t in g_tables}
1853
+ tables = [t for t in tables if t["name"] not in seen] + g_tables
1854
+ findings += g_findings
1855
+ kept = {}
1856
+ if pending and hasattr(sb, "release"):
1857
+ # the tables the next group reads too stay loaded (built once); the others' disk and memory go to it
1858
+ following = set(pending[0]["tables"]) if pending else set()
1859
+ kept = {t["name"]: t for t in g_tables if t["name"] in following and t.get("ok")}
1860
+ gone = [t["name"] for t in g_tables if t["name"] not in kept]
1861
+ if settings.get("keep_released_tables") is not False and isinstance(getattr(sb, "loaded", None), dict):
1862
+ # a sandbox kept for the run's later benches: the tables stay on disk for them (a follow-up
1863
+ # proof reads them as loaded) until a load needs their disk (load_tables); their caches go now
1864
+ sb.releasable = set(getattr(sb, "releasable", None) or ()) | set(gone)
1865
+ if hasattr(sb, "drop_caches"):
1866
+ sb.drop_caches()
1867
+ else:
1868
+ sb.release(gone)
1869
+ for name_gone in gone:
1870
+ if isinstance(getattr(sb, "loaded", None), dict):
1871
+ sb.loaded.pop(name_gone, None) # dropped: a later run loads it again
1872
+ if hasattr(sb, "bound_memory"):
1873
+ event = sb.bound_memory(f"after group {g_index}")
1874
+ if event:
1875
+ log(f"[yellow]server restarted after group {g_index}: {event['why']}; RSS "
1876
+ f"{event['resident_before'] / 1e6:,.0f} -> {event['resident_after'] / 1e6:,.0f} MB[/yellow]")
1877
+ break
1878
+ except SandboxError as e:
1879
+ # the sandbox was lost (the host killed it, it did not come back): the group runs once more on a fresh
1880
+ # sandbox; when that is lost too, its candidates are recorded as not judged and the run goes on
1881
+ why = str(e)[:300]
1882
+ kept = {}
1883
+ try:
1884
+ sb.stop()
1885
+ sb.start()
1886
+ if isinstance(getattr(sb, "loaded", None), dict):
1887
+ sb.loaded.clear() # a fresh sandbox holds no table
1888
+ fresh_ok = True
1889
+ except SandboxError as again:
1890
+ fresh_ok, why = False, f"{why}; a fresh sandbox did not start: {str(again)[:200]}"
1891
+ result.setdefault("sandbox_lost", []).append({"fraction": fraction, "group": g_index, "attempt": g_attempt,
1892
+ "why": why, "fresh_sandbox": fresh_ok})
1893
+ log(f"[red]group {g_index}: the sandbox was lost ({why})[/red]" + ("; the group runs again on a fresh sandbox"
1894
+ if g_attempt == 1 and fresh_ok else "; its candidates are not judged"))
1895
+ if g_attempt == 1 and fresh_ok:
1896
+ continue
1897
+ lost_groups = [group] + (pending if not fresh_ok else [])
1898
+ done = {f["finding"] for f in findings}
1899
+ findings += [lost_record(f, why) for g in lost_groups for f in sorted(g["findings"]) if f not in done]
1900
+ if not fresh_ok:
1901
+ pending = []
1902
+ break
1903
+ if on_checkpoint is not None:
1904
+ # what is measured so far, written as it lands: a run that is lost later keeps it
1905
+ on_checkpoint({**result, "partial": True, "scales": result["scales"] + [{"fraction": fraction, "tables": list(tables),
1906
+ "findings": list(findings), "partial": True}]})
1907
+ timer.scales.append({"fraction": fraction, "s": round(time.monotonic() - scale_began, 1), "load_groups": g_index,
1908
+ "tables": len(tables), "candidates": len(findings)})
1909
+ previous_rows = {t["name"]: int(t["target_rows"]) for t in tables if t.get("ok") and t.get("target_rows")}
1910
+ order = {c["finding"]: i for i, c in enumerate(rank["candidates"])}
1911
+ findings.sort(key=lambda f: order.get(f["finding"], len(order)))
1912
+ position = {d["name"]: i for i, d in enumerate(rank["table_definitions"])}
1913
+ tables.sort(key=lambda t: position.get(t["name"], len(position)))
1914
+ if n == len(scales) - 1:
1915
+ from . import writecost
1916
+ result["insert_cost"] = {**writecost.settings_of(settings), "measured": insert_measured}
1917
+ result["scales"].append({"fraction": fraction, "tables": tables, "findings": findings,
1918
+ **({"groups": grouped} if grouped is not None else {}),
1919
+ **({"clock": clock} if clock else {}),
1920
+ **({"load_groups": group_records} if len(group_records) > 1 else {}),
1921
+ **({"fixture_shares": share_notes} if share_notes else {}),
1922
+ **({"part_shapes": {t["name"]: t["part_shape"] for t in profile["tables"] if t.get("part_shape")}}
1923
+ if any(t.get("part_shape") for t in profile["tables"]) else {}),
1924
+ **({"fit": fit_history, "fitted_fixtures": {t["name"]: t.get("fixtures") or [] for t in profile["tables"]},
1925
+ "param_overrides": profile.get("param_overrides") or {}} if fit_history else {})})
1926
+ statements_timing = sb.activity.record() if hasattr(sb, "activity") else None
1927
+ if getattr(sb, "filled_reads", None):
1928
+ # statements that named a column holding filler: their rows and bytes read stand, the values they compared do not
1929
+ result["filled_reads"] = list(sb.filled_reads)
1930
+ result["limits"].append(f"{len(sb.filled_reads)} measured statement(s) named a column that held filler (filled_reads): "
1931
+ "their rows and bytes read are the full table's, the values they filtered or returned are not.")
1932
+ log(f"[yellow]{len(sb.filled_reads)} measured statement(s) named a column that held filler: see filled_reads in bench.json[/yellow]")
1933
+ if getattr(sb, "stripped", None):
1934
+ result["stripped"] = sorted(set(sb.stripped))
1935
+ if getattr(sb, "restarts", None):
1936
+ # restarts that gave back memory the server held (engines/clickhouse.bound_memory): events, not failures
1937
+ result["memory"]["server_restarts"] = list(sb.restarts)
1938
+ if any(s.get("clock") for s in result["scales"]):
1939
+ result["limits"].append("Every reading of the clock in a measured query (now(), CURRENT_DATE, today()) is one fixed instant, taken "
1940
+ "after the data was loaded, so a baseline and its variants see the same time window.")
1941
+ result["relations_skipped"] = [{**_public(r), "table": r["table"], "reason": r["reason"]} for r in related["skipped"]]
1942
+ judge_timeouts(result)
1943
+ result["summary"] = summary(result)
1944
+ # why each candidate did or did not end with a verified win: state, reason code, evidence (blockers.py)
1945
+ result["outcomes"] = blockers_mod.for_bench(rank, result, blocker_settings)
1946
+ result["duration_s"] = round(time.monotonic() - started, 1)
1947
+ cuts = [{"finding": f["finding"], **f["cut"]} for sc in result["scales"] for f in sc.get("findings") or [] if f.get("cut")]
1948
+ result["timing"] = {**timer.record(result["duration_s"]), **({"cut": cuts} if cuts else {}),
1949
+ **({"statements": statements_timing} if statements_timing else {}),
1950
+ # each table load: seconds, rows, bytes (a table reused from an earlier bench of the run: reused)
1951
+ "tables": [{"name": t["name"], "fraction": sc.get("fraction"), "load_s": t.get("load_s"), "rows": t.get("rows"),
1952
+ "bytes_on_disk": t.get("bytes_on_disk"), **({"reused": True} if t.get("reused_from_earlier_run") else {})}
1953
+ for sc in result["scales"] for t in sc.get("tables") or []
1954
+ if t.get("load_s") is not None or t.get("reused_from_earlier_run")]}
1955
+ return result
1956
+
1957
+
1958
+ # What one unit of sandbox work takes before this repository has a bench of its own (`timing` in bench.json): a table
1959
+ # load, a candidate measured at one scale (its baseline, its variants, their sameness and CPU runs), an insert-side
1960
+ # measurement (an index on the largest table copy), an advisor suggestion (built, every statement it serves measured).
1961
+ # Rough priors (PostgreSQL 17, podman on a laptop).
1962
+ SECONDS_PRIOR = {"load": 6.0, "measure": 8.0, "insert_cost": 20.0, "advisor": 25.0}
1963
+
1964
+
1965
+ def estimate_seconds(candidates: int, tables: int, scales: int, index_variants: int, advisor: int,
1966
+ history: dict | None = None) -> dict:
1967
+ """The sandbox time a bench is planned to take: (low, high) seconds and the basis, from the last bench's `timing` of
1968
+ this out dir (per unit of work) when there is one, else SECONDS_PRIOR. Low is 0.6x and high 1.6x the middle."""
1969
+ rates, basis = dict(SECONDS_PRIOR), "prior"
1970
+ phases = ((history or {}).get("timing") or {}).get("by_phase") or {}
1971
+ for k in ("load", "measure", "insert_cost"):
1972
+ p = phases.get(k) or {}
1973
+ if p.get("n") and p.get("s") is not None:
1974
+ rates[k], basis = float(p["s"]) / max(int(p["n"]), 1), "learned"
1975
+ hooks = phases.get("groups_loops_advisor") or {}
1976
+ n_adv = int(((history or {}).get("timing") or {}).get("advisor_suggestions") or 0)
1977
+ if hooks.get("s") and n_adv:
1978
+ rates["advisor"], basis = float(hooks["s"]) / n_adv, "learned"
1979
+ mid = (rates["load"] * tables * scales + rates["measure"] * candidates * scales + rates["insert_cost"] * index_variants
1980
+ + rates["advisor"] * advisor)
1981
+ return {"low_s": int(mid * 0.6), "high_s": int(mid * 1.6), "basis": basis, "rates": {k: round(v, 2) for k, v in rates.items()}}
1982
+
1983
+
1984
+ class PhaseTimer:
1985
+ """Wall-clock seconds by phase of one bench run (bench.json `timing`): what the next run's estimate learns from."""
1986
+
1987
+ def __init__(self):
1988
+ self.s: dict[str, float] = {}
1989
+ self.n: dict[str, int] = {}
1990
+ self.scales: list[dict] = []
1991
+
1992
+ def add(self, phase: str, seconds: float, n: int = 1) -> None:
1993
+ self.s[phase] = self.s.get(phase, 0.0) + max(float(seconds), 0.0)
1994
+ self.n[phase] = self.n.get(phase, 0) + int(n)
1995
+
1996
+ def time(self, phase: str, n: int = 1):
1997
+ timer = self
1998
+
1999
+ class _T:
2000
+ def __enter__(self):
2001
+ self.t = time.monotonic()
2002
+ return self
2003
+
2004
+ def __exit__(self, *exc):
2005
+ timer.add(phase, time.monotonic() - self.t, n)
2006
+ return False
2007
+ return _T()
2008
+
2009
+ def record(self, total: float) -> dict:
2010
+ known = sum(self.s.values())
2011
+ return {"total_s": round(total, 1), "by_phase": {k: {"s": round(v, 1), "n": self.n.get(k, 0)} for k, v in sorted(self.s.items(), key=lambda kv: -kv[1])},
2012
+ "other_s": round(max(total - known, 0.0), 1), "by_scale": self.scales}
2013
+
2014
+
2015
+ def settled_why(group: dict, by_name: dict, planned_rows: dict[str, int], real_tables: dict | None, max_rows: int, largest: float,
2016
+ least: int, growth: float) -> str:
2017
+ """Why a load group adds nothing at this (smaller) scale, or "": every table it loads either has here the rows the
2018
+ largest scale gives it (it cannot grow by `growth`: the same measurement twice), or is loaded at the largest scale at
2019
+ its real row count from the pulled catalog (this scale would measure a cut-down copy of a table whose size is known)."""
2020
+ if not group or not group.get("findings") or not group.get("tables"):
2021
+ return ""
2022
+ reasons = set()
2023
+ for name in group["tables"]:
2024
+ t = by_name.get(name)
2025
+ if t is None:
2026
+ return ""
2027
+ last = sandbox_rows(int(t.get("rows") or 0), max_rows, largest, least)
2028
+ now = int(planned_rows.get(name) or sandbox_rows(int(t.get("rows") or 0), max_rows, largest, least))
2029
+ real = int(((real_tables or {}).get(name) or {}).get("rows") or 0)
2030
+ if now and last < now * growth:
2031
+ reasons.add("same_rows")
2032
+ elif real and last == real:
2033
+ reasons.add("real_row_count")
2034
+ else:
2035
+ return ""
2036
+ return "real_row_count" if reasons == {"real_row_count"} else "same_rows" if reasons == {"same_rows"} else "same_rows_or_real_row_count"
2037
+
2038
+
2039
+ # One sandbox for every bench of a run (`codecop scan`: the free measurements, the proof of the agent's answers, the follow-up):
2040
+ # kept running between them, so a table loaded with the same definition, profile and rows is not loaded again
2041
+ # (load_tables, `sb.loaded`). Off unless a caller turns it on (keep_sandbox); close_kept() stops it.
2042
+ KEPT: dict = {"on": False, "sb": None, "key": None}
2043
+
2044
+
2045
+ def keep_sandbox(on: bool = True) -> None:
2046
+ KEPT["on"] = bool(on)
2047
+ if not on:
2048
+ close_kept()
2049
+
2050
+
2051
+ def close_kept() -> None:
2052
+ sb, KEPT["sb"], KEPT["key"] = KEPT.get("sb"), None, None
2053
+ if sb is not None:
2054
+ try:
2055
+ sb.__exit__(None, None, None)
2056
+ except Exception: # noqa: BLE001 -- stopping a sandbox that is already gone
2057
+ pass
2058
+
2059
+
2060
+ class _Kept:
2061
+ def __init__(self, engine, version: str, runtime: str | None):
2062
+ self.engine, self.version, self.runtime = engine, version, runtime
2063
+
2064
+ def __enter__(self):
2065
+ key = (self.engine.name, self.version, self.runtime)
2066
+ sb = KEPT.get("sb")
2067
+ if sb is not None and KEPT.get("key") == key:
2068
+ try:
2069
+ if not hasattr(sb, "_answers") or sb._answers():
2070
+ sb.reused_from_earlier_run = True
2071
+ return sb
2072
+ except Exception: # noqa: BLE001
2073
+ pass
2074
+ close_kept()
2075
+ elif sb is not None:
2076
+ close_kept()
2077
+ sb = self.engine.sandbox(self.version, runtime=self.runtime).__enter__()
2078
+ sb.loaded = {} # table -> (load key, entry): what is loaded now, for the next run of this process
2079
+ KEPT["sb"], KEPT["key"] = sb, key
2080
+ return sb
2081
+
2082
+ def __exit__(self, *exc):
2083
+ if exc and exc[0] is not None and issubclass(exc[0], (SandboxError, KeyboardInterrupt)):
2084
+ close_kept() # a lost or interrupted sandbox is not kept
2085
+ return False
2086
+
2087
+
2088
+ def sandbox_of(engine, version: str, runtime: str | None):
2089
+ """The sandbox of a bench run: a fresh one (stopped at the end), or the run's kept one (keep_sandbox)."""
2090
+ if KEPT.get("on"):
2091
+ return _Kept(engine, version, runtime)
2092
+ return engine.sandbox(version, runtime=runtime)
2093
+
2094
+
2095
+ def load_key(definition: dict, prof: dict | None, wanted: int, factor: float, row_factor, part_size_ratio, realism: tuple,
2096
+ keep: int | None, real: dict | None, parents: list, named: list | None = None) -> str:
2097
+ """What a loaded table depends on: its definition, its profile (columns, fixtures), the rows planned, the realism,
2098
+ the tables it follows and, when unread columns are filled, which columns the run's statements name. The same key
2099
+ twice in one kept sandbox: the table is not loaded again."""
2100
+ return json.dumps([definition.get("create_sql"), definition.get("name"), prof, wanted, round(float(factor or 1.0), 6),
2101
+ row_factor, part_size_ratio, list(realism), keep, real, parents] + ([named] if named is not None else []),
2102
+ sort_keys=True, default=str)
2103
+
2104
+
2105
+ def lost_record(finding: str, why: str) -> dict:
2106
+ """The record of a candidate whose load group was lost with the sandbox: not judged, with the reason."""
2107
+ detail = f"Not benchmarked: the sandbox was lost before this candidate was measured ({why[:200]})"
2108
+ return {"finding": finding, "not_benchmarked": {"reason": "sandbox_lost", "tables": [], "detail": detail},
2109
+ "baseline": Measurement(ok=False, error=detail).to_dict(), "variants": []}
2110
+
2111
+
2112
+ TIMED_OUT = re.compile(r"canceling statement due to statement timeout|TIMEOUT_EXCEEDED|Timeout exceeded: elapsed|"
2113
+ r"statement did not finish within", re.I)
2114
+
2115
+
2116
+ def timed_out(record: dict) -> bool:
2117
+ base = record.get("baseline") or {}
2118
+ return not base.get("ok") and bool(TIMED_OUT.search(base.get("error") or ""))
2119
+
2120
+
2121
+ def judge_timeouts(result: dict) -> None:
2122
+ """A baseline that hit the statement time limit at the largest scale is judged at the largest scale where it finished.
2123
+
2124
+ The largest scale's record is replaced by that scale's (`judged_at`: its fraction and largest table rows), and keeps
2125
+ the timeout as a fact (`timed_out`: the scale, the rows of its largest table, the limit and the server's message), so
2126
+ the report says both. With no scale where it finished, the record stays failed and says it timed out."""
2127
+ scales = result.get("scales") or []
2128
+ if not scales:
2129
+ return
2130
+ last = scales[-1]
2131
+ rows_at = lambda sc, f: max((t.get("rows", 0) for t in sc.get("tables") or [] if t.get("ok")), default=0) # noqa: E731
2132
+ for i, rec in enumerate(last.get("findings") or []):
2133
+ if not timed_out(rec):
2134
+ continue
2135
+ fact = {"fraction": last["fraction"], "largest_table_rows": rows_at(last, rec["finding"]),
2136
+ "statement_timeout_s": result.get("statement_timeout_s"), "error": (rec.get("baseline") or {}).get("error", "")[:200]}
2137
+ earlier = next((sc for sc in reversed(scales[:-1])
2138
+ for f in sc.get("findings") or [] if f["finding"] == rec["finding"] and (f.get("baseline") or {}).get("ok")), None)
2139
+ if earlier is None:
2140
+ last["findings"][i] = {**rec, "timed_out": fact}
2141
+ continue
2142
+ smaller = next(f for f in earlier["findings"] if f["finding"] == rec["finding"])
2143
+ last["findings"][i] = {**smaller, "timed_out": fact,
2144
+ "judged_at": {"fraction": earlier["fraction"], "largest_table_rows": rows_at(earlier, rec["finding"])}}
2145
+
2146
+
2147
+ def runtime_parts(c: dict, profile: dict | None) -> list[str]:
2148
+ """What of the candidate's baseline is only known at run time once its parameters are bound (blockers.unbound_parts)."""
2149
+ try:
2150
+ bound = set(fidelity.params_of(c, profile or {}) or {})
2151
+ except Exception: # noqa: BLE001 -- the parameters as the candidate carries them
2152
+ bound = set()
2153
+ bound |= set(c.get("params") or {})
2154
+ return blockers_mod.unbound_parts(c.get("baseline_sql") or "", bound)
2155
+
2156
+
2157
+ def measure_group(sb, rank: dict, tables: list[dict], profile: dict, production: dict, heavy: dict | None, runs: int, log, at_scale,
2158
+ result: dict, everyone: list[str] | None = None) -> list[dict]:
2159
+ """Every candidate of `rank` measured on the loaded `tables`: its baseline, heavy run and variants (bench_candidate).
2160
+ `everyone`: the findings of the whole run, in order, so the progress counts are the run's and not the group's."""
2161
+ findings = []
2162
+ everyone = everyone or [c["finding"] for c in rank["candidates"]]
2163
+ for c in rank["candidates"]:
2164
+ i = everyone.index(c["finding"]) if c["finding"] in everyone else 0
2165
+
2166
+ def tell(name: str, label: str, counts: dict, i=i) -> None:
2167
+ at_scale(name, label, {**counts, "candidate": i + 1, "candidates": len(everyone)})
2168
+ blocked = blocked_by(c, tables)
2169
+ if blocked:
2170
+ findings.append({"finding": c["finding"], "not_benchmarked": blocked,
2171
+ "baseline": Measurement(ok=False, error=blocked["detail"]).to_dict(), "variants": []})
2172
+ log(f"{c['finding']}: [yellow]not benchmarked[/yellow]: {blocked['detail'][:200]}")
2173
+ tell("baseline", f"{c['finding']} not benchmarked", {"finding": c["finding"], "ok": False, "not_benchmarked": True,
2174
+ "variants": len(c["variants"])})
2175
+ continue
2176
+ left = runtime_parts(c, profile)
2177
+ if left:
2178
+ # a placeholder no value is known for, or a part discover could not read: sent as it is it fails as a syntax
2179
+ # error; it is classed here, before anything runs, and is not counted as a failure of the sandbox
2180
+ detail = blockers_mod.runtime_detail(left)
2181
+ findings.append({"finding": c["finding"], "not_benchmarked": {"reason": blockers_mod.RUNTIME_TEXT, "detail": detail, "parts": left[:8]},
2182
+ "baseline": Measurement(ok=False, error=detail).to_dict(), "variants": []})
2183
+ log(f"{c['finding']}: [yellow]{detail}[/yellow]")
2184
+ tell("baseline", f"{c['finding']} not benchmarked", {"finding": c["finding"], "ok": False, "not_benchmarked": True,
2185
+ "variants": len(c["variants"])})
2186
+ continue
2187
+ try:
2188
+ largest = max((t.get("rows", 0) for t in tables if t["name"] in c.get("tables", [])), default=0)
2189
+ known = {"production": production[c["finding"]], "table_rows": largest} if c["finding"] in production else {}
2190
+ heavy_id = c["finding"] + fidelity.HEAVY
2191
+ if known and heavy and heavy_id in heavy["production"]:
2192
+ known["heavy"] = {"params": fidelity.params_of({**c, "finding": heavy_id}, profile), "production": heavy["production"][heavy_id]}
2193
+ elif known and heavy:
2194
+ known["heavy"] = next(({"built": False, "reason": n.get("reason", "")} for n in heavy["notes"]
2195
+ if n["finding"] == c["finding"] and not n["built"]), None)
2196
+ if known and not (known.get("heavy") or {}).get("params") and any(v.get("rule") == "empty_runs" for v in c.get("variants") or []):
2197
+ # an empty-runs scenario with no heavy run built (its 99th-percentile run is near the median): the
2198
+ # candidate's own values, whose fixture rows exist, are the run that shows sameness (scenario_bind.py)
2199
+ known["heavy"] = {"params": dict(c.get("params") or {}), "production": {}, "basis": "own_values"}
2200
+ if (profile.get("param_overrides") or {}).get(c["finding"]):
2201
+ c = {**c, "params": fidelity.params_of(c, profile)} # the fit gave this query values of its own
2202
+ emptied = any(e.get("empty") and e["finding"] == c["finding"] for e in result.get("empty_runs") or [])
2203
+ if hasattr(sb, "bound_memory"):
2204
+ sb.bound_memory(f"before {c['finding']}") # memory kept by the queries before: given back when high
2205
+ measured = bench_candidate(sb, c, runs, log, tell, **known, **({"typical_empty": True} if emptied and known else {}))
2206
+ notes = sandbox_notes(c, tables)
2207
+ if notes:
2208
+ measured["sandbox_notes"] = notes
2209
+ for key in ("time_window",):
2210
+ if c.get(key):
2211
+ measured[key] = c[key]
2212
+ if (c.get("observed") or {}).get("profile_basis"):
2213
+ measured["profile_basis"] = c["observed"]["profile_basis"] # per table: agent profile or catalog only
2214
+ findings.append(measured)
2215
+ except SandboxError as lost:
2216
+ # One query took the server down. That is this candidate's result, not the end of the run:
2217
+ # start the server again (the loaded data is kept) and go on with the next candidate.
2218
+ # Both steps go through the sandbox, so every engine recovers the same way.
2219
+ why = sb.revive()
2220
+ for v in c["variants"]:
2221
+ sb.undo_setup(v.get("setup_sql") or [])
2222
+ error = f"the sandbox server stopped while running this candidate ({why or 'connection lost'}: {str(lost)[:200]}); it was started again"
2223
+ findings.append({"finding": c["finding"], "baseline": Measurement(ok=False, error=error).to_dict(), "variants": [],
2224
+ "sandbox_restarted": True})
2225
+ result["sandbox_restarts"] = result.get("sandbox_restarts", 0) + 1
2226
+ log(f"{c['finding']}: [red]{error}[/red]")
2227
+ tell("baseline", f"{c['finding']} stopped the sandbox", {"finding": c["finding"], "ok": False, "sandbox_restarted": True,
2228
+ "variants": len(c["variants"])})
2229
+ except Exception as e: # noqa: BLE001 -- one candidate CodeCop could not handle is its own result, not the end of the run
2230
+ error = f"could not be judged: {type(e).__name__}: {e}"[:400]
2231
+ for v in c.get("variants") or []:
2232
+ try:
2233
+ sb.undo_setup(v.get("setup_sql") or [])
2234
+ except Exception: # noqa: BLE001
2235
+ pass
2236
+ findings.append({"finding": c["finding"], "baseline": Measurement(ok=False, error=error).to_dict(), "variants": [],
2237
+ "could_not_judge": error})
2238
+ log(f"{c['finding']}: [red]{error}[/red]")
2239
+ tell("baseline", f"{c['finding']} could not be judged", {"finding": c["finding"], "ok": False, "variants": len(c["variants"])})
2240
+ return findings
2241
+
2242
+
2243
+ GROUP_LOADS = True # setting group_loads under [bench]: tables no candidate reads together are loaded group by group
2244
+ MAX_CANDIDATE_S = 1800.0 # setting max_candidate_s under [bench]: one candidate's variants stop after this long (0: no cap)
2245
+ # Before any group was measured, a group is planned at this many bytes of memory per planned byte of its tables, on top of
2246
+ # what a fresh server holds (setting memory_per_planned_byte under [bench]). A loaded table at rest holds little memory;
2247
+ # what a group needs is its loads and its queries, and those grow with the tables it holds.
2248
+ MEMORY_PER_PLANNED_BYTE = 1.0
2249
+
2250
+
2251
+ def plan_groups(rank: dict, related: dict, planned_rows: dict[str, int], by_name: dict, row_bytes: dict, realism: tuple,
2252
+ settings: dict, together: list[set[str]] | None = None) -> list[dict]:
2253
+ """The candidates in groups that share no table: [{findings, tables, units}], the largest (by planned bytes) first.
2254
+
2255
+ Two candidates that read one table, or tables tied by a relation (relations.py: a child follows its parent's rows),
2256
+ are in one group. With `group_loads` off (setting under [bench]) everything is one group, as before.
2257
+
2258
+ `units`: the parts a group may be split into when it does not fit the memory (take_group): one per set of candidates
2259
+ that read the same tables, each with the tables it needs (its own and the parents they follow); candidates that must
2260
+ run together (`together`: the members of a scan group) are in one unit. Ties between candidates are transitive, so one
2261
+ group can hold dozens of tables; a unit holds only what its candidates read."""
2262
+ cands = list(rank["candidates"])
2263
+ defined = {d["name"] for d in rank["table_definitions"]}
2264
+ parents: dict[str, set[str]] = {}
2265
+ for rel in (related or {}).get("relations") or []:
2266
+ if rel.get("table") in defined and rel.get("parent") in defined:
2267
+ parents.setdefault(rel["table"], set()).add(rel["parent"])
2268
+
2269
+ def needs(names: set[str]) -> set[str]:
2270
+ out, todo = set(), list(names)
2271
+ while todo:
2272
+ t = todo.pop()
2273
+ if t not in out:
2274
+ out.add(t)
2275
+ todo += sorted(parents.get(t) or ())
2276
+ return out
2277
+
2278
+ def units_of(findings: set[str]) -> list[dict]:
2279
+ units: list[dict] = []
2280
+ for c in cands:
2281
+ if c["finding"] not in findings:
2282
+ continue
2283
+ key = tuple(sorted(needs({t for t in c.get("tables") or [] if t in defined})))
2284
+ u = next((x for x in units if x["key"] == key), None)
2285
+ if u is None:
2286
+ u = {"key": key, "findings": set(), "tables": set(key)}
2287
+ units.append(u)
2288
+ u["findings"].add(c["finding"])
2289
+ for members in together or []:
2290
+ hit = [u for u in units if u["findings"] & members]
2291
+ for u in hit[1:]:
2292
+ hit[0]["findings"] |= u["findings"]
2293
+ hit[0]["tables"] |= u["tables"]
2294
+ units.remove(u)
2295
+ units.sort(key=lambda u: (sorted(u["tables"]), sorted(u["findings"]))) # units that share tables side by side
2296
+ return [{"findings": u["findings"], "tables": u["tables"]} for u in units]
2297
+
2298
+ if settings.get("group_loads") is False or not cands or not rank["table_definitions"]:
2299
+ everything = {c["finding"] for c in cands}
2300
+ return [{"findings": everything, "tables": set(defined), "units": units_of(everything)}]
2301
+ parent: dict[str, str] = {}
2302
+
2303
+ def find(x: str) -> str:
2304
+ while parent.setdefault(x, x) != x:
2305
+ parent[x] = parent[parent[x]]
2306
+ x = parent[x]
2307
+ return x
2308
+
2309
+ def union(a: str, b: str) -> None:
2310
+ parent[find(a)] = find(b)
2311
+
2312
+ for c in cands:
2313
+ names = [t for t in c.get("tables") or [] if t in defined] or [f"(none):{c['finding']}"]
2314
+ for t in names[1:]:
2315
+ union(names[0], t)
2316
+ find(names[0])
2317
+ for child, ps in parents.items():
2318
+ for p in ps:
2319
+ union(child, p)
2320
+ groups: dict[str, dict] = {}
2321
+ for c in cands:
2322
+ names = [t for t in c.get("tables") or [] if t in defined] or [f"(none):{c['finding']}"]
2323
+ g = groups.setdefault(find(names[0]), {"findings": set(), "tables": set()})
2324
+ g["findings"].add(c["finding"])
2325
+ g["tables"] |= {t for t in names if t in defined}
2326
+ for d in rank["table_definitions"]: # a definition no candidate reads (a relation's parent) joins its group
2327
+ root = find(d["name"])
2328
+ if root in groups:
2329
+ groups[root]["tables"].add(d["name"])
2330
+ for g in groups.values():
2331
+ g["units"] = units_of(g["findings"])
2332
+ out = sorted(groups.values(), key=lambda g: -group_bytes(g["tables"], planned_rows, by_name, row_bytes, realism))
2333
+ return out or [{"findings": set(), "tables": set(), "units": []}]
2334
+
2335
+
2336
+ def group_bytes(tables, planned_rows: dict[str, int], by_name: dict, row_bytes: dict, realism: tuple) -> int:
2337
+ """Bytes the planned rows of these tables take (on disk, as sizing estimates them)."""
2338
+ return int(sum(planned_rows.get(n, 0) * (row_bytes.get(n) or estimated_row_bytes(by_name[n]["columns"], realism, by_name[n].get("fixtures")))
2339
+ for n in tables if n in by_name))
2340
+
2341
+
2342
+ def group_memory(tables, ratio: float, fresh: int, planned_rows: dict, by_name: dict, row_bytes: dict, realism: tuple) -> int:
2343
+ """The memory a group is planned to need: a fresh server's, and `ratio` bytes per planned byte of its tables."""
2344
+ return int(fresh + ratio * group_bytes(tables, planned_rows, by_name, row_bytes, realism))
2345
+
2346
+
2347
+ def EMPTY_GROUP() -> dict:
2348
+ """The one load group of a run with no candidate (a follow-up proof whose members need no statement): nothing to load,
2349
+ the hooks still run. A group, like plan_groups' (it was a bare list, which take_group could not read)."""
2350
+ return {"findings": set(), "tables": set(), "units": []}
2351
+
2352
+
2353
+ def take_group(pending: list[dict], ratio: float | None, sb, planned_rows: dict, by_name: dict, row_bytes: dict, realism: tuple,
2354
+ settings: dict) -> tuple[dict, list[dict], int | None]:
2355
+ """The next group to load, never planned above the memory budget (`group_memory_share`, default the load's
2356
+ load_memory_share, of the server's memory limit now: the limit follows the host's free memory).
2357
+
2358
+ A group is planned to need a fresh server's memory plus `ratio` per planned byte of its tables (measured on the groups
2359
+ so far: their peak above a fresh server per planned byte; `memory_per_planned_byte` before any). A group that does not
2360
+ fit is split by its units (plan_groups): the first units that fit load now, the rest are the next group (bench.run
2361
+ keeps the tables they share loaded). A unit that alone does not fit gets `row_factor`: its tables' rows are scaled
2362
+ down to fit, and each such table says so. Groups after a group that fits join it while they fit.
2363
+ Returns (group, the rest, the budget in bytes or None)."""
2364
+ first, rest = pending[0], pending[1:]
2365
+ budget = None
2366
+ if hasattr(sb, "_load_memory_budget"):
2367
+ share = settings.get("group_memory_share")
2368
+ if hasattr(sb, "wait_for_memory"):
2369
+ sb.wait_for_memory() # a host that other containers hold: some of its memory back before planning
2370
+ base = sb.plan_memory_budget() if hasattr(sb, "plan_memory_budget") else sb._load_memory_budget()
2371
+ if share is not None and getattr(sb, "load_memory_share", 0):
2372
+ base = int(base / sb.load_memory_share * min(max(float(share), 0.05), 0.95))
2373
+ budget = base or None
2374
+ fresh = int(getattr(sb, "fresh_resident", 0) or 0)
2375
+ per = ratio if ratio is not None else float(settings.get("memory_per_planned_byte") or MEMORY_PER_PLANNED_BYTE)
2376
+
2377
+ def need(tables) -> int:
2378
+ return group_memory(tables, per, fresh, planned_rows, by_name, row_bytes, realism)
2379
+
2380
+ group = {"findings": set(first["findings"]), "tables": set(first["tables"]), "units": list(first.get("units") or [])}
2381
+ if budget and need(group["tables"]) > budget and len(group["units"]) > 1:
2382
+ took, left = [], []
2383
+ tables: set[str] = set()
2384
+ for u in group["units"]:
2385
+ if not took or (not left and need(tables | u["tables"]) <= budget):
2386
+ took.append(u)
2387
+ tables |= u["tables"]
2388
+ else:
2389
+ left.append(u)
2390
+ if left:
2391
+ rest = [{"findings": set().union(*(u["findings"] for u in left)), "tables": set().union(*(u["tables"] for u in left)),
2392
+ "units": left, "split_from": True}] + rest
2393
+ group = {"findings": set().union(*(u["findings"] for u in took)), "tables": tables, "units": took, "split": True}
2394
+ if budget and need(group["tables"]) > budget:
2395
+ planned = group_bytes(group["tables"], planned_rows, by_name, row_bytes, realism)
2396
+ group["row_factor"] = max(min((budget - fresh) / max(per * planned, 1.0), 1.0), 0.01) if planned else 1.0
2397
+ return group, rest, budget
2398
+ if not rest or not budget or ratio is None or group.get("split"):
2399
+ return group, rest, budget
2400
+ left = []
2401
+ for g in rest:
2402
+ joined = group["tables"] | g["tables"]
2403
+ if not g.get("split_from") and need(joined) <= budget:
2404
+ group["findings"] |= g["findings"]
2405
+ group["tables"] = joined
2406
+ group["units"] = list(group.get("units") or []) + list(g.get("units") or [])
2407
+ else:
2408
+ left.append(g)
2409
+ return group, left, budget
2410
+
2411
+
2412
+ def blocked_by(cand: dict, tables: list[dict]) -> dict | None:
2413
+ """Why this candidate can not be measured: one of the tables it reads was not built. None when all of them were.
2414
+
2415
+ {reason: "table_not_built", tables: [{table, error}], detail}. A table with no entry (a name the definitions do
2416
+ not have) is left to the baseline: the server then says which relation is missing."""
2417
+ held = cand.get("held_back")
2418
+ if held:
2419
+ # found before the sandbox was built (definitions.complete): the query reads a column no definition has
2420
+ return {"reason": held.get("reason") or "definition_incomplete", "tables": [],
2421
+ "detail": "Not benchmarked: " + (held.get("detail") or "its table definition is incomplete")}
2422
+ by_name = {t["name"].replace('"', "").lower(): t for t in tables}
2423
+ bad = []
2424
+ for name in cand.get("tables") or []:
2425
+ t = by_name.get(name.replace('"', "").lower())
2426
+ if t is not None and not t.get("ok"):
2427
+ bad.append({"table": t["name"], "error": (t.get("error") or "not built")[:600]})
2428
+ if not bad:
2429
+ return None
2430
+ detail = "; ".join(f"table {b['table']} could not be built in the sandbox: {' '.join(b['error'].split())[:300]}" for b in bad)
2431
+ return {"reason": "table_not_built", "tables": bad, "detail": "Not benchmarked: " + detail}
2432
+
2433
+
2434
+ def sandbox_notes(cand: dict, tables: list[dict]) -> list[str]:
2435
+ """What about the sandbox's copy of this candidate's tables differs from the definition in a way that can move a
2436
+ verdict: an index that could not be built (a variant that adds it back would "win"), an invariant that was not kept."""
2437
+ wanted = {n.replace('"', "").lower() for n in cand.get("tables") or []}
2438
+ out = []
2439
+ for t in tables:
2440
+ if t["name"].replace('"', "").lower() not in wanted:
2441
+ continue
2442
+ out += [f"{t['name']}: {x}" for x in t.get("indexes_left_out") or []]
2443
+ out += [f"{t['name']}.{r['column']} was not made to follow {r['parent']}: {r['reason']}" for r in t.get("relations") or []
2444
+ if not r.get("enforced")]
2445
+ out += [f"{t['name']}.{r['column']}: {r['orphans'] + r['mismatched']:,} rows do not agree with {r['parent']}"
2446
+ for r in t.get("relations") or [] if r.get("enforced") and (r.get("orphans") or r.get("mismatched"))]
2447
+ return out
2448
+
2449
+
2450
+ def summary(result: dict) -> dict:
2451
+ """Counts at the largest scale: what was measured and what was not. `nothing_benchmarked` is true when there were
2452
+ candidates and not one baseline ran: the run has no result, and the command exits non-zero."""
2453
+ scales = result.get("scales") or []
2454
+ findings = scales[-1]["findings"] if scales else []
2455
+ tables = scales[-1]["tables"] if scales else []
2456
+ ok = sum(1 for f in findings if (f.get("baseline") or {}).get("ok"))
2457
+ skipped = sum(1 for f in findings if f.get("not_benchmarked"))
2458
+ # classed before anything ran (a part only known at run time): neither a failure nor a reason to say nothing ran
2459
+ run_time = sum(1 for f in findings if (f.get("not_benchmarked") or {}).get("reason") == blockers_mod.RUNTIME_TEXT)
2460
+ unjudged = sum(1 for f in findings if f.get("could_not_judge"))
2461
+ return {"candidates": len(findings), "benchmarked": ok, "not_benchmarked": skipped, "baseline_failed": len(findings) - ok - skipped,
2462
+ **({"known_at_run_time": run_time} if run_time else {}), **({"could_not_judge": unjudged} if unjudged else {}),
2463
+ "tables": len(tables), "tables_not_built": sum(1 for t in tables if not t.get("ok")),
2464
+ "nothing_benchmarked": len(findings) > run_time and ok == 0}