codecop 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (222) hide show
  1. codecop/__init__.py +7 -0
  2. codecop/access.py +140 -0
  3. codecop/access_postgres.py +284 -0
  4. codecop/advisor.py +1512 -0
  5. codecop/advisor_bench.py +493 -0
  6. codecop/advisor_ch.py +2080 -0
  7. codecop/advisor_view.py +381 -0
  8. codecop/advisors.py +184 -0
  9. codecop/agent.py +221 -0
  10. codecop/agentfacts.py +745 -0
  11. codecop/apply/__init__.py +327 -0
  12. codecop/apply/check.py +344 -0
  13. codecop/apply/cli.py +162 -0
  14. codecop/apply/clickhouse.py +379 -0
  15. codecop/apply/common.py +238 -0
  16. codecop/apply/html.py +264 -0
  17. codecop/apply/patch.py +213 -0
  18. codecop/apply/postgres.py +102 -0
  19. codecop/apply/trial.py +166 -0
  20. codecop/assemble.py +104 -0
  21. codecop/baseline.py +1043 -0
  22. codecop/bench.py +2464 -0
  23. codecop/blockers.py +935 -0
  24. codecop/budget.py +980 -0
  25. codecop/catalog_profile.py +525 -0
  26. codecop/changed.py +261 -0
  27. codecop/cicmd.py +1002 -0
  28. codecop/cli.py +5421 -0
  29. codecop/client.py +729 -0
  30. codecop/coverage.py +1067 -0
  31. codecop/coverage_reasons.py +116 -0
  32. codecop/crashlog.py +70 -0
  33. codecop/datagen.py +766 -0
  34. codecop/datagen_postgres.py +630 -0
  35. codecop/datagen_sqlite.py +323 -0
  36. codecop/dbcli.py +885 -0
  37. codecop/definitions.py +457 -0
  38. codecop/discover/__init__.py +702 -0
  39. codecop/discover/arms.py +160 -0
  40. codecop/discover/base.py +234 -0
  41. codecop/discover/dialect.py +296 -0
  42. codecop/discover/elixir.py +64 -0
  43. codecop/discover/engine_go.py +320 -0
  44. codecop/discover/go.py +1947 -0
  45. codecop/discover/java.py +1528 -0
  46. codecop/discover/loops.py +1671 -0
  47. codecop/discover/named_go.py +258 -0
  48. codecop/discover/origins.py +4565 -0
  49. codecop/discover/origins_ts.py +1584 -0
  50. codecop/discover/orm_django.py +2772 -0
  51. codecop/discover/orm_django_models.py +814 -0
  52. codecop/discover/orm_django_sql.py +662 -0
  53. codecop/discover/orm_ent.py +565 -0
  54. codecop/discover/orm_ex_ecto.py +2138 -0
  55. codecop/discover/orm_go.py +2134 -0
  56. codecop/discover/orm_go_bun.py +602 -0
  57. codecop/discover/orm_go_run.py +636 -0
  58. codecop/discover/orm_go_types.py +1082 -0
  59. codecop/discover/orm_java.py +1450 -0
  60. codecop/discover/orm_jdbi.py +743 -0
  61. codecop/discover/orm_jooq.py +806 -0
  62. codecop/discover/orm_jpa.py +1307 -0
  63. codecop/discover/orm_mybatis.py +730 -0
  64. codecop/discover/orm_py.py +557 -0
  65. codecop/discover/orm_py_peewee.py +1266 -0
  66. codecop/discover/orm_py_prisma.py +298 -0
  67. codecop/discover/orm_rb_activerecord.py +1906 -0
  68. codecop/discover/orm_rust.py +1248 -0
  69. codecop/discover/orm_rust_seaorm.py +734 -0
  70. codecop/discover/orm_sqlalchemy.py +2475 -0
  71. codecop/discover/orm_stats.py +307 -0
  72. codecop/discover/orm_tables.py +29 -0
  73. codecop/discover/orm_ts.py +503 -0
  74. codecop/discover/orm_ts_drizzle.py +697 -0
  75. codecop/discover/orm_ts_knex.py +1117 -0
  76. codecop/discover/orm_ts_kysely.py +861 -0
  77. codecop/discover/orm_ts_prisma.py +1045 -0
  78. codecop/discover/orm_ts_schema.py +169 -0
  79. codecop/discover/orm_ts_sequelize.py +1401 -0
  80. codecop/discover/orm_ts_typeorm.py +1067 -0
  81. codecop/discover/probes.py +323 -0
  82. codecop/discover/python.py +595 -0
  83. codecop/discover/ruby.py +793 -0
  84. codecop/discover/rust.py +2378 -0
  85. codecop/discover/schema.py +520 -0
  86. codecop/discover/schema_ent.py +145 -0
  87. codecop/discover/schema_ts.py +420 -0
  88. codecop/discover/tsresolve.py +257 -0
  89. codecop/discover/typescript.py +1728 -0
  90. codecop/discover/xml_mapper.py +526 -0
  91. codecop/engines/__init__.py +515 -0
  92. codecop/engines/base.py +498 -0
  93. codecop/engines/clickhouse.py +1558 -0
  94. codecop/engines/pg_ddl.py +444 -0
  95. codecop/engines/pg_hints.py +137 -0
  96. codecop/engines/postgres.py +1060 -0
  97. codecop/engines/sqlite.py +742 -0
  98. codecop/families/__init__.py +3 -0
  99. codecop/families/build.py +280 -0
  100. codecop/families/cli.py +177 -0
  101. codecop/families/coverage_hook.py +62 -0
  102. codecop/families/driver.py +221 -0
  103. codecop/families/goslice.py +229 -0
  104. codecop/families/goslice_tool/go.mod +3 -0
  105. codecop/families/goslice_tool/main.go +403 -0
  106. codecop/families/holes.py +451 -0
  107. codecop/families/images/Dockerfile.go +5 -0
  108. codecop/families/images/Dockerfile.python +4 -0
  109. codecop/families/images/Dockerfile.rust +4 -0
  110. codecop/families/isolate.py +171 -0
  111. codecop/families/locate.py +270 -0
  112. codecop/families/model.py +301 -0
  113. codecop/families/plangate.py +271 -0
  114. codecop/families/tagpatch.py +174 -0
  115. codecop/fidelity.py +671 -0
  116. codecop/fixgroups.py +130 -0
  117. codecop/formerly.py +91 -0
  118. codecop/grantscript.py +254 -0
  119. codecop/groupbench.py +1375 -0
  120. codecop/groups.py +594 -0
  121. codecop/groups_view.py +186 -0
  122. codecop/heat.py +1405 -0
  123. codecop/heatcli.py +219 -0
  124. codecop/joins.py +1749 -0
  125. codecop/joins_view.py +127 -0
  126. codecop/kinds/__init__.py +507 -0
  127. codecop/kinds/calls/__init__.py +501 -0
  128. codecop/kinds/calls/extract.py +1097 -0
  129. codecop/kinds/calls/harness.py +408 -0
  130. codecop/kinds/calls/measure.py +342 -0
  131. codecop/kinds/calls/rules.py +139 -0
  132. codecop/kinds/calls/runners/RunCalls.java +167 -0
  133. codecop/kinds/calls/runners/run_go.go +141 -0
  134. codecop/kinds/calls/runners/run_node.js +186 -0
  135. codecop/kinds/calls/runners/run_python.py +319 -0
  136. codecop/kinds/calls/runners/run_rust.rs +200 -0
  137. codecop/kinds/calls/standin.py +340 -0
  138. codecop/kinds/pipeline.py +288 -0
  139. codecop/kinds/regex/__init__.py +1167 -0
  140. codecop/kinds/regex/engines/RegexHarness.java +129 -0
  141. codecop/kinds/regex/engines/run_go.go +294 -0
  142. codecop/kinds/regex/engines/run_node.js +99 -0
  143. codecop/kinds/regex/engines/run_python.py +295 -0
  144. codecop/kinds/regex/engines/run_rust.rs +149 -0
  145. codecop/kinds/regex/extract.py +1438 -0
  146. codecop/kinds/regex/harness.py +235 -0
  147. codecop/kinds/regex/measure.py +270 -0
  148. codecop/kinds/regex/shapes.py +418 -0
  149. codecop/kinds/regex/syntax.py +1721 -0
  150. codecop/kinds/testkind.py +107 -0
  151. codecop/kinds/transaction/__init__.py +228 -0
  152. codecop/kinds/transaction/bind.py +355 -0
  153. codecop/kinds/transaction/measure.py +264 -0
  154. codecop/kinds/transaction/plan.py +462 -0
  155. codecop/kinds/transaction/rules.py +540 -0
  156. codecop/kinds/transaction/sandbox.py +94 -0
  157. codecop/kinds/transaction/scenarios.py +520 -0
  158. codecop/kinds/transaction/schedule.py +483 -0
  159. codecop/kinds/transaction/shapes.py +418 -0
  160. codecop/kinds/transaction/verify.py +293 -0
  161. codecop/live.py +237 -0
  162. codecop/loopbench.py +2071 -0
  163. codecop/loopschema.py +591 -0
  164. codecop/mcpserver.py +120 -0
  165. codecop/mechanism.py +214 -0
  166. codecop/members.py +200 -0
  167. codecop/multi.py +443 -0
  168. codecop/observed.py +1868 -0
  169. codecop/parts.py +102 -0
  170. codecop/patterns.py +830 -0
  171. codecop/patterns_view.py +559 -0
  172. codecop/plangate.py +242 -0
  173. codecop/profile.py +439 -0
  174. codecop/prompts/areas.md +19 -0
  175. codecop/prompts/observed_variants.md +20 -0
  176. codecop/prompts/profile.md +60 -0
  177. codecop/prompts/profile_postgres.md +68 -0
  178. codecop/prompts/profile_sizes.md +26 -0
  179. codecop/prompts/profile_sqlite.md +69 -0
  180. codecop/prompts/rank.md +84 -0
  181. codecop/prompts/rank_postgres.md +96 -0
  182. codecop/prompts/rank_sqlite.md +94 -0
  183. codecop/prompts/scenario_variants.md +20 -0
  184. codecop/rank.py +1473 -0
  185. codecop/realdb/__init__.py +688 -0
  186. codecop/realdb/clickhouse.py +1223 -0
  187. codecop/realdb/facts.py +815 -0
  188. codecop/realdb/locality.py +964 -0
  189. codecop/realdb/locks.py +355 -0
  190. codecop/realdb/match.py +531 -0
  191. codecop/realdb/postgres.py +643 -0
  192. codecop/realdb/ratios.py +77 -0
  193. codecop/realdb/sample.py +126 -0
  194. codecop/relations.py +227 -0
  195. codecop/report.py +1854 -0
  196. codecop/resources.py +332 -0
  197. codecop/resources_view.py +266 -0
  198. codecop/rules/entry_points.toml +1013 -0
  199. codecop/rules/sinks.toml +362 -0
  200. codecop/runsonce.py +8 -0
  201. codecop/sandboxschema.py +555 -0
  202. codecop/scenario_agent.py +172 -0
  203. codecop/scenario_bind.py +507 -0
  204. codecop/scenario_sql.py +971 -0
  205. codecop/scenarios.py +675 -0
  206. codecop/scenarios_view.py +274 -0
  207. codecop/schemacli.py +67 -0
  208. codecop/schemas/areas_output.schema.json +21 -0
  209. codecop/schemas/profile_output.schema.json +362 -0
  210. codecop/schemas/rank_output.schema.json +385 -0
  211. codecop/sizes.py +200 -0
  212. codecop/sqlinfo.py +558 -0
  213. codecop/typedparams.py +576 -0
  214. codecop/verdicts.py +212 -0
  215. codecop/writebench.py +720 -0
  216. codecop/writecost.py +440 -0
  217. codecop/writes.py +1208 -0
  218. codecop-0.1.0.dist-info/METADATA +42 -0
  219. codecop-0.1.0.dist-info/RECORD +222 -0
  220. codecop-0.1.0.dist-info/WHEEL +4 -0
  221. codecop-0.1.0.dist-info/entry_points.txt +2 -0
  222. codecop-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,1558 @@
1
+ """ClickHouse sandbox adapter: a throwaway server in a container, driven over HTTP.
2
+
3
+ Everything that builds, loads or alters a table happens here and only here. This
4
+ module never connects to anything but the container it started.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import http.client
11
+ import json
12
+ import re
13
+ import subprocess
14
+ import time
15
+ import urllib.error
16
+ import urllib.parse
17
+ import urllib.request
18
+ import uuid
19
+ from concurrent.futures import ThreadPoolExecutor
20
+ from datetime import date
21
+ from ..datagen import ident
22
+ from .base import Measurement, QueryError, SandboxError, fill_resources, find_runtime, list_sandboxes, outside_quotes # noqa: F401 (re-exported)
23
+ from .base import Activity, StopOnSignal, publish_args, reap_orphans, remove_sandbox, sandbox_network, sandbox_run_args, start_container, statement_kind
24
+
25
+ IMAGE = "docker.io/clickhouse/clickhouse-server"
26
+ MAX_QUERY_SECONDS = 180 # a measured query that runs longer on sandbox-sized data is recorded as failed
27
+ CLUSTER_ENGINE = re.compile(r"\b(Replicated|Shared)(\w*MergeTree)\b(?:\s*\(((?:[^()']|'[^']*'|\([^()]*\))*)\))?", re.I)
28
+
29
+
30
+ CREATED = re.compile(r"^\s*CREATE\s+(?:OR\s+REPLACE\s+)?(MATERIALIZED\s+VIEW|VIEW|TABLE|DICTIONARY)\s+(?:IF\s+NOT\s+EXISTS\s+)?([`\"\w.]+)", re.I)
31
+ PLAIN_COPY = re.compile(r"^\s*INSERT\s+INTO\s+([`\"\w.]+)\s+SELECT\s+\*\s+FROM\s+([`\"\w.]+)\s*;?\s*$", re.I)
32
+ DEDUPLICATING = re.compile(r"\b(?:Replicated|Shared)?(Replacing|Coalescing)MergeTree\b", re.I)
33
+ # Unknown without a sample of the real table: the share of rows that exist in more than one version (not yet merged away).
34
+ DEFAULT_DUPLICATE_SHARE = 0.1
35
+ DEFAULT_PARTS_PER_PARTITION = 4.0
36
+ MAX_PARTS_PER_PARTITION = 12
37
+ STAGE_SUFFIX = "__codecop_stage"
38
+ ROWS_SUFFIX = "__codecop_rows"
39
+ MAX_CUT_PARTITIONS = 500
40
+ FULL_SUFFIX = "__codecop_full" # a sample of rows with full content when unread columns hold filler (full_width_sample)
41
+ KEYS_SUFFIX = "__codecop_keys" # row numbers and their time, partitioned like the table (_load_time_ranged_direct)
42
+ MERGE_WORKERS = 4
43
+ GENERATED_FILL = re.compile(r"^\((?P<cols>[^()]*)\) (?P<body>(?:WITH .*? )?SELECT .*? FROM numbers\(\d+, \d+\))(?P<tail>(?: SETTINGS [\w ,.=]+)?)$", re.S)
44
+
45
+
46
+ def _direct_body(fill: str) -> tuple[str, str] | None:
47
+ """(the SELECT, its SETTINGS clause) of a generating INSERT's text after `INSERT INTO t `, when every value in it
48
+ comes from the row number alone (one `numbers(o, n)`, no relation lookups); else None."""
49
+ m = GENERATED_FILL.match(fill)
50
+ if not m or fill.count("numbers(") != 1 or "joinGet" in fill:
51
+ return None
52
+ return m.group("body"), m.group("tail")
53
+ # A merge may not produce a part larger than this, so no merge is ever chosen and the loaded parts stay as they are.
54
+ # Mutations (a variant's ADD INDEX or projection) still run, which SYSTEM STOP MERGES would block.
55
+ KEEP_PARTS = "max_bytes_to_merge_at_max_space_in_pool = 1"
56
+ ADDED = re.compile(r"^\s*ALTER\s+TABLE\s+([`\"\w.]+)\s+ADD\s+(PROJECTION|INDEX)\s+(?:IF\s+NOT\s+EXISTS\s+)?([`\"\w]+)", re.I)
57
+
58
+
59
+ quote_ident = ident # one column or table name, backquoted (datagen.ident); every name the sandbox writes goes through it
60
+
61
+
62
+ def quote_table(name: str) -> str:
63
+ """A table name, possibly `database.table`, with each part backquoted. A name that already carries quotes is taken as
64
+ written (a variant's own setup statement names its tables itself)."""
65
+ n = str(name)
66
+ if "`" in n or '"' in n:
67
+ return n
68
+ return ".".join(quote_ident(p) for p in n.split(".", 1))
69
+
70
+
71
+ def undo_statements(setup_sql: list[str]) -> list[str]:
72
+ """Statements that remove what a variant's setup created, newest first."""
73
+ undo = []
74
+ for stmt in setup_sql:
75
+ m = CREATED.match(stmt)
76
+ if m:
77
+ kind = "VIEW" if "VIEW" in m.group(1).upper() else m.group(1).upper()
78
+ undo.append(f"DROP {kind} IF EXISTS {m.group(2)} SYNC")
79
+ continue
80
+ m = ADDED.match(stmt)
81
+ if m:
82
+ undo.append(f"ALTER TABLE {m.group(1)} DROP {m.group(2).upper()} IF EXISTS {m.group(3)} SETTINGS mutations_sync = 2")
83
+ return list(reversed(undo))
84
+
85
+
86
+ def plain_engine(create_sql: str) -> str:
87
+ """Replicated*/Shared* engines need a cluster (or ClickHouse Cloud); the sandbox is one server, so every such engine
88
+ becomes its local equivalent: ReplicatedReplacingMergeTree('/path', '{replica}', ver) and
89
+ SharedReplacingMergeTree('/clickhouse/tables/{uuid}/{shard}', '{replica}', ver) become ReplacingMergeTree(ver); the
90
+ forms with no arguments (SharedMergeTree, ReplicatedMergeTree with the server's default path) become MergeTree().
91
+ Only the leading quoted arguments are cluster paths: an engine's own string argument after a column name stays."""
92
+ def swap(m: re.Match) -> str:
93
+ args = [a.strip() for a in _engine_args(m.group(3) or "")]
94
+ if len(args) >= 2 and all(a.startswith(("'", '"')) for a in args[:2]):
95
+ rest = args[2:]
96
+ elif args and args[0].startswith(("'", '"')) and m.group(1).lower() == "shared":
97
+ rest = args[1:]
98
+ else:
99
+ rest = args
100
+ return f"{m.group(2)}({', '.join(rest)})"
101
+ return CLUSTER_ENGINE.sub(swap, create_sql or "")
102
+
103
+
104
+ def _engine_args(text: str) -> list[str]:
105
+ out, depth, cur, quote = [], 0, "", ""
106
+ for c in text:
107
+ if quote:
108
+ cur += c
109
+ if c == quote:
110
+ quote = ""
111
+ continue
112
+ if c in "'\"":
113
+ quote = c
114
+ elif c == "(":
115
+ depth += 1
116
+ elif c == ")":
117
+ depth -= 1
118
+ if c == "," and depth == 0:
119
+ out.append(cur)
120
+ cur = ""
121
+ else:
122
+ cur += c
123
+ if cur.strip():
124
+ out.append(cur)
125
+ return [a for a in out if a.strip()]
126
+
127
+
128
+ def copy_columns(into: dict[str, str], have: dict[str, str]) -> str:
129
+ """`(a, b) SELECT a, b` for a copy from a table with columns `have` into one with columns `into`, matched by name (both
130
+ the columns a row can be written to, in table order). `SELECT *` when no column is shared."""
131
+ names = [n for n in into if n in have]
132
+ if not names:
133
+ return "SELECT *"
134
+ listed = ", ".join(quote_ident(n) for n in names)
135
+ return f"({listed}) SELECT {listed}"
136
+
137
+
138
+ COPY_AS = re.compile(r"^\s*CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`\"\w.]+\s+AS\s+([`\"\w.]+)\s+ENGINE\b", re.I)
139
+ MIN_GRANULARITY = 64 # `[bench] min_index_granularity`: the smallest scaled granule (rows)
140
+ DEFAULT_GRANULARITY_BYTES = 10_485_760
141
+ MIN_GRANULARITY_BYTES = 1024 # the server refuses an adaptive granule limit below min_index_granularity_bytes
142
+
143
+
144
+ def with_merge_settings(create_sql: str, wanted: dict[str, int]) -> str:
145
+ """The CREATE statement with these MergeTree settings set: replaced where its SETTINGS clause has them, added to it
146
+ otherwise, or a SETTINGS clause appended (before a trailing COMMENT)."""
147
+ sql = create_sql.rstrip().rstrip(";")
148
+ m = re.search(r"\bSETTINGS\b", sql, re.I)
149
+ if m:
150
+ for k, v in wanted.items():
151
+ sql, n = re.subn(rf"\b{k}\s*=\s*\d+", f"{k} = {int(v)}", sql, flags=re.I)
152
+ if not n:
153
+ at = re.search(r"\bSETTINGS\b", sql, re.I).end()
154
+ sql = f"{sql[:at]} {k} = {int(v)},{sql[at:]}"
155
+ return sql
156
+ clause = " SETTINGS " + ", ".join(f"{k} = {int(v)}" for k, v in wanted.items())
157
+ c = re.search(r"\s+COMMENT\s+'(?:[^'\\]|\\.)*'\s*$", sql, re.I)
158
+ return sql[:c.start()] + clause + sql[c.start():] if c else sql + clause
159
+
160
+
161
+ def scaled_granularity(create_sql: str, rows_per_mark: float, share: float, least: int = MIN_GRANULARITY) -> dict | None:
162
+ """The index granularity that gives a sandbox table at `share` of production's rows as many granules a part as
163
+ production has (rows per mark x share, at least `least`), and the adaptive byte limit scaled with it. None when no
164
+ scaling is needed (share 1 or more, or nothing known). Re-keys and projections are judged on the marks this gives;
165
+ skip indexes never are: small granules hold a scattered value less often."""
166
+ if not rows_per_mark or not share or share >= 1:
167
+ return None
168
+ g = max(int(least), int(round(rows_per_mark * share)))
169
+ current = int((re.search(r"\bindex_granularity\s*=\s*(\d+)", create_sql or "", re.I) or [0, 8192])[1])
170
+ if g >= current:
171
+ return None
172
+ gb = re.search(r"\bindex_granularity_bytes\s*=\s*(\d+)", create_sql or "", re.I)
173
+ real_bytes = int(gb.group(1)) if gb else DEFAULT_GRANULARITY_BYTES
174
+ out = {"index_granularity": g, "rows_per_mark_real": round(float(rows_per_mark), 1), "share": round(float(share), 6),
175
+ "floor_hit": g == int(least) and rows_per_mark * share < least}
176
+ if real_bytes: # 0 turns adaptive granules off: kept off
177
+ out["index_granularity_bytes"] = max(MIN_GRANULARITY_BYTES, int(round(real_bytes * share)))
178
+ return out
179
+
180
+
181
+ def local_engine_setup(statement: str) -> str:
182
+ """A variant's setup statement as the one-server sandbox can run it: a CREATE TABLE (a re-keyed copy, a twin) with
183
+ its engine mapped to the local equivalent (plain_engine). Anything else is returned as written."""
184
+ return plain_engine(statement) if CREATED.match(statement or "") and CLUSTER_ENGINE.search(statement or "") else statement
185
+
186
+
187
+ class ClickHouseSandbox:
188
+ engine = "clickhouse"
189
+ label = "ClickHouse"
190
+ copy_kinds = ("ordering_key", "column_type") # variants that copy the whole table once
191
+
192
+ @property
193
+ def activity(self) -> Activity:
194
+ """Seconds of this sandbox's statements by kind (engines/base.Activity), for bench.json `timing.statements`."""
195
+ got = self.__dict__.get("_activity")
196
+ if got is None:
197
+ got = self.__dict__["_activity"] = Activity()
198
+ return got
199
+ floor_bytes = 0
200
+ floor_rows = 0
201
+
202
+ def __init__(self, version: str, name: str | None = None, runtime: str | None = None, port: int = 0):
203
+ self.version = version
204
+ self.runtime = runtime or find_runtime()
205
+ self.name = name or f"codecop-ch-{uuid.uuid4().hex[:8]}"
206
+ self.port = port
207
+ self.database = "default"
208
+ # Per-query limits for measured queries, set once the server is up: a query that would exhaust the
209
+ # sandbox fails with the server's own message instead of taking the server down.
210
+ self.query_limits: dict = {}
211
+ # Which parts of data realism are on (datagen.REALISM). bench.run sets it; any other user of the sandbox
212
+ # (the migration check, a test) gets a plain server: no merge settings changed, no staged loads.
213
+ self.realism: tuple = ()
214
+ self.parts_plan: dict[str, int] = {} # table -> parts per partition to build (plan_parts)
215
+ self.layout_plan: dict[str, dict] = {} # table -> the real parts per partition by age, when a pull has them (plan_parts)
216
+ self.time_plan: dict[str, dict] = {} # table -> the time column its parts are cut by, and their shape (plan_time_ranges)
217
+ self.max_parts_per_partition = MAX_PARTS_PER_PARTITION # setting bench.max_parts_per_partition
218
+ self.load_workers = MERGE_WORKERS # setting bench.load_workers: partitions loaded side by side
219
+ # setting bench.max_cut_partitions: a load that writes more partitions than this is not cut into parts one
220
+ # partition at a time (each is several statements); its rows go in with one INSERT, said in the table's record.
221
+ # A partition key on generated ids (tenant, user, day) can make thousands of tiny partitions, each cut a slow load.
222
+ self.max_cut_partitions = MAX_CUT_PARTITIONS
223
+ self.uncut: dict[str, int] = {} # table -> partitions it had when loaded with one INSERT
224
+ self.insert_block_bytes = 64_000_000 # setting bench.insert_block_bytes: uncompressed bytes per block a generating INSERT may hold
225
+ self.copy_block_bytes = 64_000_000 # setting bench.copy_block_bytes: the same for a copy whose rows all go to one partition
226
+ self.load_memory_share = 0.6 # setting bench.load_memory_share: of the server's memory limit, what cuts side by side may hold
227
+ self._maps: dict[tuple, dict] = {} # a parent's key and shared columns -> its lookup tables (relation_maps)
228
+ self.max_relation_parents = 5_000_000 # setting bench.max_relation_parents: parent keys a relation chooses among
229
+ self.clock: str | None = None # the instant now() stands for in measured queries (freeze_clock)
230
+ self._projection_mode: set[str] = set() # tables given deduplicate_merge_projection_mode for a variant's projection
231
+ self.session_settings: dict = {} # settings a table definition needed (create_table), sent with every statement
232
+ self.granularity_plan: dict[str, dict] = {} # table -> its granules scaled to production's (scale_granularity)
233
+ self.full_width: dict[str, str] = {} # table -> its sample of rows with full content (full_width_sample)
234
+ self.filled_columns: dict[str, set] = {} # table -> its columns that hold filler (bench.ReadColumns); filled_reads
235
+ self.min_granularity = MIN_GRANULARITY # setting bench.min_index_granularity
236
+
237
+ # ---- lifecycle ------------------------------------------------------
238
+ def start(self, timeout_s: int = 90) -> None:
239
+ import os as _os
240
+ # a busy host (disk wait) can take longer to start a server: CODECOP_SANDBOX_START_TIMEOUT_S raises the wait
241
+ timeout_s = int(_os.environ.get("CODECOP_SANDBOX_START_TIMEOUT_S") or timeout_s)
242
+ image = f"{IMAGE}:{self.version}"
243
+ self.reaped = reap_orphans(self.runtime) # sandboxes of runs that were killed: their disk comes back first
244
+ cmd = [self.runtime, "run", "-d", "--name", self.name, *sandbox_run_args(self.runtime, self.name, "/var/lib/clickhouse", image),
245
+ *publish_args(8123, self.port), "-e", "CLICKHOUSE_SKIP_USER_SETUP=1",
246
+ "--ulimit", "nofile=262144:262144", image]
247
+ proc = start_container(cmd) # with the caps (engines/base.limit_args); without an I/O cap the runtime refuses
248
+ if proc.returncode != 0:
249
+ self.stop()
250
+ raise SandboxError(f"Could not start {image}: {proc.stderr.strip()[:400]}")
251
+ if not self._wait_ready(timeout_s):
252
+ self.stop()
253
+ raise SandboxError(f"ClickHouse {self.version} did not become ready in {timeout_s}s.")
254
+ try:
255
+ total = int(float(self._http("SELECT value FROM system.asynchronous_metrics WHERE metric = 'OSMemoryTotal'").strip() or 0))
256
+ except (QueryError, ValueError):
257
+ total = 0
258
+ self.query_limits = {"max_execution_time": self.statement_timeout_s, **({"max_memory_usage": total // 2} if total else {})}
259
+ try:
260
+ # the server's own default max_threads is its processors: 'auto(4)' (NumberOfCPUCores is not on 24.8)
261
+ self.cores = int((re.search(r"\d+", self._http("SELECT value FROM system.settings WHERE name = 'max_threads'")) or [0])[0])
262
+ except (QueryError, ValueError, TypeError):
263
+ self.cores = 0
264
+ time.sleep(1.0)
265
+ self.fresh_resident = self.memory_state()["resident"] # what a server holds before any load (bound_memory)
266
+ self.restarts = []
267
+
268
+ statement_timeout_s: float = MAX_QUERY_SECONDS # `[bench] statement_timeout_s` (set_statement_timeout)
269
+
270
+ def set_statement_timeout(self, seconds: float) -> None:
271
+ """The longest a measured statement may run before the server cancels it (`[bench] statement_timeout_s`)."""
272
+ self.statement_timeout_s = max(float(seconds), 0.001)
273
+ if self.query_limits:
274
+ self.query_limits["max_execution_time"] = self.statement_timeout_s
275
+
276
+ def _wait_ready(self, timeout_s: int) -> bool:
277
+ """Find the published port (it can change when the container is started again) and wait for the server.
278
+ On a sandbox network (a hosted job) there is no published port: the server is <container name>:8123."""
279
+ if sandbox_network():
280
+ self.port = 8123
281
+ return self._poll_ready(timeout_s)
282
+ port = subprocess.run([self.runtime, "port", self.name, "8123/tcp"], capture_output=True, text=True).stdout
283
+ m = re.search(r":(\d+)\s*$", port.strip().splitlines()[0]) if port.strip() else None
284
+ if not m:
285
+ return False
286
+ self.port = int(m.group(1))
287
+ return self._poll_ready(timeout_s)
288
+
289
+ def _poll_ready(self, timeout_s: int) -> bool:
290
+ deadline = time.monotonic() + timeout_s
291
+ while time.monotonic() < deadline:
292
+ try:
293
+ if self._http("SELECT 1", timeout=5).strip() == "1":
294
+ return True
295
+ except (SandboxError, OSError):
296
+ time.sleep(0.4)
297
+ return False
298
+
299
+ def revive(self, timeout_s: int = 90) -> str:
300
+ """After a lost connection: start the container again if the server stopped. The data is still there.
301
+
302
+ Returns why it had stopped ('' when it was still running). Raises SandboxError when it does not come back."""
303
+ try:
304
+ if self._http("SELECT 1", timeout=5).strip() == "1":
305
+ return ""
306
+ except (SandboxError, QueryError):
307
+ pass
308
+ state = subprocess.run([self.runtime, "inspect", "-f", "{{.State.ExitCode}} {{.State.OOMKilled}}", self.name],
309
+ capture_output=True, text=True).stdout.split()
310
+ why = "out of memory" if state[1:] == ["true"] or state[:1] == ["137"] else f"exit code {state[0]}" if state else "unknown"
311
+ subprocess.run([self.runtime, "start", self.name], capture_output=True)
312
+ if not self._wait_ready(timeout_s):
313
+ raise SandboxError(f"The sandbox server stopped ({why}) and did not start again.")
314
+ return why
315
+
316
+ def stop(self) -> None:
317
+ remove_sandbox(self.runtime, self.name) # the container, its anonymous volumes and its data volume
318
+
319
+ def __enter__(self) -> "ClickHouseSandbox":
320
+ self._signals = StopOnSignal().__enter__() # SIGTERM ends the run through __exit__, not around it
321
+ try:
322
+ self.start()
323
+ except BaseException:
324
+ self.stop()
325
+ self._signals.__exit__()
326
+ raise
327
+ return self
328
+
329
+ def __exit__(self, *exc) -> None:
330
+ try:
331
+ self.stop()
332
+ finally:
333
+ if getattr(self, "_signals", None):
334
+ self._signals.__exit__()
335
+
336
+ # ---- statements -----------------------------------------------------
337
+ def _http(self, sql: str, params: dict | None = None, settings: dict | None = None, timeout: int = 600) -> str:
338
+ query = {"database": self.database, **getattr(self, "session_settings", {}), **(settings or {})}
339
+ for k, v in (params or {}).items():
340
+ query[f"param_{k}"] = v
341
+ url = f"{self.base_url()}/?{urllib.parse.urlencode(query)}"
342
+ req = urllib.request.Request(url, data=sql.encode("utf-8"), method="POST")
343
+ began = time.monotonic()
344
+ try:
345
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
346
+ text = resp.read().decode("utf-8", "replace")
347
+ kind = statement_kind(sql)
348
+ self.activity.add(kind, began, time.monotonic())
349
+ if kind == "measure" and getattr(self, "filled_columns", None):
350
+ self._note_filled_read(sql)
351
+ return text
352
+ except urllib.error.HTTPError as e:
353
+ raise QueryError(e.read().decode("utf-8", "replace").strip()[:1500]) from e
354
+ except urllib.error.URLError as e:
355
+ raise SandboxError(f"Sandbox not reachable: {e.reason}") from e
356
+ except (http.client.HTTPException, OSError) as e: # the server went away in the middle of a request
357
+ raise SandboxError(f"Sandbox connection lost: {type(e).__name__}") from e
358
+
359
+ def base_url(self) -> str:
360
+ """Where the server answers: a published port on 127.0.0.1, or the container by name on a sandbox network."""
361
+ return f"http://{self.name}:8123" if sandbox_network() else f"http://127.0.0.1:{self.port}"
362
+
363
+ def execute(self, sql: str, params: dict | None = None, settings: dict | None = None) -> str:
364
+ if sql.lstrip()[:6].upper() == "INSERT":
365
+ # A real table partitioned by day takes generated rows for hundreds of partitions in one block, and a variant
366
+ # copy does the same. The server's default cap of 100 partitions per block is for production inserts.
367
+ # The generated statement carries a vocabulary of phrases, so it is longer than the default query size limit.
368
+ settings = {"max_partitions_per_insert_block": 0, "max_query_size": 16_000_000, **(settings or {})}
369
+ return self._http(sql, params, settings)
370
+
371
+ def rows(self, sql: str, params: dict | None = None) -> list[dict]:
372
+ text = self._http(sql.rstrip().rstrip(";") + " FORMAT JSONEachRow", params)
373
+ return [json.loads(line) for line in text.splitlines() if line.strip()]
374
+
375
+ def server_version(self) -> str:
376
+ return self._http("SELECT version()").strip()
377
+
378
+ def create_table(self, definition: dict | str) -> list[str]:
379
+ """Drop and rebuild one table. Accepts the agent's definition, or a bare CREATE statement."""
380
+ if isinstance(definition, str):
381
+ self.execute(plain_engine(definition))
382
+ return []
383
+ name = definition["name"]
384
+ if "." in name:
385
+ self.execute(f"CREATE DATABASE IF NOT EXISTS `{name.split('.')[0]}`")
386
+ self.execute(f"DROP TABLE IF EXISTS {quote_table(name)} SYNC")
387
+ self._drop_full_width(name)
388
+ notes: list[str] = []
389
+ for _ in range(6):
390
+ try:
391
+ self.execute(plain_engine(definition["create_sql"]))
392
+ break
393
+ except QueryError as e:
394
+ # A type the server holds behind a switch ("Set setting allow_experimental_json_type = 1 in order to
395
+ # allow it"): the repository's own server has it on, or the table would not exist there. Turned on for
396
+ # every statement the sandbox sends from here on, and said.
397
+ gate = re.search(r"[Ss]et (?:setting )?[`']?(allow_\w+)[`']? ?= ?1", str(e))
398
+ if not gate or gate.group(1) in self.session_settings:
399
+ raise
400
+ self.session_settings[gate.group(1)] = 1
401
+ notes.append(f"the server allows this definition only with {gate.group(1)} = 1: set for the sandbox session")
402
+ if "physical" in self.realism:
403
+ self._keep_parts(name) # no background merges: each load step is merged in a staging table and attached (load)
404
+ return notes
405
+
406
+ def scale_granularity(self, definition: dict, rows_per_mark: float | None, share: float | None) -> dict:
407
+ """The definition with its granules scaled to production's (scaled_granularity): a sandbox part then has as many
408
+ granules as the real part of its age, and a statement selects as many marks as it does on production. Its
409
+ projections inherit the table's granularity (checked on 26.6); a re-keyed copy gets it in apply_setup. Recorded
410
+ in `granularity_plan`. Without physical realism, or when nothing is known, the definition is returned as is."""
411
+ name = definition.get("name") or ""
412
+ self.granularity_plan.pop(name, None)
413
+ if "physical" not in self.realism or not re.search(r"MergeTree", definition.get("create_sql") or "", re.I):
414
+ return definition
415
+ got = scaled_granularity(definition.get("create_sql") or "", rows_per_mark or 0, share or 0, self.min_granularity)
416
+ if not got:
417
+ return definition
418
+ wanted = {k: got[k] for k in ("index_granularity", "index_granularity_bytes") if k in got}
419
+ self.granularity_plan[name] = got
420
+ return {**definition, "create_sql": with_merge_settings(definition["create_sql"], wanted)}
421
+
422
+ def _granularity_of(self, table: str) -> dict | None:
423
+ bare = table.replace("`", "").replace('"', "")
424
+ return self.granularity_plan.get(bare) or next((v for k, v in self.granularity_plan.items() if k.split(".")[-1] == bare.split(".")[-1]), None)
425
+
426
+ def _keep_parts(self, name: str) -> None:
427
+ """Parts stay as they are: the measurement does not depend on how far background merges got, and row
428
+ versions that a merge would remove are still there, as on a table that is written to all day."""
429
+ try:
430
+ self.execute(f"ALTER TABLE {quote_table(name)} MODIFY SETTING {KEEP_PARTS}")
431
+ except QueryError:
432
+ pass # not a MergeTree table
433
+
434
+ def column_types(self, name: str) -> dict[str, str]:
435
+ """Columns a row can be written to: a MATERIALIZED or ALIAS column is computed, never inserted."""
436
+ return {r["name"]: r["type"] for r in self.rows(
437
+ "SELECT name, type FROM system.columns WHERE table = {t:String} AND database = {d:String} "
438
+ "AND default_kind NOT IN ('MATERIALIZED', 'ALIAS', 'EPHEMERAL')",
439
+ {"t": name.split(".")[-1], "d": name.split(".")[0] if "." in name else self.database})}
440
+
441
+ def plan_parts(self, definition: dict, per_partition: float | None, duplicate_share: float | None = None,
442
+ layout: dict | None = None) -> int:
443
+ """How many load steps this table gets.
444
+
445
+ Without a layout each step is one part per partition, and the parts wanted in each partition are the real table's
446
+ average when known, else the default. With the real layout (`layout`: facts.part_layout, parts per partition by
447
+ age) the steps are as many as the fullest partition has parts, and `load` gives each partition the count of the
448
+ real partition of its age: many small parts in the newest ones, one or two in the old ones.
449
+ On a deduplicating table one part is the part of duplicate versions that `add_versions` writes, so the load makes
450
+ one fewer."""
451
+ name = definition["name"]
452
+ most = int(self.max_parts_per_partition)
453
+ versions = bool(DEDUPLICATING.search(definition.get("create_sql") or "")) and (duplicate_share is None or duplicate_share > 0)
454
+ # parts cut by time write the duplicate versions into the parts themselves (_load_time_ranged): no part of their own
455
+ less = 1 if versions and "physical" in self.realism and name not in self.time_plan else 0
456
+ known = [p for p in (layout or {}).get("parts") or [] if p] + [p for p in [(layout or {}).get("older")] if p]
457
+ self.layout_plan.pop(name, None)
458
+ if known and "physical" in self.realism:
459
+ wanted = int(min(max(round(max(known)), 1), most))
460
+ self.layout_plan[name] = {**layout, "less": less}
461
+ else:
462
+ wanted = int(min(max(round(per_partition or DEFAULT_PARTS_PER_PARTITION), 1), most))
463
+ self.parts_plan[name] = max(wanted - less, 1)
464
+ if name in self.time_plan:
465
+ self.time_plan[name].update(parts=self.parts_plan[name], layout=name in self.layout_plan,
466
+ layout_basis="real parts per partition, by age" if name in self.layout_plan
467
+ else "real table average" if per_partition else "default")
468
+ return self.parts_plan[name]
469
+
470
+ def plan_time_ranges(self, definition: dict, types: dict[str, str], filtered: set[str] | None, ratio: float,
471
+ ratio_basis: str, duplicate_share: float | None = None) -> dict | None:
472
+ """Decide whether this table's parts are cut by time (parts.py) and how: {column, basis, ratio, ratio_basis}.
473
+ None when it has no time column the partition key or the sorting key (and the queries) depend on, without
474
+ physical realism, or on an engine that is not a MergeTree. Call before plan_parts."""
475
+ from .. import parts
476
+ name = definition["name"]
477
+ self.time_plan.pop(name, None)
478
+ if "physical" not in self.realism:
479
+ return None
480
+ found = self.rows("SELECT engine, partition_key, sorting_key FROM system.tables WHERE database = {d:String} AND name = {t:String}",
481
+ {"t": name.split(".")[-1], "d": name.split(".")[0] if "." in name else self.database})
482
+ if not found or not found[0]["engine"].endswith("MergeTree"):
483
+ return None
484
+ chosen = parts.time_column(found[0]["partition_key"], found[0]["sorting_key"], types, filtered)
485
+ if not chosen:
486
+ return None
487
+ versions = bool(DEDUPLICATING.search(definition.get("create_sql") or ""))
488
+ share = (DEFAULT_DUPLICATE_SHARE if duplicate_share is None else min(max(float(duplicate_share), 0.0), 0.9)) if versions else 0.0
489
+ self.time_plan[name] = {"column": chosen[0], "basis": chosen[1], "ratio": parts.clamp_ratio(ratio), "ratio_basis": ratio_basis,
490
+ "partition_key": found[0]["partition_key"], "nullable": types[chosen[0]].startswith("Nullable"),
491
+ "duplicate_share": share, "duplicate_share_basis": "default" if duplicate_share is None else "profile"}
492
+ return self.time_plan[name]
493
+
494
+ def _parts_wanted(self, plan: dict, back: int) -> int:
495
+ """Parts the partition `back` periods before the newest should hold after the load, from the real layout."""
496
+ parts = plan.get("parts") or []
497
+ real = parts[back] if back < len(parts) and parts[back] else None
498
+ if real is None:
499
+ # no real partition of that age: an older one (`older`), else the nearest real one before it in time
500
+ real = plan.get("older") if back >= len(parts) and plan.get("older") else next(
501
+ (p for p in reversed(parts[:back + 1]) if p), None) or next((p for p in parts[back:] if p), None) or 1
502
+ return max(int(min(max(round(real), 1), int(self.max_parts_per_partition))) - int(plan.get("less") or 0), 1)
503
+
504
+ def insert_statements(self, name: str, rows: int, columns: list[dict], types: dict[str, str], *,
505
+ fixtures: list[dict] | None = None, placed: dict | None = None,
506
+ relations: list[dict] | None = None, filler: set[str] | None = None) -> list[str]:
507
+ from ..datagen import insert_statements
508
+ short = name.split(".")[-1]
509
+ batches = {"batches": self.parts_plan[name]} if "physical" in self.realism and name in self.parts_plan else {}
510
+ return [s.replace(f"INSERT INTO {quote_ident(short)}", f"INSERT INTO {quote_table(name)}", 1)
511
+ for s in insert_statements(short, rows, columns, types, fixtures=fixtures, placed=placed, realism=self.realism,
512
+ relations=relations, insert_block_bytes=self.insert_block_bytes, filler=filler, **batches)]
513
+
514
+ # ---- relations (relations.py) ---------------------------------------
515
+ def relation_maps(self, name: str, relations: list[dict]) -> list[dict]:
516
+ """Prepare this table's relations against its loaded parents: the parent's keys in Join-engine tables, which an
517
+ INSERT ... SELECT can look up row by row (joinGet). Returns the relations as datagen wants them."""
518
+ from ..datagen import as_text
519
+ out = []
520
+ for rel in relations:
521
+ parent, key = rel["parent"], rel["parent_column"]
522
+ shared = [s["parent_column"] for s in rel.get("same_as_parent") or []]
523
+ mark = (parent, key, tuple(shared))
524
+ if mark not in self._maps:
525
+ base = f"codecop_rel_{len(self._maps) + 1}"
526
+ names = ["x"] + [f"d{i}" for i in range(1, len(shared))]
527
+ # one row per key: the smallest tuple of shared values, so duplicate versions of a row give one answer
528
+ packed = f"min(tuple({', '.join(as_text(quote_ident(c)) for c in shared)})) AS t" if shared else "'' AS t"
529
+ unpack = ", ".join(f"t.{i + 1} AS {n}" for i, n in enumerate(names)) if shared else "'' AS x"
530
+ self._drop_maps(base)
531
+ self.execute(
532
+ f"CREATE TABLE {base} ENGINE = MergeTree ORDER BY rn AS SELECT toUInt64(row_number() OVER (ORDER BY k) - 1) AS rn, k, "
533
+ f"{', '.join(names) if shared else 'x'}, toUInt64(row_number() OVER (PARTITION BY x ORDER BY k) - 1) AS grn FROM ("
534
+ f"SELECT k, {unpack} FROM (SELECT {as_text(quote_ident(key))} AS k, {packed} FROM {quote_table(parent)} WHERE isNotNull({quote_ident(key)}) "
535
+ f"GROUP BY k ORDER BY k LIMIT {int(self.max_relation_parents)}))")
536
+ cols = ", ".join(names) if shared else "x"
537
+ self.execute(f"CREATE TABLE {base}_k ENGINE = Join(ANY, LEFT, k) AS SELECT k, toUInt8(1) AS one, {cols} FROM {base}")
538
+ self.execute(f"CREATE TABLE {base}_a ENGINE = Join(ANY, LEFT, rn) AS SELECT rn, k FROM {base}")
539
+ if shared:
540
+ self.execute(f"CREATE TABLE {base}_g ENGINE = Join(ANY, LEFT, x, grn) AS SELECT x, grn, k FROM {base}")
541
+ self.execute(f"CREATE TABLE {base}_n ENGINE = Join(ANY, LEFT, x) AS SELECT x, count() AS n FROM {base} GROUP BY x")
542
+ total = int(self._http(f"SELECT count() FROM {base}").strip() or 0)
543
+ self.execute(f"DROP TABLE IF EXISTS {base} SYNC")
544
+ db = self.database
545
+ self._maps[mark] = {"base": base, "total": total,
546
+ "tables": {s: f"{db}.{base}_{s}" for s in ("k", "a") + (("g", "n") if shared else ())}}
547
+ m = self._maps[mark]
548
+ same = [(s["column"], "x" if i == 0 else f"d{i}") for i, s in enumerate(rel.get("same_as_parent") or [])]
549
+ out.append({"relation": rel, "column": rel["column"], "group": same[0][0] if same else None, "same": same,
550
+ "skewed": rel.get("distribution") == "skewed", "tables": m["tables"], "total": m["total"]})
551
+ return out
552
+
553
+ def relation_check(self, name: str, prepared: list[dict]) -> list[dict]:
554
+ """Count, in the loaded table, the rows that break each relation: a key with no parent row, a shared column
555
+ that differs from the parent's."""
556
+ from ..datagen import as_text
557
+ out = []
558
+ for p in prepared:
559
+ key = as_text(quote_ident(p['column']))
560
+ t = p["tables"]["k"]
561
+ differs = " OR ".join(f"joinGet('{t}', '{lookup}', {key}) != {as_text(quote_ident(col))}" for col, lookup in p["same"]) or "0"
562
+ row = self.rows(f"SELECT countIf(joinGet('{t}', 'one', {key}) = 0) AS orphans, "
563
+ f"countIf(joinGet('{t}', 'one', {key}) = 1 AND ({differs})) AS mismatched, count() AS checked "
564
+ f"FROM {quote_table(name)} WHERE isNotNull({quote_ident(p['column'])})")[0]
565
+ out.append({"orphans": int(row["orphans"]), "mismatched": int(row["mismatched"]), "checked": int(row["checked"]),
566
+ "parents": p["total"]})
567
+ return out
568
+
569
+ def _drop_maps(self, base: str) -> None:
570
+ for suffix in ("", "_k", "_a", "_g", "_n"):
571
+ try:
572
+ self.execute(f"DROP TABLE IF EXISTS {base}{suffix} SYNC")
573
+ except QueryError:
574
+ pass
575
+
576
+ def drop_relation_maps(self) -> None:
577
+ for m in self._maps.values():
578
+ self._drop_maps(m["base"])
579
+ self._maps = {}
580
+
581
+ def finish_table(self, definition: dict) -> dict:
582
+ return {}
583
+
584
+ # ---- physical state ---------------------------------------------------
585
+ def _merging_stage(self, stage: str) -> None:
586
+ """A staging table merges (its copy of the target's settings blocks merges), and merges column by column.
587
+
588
+ A horizontal merge reads every column of every source part at once: on a wide table one merge of a partition can
589
+ hold most of a GB, and several side by side (with the copies) pass the server's memory limit. A vertical merge,
590
+ which the server uses only from 131,072 rows and 11 columns on, holds a small fraction of that. The merged
591
+ part is the same."""
592
+ self.execute(f"ALTER TABLE {quote_table(stage)} RESET SETTING max_bytes_to_merge_at_max_space_in_pool")
593
+ try:
594
+ self.execute(f"ALTER TABLE {quote_table(stage)} MODIFY SETTING vertical_merge_algorithm_min_rows_to_activate = 1, "
595
+ "vertical_merge_algorithm_min_columns_to_activate = 1")
596
+ except QueryError:
597
+ pass # an engine or a server without these settings merges as it does
598
+
599
+ def _too_many_partitions(self, name: str, n: int) -> bool:
600
+ cap = int(getattr(self, "max_cut_partitions", MAX_CUT_PARTITIONS) or 0)
601
+ if cap and n > cap:
602
+ self.uncut[name] = n
603
+ return True
604
+ return False
605
+
606
+ def _as_one_part_each(self, name: str, fill: str, params: dict | None = None, settings: dict | None = None) -> None:
607
+ """Run `fill` (an INSERT whose target is written `{stage}`) and add its rows to `name` as exactly one part per partition.
608
+
609
+ A wide-row insert is cut into many blocks, each a part, and background merges would then combine them at their
610
+ own pace. Here the rows go to a staging table first, are merged there into one part per partition, and those parts
611
+ are attached to the table. So every load step adds one part to each partition, like one day's merged inserts."""
612
+ stage = f"{name}{STAGE_SUFFIX}"
613
+ qs, qn = quote_table(stage), quote_table(name)
614
+ self.execute(f"DROP TABLE IF EXISTS {qs} SYNC")
615
+ self.execute(f"CREATE TABLE {qs} AS {qn}")
616
+ try:
617
+ self._merging_stage(stage)
618
+ self.execute(fill.replace("{stage}", qs), params, settings=settings)
619
+ table = stage.split(".")[-1]
620
+ written = self.rows("SELECT partition_id, count() AS parts FROM system.parts WHERE database = {d:String} "
621
+ "AND table = {t:String} AND active GROUP BY partition_id ORDER BY partition_id", self._where(stage))
622
+ if self._too_many_partitions(name, len(written)):
623
+ self.execute(f"INSERT INTO {qn} SELECT * FROM {qs}")
624
+ return
625
+ several = [r["partition_id"] for r in written if int(r["parts"]) > 1]
626
+
627
+ def merge(partition_id: str) -> None:
628
+ self.execute(f"OPTIMIZE TABLE {qs} PARTITION ID {{p:String}} FINAL", {"p": partition_id},
629
+ settings={"alter_sync": 2, "optimize_throw_if_noop": 0})
630
+
631
+ if several: # partitions merge side by side: a merge is one thread, and compression is most of its work
632
+ with ThreadPoolExecutor(max_workers=MERGE_WORKERS) as pool:
633
+ list(pool.map(merge, several))
634
+ for r in written:
635
+ self.execute(f"ALTER TABLE {qn} ATTACH PARTITION ID {{p:String}} FROM {qs}", {"p": r["partition_id"]})
636
+ finally:
637
+ self.execute(f"DROP TABLE IF EXISTS {qs} SYNC")
638
+
639
+ def load(self, name: str, statements: list[str]) -> None:
640
+ """Run a table's generated INSERTs. With physical realism each one becomes one part per partition."""
641
+ if "physical" not in self.realism or not self._is_merge_tree(name):
642
+ for stmt in statements:
643
+ self.execute(stmt)
644
+ return
645
+ head = f"INSERT INTO {quote_table(name)} "
646
+ if name in self.time_plan and all(stmt.startswith(head) for stmt in statements):
647
+ fills = [stmt[len(head):] for stmt in statements]
648
+ direct = getattr(self, "ranged_load", "direct") == "direct" and all(_direct_body(f) is not None for f in fills)
649
+ if not (direct and self._load_time_ranged_direct(name, fills, self.time_plan[name])):
650
+ self._load_time_ranged(name, fills, self.time_plan[name])
651
+ return
652
+ if name in self.layout_plan and all(stmt.startswith(head) for stmt in statements):
653
+ self._load_by_layout(name, [stmt[len(head):] for stmt in statements], self.layout_plan[name])
654
+ return
655
+ for stmt in statements:
656
+ if not stmt.startswith(head):
657
+ self.execute(stmt)
658
+ continue
659
+ self._as_one_part_each(name, "INSERT INTO {stage} " + stmt[len(head):])
660
+
661
+ def _load_by_layout(self, name: str, fills: list[str], plan: dict) -> None:
662
+ """Load a table so that each partition holds as many parts as the real partition of its age.
663
+
664
+ Every load step goes to a staging table that is kept between the steps. A partition that should end with k parts
665
+ is merged there and moved to the table k times, evenly spaced over the steps: the newest partitions after every
666
+ step (many small parts), an old one once, at the end (one part). The age of a partition is counted in the real
667
+ table's periods back from today. A partition whose id is not a period is moved after every step, as before."""
668
+ from .. import sizes
669
+ stage = f"{name}{STAGE_SUFFIX}"
670
+ table = stage.split(".")[-1]
671
+ qs, qn = quote_table(stage), quote_table(name)
672
+ self.execute(f"DROP TABLE IF EXISTS {qs} SYNC")
673
+ self.execute(f"CREATE TABLE {qs} AS {qn}")
674
+ today = date.fromisoformat(self._http("SELECT toString(today())").strip())
675
+ steps = len(fills)
676
+ try:
677
+ self._merging_stage(stage)
678
+ for step, fill in enumerate(fills):
679
+ self.execute(f"INSERT INTO {qs} {fill}")
680
+ written = self.rows("SELECT partition_id, count() AS parts FROM system.parts WHERE database = {d:String} "
681
+ "AND table = {t:String} AND active GROUP BY partition_id ORDER BY partition_id", self._where(stage))
682
+ if self._too_many_partitions(name, len(written)):
683
+ continue # the rows stay in the stage; one INSERT after the last step
684
+ due = []
685
+ for r in written:
686
+ day = sizes.partition_day(r["partition_id"])
687
+ wanted = self._parts_wanted(plan, sizes.periods_back(plan["unit"], today, day)) if day else steps
688
+ if (step + 1) * wanted // steps > step * wanted // steps:
689
+ due.append(r)
690
+
691
+ def merge(partition_id: str) -> None:
692
+ self.execute(f"OPTIMIZE TABLE {qs} PARTITION ID {{p:String}} FINAL", {"p": partition_id},
693
+ settings={"alter_sync": 2, "optimize_throw_if_noop": 0})
694
+
695
+ several = [r["partition_id"] for r in due if int(r["parts"]) > 1]
696
+ if several:
697
+ with ThreadPoolExecutor(max_workers=MERGE_WORKERS) as pool:
698
+ list(pool.map(merge, several))
699
+ for r in due:
700
+ self.execute(f"ALTER TABLE {qn} ATTACH PARTITION ID {{p:String}} FROM {qs}", {"p": r["partition_id"]})
701
+ self.execute(f"ALTER TABLE {qs} DROP PARTITION ID {{p:String}}", {"p": r["partition_id"]})
702
+ if name in self.uncut:
703
+ self.execute(f"INSERT INTO {qn} SELECT * FROM {qs}")
704
+ finally:
705
+ self.execute(f"DROP TABLE IF EXISTS {qs} SYNC")
706
+
707
+ def _load_time_ranged(self, name: str, fills: list[str], plan: dict) -> None:
708
+ """Load a table so that each part of a partition holds one contiguous range of its time column (parts.py).
709
+
710
+ The generated rows go first to a table of their own, partitioned as the target and sorted by the time column, so
711
+ one range of time is one run of granules there. Then each partition is cut: k parts (the real count of the
712
+ partition of its age, else the table's average, else the default), the oldest covering the largest share of the
713
+ partition's time and each newer one `ratio` times the one before. Each range is copied to a staging table,
714
+ merged there into one part and attached, oldest first, so the parts' block numbers follow time as in
715
+ production. On a deduplicating table the newer versions of a share of a range's rows are copied with the next
716
+ range. A partition is dropped from the rows table once it is cut, so the disk holds the table about once."""
717
+ from .. import parts, sizes
718
+ rows_table = quote_table(f"{name}{ROWS_SUFFIX}")
719
+ qn = quote_table(name)
720
+ col = plan["column"]
721
+ key = f"assumeNotNull({quote_ident(col)})" if plan.get("nullable") else quote_ident(col)
722
+ # a table with no partition key (its parts are cut by the sorting key's time column) is one partition: tuple()
723
+ partition_by = (plan.get("partition_key") or "").strip() or "tuple()"
724
+ self.execute(f"DROP TABLE IF EXISTS {rows_table} SYNC")
725
+ self.execute(f"CREATE TABLE {rows_table} AS {qn} ENGINE = MergeTree PARTITION BY {partition_by} ORDER BY {key} "
726
+ f"SETTINGS {KEEP_PARTS}")
727
+ today = date.fromisoformat(self._http("SELECT toString(today())").strip())
728
+ layout = self.layout_plan.get(name)
729
+ cut: dict = {"partitions": 0, "parts": 0, "duplicate_rows": 0}
730
+ try:
731
+ for fill in fills:
732
+ self.execute(f"INSERT INTO {rows_table} {fill}")
733
+ micros = f"toUnixTimestamp64Micro(toDateTime64({{f}}({quote_ident(col)}), 6, 'UTC'))"
734
+ spans = self.rows(f"SELECT _partition_id AS p, count() AS rows, {micros.format(f='min')} AS lo, {micros.format(f='max')} AS hi "
735
+ f"FROM {rows_table} GROUP BY p ORDER BY p")
736
+ share = float(plan.get("duplicate_share") or 0)
737
+ if self._too_many_partitions(name, len(spans)):
738
+ self.execute(f"INSERT INTO {qn} SELECT * FROM {rows_table}")
739
+ cut.update(partitions=len(spans), parts=None, uncut="too_many_partitions")
740
+ plan["built"] = cut
741
+ return
742
+
743
+ def between(lo: int | None, hi: int | None) -> str:
744
+ said = ([f"{key} >= fromUnixTimestamp64Micro({int(lo)}, 'UTC')"] if lo is not None else []) \
745
+ + ([f"{key} < fromUnixTimestamp64Micro({int(hi)}, 'UTC')"] if hi is not None else [])
746
+ return " AND ".join(said) or "1"
747
+
748
+ def cut_partition(span: dict) -> tuple[int, int, int]:
749
+ pid = str(span["p"])
750
+ tag = f"codecop-cut-{uuid.uuid4().hex[:10]}"
751
+ n_stmt = iter(range(1_000_000))
752
+ copy = self._copy_settings(rows_table, pid) # the width of this partition's rows
753
+ day = sizes.partition_day(pid)
754
+ if layout and day:
755
+ k = self._parts_wanted(layout, sizes.periods_back(layout["unit"], today, day))
756
+ else:
757
+ k = int(plan.get("parts") or self.parts_plan.get(name) or 1)
758
+ lo, hi = int(span["lo"] or 0), int(span["hi"] or 0)
759
+ inner = parts.boundaries(lo, hi, min(k, max(int(span["rows"]), 1)), plan["ratio"])
760
+ ranges = list(zip([None] + inner, inner + [None]))
761
+ stage = f"{name}{STAGE_SUFFIX}{tag[-10:]}"
762
+ qs = quote_table(stage)
763
+ self.execute(f"DROP TABLE IF EXISTS {qs} SYNC")
764
+ self.execute(f"CREATE TABLE {qs} AS {qn}")
765
+ dups = 0
766
+ try:
767
+ self._merging_stage(stage)
768
+ where = "_partition_id = {p:String}"
769
+ for j, (a, b) in enumerate(ranges):
770
+ self.execute(f"INSERT INTO {qs} SELECT * FROM {rows_table} WHERE {where} AND {between(a, b)}", {"p": pid},
771
+ settings={**copy, "query_id": f"{tag}-{next(n_stmt)}"})
772
+ if j and share > 0:
773
+ # a newer version of some of the previous range's rows, written with this later part
774
+ pa, pb = ranges[j - 1]
775
+ self.execute(f"INSERT INTO {qs} SELECT * FROM {rows_table} WHERE {where} AND {between(pa, pb)} "
776
+ f"AND cityHash64(_part, _part_offset) % 100000 < {int(share * 100000)}", {"p": pid},
777
+ settings={**copy, "query_id": f"{tag}-{next(n_stmt)}"})
778
+ written = self.rows("SELECT count() AS parts, sum(rows) AS rows FROM system.parts WHERE database = {d:String} "
779
+ "AND table = {t:String} AND active AND partition_id = {p:String}", {**self._where(stage), "p": pid})
780
+ if not written or not int(written[0]["parts"]):
781
+ continue
782
+ if int(written[0]["parts"]) > 1:
783
+ self.execute(f"OPTIMIZE TABLE {qs} PARTITION ID {{p:String}} FINAL", {"p": pid},
784
+ settings={"alter_sync": 2, "optimize_throw_if_noop": 0})
785
+ self.execute(f"ALTER TABLE {qn} ATTACH PARTITION ID {{p:String}} FROM {qs}", {"p": pid})
786
+ self.execute(f"ALTER TABLE {qs} DROP PARTITION ID {{p:String}}", {"p": pid})
787
+ if share > 0:
788
+ dups = int(self._http(f"SELECT count() FROM {qn} WHERE _partition_id = {{p:String}}", {"p": pid}).strip() or 0) - int(span["rows"])
789
+ peak = self._peak_memory(tag, stage)
790
+ finally:
791
+ self.execute(f"DROP TABLE IF EXISTS {qs} SYNC")
792
+ self.execute(f"ALTER TABLE {rows_table} DROP PARTITION ID {{p:String}}", {"p": pid})
793
+ return len(ranges), max(dups, 0), peak
794
+
795
+ # the largest partition is cut alone first and what it held is measured: as many cuts then run side by
796
+ # side as the server's memory holds (at most load_workers). A table of many wide columns can hold GBs per
797
+ # cut, a narrow one a few hundred MB: a fixed number of workers is wrong for one or the other.
798
+ spans = sorted(spans, key=lambda x: -int(x["rows"]))
799
+ done = [cut_partition(spans[0])] if spans else []
800
+ peak = max((d[2] for d in done), default=0)
801
+ budget = self._load_memory_budget()
802
+ most = max(int(self.load_workers or 1), 1)
803
+ workers = max(min(most, int(budget // peak)), 1) if peak and budget else most
804
+ with ThreadPoolExecutor(max_workers=workers) as pool:
805
+ done += list(pool.map(cut_partition, spans[1:]))
806
+ cut.update(workers=workers, peak_bytes=peak, memory_budget_bytes=budget)
807
+ cut.update(partitions=len(done), parts=sum(d[0] for d in done), duplicate_rows=sum(d[1] for d in done))
808
+ finally:
809
+ self.execute(f"DROP TABLE IF EXISTS {rows_table} SYNC")
810
+ plan["built"] = cut
811
+
812
+ def _load_time_ranged_direct(self, name: str, fills: list[str], plan: dict) -> bool:
813
+ """_load_time_ranged without the table of generated rows (`[bench] ranged_load = "direct"`). False when this
814
+ table can not take it (its partition key reads more than the time column): then nothing was written.
815
+
816
+ The copy path writes every generated row once to a table sorted by time, then reads each range of it back into a
817
+ staging table: the whole table is written, compressed and read twice before the merge, and with wide rows each
818
+ range read also takes the boundary granules of every unmerged part of that table (several times the copied bytes read
819
+ in a large load). Here only each row's number and time go first to a narrow table partitioned like the target (so
820
+ its partition ids are the target's); then each range is generated straight into the staging table from its row
821
+ numbers. A value depends on its row number only (datagen) and the clock is fixed for the whole load, so every
822
+ row is the one the copy path writes. Ranges, merges, attaches and duplicate versions are as in _load_time_ranged."""
823
+ from .. import parts, sizes
824
+ body, tail = _direct_body(fills[0])
825
+ cols = fills[0][:fills[0].index(") ") + 1]
826
+ keys_table = quote_table(f"{name}{KEYS_SUFFIX}")
827
+ qn = quote_table(name)
828
+ col = plan["column"]
829
+ key = f"assumeNotNull({quote_ident(col)})" if plan.get("nullable") else quote_ident(col)
830
+ partition_by = (plan.get("partition_key") or "").strip() or "tuple()"
831
+ saved, self.clock = self.clock, self._http("SELECT toString(now64(6, 'UTC'))").strip()
832
+ try:
833
+ body = self.frozen(body) # one instant for the whole load: a row's time is the same in every statement
834
+ finally:
835
+ self.clock = saved
836
+ generated = re.search(r"\bnumbers\(\d+, \d+\)", body).group(0)
837
+ numbered = re.sub(r"\bSELECT\s", "SELECT number AS codecop_n, ", body, count=1)
838
+ self.execute(f"DROP TABLE IF EXISTS {keys_table} SYNC")
839
+ try:
840
+ self.execute(f"CREATE TABLE {keys_table} ENGINE = MergeTree PARTITION BY {partition_by} ORDER BY {key} "
841
+ f"AS SELECT codecop_n, {quote_ident(col)} FROM ({numbered}) WHERE 0")
842
+ except QueryError:
843
+ return False # the partition key reads other columns: the copy path
844
+ micros = f"toUnixTimestamp64Micro(toDateTime64({{f}}({quote_ident(col)}), 6, 'UTC'))"
845
+ today = date.fromisoformat(self._http("SELECT toString(today())").strip())
846
+ layout = self.layout_plan.get(name)
847
+ cut: dict = {"partitions": 0, "parts": 0, "duplicate_rows": 0, "path": "direct"}
848
+ share = float(plan.get("duplicate_share") or 0)
849
+ try:
850
+ for fill in fills:
851
+ m = re.search(r"\bnumbers\(\d+, \d+\)", fill)
852
+ if m:
853
+ self.execute(f"INSERT INTO {keys_table} SELECT codecop_n, {quote_ident(col)} FROM ({numbered.replace(generated, m.group(0), 1)})")
854
+ spans = self.rows(f"SELECT _partition_id AS p, count() AS rows, {micros.format(f='min')} AS lo, {micros.format(f='max')} AS hi "
855
+ f"FROM {keys_table} GROUP BY p ORDER BY p")
856
+
857
+ def between(lo: int | None, hi: int | None) -> str:
858
+ said = ([f"{key} >= fromUnixTimestamp64Micro({int(lo)}, 'UTC')"] if lo is not None else []) \
859
+ + ([f"{key} < fromUnixTimestamp64Micro({int(hi)}, 'UTC')"] if hi is not None else [])
860
+ return " AND ".join(said) or "1"
861
+
862
+ def rows_of(pid: str, cond: str) -> str:
863
+ return body.replace(generated, f"(SELECT codecop_n AS number FROM {keys_table} WHERE _partition_id = '{pid}' AND {cond})", 1)
864
+
865
+ def plan_of(span: dict) -> list:
866
+ """The partition's ranges of time, oldest first (as _load_time_ranged cuts them)."""
867
+ pid = str(span["p"])
868
+ day = sizes.partition_day(pid)
869
+ if layout and day:
870
+ k = self._parts_wanted(layout, sizes.periods_back(layout["unit"], today, day))
871
+ else:
872
+ k = int(plan.get("parts") or self.parts_plan.get(name) or 1)
873
+ lo, hi = int(span["lo"] or 0), int(span["hi"] or 0)
874
+ inner = parts.boundaries(lo, hi, min(k, max(int(span["rows"]), 1)), plan["ratio"])
875
+ return list(zip([None] + inner, inner + [None]))
876
+
877
+ def prepare(task: tuple) -> tuple[str, int]:
878
+ """One range of one partition made into one part, in a staging table of its own: (the table, the most
879
+ memory one of its statements held). Ranges are independent until they are attached, so they are made
880
+ side by side: a generating INSERT and a merge each run on about one core."""
881
+ pid, j, ranges = task
882
+ a, b = ranges[j]
883
+ tag = f"codecop-cut-{uuid.uuid4().hex[:10]}"
884
+ stage = f"{name}{STAGE_SUFFIX}{tag[-10:]}"
885
+ qs = quote_table(stage)
886
+ self.execute(f"DROP TABLE IF EXISTS {qs} SYNC")
887
+ self.execute(f"CREATE TABLE {qs} AS {qn}")
888
+ try:
889
+ # the stage keeps the table's no-merge setting while it is written: a background merge of the
890
+ # blocks still coming in is work the final merge does again (on one copy path a third of
891
+ # the merge time); merges are allowed, column by column, just before that merge
892
+ # the generating INSERT carries its block sizes, from the profile's row width (tail)
893
+ self.execute(f"INSERT INTO {qs} {cols} {rows_of(pid, between(a, b))}{tail}", settings={"query_id": f"{tag}-0"})
894
+ if j and share > 0:
895
+ # a newer version of some of the previous range's rows (the same rows: the same numbers)
896
+ pa, pb = ranges[j - 1]
897
+ self.execute(f"INSERT INTO {qs} {cols} {rows_of(pid, between(pa, pb) + f' AND cityHash64(codecop_n) % 100000 < {int(share * 100000)}')}{tail}",
898
+ settings={"query_id": f"{tag}-1"})
899
+ written = self.rows("SELECT count() AS parts FROM system.parts WHERE database = {d:String} "
900
+ "AND table = {t:String} AND active AND partition_id = {p:String}", {**self._where(stage), "p": pid})
901
+ if written and int(written[0]["parts"]) > 1:
902
+ self._merging_stage(stage)
903
+ self.execute(f"OPTIMIZE TABLE {qs} PARTITION ID {{p:String}} FINAL", {"p": pid},
904
+ settings={"alter_sync": 2, "optimize_throw_if_noop": 0})
905
+ return stage, self._peak_memory(tag, stage)
906
+ except BaseException:
907
+ self.execute(f"DROP TABLE IF EXISTS {qs} SYNC")
908
+ raise
909
+
910
+ def attach(pid: str, stage: str) -> None:
911
+ qs = quote_table(stage)
912
+ try:
913
+ if self.rows("SELECT count() AS n FROM system.parts WHERE database = {d:String} AND table = {t:String} AND active",
914
+ self._where(stage))[0]["n"]:
915
+ self.execute(f"ALTER TABLE {qn} ATTACH PARTITION ID {{p:String}} FROM {qs}", {"p": pid})
916
+ finally:
917
+ self.execute(f"DROP TABLE IF EXISTS {qs} SYNC")
918
+
919
+ spans = sorted(spans, key=lambda x: -int(x["rows"]))
920
+ ranges_of = {str(s["p"]): plan_of(s) for s in spans}
921
+ tasks = [(str(s["p"]), j, ranges_of[str(s["p"])]) for s in spans for j in range(len(ranges_of[str(s["p"])]))]
922
+ # the first range alone: what it held decides how many run side by side (the memory budget, at most
923
+ # load_workers), as the copy path measures its first partition
924
+ made: dict = {}
925
+ peak = 0
926
+ if tasks:
927
+ made[tasks[0][:2]] = prepare(tasks[0])
928
+ peak = made[tasks[0][:2]][1]
929
+ budget = self._load_memory_budget()
930
+ most = max(int(self.load_workers or 1), 1)
931
+ workers = max(min(most, int(budget // peak)), 1) if peak and budget else most
932
+ with ThreadPoolExecutor(max_workers=workers) as pool:
933
+ futures = {t[:2]: pool.submit(prepare, t) for t in tasks[1:]}
934
+ try:
935
+ for s in spans:
936
+ pid = str(s["p"])
937
+ # oldest range first, so block numbers follow time as in production
938
+ for j in range(len(ranges_of[pid])):
939
+ stage, held = made.pop((pid, j)) if (pid, j) in made else futures.pop((pid, j)).result()
940
+ peak = max(peak, held)
941
+ attach(pid, stage)
942
+ finally:
943
+ for f in futures.values(): # a failure: what the others made is dropped, not left behind
944
+ try:
945
+ self.execute(f"DROP TABLE IF EXISTS {quote_table(f.result()[0])} SYNC")
946
+ except BaseException: # noqa: BLE001
947
+ pass
948
+ dups = 0
949
+ if share > 0:
950
+ dups = int(self._http(f"SELECT count() FROM {qn}").strip() or 0) - sum(int(s["rows"]) for s in spans)
951
+ cut.update(workers=workers, peak_bytes=peak, memory_budget_bytes=budget, partitions=len(spans), parts=len(tasks),
952
+ duplicate_rows=max(dups, 0))
953
+ finally:
954
+ self.execute(f"DROP TABLE IF EXISTS {keys_table} SYNC")
955
+ plan["built"] = cut
956
+ return True
957
+
958
+ def _peak_memory(self, tag: str, stage: str) -> int:
959
+ """The most memory one statement of a cut held: its copies (query_log, by query id) and its merges (part_log)."""
960
+ try:
961
+ self._http("SYSTEM FLUSH LOGS")
962
+ r = self.rows("SELECT greatest(ifNull((SELECT max(memory_usage) FROM system.query_log WHERE query_id LIKE {q:String} "
963
+ "AND type != 'QueryStart'), 0), ifNull((SELECT max(peak_memory_usage) FROM system.part_log WHERE database = {d:String} "
964
+ "AND table = {t:String} AND event_type = 'MergeParts'), 0)) AS peak", {"q": f"{tag}-%", **self._where(stage)})
965
+ return int(r[0]["peak"] or 0) if r else 0
966
+ except (QueryError, ValueError, TypeError):
967
+ return 0
968
+
969
+ def server_now(self) -> str:
970
+ """The server's time, for memory_peak_since."""
971
+ return self._http("SELECT toString(now64(6))").strip()
972
+
973
+ def memory_peak_since(self, since: str) -> int:
974
+ """The most memory the server held since `since` (server_now): the largest statement (query_log), the largest
975
+ merge (part_log), and what it holds now (MemoryTracking). 0 when the logs can not be read."""
976
+ try:
977
+ self._http("SYSTEM FLUSH LOGS")
978
+ except QueryError:
979
+ pass
980
+ peak = 0
981
+ # each source on its own: a server without part_log (or with another column) still gives the others
982
+ for sql in ("SELECT max(memory_usage) AS v FROM system.query_log WHERE event_time >= toDateTime(left({s:String}, 19)) AND type != 'QueryStart'",
983
+ "SELECT max(peak_memory_usage) AS v FROM system.part_log WHERE event_time >= toDateTime(left({s:String}, 19))",
984
+ "SELECT value AS v FROM system.metrics WHERE metric = 'MemoryTracking'",
985
+ # the RSS the server's limit check reads, sampled each second (what the tracker above does not count)
986
+ "SELECT max(value) AS v FROM system.asynchronous_metric_log WHERE metric = 'MemoryResident' "
987
+ "AND event_time >= toDateTime(left({s:String}, 19))"):
988
+ try:
989
+ r = self.rows(sql, {"s": since})
990
+ peak = max(peak, int(float(r[0]["v"] or 0)) if r else 0)
991
+ except (QueryError, ValueError, TypeError, KeyError):
992
+ continue
993
+ return peak
994
+
995
+ def release(self, tables: list[str]) -> None:
996
+ """Drop tables no later group reads, and the caches that hold their marks and blocks: their disk and memory go to
997
+ the next group (bench.run, groups)."""
998
+ for name in tables:
999
+ try:
1000
+ self.execute(f"DROP TABLE IF EXISTS {quote_table(name)} SYNC")
1001
+ except QueryError:
1002
+ pass
1003
+ self._drop_full_width(name)
1004
+ self.restarted_resident = 0 # the tables a restarted server held are gone: a fresh server is the floor again
1005
+ self.drop_caches()
1006
+
1007
+ def full_width_sample(self, name: str, statements: list[str]) -> str:
1008
+ """Run `statements` (the table's generating INSERTs without filler) into a table of their own beside `name`: rows
1009
+ with full content for the insert-side measurements (writecost.measure) of a table whose unread columns hold
1010
+ filler. Returns the sample's name."""
1011
+ sample = f"{name}{FULL_SUFFIX}"
1012
+ qs, head = quote_table(sample), f"INSERT INTO {quote_table(name)} "
1013
+ self._drop_full_width(name)
1014
+ self.execute(f"CREATE TABLE {qs} AS {quote_table(name)}")
1015
+ for stmt in statements:
1016
+ if stmt.startswith(head):
1017
+ self.execute(f"INSERT INTO {qs} " + stmt[len(head):])
1018
+ self.full_width[name] = sample
1019
+ return sample
1020
+
1021
+ def _note_filled_read(self, sql: str) -> None:
1022
+ """A measured statement that names a column holding filler (bench.ReadColumns missed it): recorded, once per
1023
+ statement, in `filled_reads`. Its rows and bytes read are those of the full table (the filler has the column's
1024
+ length); the values it compares are not."""
1025
+ if "system." in sql[:400]:
1026
+ return
1027
+ words = None
1028
+ for table, cols in self.filled_columns.items():
1029
+ short = table.split(".")[-1]
1030
+ if short not in sql:
1031
+ continue
1032
+ if words is None:
1033
+ words = {w.lower() for w in re.findall(r"[A-Za-z_][A-Za-z0-9_]*", sql)}
1034
+ hit = sorted(c for c in cols if c.lower() in words)
1035
+ if hit:
1036
+ mark = hashlib.sha1(sql.encode()).hexdigest()[:12]
1037
+ seen = self.__dict__.setdefault("filled_reads", [])
1038
+ if not any(r["statement"] == mark for r in seen):
1039
+ seen.append({"table": table, "columns": hit, "statement": mark, "sql_head": re.sub(r"\s+", " ", sql[:160])})
1040
+
1041
+ def _drop_full_width(self, name: str) -> None:
1042
+ (getattr(self, "filled_columns", None) or {}).pop(name, None)
1043
+ sample = (getattr(self, "full_width", None) or {}).pop(name, None)
1044
+ if sample:
1045
+ try:
1046
+ self.execute(f"DROP TABLE IF EXISTS {quote_table(sample)} SYNC")
1047
+ except QueryError:
1048
+ pass
1049
+
1050
+ # ---- memory held by the server between loads -------------------------------------------------
1051
+ # After a load the server's RSS stays well above a fresh server's, after every table is dropped and after SYSTEM DROP
1052
+ # MARK / UNCOMPRESSED / QUERY / PRIMARY INDEX / QUERY CONDITION / PAGE / MMAP / COMPILED EXPRESSION CACHE and SYSTEM
1053
+ # JEMALLOC PURGE: jemalloc keeps the memory allocated while MemoryTracking reports far less, so it is not a cache and
1054
+ # not freed pages, and only a restart gives it back. The server's limit check reads that RSS ("would use ... current
1055
+ # RSS: ..."), so after a few wide tables a load can fail with code 241 whatever it needs itself. max_server_memory_usage
1056
+ # is not fixed either: it follows the memory the host has free, which moves while other containers run.
1057
+ restart_rss_share = 0.4 # setting bench.restart_rss_share: restart when RSS is above this share of the limit ...
1058
+ restart_rss_growth = 300_000_000 # ... and this many bytes above a fresh server's (setting bench.restart_rss_growth_bytes)
1059
+
1060
+ def memory_state(self) -> dict:
1061
+ """{resident, limit, available, tracked}: the server's RSS, its memory limit now, the memory the host has
1062
+ available, and what the server's own tracker counts. Zeros when they can not be read."""
1063
+ out = {"resident": 0, "limit": 0, "available": 0, "tracked": 0}
1064
+ try:
1065
+ for r in self.rows("SELECT metric, value FROM system.asynchronous_metrics WHERE metric IN ('MemoryResident', 'OSMemoryAvailable')"):
1066
+ out["resident" if r["metric"] == "MemoryResident" else "available"] = int(float(r["value"]))
1067
+ r = self.rows("SELECT value FROM system.metrics WHERE metric = 'MemoryTracking'")
1068
+ out["tracked"] = int(float(r[0]["value"])) if r else 0
1069
+ r = self.rows("SELECT value FROM system.server_settings WHERE name = 'max_server_memory_usage'")
1070
+ out["limit"] = int(float(r[0]["value"])) if r else 0
1071
+ self.limit_seen = max(int(getattr(self, "limit_seen", 0) or 0), out["limit"])
1072
+ except QueryError as e:
1073
+ # a server at its limit refuses even this query ("memory limit exceeded"): that is the state to act on
1074
+ out["refused"] = "memory limit" in str(e).lower() or "241" in str(e)
1075
+ except (ValueError, KeyError, IndexError):
1076
+ pass
1077
+ return out
1078
+
1079
+ def restart_server(self, why: str) -> dict:
1080
+ """Restart the server in its container: the tables on disk stay, the memory it held is given back. A recorded
1081
+ event ({why, resident_before, resident_after, seconds}), not a failure; `restarts` lists them."""
1082
+ before = self.memory_state()
1083
+ started = time.monotonic()
1084
+ subprocess.run([self.runtime, "restart", "-t", "30", self.name], capture_output=True)
1085
+ if not self._wait_ready(120):
1086
+ raise SandboxError(f"The sandbox server did not come back after a restart ({why}).")
1087
+ time.sleep(1.5) # the asynchronous metrics are read once a second
1088
+ if not self._wait_ready(60):
1089
+ raise SandboxError(f"The sandbox server did not stay up after a restart ({why}).")
1090
+ after = self.memory_state()
1091
+ event = {"why": why, "resident_before": before["resident"], "resident_after": after["resident"],
1092
+ "limit_before": before["limit"], "limit_after": after["limit"], "seconds": round(time.monotonic() - started, 1)}
1093
+ self.restarts = getattr(self, "restarts", []) + [event]
1094
+ # what a restarted server holds with the tables now loaded: the floor a later restart must be well above to help
1095
+ # (a restart can give back almost nothing: the loaded tables' own memory, not memory kept from earlier loads)
1096
+ self.restarted_resident = after["resident"]
1097
+ return event
1098
+
1099
+ def bound_memory(self, stage: str, force: bool = False) -> dict | None:
1100
+ """Give memory back before a load: the caches and the allocator's free pages, then, when the server still holds
1101
+ more than `restart_rss_share` of its limit and `restart_rss_growth` over a fresh server, a restart. Returns the
1102
+ restart event, or None when none was needed."""
1103
+ self.drop_caches()
1104
+ state = self.memory_state()
1105
+ fresh = max(getattr(self, "fresh_resident", 0) or 0, getattr(self, "restarted_resident", 0) or 0)
1106
+ if state.get("refused"):
1107
+ return self.restart_server(f"{stage}: the server refused a metrics query, it is at its memory limit")
1108
+ if not state["resident"] or not state["limit"]:
1109
+ return self.restart_server(f"{stage}: forced") if force else None
1110
+ high = state["resident"] > state["limit"] * float(self.restart_rss_share) and state["resident"] > fresh + int(self.restart_rss_growth)
1111
+ if force or high:
1112
+ why = (f"{stage}: the server held {state['resident'] / 1e6:,.0f} MB of {state['limit'] / 1e6:,.0f} MB allowed "
1113
+ f"({state['tracked'] / 1e6:,.0f} MB in use by its tracker)")
1114
+ return self.restart_server(why)
1115
+ return None
1116
+
1117
+ wait_memory_s = 180 # setting bench.wait_for_memory_s: after code 241, how long to wait for the host's memory
1118
+ wait_memory_bytes = 1_500_000_000 # ... until the server's limit is this far above what it holds (bench.wait_for_memory_bytes)
1119
+
1120
+ def wait_for_memory(self) -> dict:
1121
+ """After a load passed the limit: wait (at most `wait_memory_s`) until the limit, which follows the host's free memory,
1122
+ is `wait_memory_bytes` above what the server holds. Returns {waited_s, headroom}."""
1123
+ started = time.monotonic()
1124
+ state = self.memory_state()
1125
+ while state["limit"] and state["limit"] - state["resident"] < int(self.wait_memory_bytes) and time.monotonic() - started < float(self.wait_memory_s):
1126
+ time.sleep(5)
1127
+ state = self.memory_state()
1128
+ return {"waited_s": round(time.monotonic() - started, 1), "headroom": state["limit"] - state["resident"]}
1129
+
1130
+ def drop_caches(self) -> None:
1131
+ for statement in ("SYSTEM DROP MARK CACHE", "SYSTEM DROP UNCOMPRESSED CACHE", "SYSTEM DROP QUERY CACHE",
1132
+ "SYSTEM JEMALLOC PURGE"): # the allocator keeps freed memory as the server's RSS until purged
1133
+ try:
1134
+ self.execute(statement)
1135
+ except (QueryError, SandboxError):
1136
+ pass
1137
+
1138
+ def neighbours(self) -> dict:
1139
+ """Other containers running on the same host (a shared host): {containers, memory_bytes}. Counts only, no
1140
+ names: the memory they hold is memory the server's limit (it follows the host's free memory) does not have."""
1141
+ try:
1142
+ text = subprocess.run([self.runtime, "stats", "--no-stream", "--format", "{{.Name}}\t{{.MemUsage}}"],
1143
+ capture_output=True, text=True, timeout=60).stdout
1144
+ except (OSError, subprocess.SubprocessError):
1145
+ return {"containers": 0, "memory_bytes": 0, "known": False}
1146
+ count, held = 0, 0
1147
+ units = {"b": 1, "kb": 1e3, "kib": 1024, "mb": 1e6, "mib": 2 ** 20, "gb": 1e9, "gib": 2 ** 30}
1148
+ for line in text.splitlines():
1149
+ name, _, usage = line.partition("\t")
1150
+ if not name.strip() or name.strip() == self.name:
1151
+ continue
1152
+ count += 1
1153
+ m = re.match(r"\s*([\d.]+)\s*([a-zA-Z]+)", usage)
1154
+ if m:
1155
+ held += int(float(m.group(1)) * units.get(m.group(2).lower(), 1))
1156
+ return {"containers": count, "memory_bytes": held, "known": True}
1157
+
1158
+ def plan_memory_budget(self) -> int:
1159
+ """The budget a load group is planned against: `load_memory_share` of the largest limit the server had this run.
1160
+ The limit follows the host's free memory: planned on a moment when other containers hold most of the host,
1161
+ every table of a scale would be cut to a few rows. A load that then passes the momentary limit is retried (bench)."""
1162
+ now = self._load_memory_budget()
1163
+ seen = int(getattr(self, "limit_seen", 0) or 0)
1164
+ return max(now, int(seen * self.load_memory_share))
1165
+
1166
+ def _load_memory_budget(self) -> int:
1167
+ """Bytes the cuts may hold side by side: `load_memory_share` of the server's own memory limit (0 when unknown)."""
1168
+ try:
1169
+ r = self.rows("SELECT value FROM system.server_settings WHERE name = 'max_server_memory_usage'")
1170
+ limit = int(float(r[0]["value"])) if r else 0
1171
+ except (QueryError, ValueError):
1172
+ limit = 0
1173
+ if not limit:
1174
+ limit = int((self.query_limits or {}).get("max_memory_usage") or 0) * 2
1175
+ return int(limit * self.load_memory_share)
1176
+
1177
+ def _copy_settings(self, source: str, partition: str | None = None) -> dict:
1178
+ """Block sizes for an INSERT ... SELECT that copies rows of `source`, from its real row width: a block holds about
1179
+ `copy_block_bytes` of uncompressed data (bench.copy_block_bytes) whatever the width of a row.
1180
+
1181
+ A copy writes all its rows to one partition, so each part written gets the whole block; a generating INSERT
1182
+ spreads a block over a dozen partitions. Measured on a wide table (over a hundred columns, rows of several kB): one copy
1183
+ of a partition held GBs at the server's defaults and at 64 MB blocks, about a hundred MB at 4 MB. Smaller blocks are not
1184
+ the answer: the merged part keeps granules no larger than the copied blocks (rows per mark fell from about 250
1185
+ to under 100 at 4 MB), and rows read follow granules. So the blocks stay at 64 MB and the number of cuts run
1186
+ side by side is measured instead (_load_time_ranged). The width is that of `partition`, or of the widest
1187
+ partition (rows grow with the width of their age, sizes.py)."""
1188
+ r = self.rows("SELECT max(w) AS w FROM (SELECT sum(data_uncompressed_bytes) / greatest(sum(rows), 1) AS w FROM system.parts "
1189
+ "WHERE database = {d:String} AND table = {t:String} AND active AND (partition_id = {p:String} OR {p:String} = '') "
1190
+ "GROUP BY partition_id)", {**self._where(source), "p": partition or ""})
1191
+ from ..datagen import block_settings
1192
+ return block_settings(float(r[0]["w"] or 0) if r else 0, self.copy_block_bytes)
1193
+
1194
+ def _is_merge_tree(self, name: str) -> bool:
1195
+ r = self.rows("SELECT engine FROM system.tables WHERE database = {d:String} AND name = {t:String}", self._where(name))
1196
+ return bool(r) and r[0]["engine"].endswith("MergeTree")
1197
+
1198
+ def add_versions(self, definition: dict, share: float | None) -> dict:
1199
+ """Physical state of a deduplicating table: write a share of its rows a second time, as newer versions.
1200
+
1201
+ A ReplacingMergeTree in production always holds rows that exist in several parts until a merge removes them.
1202
+ FINAL has to merge those at read time, and a query without FINAL sees them. A freshly generated table has none,
1203
+ so FINAL there is nearly free. `share` None means the stated default. Returns what was done, for the bench record."""
1204
+ name = definition["name"]
1205
+ if "physical" not in self.realism or not self._is_merge_tree(name):
1206
+ return {}
1207
+ done: dict = {}
1208
+ timed = self.time_plan.get(name) or {}
1209
+ if DEDUPLICATING.search(definition.get("create_sql") or "") and timed.get("built"):
1210
+ # the versions were written with the parts cut by time (_load_time_ranged): one part later than the row
1211
+ done = {"duplicate_share": timed["duplicate_share"], "duplicate_share_basis": timed["duplicate_share_basis"],
1212
+ "duplicate_rows": timed["built"]["duplicate_rows"], "duplicate_placement": "the next newer part of the same partition"}
1213
+ elif DEDUPLICATING.search(definition.get("create_sql") or ""):
1214
+ used = DEFAULT_DUPLICATE_SHARE if share is None else min(max(float(share), 0.0), 0.9)
1215
+ if used > 0:
1216
+ self._as_one_part_each(name, f"INSERT INTO {{stage}} SELECT * FROM {quote_table(name)} WHERE rand(7) % 100000 < {int(used * 100000)}",
1217
+ settings=self._copy_settings(name))
1218
+ done = {"duplicate_share": used, "duplicate_share_basis": "default" if share is None else "profile"}
1219
+ layout = self.rows("SELECT count() / greatest(uniqExact(partition_id), 1) AS per_partition FROM system.parts "
1220
+ "WHERE database = {d:String} AND table = {t:String} AND active", self._where(name))
1221
+ return {**done, "parts_per_partition": round(float(layout[0]["per_partition"]), 1) if layout else 0, **self._layout_built(name)}
1222
+
1223
+ def _layout_built(self, name: str) -> dict:
1224
+ """What the load made of the real part layout, for the bench record: the sandbox's parts in its newest and in
1225
+ its oldest partition beside the real table's, and rows per mark. Counts only; no partition is named."""
1226
+ plan = self.layout_plan.get(name)
1227
+ timed = self.time_plan.get(name) or {}
1228
+ if not plan and not timed.get("built"):
1229
+ return {}
1230
+ built = self.rows("SELECT partition_id, count() AS parts, sum(rows) AS rows, sum(marks) AS marks FROM system.parts "
1231
+ "WHERE database = {d:String} AND table = {t:String} AND active GROUP BY partition_id "
1232
+ "ORDER BY partition_id DESC", self._where(name))
1233
+ if not built:
1234
+ return {}
1235
+ rows, marks = sum(int(r["rows"]) for r in built), sum(int(r["marks"]) for r in built)
1236
+ out = {"partitions": len(built), "newest_parts": int(built[0]["parts"]), "oldest_parts": int(built[-1]["parts"]),
1237
+ "most_parts_built": int(self.max_parts_per_partition), "rows_per_mark": round(rows / marks, 1) if marks else None}
1238
+ if plan:
1239
+ real = [p for p in plan.get("parts") or [] if p]
1240
+ out = {"basis": "real parts per partition, by age", "unit": plan["unit"], **out,
1241
+ "real_newest_parts": real[0] if real else None, "real_oldest_parts": plan.get("older") or (real[-1] if real else None),
1242
+ "real_rows_per_mark": plan.get("rows_per_mark")}
1243
+ else:
1244
+ out = {"basis": timed.get("layout_basis") or "default", **out}
1245
+ if timed.get("built"):
1246
+ # each part holds one range of the time column (parts.py): the shape it was cut to, and the newest partition's
1247
+ # parts as built, oldest first, as shares of its rows (counts only; no partition is named)
1248
+ newest = self.rows("SELECT rows FROM system.parts WHERE database = {d:String} AND table = {t:String} AND active "
1249
+ "AND partition_id = {p:String} ORDER BY min_block_number", {**self._where(name), "p": built[0]["partition_id"]})
1250
+ total = sum(int(r["rows"]) for r in newest) or 1
1251
+ out.update(parts_hold="time ranges", time_column=timed["column"], time_column_basis=timed["basis"],
1252
+ part_size_ratio=round(float(timed["ratio"]), 4), part_size_basis=timed.get("ratio_basis") or "default",
1253
+ newest_part_shares=[round(int(r["rows"]) / total, 4) for r in newest],
1254
+ cut_workers=timed["built"].get("workers"), cut_peak_bytes=timed["built"].get("peak_bytes"))
1255
+ return {"part_layout": out}
1256
+
1257
+ def apply_setup(self, statements: list[str]) -> list[str]:
1258
+ """Run a variant's setup. Returns notes on what the sandbox had to add for it to run.
1259
+
1260
+ A projection on a ReplacingMergeTree (or another deduplicating engine) is refused until the table says what a
1261
+ merge does with it: `deduplicate_merge_projection_mode`. The sandbox sets it to `rebuild`, the mode that keeps
1262
+ the projection correct, and says so: production needs the same setting before the migration."""
1263
+ notes: list[str] = []
1264
+ for stmt in statements:
1265
+ stmt = local_engine_setup(stmt.strip().rstrip(";")) # a Shared*/Replicated* engine has no cluster here
1266
+ source = COPY_AS.match(stmt)
1267
+ scaled = self._granularity_of(source.group(1)) if source else None
1268
+ if scaled:
1269
+ # CREATE TABLE copy AS t ENGINE = ... takes the columns, not t's settings: the copy gets t's scaled granules
1270
+ stmt = with_merge_settings(stmt, {k: scaled[k] for k in ("index_granularity", "index_granularity_bytes") if k in scaled})
1271
+ copy = PLAIN_COPY.match(stmt)
1272
+ if copy and "physical" in self.realism and self._is_merge_tree(copy.group(1).strip("`\"")) \
1273
+ and self._is_merge_tree(copy.group(2).strip("`\"")):
1274
+ self._copy_by_part(copy.group(1), copy.group(2))
1275
+ continue
1276
+ if copy:
1277
+ # a re-keyed copy whose columns the agent wrote in another order: SELECT * maps them by position
1278
+ stmt = f"INSERT INTO {copy.group(1)} {self._copy_columns(copy.group(1), copy.group(2))} FROM {copy.group(2)}"
1279
+ try:
1280
+ self.execute(stmt, settings={"mutations_sync": 2})
1281
+ except QueryError as e:
1282
+ added = ADDED.match(stmt)
1283
+ gate = re.search(r"[Ss]et (?:setting )?[`']?(allow_\w+)[`']? ?= ?1", str(e))
1284
+ if gate and gate.group(1) not in self.session_settings:
1285
+ # an index type the server holds behind a switch (a text index): on for the session, and said
1286
+ self.session_settings[gate.group(1)] = 1
1287
+ notes.append(f"the server allows this setup only with {gate.group(1)} = 1: set for the sandbox session; production needs it too")
1288
+ self.execute(stmt, settings={"mutations_sync": 2})
1289
+ continue
1290
+ if not (added and "deduplicate_merge_projection_mode" in str(e) and added.group(1) not in self._projection_mode):
1291
+ raise
1292
+ table = added.group(1)
1293
+ self.execute(f"ALTER TABLE {table} MODIFY SETTING deduplicate_merge_projection_mode = 'rebuild'")
1294
+ self._projection_mode.add(table)
1295
+ notes.append(f"needs the table setting deduplicate_merge_projection_mode = 'rebuild' on {table.strip('`')}: a "
1296
+ "deduplicating engine refuses a projection without it. Set in the sandbox; the migration must set it too")
1297
+ self.execute(stmt, settings={"mutations_sync": 2})
1298
+ created = CREATED.match(stmt)
1299
+ if created and created.group(1).upper() == "TABLE" and "physical" in self.realism:
1300
+ self._keep_parts(created.group(2))
1301
+ return notes
1302
+
1303
+ def undo_setup(self, statements: list[str]) -> None:
1304
+ for stmt in undo_statements(statements):
1305
+ try:
1306
+ self.execute(stmt)
1307
+ except QueryError:
1308
+ pass
1309
+ for table in sorted(getattr(self, "_projection_mode", ())):
1310
+ try:
1311
+ self.execute(f"ALTER TABLE {table} RESET SETTING deduplicate_merge_projection_mode")
1312
+ except QueryError:
1313
+ pass
1314
+ self._projection_mode = set()
1315
+
1316
+ def _copy_columns(self, target: str, source: str) -> str:
1317
+ """`(a, b) SELECT a, b`: the columns of `target` a row can be written to that `source` has, by name. A copy written
1318
+ SELECT * maps columns by position, and a re-keyed copy whose definition lists them in another order fails (UUID
1319
+ into DateTime64) or, worse, loads the wrong values. Falls back to `SELECT *` when the columns can not be read."""
1320
+ try:
1321
+ into = self.column_types(target.strip("`\""))
1322
+ have = self.column_types(source.strip("`\""))
1323
+ except QueryError:
1324
+ return "SELECT *"
1325
+ return copy_columns(into, have)
1326
+
1327
+ def _copy_by_part(self, target: str, source: str) -> None:
1328
+ """Copy a table so that the copy has as many parts per partition as the original, duplicate versions included.
1329
+
1330
+ One INSERT ... SELECT * would leave the copy to background merges, which combine its parts and remove every
1331
+ duplicate version: a re-keyed copy would then win under FINAL only because it is tidier than the table it
1332
+ replaces. The n-th part of every partition is copied together and becomes the n-th part of the copy."""
1333
+ table = source.strip("`\"").split(".")[-1]
1334
+ parts = self.rows("SELECT name, row_number() OVER (PARTITION BY partition_id ORDER BY min_block_number, name) AS n FROM system.parts "
1335
+ "WHERE database = {d:String} AND table = {t:String} AND active", self._where(source))
1336
+ rounds: dict[int, list[str]] = {}
1337
+ for r in parts:
1338
+ rounds.setdefault(int(r["n"]), []).append(r["name"])
1339
+ if not rounds or len(rounds) > 4 * MAX_PARTS_PER_PARTITION:
1340
+ self.execute(f"INSERT INTO {target} {self._copy_columns(target, source)} FROM {source}", settings={"mutations_sync": 2})
1341
+ return
1342
+ cols = self._copy_columns(target, source)
1343
+ copy = self._copy_settings(table)
1344
+ for n in sorted(rounds):
1345
+ names = ", ".join("'" + x.replace("'", "") + "'" for x in rounds[n])
1346
+ self._as_one_part_each(target.strip("`\""), f"INSERT INTO {{stage}} {cols} FROM {source} WHERE _part IN ({names})", settings=copy)
1347
+
1348
+ def wait_idle(self, timeout_s: int = 60) -> None:
1349
+ """Wait for background merges to finish: they hold memory an insert may need."""
1350
+ deadline = time.monotonic() + timeout_s
1351
+ while time.monotonic() < deadline:
1352
+ try:
1353
+ if self._http("SELECT count() FROM system.merges").strip() == "0":
1354
+ return
1355
+ except QueryError:
1356
+ return
1357
+ time.sleep(1.0)
1358
+
1359
+ def storage_bytes(self, tables: list[str], setup_sql: list[str]) -> int:
1360
+ created = [m.group(2).replace("`", "").replace('"', "") for s in setup_sql if (m := CREATED.match(s))]
1361
+ return sum(self.table_stats(t).get("bytes_on_disk", 0) for t in list(tables) + created)
1362
+
1363
+ def _where(self, name: str) -> dict:
1364
+ """The `d` (database) and `t` (table) parameters of a system-table lookup for `name`: a database-qualified
1365
+ name (`app.runs`) lives in its own database, not in the session's."""
1366
+ bare = name.replace("`", "").replace('"', "")
1367
+ db, _, table = bare.rpartition(".")
1368
+ return {"d": db or self.database, "t": table}
1369
+
1370
+ def table_stats(self, table: str) -> dict:
1371
+ r = self.rows(
1372
+ "SELECT sum(rows) AS rows, sum(bytes_on_disk) AS bytes_on_disk, sum(data_uncompressed_bytes) AS uncompressed, "
1373
+ "count() AS parts FROM system.parts WHERE database = {d:String} AND table = {t:String} AND active",
1374
+ self._where(table))
1375
+ return {k: int(v) for k, v in r[0].items()} if r else {}
1376
+
1377
+ def free_bytes(self) -> int:
1378
+ r = self.rows("SELECT free_space FROM system.disks WHERE name = 'default'")
1379
+ return int(r[0]["free_space"]) if r else 0
1380
+
1381
+ # ---- measurement ----------------------------------------------------
1382
+ def freeze_clock(self) -> str:
1383
+ """Fix the instant `now()` stands for in every measured query from here on, and return it.
1384
+
1385
+ A baseline and its variant run seconds apart; with `created_at >= now() - INTERVAL 1 DAY` the window moves
1386
+ between the two and rows fall out of it, so a projection that can not change a result seems to."""
1387
+ self.clock = self._http("SELECT toString(now64(6, 'UTC'))").strip()
1388
+ return self.clock
1389
+
1390
+ def frozen(self, sql: str) -> str:
1391
+ """The statement with every reading of the clock replaced by the frozen instant (see freeze_clock)."""
1392
+ if not self.clock:
1393
+ return sql
1394
+ seconds = self.clock.split(".")[0]
1395
+
1396
+ def change(text: str) -> str:
1397
+ text = re.sub(r"\bnow64\s*\(\s*(\d+)?\s*(?:,\s*'[^']*'\s*)?\)", lambda m: f"toDateTime64('{self.clock}', {m.group(1) or 3}, 'UTC')",
1398
+ text, flags=re.I)
1399
+ text = re.sub(r"\b(?:now|current_timestamp)\s*\(\s*\)|\bCURRENT_TIMESTAMP\b(?!\s*\()", f"toDateTime('{seconds}', 'UTC')", text, flags=re.I)
1400
+ text = re.sub(r"\b(?:today|curdate|current_date)\s*\(\s*\)|\bCURRENT_DATE\b(?!\s*\()", f"toDate('{seconds[:10]}')", text, flags=re.I)
1401
+ return re.sub(r"\byesterday\s*\(\s*\)", f"(toDate('{seconds[:10]}') - 1)", text, flags=re.I)
1402
+ return outside_quotes(sql, change)
1403
+
1404
+ # ---- the resource profile of a run -----------------------------------------------------------------------------
1405
+ # Read from the server's query log per run (verified on 24.8, 25.8 and 26.6): user and system CPU from getrusage
1406
+ # (UserTimeMicroseconds, SystemTimeMicroseconds: counted on every server), the memory tracker's peak (memory_usage:
1407
+ # what the query asked for, never the server's RSS), threads (peak_threads_usage, threads at
1408
+ # once, where the server has it; else length(thread_ids), threads ever used), the disk a sort or an aggregation
1409
+ # spilled (External*), and OS counters that need the kernel's task statistics (absent in many containers: 0 then).
1410
+ resource_threads: int | None = 4 # `[bench] resource_threads`: max_threads of every measured run (None: the server's)
1411
+ cores: int = 0 # the sandbox's processors (NumberOfCPUCores), the most threads a run is given
1412
+ _thread_column: str | None = None # peak_threads_usage where the server has it, else length(thread_ids)
1413
+
1414
+ def run_settings(self) -> dict:
1415
+ """The settings every measured run is sent with: no query cache, the limits, and max_threads pinned (memory and wall
1416
+ time follow the thread count; CPU time does not, much)."""
1417
+ threads = self.threads_for_run()
1418
+ return {"use_query_cache": 0, **self.query_limits, **({"max_threads": threads} if threads else {})}
1419
+
1420
+ thread_override: int | None = None # production's average threads for the shape being measured (bench_candidate)
1421
+
1422
+ def threads_for_run(self) -> int | None:
1423
+ wanted = self.thread_override or self.resource_threads
1424
+ if not wanted:
1425
+ return None
1426
+ return max(min(int(wanted), self.cores), 1) if self.cores else int(wanted)
1427
+
1428
+ def _threads_expr(self) -> str:
1429
+ if self._thread_column is None:
1430
+ try:
1431
+ has = self.rows("SELECT count() AS n FROM system.columns WHERE database = 'system' AND table = 'query_log' "
1432
+ "AND name = 'peak_threads_usage'")
1433
+ self._thread_column = "peak_threads_usage" if has and int(has[0]["n"]) else "length(thread_ids)"
1434
+ except QueryError:
1435
+ self._thread_column = "length(thread_ids)"
1436
+ return self._thread_column
1437
+
1438
+ def _logged_runs(self, pattern: str) -> list[dict]:
1439
+ pe = lambda e: f"ProfileEvents['{e}']" # noqa: E731
1440
+ return self.rows(
1441
+ "SELECT query_id, read_rows, read_bytes, result_rows, result_bytes, memory_usage, query_duration_ms, "
1442
+ f"{pe('SelectedParts')} AS parts, {pe('SelectedMarks')} AS marks, {pe('SelectedMarksTotal')} AS marks_total, "
1443
+ f"{pe('RealTimeMicroseconds')} AS real_us, {pe('UserTimeMicroseconds')} AS user_us, {pe('SystemTimeMicroseconds')} AS system_us, "
1444
+ f"{pe('OSIOWaitMicroseconds')} AS io_wait_us, mapContains(ProfileEvents, 'OSIOWaitMicroseconds') AS counts_io_wait, "
1445
+ f"{pe('ExternalSortUncompressedBytes')} + {pe('ExternalAggregationUncompressedBytes')} AS spill_bytes, "
1446
+ f"{pe('ExternalSortWritePart')} + {pe('ExternalAggregationWritePart')} AS spill_parts, "
1447
+ f"{self._threads_expr()} AS threads, projections "
1448
+ "FROM system.query_log WHERE type = 'QueryFinish' AND query_id LIKE {p:String} ORDER BY query_id", {"p": pattern})
1449
+
1450
+ @staticmethod
1451
+ def run_resources(r: dict) -> dict:
1452
+ """One logged run as the bench's resource sample: {cpu_ms, cpu_user_ms, cpu_system_ms, memory_bytes, duration_ms,
1453
+ threads, spill_bytes, result_bytes, io_wait_ms}."""
1454
+ user, system = int(r.get("user_us") or 0) / 1000, int(r.get("system_us") or 0) / 1000
1455
+ return {"cpu_ms": round(user + system, 3), "cpu_user_ms": round(user, 3), "cpu_system_ms": round(system, 3),
1456
+ "memory_bytes": int(r.get("memory_usage") or 0), "duration_ms": float(r.get("query_duration_ms") or 0),
1457
+ "threads": int(r.get("threads") or 0) or None, "spill_bytes": int(r.get("spill_bytes") or 0),
1458
+ # FORMAT Null sends nothing: the server counts no result bytes then (0 is "not counted", not "empty")
1459
+ "result_bytes": int(r["result_bytes"]) if int(r.get("result_bytes") or 0) > 0 else None,
1460
+ "io_wait_ms": round(int(r.get("io_wait_us") or 0) / 1000, 3) if int(r.get("counts_io_wait") or 0) else None}
1461
+
1462
+ def sample(self, statements: list[tuple[str, dict | None]]) -> list[dict]:
1463
+ """Run each statement once, in the order given (baseline and variant interleaved by the caller), and return each
1464
+ run's resources (run_resources) in that order. No warm-up: the caller has measured both already. One log flush."""
1465
+ tag = uuid.uuid4().hex[:12]
1466
+ for i, (sql, params) in enumerate(statements):
1467
+ self._http(self.frozen(sql.strip().rstrip(";")) + " FORMAT Null", params,
1468
+ {"query_id": f"codecop-{tag}-{i:04d}", "log_queries": 1, **self.run_settings()})
1469
+ self._http("SYSTEM FLUSH LOGS")
1470
+ found = {r["query_id"]: r for r in self._logged_runs(f"codecop-{tag}-%")}
1471
+ out = []
1472
+ for i in range(len(statements)):
1473
+ r = found.get(f"codecop-{tag}-{i:04d}")
1474
+ out.append(self.run_resources(r) if r else {})
1475
+ return out
1476
+
1477
+ def measure(self, sql: str, params: dict | None = None, runs: int = 3) -> Measurement:
1478
+ """Run a SELECT and report what it read. The first run is a warm-up and is not timed."""
1479
+ sql = self.frozen(sql.strip().rstrip(";"))
1480
+ m = Measurement(ok=False)
1481
+ tag = uuid.uuid4().hex[:12]
1482
+ try:
1483
+ for i in range(runs + 1):
1484
+ self._http(sql + " FORMAT Null", params,
1485
+ {"query_id": f"codecop-{tag}-{i}", "log_queries": 1, **self.run_settings()})
1486
+ self._http("SYSTEM FLUSH LOGS")
1487
+ logged = self._logged_runs(f"codecop-{tag}-%")
1488
+ if not logged:
1489
+ m.error = "query did not appear in system.query_log"
1490
+ return m
1491
+ timed = [r for r in logged if not r["query_id"].endswith("-0")] or logged
1492
+ best = min(timed, key=lambda r: int(r["query_duration_ms"]))
1493
+ m.read_rows, m.read_bytes = int(best["read_rows"]), int(best["read_bytes"])
1494
+ m.result_rows, m.memory_bytes = int(best["result_rows"]), max(int(r["memory_usage"]) for r in timed)
1495
+ m.duration_ms = float(best["query_duration_ms"])
1496
+ m.runs = [float(r["query_duration_ms"]) for r in timed]
1497
+ m.selected_parts, m.selected_marks, m.total_marks = int(best["parts"]), int(best["marks"]), int(best["marks_total"])
1498
+ m.projections = sorted({str(x) for x in best.get("projections") or []})
1499
+ fill_resources(m, [self.run_resources(r) for r in timed], "rusage", "tracker")
1500
+ m.threads_setting = self.threads_for_run()
1501
+ m.result_hash = self.result_hash(sql, params)
1502
+ try:
1503
+ m.explain = self._http(f"EXPLAIN indexes = 1 {sql}", params).strip()
1504
+ except QueryError as e:
1505
+ m.explain = f"(EXPLAIN failed: {str(e)[:200]})"
1506
+ m.ok = True
1507
+ except QueryError as e:
1508
+ m.error = str(e)
1509
+ return m
1510
+
1511
+ def projection_note(self, m: Measurement, setup_sql: list[str]) -> str:
1512
+ """Why a projection variant read what it read, read while its projection is still there: whether the server used
1513
+ it (query_log `projections`) and, when it did, the rows per granule of its parts beside the table's own.
1514
+
1515
+ On a wide table a projection can be used and read more rows than the table does without it: a projection of narrow columns keeps
1516
+ the default 8,192 rows per granule, while the table's wide rows make granules of a few hundred rows (adaptive
1517
+ granularity). A sandbox part smaller than one projection granule is read whole through the projection while the
1518
+ table prunes inside it: real reads, and an effect of the sandbox's small parts."""
1519
+ added = [a for a in (ADDED.match(s.strip()) for s in setup_sql or []) if a and a.group(2).upper() == "PROJECTION"]
1520
+ if not added:
1521
+ return ""
1522
+ table, name = added[0].group(1).strip("`\""), added[0].group(3).strip("`\"")
1523
+ used = [p for p in m.projections if p.split(".")[-1].strip("`") == name]
1524
+ if not used:
1525
+ return ("the server did not use projection " + name + " (system.query_log lists "
1526
+ + (", ".join(m.projections) if m.projections else "no projection") + " for the variant's run)")
1527
+ short = table.split(".")[-1]
1528
+ try:
1529
+ proj = self.rows("SELECT sum(rows) AS rows, sum(marks) AS marks, count() AS parts FROM system.projection_parts WHERE active "
1530
+ "AND table = {t:String} AND name = {n:String}", {"t": short, "n": name})[0]
1531
+ base = self.rows("SELECT sum(rows) AS rows, sum(marks) AS marks, count() AS parts FROM system.parts WHERE active "
1532
+ "AND table = {t:String}", {"t": short})[0]
1533
+ except (QueryError, IndexError, KeyError):
1534
+ return f"the server used projection {name}"
1535
+ p_per = int(proj["rows"] or 0) / max(int(proj["marks"] or 0), 1)
1536
+ b_per = int(base["rows"] or 0) / max(int(base["marks"] or 0), 1)
1537
+ per_part = int(base["rows"] or 0) / max(int(base["parts"] or 0), 1)
1538
+ text = (f"the server used projection {name}; its granules hold {p_per:,.0f} rows, the table's {b_per:,.0f}, "
1539
+ f"and a part holds {per_part:,.0f} rows")
1540
+ if p_per > b_per * 1.5 and per_part <= p_per * 2:
1541
+ text += (": a sandbox part is about one projection granule, so the projection reads each part it touches whole while "
1542
+ "the table prunes inside parts; production's larger parts would not read like this")
1543
+ return text
1544
+
1545
+ def result_hash(self, sql: str, params: dict | None = None) -> str:
1546
+ """Hash of the result as a multiset of rows: the row count plus two sums of per-row hashes.
1547
+
1548
+ Each row is first written out as text (`formatRowNoNewline('JSONCompactEachRow', *)`): values only, no column
1549
+ names, NULL as `null`, and any type including JSON. Hashing the columns directly (`cityHash64(*)`) gives NULL
1550
+ for a row that holds a NULL, and `sum` skips it, so rows with a NULL in them were not compared at all.
1551
+ Summing keeps duplicates (a row twice counts twice) and ignores order; two independent hashes make a
1552
+ cancelling collision between different sets of rows implausible."""
1553
+ sql = self.frozen(sql.strip().rstrip(";"))
1554
+ text = self._http(
1555
+ "SELECT count(), sum(cityHash64(codecop_row)), sum(sipHash64(codecop_row)) FROM "
1556
+ f"(SELECT formatRowNoNewline('JSONCompactEachRow', *) AS codecop_row FROM ({sql})) FORMAT TSV", params,
1557
+ {"use_query_cache": 0, **self.query_limits}).strip()
1558
+ return hashlib.sha1(text.encode()).hexdigest()[:16]