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.
- codecop/__init__.py +7 -0
- codecop/access.py +140 -0
- codecop/access_postgres.py +284 -0
- codecop/advisor.py +1512 -0
- codecop/advisor_bench.py +493 -0
- codecop/advisor_ch.py +2080 -0
- codecop/advisor_view.py +381 -0
- codecop/advisors.py +184 -0
- codecop/agent.py +221 -0
- codecop/agentfacts.py +745 -0
- codecop/apply/__init__.py +327 -0
- codecop/apply/check.py +344 -0
- codecop/apply/cli.py +162 -0
- codecop/apply/clickhouse.py +379 -0
- codecop/apply/common.py +238 -0
- codecop/apply/html.py +264 -0
- codecop/apply/patch.py +213 -0
- codecop/apply/postgres.py +102 -0
- codecop/apply/trial.py +166 -0
- codecop/assemble.py +104 -0
- codecop/baseline.py +1043 -0
- codecop/bench.py +2464 -0
- codecop/blockers.py +935 -0
- codecop/budget.py +980 -0
- codecop/catalog_profile.py +525 -0
- codecop/changed.py +261 -0
- codecop/cicmd.py +1002 -0
- codecop/cli.py +5421 -0
- codecop/client.py +729 -0
- codecop/coverage.py +1067 -0
- codecop/coverage_reasons.py +116 -0
- codecop/crashlog.py +70 -0
- codecop/datagen.py +766 -0
- codecop/datagen_postgres.py +630 -0
- codecop/datagen_sqlite.py +323 -0
- codecop/dbcli.py +885 -0
- codecop/definitions.py +457 -0
- codecop/discover/__init__.py +702 -0
- codecop/discover/arms.py +160 -0
- codecop/discover/base.py +234 -0
- codecop/discover/dialect.py +296 -0
- codecop/discover/elixir.py +64 -0
- codecop/discover/engine_go.py +320 -0
- codecop/discover/go.py +1947 -0
- codecop/discover/java.py +1528 -0
- codecop/discover/loops.py +1671 -0
- codecop/discover/named_go.py +258 -0
- codecop/discover/origins.py +4565 -0
- codecop/discover/origins_ts.py +1584 -0
- codecop/discover/orm_django.py +2772 -0
- codecop/discover/orm_django_models.py +814 -0
- codecop/discover/orm_django_sql.py +662 -0
- codecop/discover/orm_ent.py +565 -0
- codecop/discover/orm_ex_ecto.py +2138 -0
- codecop/discover/orm_go.py +2134 -0
- codecop/discover/orm_go_bun.py +602 -0
- codecop/discover/orm_go_run.py +636 -0
- codecop/discover/orm_go_types.py +1082 -0
- codecop/discover/orm_java.py +1450 -0
- codecop/discover/orm_jdbi.py +743 -0
- codecop/discover/orm_jooq.py +806 -0
- codecop/discover/orm_jpa.py +1307 -0
- codecop/discover/orm_mybatis.py +730 -0
- codecop/discover/orm_py.py +557 -0
- codecop/discover/orm_py_peewee.py +1266 -0
- codecop/discover/orm_py_prisma.py +298 -0
- codecop/discover/orm_rb_activerecord.py +1906 -0
- codecop/discover/orm_rust.py +1248 -0
- codecop/discover/orm_rust_seaorm.py +734 -0
- codecop/discover/orm_sqlalchemy.py +2475 -0
- codecop/discover/orm_stats.py +307 -0
- codecop/discover/orm_tables.py +29 -0
- codecop/discover/orm_ts.py +503 -0
- codecop/discover/orm_ts_drizzle.py +697 -0
- codecop/discover/orm_ts_knex.py +1117 -0
- codecop/discover/orm_ts_kysely.py +861 -0
- codecop/discover/orm_ts_prisma.py +1045 -0
- codecop/discover/orm_ts_schema.py +169 -0
- codecop/discover/orm_ts_sequelize.py +1401 -0
- codecop/discover/orm_ts_typeorm.py +1067 -0
- codecop/discover/probes.py +323 -0
- codecop/discover/python.py +595 -0
- codecop/discover/ruby.py +793 -0
- codecop/discover/rust.py +2378 -0
- codecop/discover/schema.py +520 -0
- codecop/discover/schema_ent.py +145 -0
- codecop/discover/schema_ts.py +420 -0
- codecop/discover/tsresolve.py +257 -0
- codecop/discover/typescript.py +1728 -0
- codecop/discover/xml_mapper.py +526 -0
- codecop/engines/__init__.py +515 -0
- codecop/engines/base.py +498 -0
- codecop/engines/clickhouse.py +1558 -0
- codecop/engines/pg_ddl.py +444 -0
- codecop/engines/pg_hints.py +137 -0
- codecop/engines/postgres.py +1060 -0
- codecop/engines/sqlite.py +742 -0
- codecop/families/__init__.py +3 -0
- codecop/families/build.py +280 -0
- codecop/families/cli.py +177 -0
- codecop/families/coverage_hook.py +62 -0
- codecop/families/driver.py +221 -0
- codecop/families/goslice.py +229 -0
- codecop/families/goslice_tool/go.mod +3 -0
- codecop/families/goslice_tool/main.go +403 -0
- codecop/families/holes.py +451 -0
- codecop/families/images/Dockerfile.go +5 -0
- codecop/families/images/Dockerfile.python +4 -0
- codecop/families/images/Dockerfile.rust +4 -0
- codecop/families/isolate.py +171 -0
- codecop/families/locate.py +270 -0
- codecop/families/model.py +301 -0
- codecop/families/plangate.py +271 -0
- codecop/families/tagpatch.py +174 -0
- codecop/fidelity.py +671 -0
- codecop/fixgroups.py +130 -0
- codecop/formerly.py +91 -0
- codecop/grantscript.py +254 -0
- codecop/groupbench.py +1375 -0
- codecop/groups.py +594 -0
- codecop/groups_view.py +186 -0
- codecop/heat.py +1405 -0
- codecop/heatcli.py +219 -0
- codecop/joins.py +1749 -0
- codecop/joins_view.py +127 -0
- codecop/kinds/__init__.py +507 -0
- codecop/kinds/calls/__init__.py +501 -0
- codecop/kinds/calls/extract.py +1097 -0
- codecop/kinds/calls/harness.py +408 -0
- codecop/kinds/calls/measure.py +342 -0
- codecop/kinds/calls/rules.py +139 -0
- codecop/kinds/calls/runners/RunCalls.java +167 -0
- codecop/kinds/calls/runners/run_go.go +141 -0
- codecop/kinds/calls/runners/run_node.js +186 -0
- codecop/kinds/calls/runners/run_python.py +319 -0
- codecop/kinds/calls/runners/run_rust.rs +200 -0
- codecop/kinds/calls/standin.py +340 -0
- codecop/kinds/pipeline.py +288 -0
- codecop/kinds/regex/__init__.py +1167 -0
- codecop/kinds/regex/engines/RegexHarness.java +129 -0
- codecop/kinds/regex/engines/run_go.go +294 -0
- codecop/kinds/regex/engines/run_node.js +99 -0
- codecop/kinds/regex/engines/run_python.py +295 -0
- codecop/kinds/regex/engines/run_rust.rs +149 -0
- codecop/kinds/regex/extract.py +1438 -0
- codecop/kinds/regex/harness.py +235 -0
- codecop/kinds/regex/measure.py +270 -0
- codecop/kinds/regex/shapes.py +418 -0
- codecop/kinds/regex/syntax.py +1721 -0
- codecop/kinds/testkind.py +107 -0
- codecop/kinds/transaction/__init__.py +228 -0
- codecop/kinds/transaction/bind.py +355 -0
- codecop/kinds/transaction/measure.py +264 -0
- codecop/kinds/transaction/plan.py +462 -0
- codecop/kinds/transaction/rules.py +540 -0
- codecop/kinds/transaction/sandbox.py +94 -0
- codecop/kinds/transaction/scenarios.py +520 -0
- codecop/kinds/transaction/schedule.py +483 -0
- codecop/kinds/transaction/shapes.py +418 -0
- codecop/kinds/transaction/verify.py +293 -0
- codecop/live.py +237 -0
- codecop/loopbench.py +2071 -0
- codecop/loopschema.py +591 -0
- codecop/mcpserver.py +120 -0
- codecop/mechanism.py +214 -0
- codecop/members.py +200 -0
- codecop/multi.py +443 -0
- codecop/observed.py +1868 -0
- codecop/parts.py +102 -0
- codecop/patterns.py +830 -0
- codecop/patterns_view.py +559 -0
- codecop/plangate.py +242 -0
- codecop/profile.py +439 -0
- codecop/prompts/areas.md +19 -0
- codecop/prompts/observed_variants.md +20 -0
- codecop/prompts/profile.md +60 -0
- codecop/prompts/profile_postgres.md +68 -0
- codecop/prompts/profile_sizes.md +26 -0
- codecop/prompts/profile_sqlite.md +69 -0
- codecop/prompts/rank.md +84 -0
- codecop/prompts/rank_postgres.md +96 -0
- codecop/prompts/rank_sqlite.md +94 -0
- codecop/prompts/scenario_variants.md +20 -0
- codecop/rank.py +1473 -0
- codecop/realdb/__init__.py +688 -0
- codecop/realdb/clickhouse.py +1223 -0
- codecop/realdb/facts.py +815 -0
- codecop/realdb/locality.py +964 -0
- codecop/realdb/locks.py +355 -0
- codecop/realdb/match.py +531 -0
- codecop/realdb/postgres.py +643 -0
- codecop/realdb/ratios.py +77 -0
- codecop/realdb/sample.py +126 -0
- codecop/relations.py +227 -0
- codecop/report.py +1854 -0
- codecop/resources.py +332 -0
- codecop/resources_view.py +266 -0
- codecop/rules/entry_points.toml +1013 -0
- codecop/rules/sinks.toml +362 -0
- codecop/runsonce.py +8 -0
- codecop/sandboxschema.py +555 -0
- codecop/scenario_agent.py +172 -0
- codecop/scenario_bind.py +507 -0
- codecop/scenario_sql.py +971 -0
- codecop/scenarios.py +675 -0
- codecop/scenarios_view.py +274 -0
- codecop/schemacli.py +67 -0
- codecop/schemas/areas_output.schema.json +21 -0
- codecop/schemas/profile_output.schema.json +362 -0
- codecop/schemas/rank_output.schema.json +385 -0
- codecop/sizes.py +200 -0
- codecop/sqlinfo.py +558 -0
- codecop/typedparams.py +576 -0
- codecop/verdicts.py +212 -0
- codecop/writebench.py +720 -0
- codecop/writecost.py +440 -0
- codecop/writes.py +1208 -0
- codecop-0.1.0.dist-info/METADATA +42 -0
- codecop-0.1.0.dist-info/RECORD +222 -0
- codecop-0.1.0.dist-info/WHEEL +4 -0
- codecop-0.1.0.dist-info/entry_points.txt +2 -0
- codecop-0.1.0.dist-info/licenses/LICENSE +21 -0
codecop/datagen.py
ADDED
|
@@ -0,0 +1,766 @@
|
|
|
1
|
+
"""Turn a data profile into ClickHouse INSERT statements.
|
|
2
|
+
|
|
3
|
+
The profile is declarative and editable: per table a row count, per column a
|
|
4
|
+
generator with its cardinality and distribution. Generation is set-based (one
|
|
5
|
+
INSERT ... SELECT FROM numbers() per batch), so millions of rows load in seconds.
|
|
6
|
+
|
|
7
|
+
Columns the profile does not mention are left out of the INSERT and take their
|
|
8
|
+
table default. Only columns that queries filter, join, group or sort on need a
|
|
9
|
+
realistic shape.
|
|
10
|
+
|
|
11
|
+
Generator kinds (the `kind` field of a column):
|
|
12
|
+
unique one distinct value per row prefix
|
|
13
|
+
key `distinct` values, uniform or skewed distinct, distribution, prefix
|
|
14
|
+
categorical a fixed list of values with weights values [{value, weight}]
|
|
15
|
+
int / float a numeric range min, max, distribution
|
|
16
|
+
timestamp spread over the last `days_back` days days_back, distribution (skewed = recent-heavy)
|
|
17
|
+
text text or a payload of a stated size and content avg_len, or content + typical_bytes + large_bytes (sizes.py)
|
|
18
|
+
constant the same value in every row value
|
|
19
|
+
expr a raw ClickHouse expression (may use `number`) sql
|
|
20
|
+
Every kind accepts:
|
|
21
|
+
null_fraction share of NULLs (Nullable columns only)
|
|
22
|
+
pinned [{value, share}] values that must exist with a given share of rows,
|
|
23
|
+
so that the parameter values a benchmark filters on match real rows
|
|
24
|
+
|
|
25
|
+
A table may also have `fixtures`: [{id, share, min_rows, values: [{column, value}]}]. All of a
|
|
26
|
+
fixture's values are set together on the same rows, so a query that filters on several
|
|
27
|
+
parameters at once finds rows. The same id covers the same row numbers in every table.
|
|
28
|
+
A fixture may also carry `size_factors`: [{column, factor}]: its rows hold values that many times
|
|
29
|
+
the column's usual size (the rows one tenant owns are often far heavier than the table's average).
|
|
30
|
+
|
|
31
|
+
Sizes and content (`realism`): with "sizes" a column's stated sizes are used; with "content" as well,
|
|
32
|
+
lengths follow a log-normal distribution and the text is built from a small vocabulary in the shape of
|
|
33
|
+
its content kind (JSON as JSON, messages as a JSON array of messages), so it compresses like real
|
|
34
|
+
payloads instead of not at all. Without either, a text column is `avg_len` random characters as before.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
from __future__ import annotations
|
|
38
|
+
|
|
39
|
+
import math
|
|
40
|
+
import re
|
|
41
|
+
import zlib
|
|
42
|
+
|
|
43
|
+
from . import sizes
|
|
44
|
+
|
|
45
|
+
INT_TYPE = re.compile(r"^(?:U?Int\d+|Decimal)")
|
|
46
|
+
STRINGY = re.compile(r"^(?:String|FixedString|Enum|UUID|IPv4|IPv6)")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
REALISM = ("sizes", "content", "physical", "fit") # what bench.run turns on by default; see bench.py
|
|
50
|
+
BLOCK_BYTES = 32_000_000 # generated rows per block are chosen to stay near this
|
|
51
|
+
# Uncompressed bytes an INSERT squashes into one block before it writes a part (setting insert_block_bytes under [bench]).
|
|
52
|
+
# The server's defaults (1,048,449 rows or 256 MiB) are sized for narrow rows: a generating INSERT of a wide table (rows of
|
|
53
|
+
# several kB, over a hundred columns) held GBs at them, whatever max_block_size or max_threads said; at 64 MB a few hundred MB.
|
|
54
|
+
INSERT_BLOCK_BYTES = 64_000_000
|
|
55
|
+
WIDE_ROW = 500 # bytes a row from which blocks are sized by bytes, not the server's row counts
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def block_settings(row_bytes: float, insert_block_bytes: int = INSERT_BLOCK_BYTES) -> dict:
|
|
59
|
+
"""Block sizes for an INSERT of rows of about `row_bytes` (uncompressed): rows per generated block (max_block_size)
|
|
60
|
+
and bytes per inserted block (min_insert_block_size_bytes, with the row count switched off: 0), so that one INSERT
|
|
61
|
+
holds about `insert_block_bytes` however wide a row is. {} for narrow rows: the server's defaults are right for them.
|
|
62
|
+
|
|
63
|
+
The inserted block is bounded by bytes only. `row_bytes` is an upper estimate (the heaviest fixture's factor times
|
|
64
|
+
the widest age's), and a row count derived from it made blocks of a few hundred real kilobytes once a fit had
|
|
65
|
+
widened a fixture: 23,000 parts in one load table, and the server delaying every insert for too many parts."""
|
|
66
|
+
if not row_bytes or row_bytes <= WIDE_ROW:
|
|
67
|
+
return {}
|
|
68
|
+
budget = max(int(insert_block_bytes or INSERT_BLOCK_BYTES), 1_000_000)
|
|
69
|
+
return {"max_block_size": int(max(16, min(65536, min(BLOCK_BYTES, budget) // row_bytes))),
|
|
70
|
+
"min_insert_block_size_rows": 0, "min_insert_block_size_bytes": budget}
|
|
71
|
+
FRAG = "codecop_frag" # the vocabulary's name inside an INSERT
|
|
72
|
+
FRAG_LENS = "codecop_frag_len" # the lengths of its phrases (filler exactly as long as the text)
|
|
73
|
+
_WORDS = ("the of and to in is that for it as with was on be by this are or from at an have not which you but they all were one can there "
|
|
74
|
+
"request response error message content result value status user tool call file path name type data text code function return "
|
|
75
|
+
"query table index model token input output system assistant session agent server client search update create delete list item "
|
|
76
|
+
"time config option default string number object array field key service account project document report summary analysis").split()
|
|
77
|
+
USER_AGENTS = ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",
|
|
78
|
+
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
|
|
79
|
+
"python-requests/2.32.3", "node-fetch/3.3.2", "Go-http-client/2.0", "curl/8.7.1")
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def fragments(count: int = 256, words: int = 4) -> list[str]:
|
|
83
|
+
"""A fixed vocabulary of short phrases. Deterministic: the same statement text on every run."""
|
|
84
|
+
out, x = [], 12345
|
|
85
|
+
for _ in range(count):
|
|
86
|
+
parts = []
|
|
87
|
+
for _ in range(words):
|
|
88
|
+
x = (x * 1103515245 + 12345) % 2147483648
|
|
89
|
+
parts.append(_WORDS[(x >> 8) % len(_WORDS)])
|
|
90
|
+
out.append(" ".join(parts))
|
|
91
|
+
return out
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
FRAGMENTS = fragments()
|
|
95
|
+
FRAG_LEN = sum(len(f) for f in FRAGMENTS) / len(FRAGMENTS)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class ProfileError(ValueError):
|
|
99
|
+
pass
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def base_type(ch_type: str) -> str:
|
|
103
|
+
"""Strip Nullable(...) and LowCardinality(...) wrappers."""
|
|
104
|
+
t = ch_type.strip()
|
|
105
|
+
while True:
|
|
106
|
+
m = re.match(r"^(Nullable|LowCardinality)\((.*)\)$", t, re.S)
|
|
107
|
+
if not m:
|
|
108
|
+
return t
|
|
109
|
+
t = m.group(2).strip()
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def quote(value) -> str:
|
|
113
|
+
return "'" + str(value).replace("\\", "\\\\").replace("'", "\\'") + "'"
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def ident(name: str) -> str:
|
|
117
|
+
"""A column or table name as ClickHouse reads a name, backquoted and escaped: a column called `hour`, `order`,
|
|
118
|
+
`key`, `my col` or `a.b` (a Nested column) is then a name and never a word of the statement."""
|
|
119
|
+
return "`" + str(name).replace("\\", "\\\\").replace("`", "\\`") + "`"
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def literal(value, ch_type: str) -> str:
|
|
123
|
+
bt = base_type(ch_type)
|
|
124
|
+
if value is None:
|
|
125
|
+
return "NULL"
|
|
126
|
+
if (INT_TYPE.match(bt) or bt.startswith(("Float", "Bool"))) and re.fullmatch(r"-?\d+(\.\d+)?|true|false", str(value), re.I):
|
|
127
|
+
return str(value)
|
|
128
|
+
if bt == "UUID" and not re.fullmatch(r"[0-9a-fA-F]{8}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{12}", str(value)):
|
|
129
|
+
# a value a statement compares a uuid column with that is not a uuid ('global'): the same uuid for the same text,
|
|
130
|
+
# instead of a load that fails on "Cannot parse uuid"
|
|
131
|
+
return f"reinterpretAsUUID(MD5({quote(value)}))"
|
|
132
|
+
return quote(value)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
class _Seeds:
|
|
136
|
+
"""Each random call needs its own argument, or ClickHouse folds identical calls into one value."""
|
|
137
|
+
|
|
138
|
+
def __init__(self, start: int):
|
|
139
|
+
self.n = start
|
|
140
|
+
|
|
141
|
+
def next(self) -> int:
|
|
142
|
+
self.n += 1
|
|
143
|
+
return self.n
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _index(spec: dict, seeds: _Seeds, distinct: int) -> str:
|
|
147
|
+
"""An integer in [0, distinct): uniform, or skewed so that low numbers are far more common."""
|
|
148
|
+
distinct = max(int(distinct), 1)
|
|
149
|
+
if spec.get("distribution", "uniform") == "skewed" and distinct > 1:
|
|
150
|
+
return f"toUInt64(least(floor(exp({_u(seeds.next())} * {math.log(distinct):.6f})) - 1, {distinct - 1}))"
|
|
151
|
+
return f"({_h(seeds.next())} % {distinct})"
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _h(seed: int) -> str:
|
|
155
|
+
"""A 64-bit integer that depends only on the row number and the seed: the same profile loads the same values on
|
|
156
|
+
every run, and one table's rows can be looked up from another's (relations)."""
|
|
157
|
+
return f"cityHash64(number, {seed})"
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _u(seed: int) -> str:
|
|
161
|
+
"""A float in [0, 1), from the row number and the seed."""
|
|
162
|
+
return f"(({_h(seed)} % 1000000007) / 1000000007)"
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _from_index(idx: str, ch_type: str, prefix: str, content: str = "") -> str:
|
|
166
|
+
"""`content` shapes a string identifier that has no prefix of its own: a uuid is 36 characters, a hash 64.
|
|
167
|
+
Both sides of a join get the same text as long as they state the same content."""
|
|
168
|
+
bt = base_type(ch_type)
|
|
169
|
+
if bt == "UUID":
|
|
170
|
+
return f"toUUID(concat('00000000-0000-4000-8000-', leftPad(toString({idx}), 12, '0')))"
|
|
171
|
+
if INT_TYPE.match(bt) or bt.startswith("Float"):
|
|
172
|
+
return idx
|
|
173
|
+
if content == "uuid":
|
|
174
|
+
return f"concat('00000000-0000-4000-8000-', leftPad(toString({idx}), 12, '0'))"
|
|
175
|
+
if content == "hash":
|
|
176
|
+
return f"lower(hex(SHA256(toString({idx}))))"
|
|
177
|
+
return f"concat({quote(prefix)}, toString({idx}))"
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _length(model: dict, seeds: _Seeds, scale: str = "") -> str:
|
|
181
|
+
"""A length in bytes per row: log-normal around the median, the tail cut at three standard deviations."""
|
|
182
|
+
if model["sigma"] <= 0:
|
|
183
|
+
base = f"{model['median']:.1f}"
|
|
184
|
+
else:
|
|
185
|
+
z = f"least(sqrt(-2 * log({_u(seeds.next())} + 1e-12)) * cos(6.283185307179586 * {_u(seeds.next())}), {sizes.Z_CAP})"
|
|
186
|
+
base = f"{model['median']:.2f} * exp({model['sigma']:.4f} * {z})"
|
|
187
|
+
if scale:
|
|
188
|
+
base = f"({base}) * {scale}"
|
|
189
|
+
return f"toUInt32(least(greatest(round({base}), 1), {sizes.MAX_VALUE_BYTES}))"
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _pick(h: str, shift: int) -> str:
|
|
193
|
+
return f"{FRAG}[1 + bitShiftRight({h}, {shift}) % {len(FRAGMENTS)}]"
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _plen(h: str, shift: int) -> str:
|
|
197
|
+
"""The length of the phrase _pick(h, shift) picks (the vocabulary's lengths, FRAG_LENS)."""
|
|
198
|
+
return f"{FRAG_LENS}[1 + bitShiftRight({h}, {shift}) % {len(FRAGMENTS)}]"
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
ROLES = ("user", "assistant", "tool", "system")
|
|
202
|
+
ROLE_OPEN, ROLE_CONTENT = '{"role":"', '","content":"'
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def shaped_text(content: str, length: str, median: float, seed: int, filler: bool = False) -> tuple[str, bool]:
|
|
206
|
+
"""(expression, uses the vocabulary) for a value of about `length` bytes that looks and compresses like `content`.
|
|
207
|
+
|
|
208
|
+
`filler`: a column no statement of the run reads (bench.ReadColumns): the value is one repeated character exactly as
|
|
209
|
+
long as the text below would be for this row (the same draws; the lengths of the phrases it would pick are added up
|
|
210
|
+
instead of the phrases being joined), so every row is as wide, byte for byte, and the granules are cut where they
|
|
211
|
+
would be. It costs nothing to compress. The short kinds (ids, addresses, hex) are cheap and kept as they are."""
|
|
212
|
+
# ClickHouse refuses repeat() past 1,000,000 times ("Too many times to repeat"): a row's filler is cut there
|
|
213
|
+
fill = f"repeat({quote(FILLER_CHAR)}, least(toUInt64({{n}}), 1000000))"
|
|
214
|
+
if content in sizes.INCOMPRESSIBLE:
|
|
215
|
+
return (fill.format(n=length) if filler else f"randomPrintableASCII({length})"), False
|
|
216
|
+
h = f"cityHash64(number, {seed})"
|
|
217
|
+
if content == "uuid":
|
|
218
|
+
return f"toString(reinterpretAsUUID(sipHash128(number, {seed})))", False
|
|
219
|
+
if content == "ip":
|
|
220
|
+
return f"IPv4NumToString(toUInt32({h} % 4294967295))", False
|
|
221
|
+
if content == "email":
|
|
222
|
+
return f"concat('user', toString({h} % 50000), '@', ['example.com', 'corp.example.org', 'mail.example.net'][1 + {h} % 3])", False
|
|
223
|
+
if content == "user_agent":
|
|
224
|
+
return f"[{', '.join(quote(u) for u in USER_AGENTS)}][1 + {h} % {len(USER_AGENTS)}]", False
|
|
225
|
+
if content == "url":
|
|
226
|
+
return (f"concat('https://', ['api', 'app', 'docs', 'cdn'][1 + {h} % 4], '.example.com/', replaceAll({_pick(h, 8)}, ' ', '/'), "
|
|
227
|
+
f"'/', toString({h} % 100000))"), True
|
|
228
|
+
if content == "path":
|
|
229
|
+
return f"concat('/', replaceAll({_pick(h, 8)}, ' ', '/'), '/', toString({h} % 1000), '.json')", True
|
|
230
|
+
if median < 24:
|
|
231
|
+
return f"substring(lower(hex(sipHash128(number, {seed}))), 1, {length})", False
|
|
232
|
+
if content in sizes.MESSAGES:
|
|
233
|
+
unit = 4 * (FRAG_LEN + 1) + 8 + 40
|
|
234
|
+
element = ("concat('{\"role\":\"', ['user', 'assistant', 'tool', 'system'][1 + x % 4], '\",\"content\":\"', "
|
|
235
|
+
f"{_pick('x', 2)}, ' ', {_pick('x', 10)}, ' ', {_pick('x', 18)}, ' ', {_pick('x', 26)}, ' ', "
|
|
236
|
+
"lower(hex(toUInt32(bitShiftRight(x, 32)))), '\"}')")
|
|
237
|
+
joined, opening, closing = "','", "'['", "']'"
|
|
238
|
+
size = (f"({len(ROLE_OPEN)} + [{', '.join(str(len(r)) for r in ROLES)}][1 + x % 4] + {len(ROLE_CONTENT)} + {_plen('x', 2)} + 1 + "
|
|
239
|
+
f"{_plen('x', 10)} + 1 + {_plen('x', 18)} + 1 + {_plen('x', 26)} + 1 + length(lower(hex(toUInt32(bitShiftRight(x, 32))))) + 2)")
|
|
240
|
+
elif content in sizes.JSONISH:
|
|
241
|
+
unit = 3 * (FRAG_LEN + 1) + 8 + 7
|
|
242
|
+
element = (f"concat('\"', {_pick('x', 0)}, '\":\"', {_pick('x', 8)}, ' ', {_pick('x', 16)}, ' ', "
|
|
243
|
+
"lower(hex(toUInt32(bitShiftRight(x, 32)))), '\"')")
|
|
244
|
+
joined, opening, closing = "','", "'{'", "'}'"
|
|
245
|
+
size = (f"(1 + {_plen('x', 0)} + 3 + {_plen('x', 8)} + 1 + {_plen('x', 16)} + 1 + "
|
|
246
|
+
"length(lower(hex(toUInt32(bitShiftRight(x, 32))))) + 1)")
|
|
247
|
+
else:
|
|
248
|
+
unit = 2 * (FRAG_LEN + 1) + 7
|
|
249
|
+
element = f"concat({_pick('x', 0)}, ' ', {_pick('x', 8)}, ' ', toString(bitShiftRight(x, 32) % 100000))"
|
|
250
|
+
joined, opening, closing = "'. '", "''", "''"
|
|
251
|
+
size = f"({_plen('x', 0)} + 1 + {_plen('x', 8)} + 1 + length(toString(bitShiftRight(x, 32) % 100000)))"
|
|
252
|
+
count = f"toUInt32(greatest(round({length} / {unit:.1f}), 1))"
|
|
253
|
+
if filler:
|
|
254
|
+
# the text's exact length: its elements' lengths (the same hashes pick the same phrases), the joiners, the brackets
|
|
255
|
+
n = (f"toUInt32(arraySum(arrayMap(x -> {size}, arrayMap(i -> cityHash64(number, {seed}, i), range({count})))) "
|
|
256
|
+
f"+ ({count} - 1) * {len(joined) - 2} + {len(opening) - 2 + len(closing) - 2})")
|
|
257
|
+
return fill.format(n=n), True
|
|
258
|
+
body = f"arrayStringConcat(arrayMap(x -> {element}, arrayMap(i -> cityHash64(number, {seed}, i), range({count}))), {joined})"
|
|
259
|
+
return (body if opening == "''" else f"concat({opening}, {body}, {closing})"), True
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
FILLER_CHAR = "x"
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def text_expr(col: dict, ch_type: str, seeds: _Seeds, realism: tuple = REALISM, scale: str = "", filler: bool = False) -> tuple[str, bool]:
|
|
266
|
+
"""The value of a `text` column and whether it needs the vocabulary.
|
|
267
|
+
|
|
268
|
+
`filler`: a column no statement of the run reads (bench.unread_columns). Its value has the length the profile gives
|
|
269
|
+
it, row by row (the same length draw, the same seeds), made of one repeated character: the row is as wide as with
|
|
270
|
+
real-looking text, so granules, parts and the bytes a statement reads are the same, and nothing is spent making and
|
|
271
|
+
compressing text no statement looks at. The seeds are drawn exactly as for real text, so every other column of the
|
|
272
|
+
row gets the value it would have had."""
|
|
273
|
+
bt = base_type(ch_type)
|
|
274
|
+
model = sizes.size_model(col) if "sizes" in realism else None
|
|
275
|
+
if model is None or "content" not in realism:
|
|
276
|
+
n = max(int(round(model["mean"])) if model else int(col.get("avg_len", 40)), 1)
|
|
277
|
+
fn = f"repeat({quote(FILLER_CHAR)}, " if filler else "randomPrintableASCII("
|
|
278
|
+
expr, vocab = (f"{fn}toUInt32(least(greatest(round({n} * {scale}), 1), 1000000)))" if scale else f"{fn}{min(n, 1000000)})"), False
|
|
279
|
+
else:
|
|
280
|
+
content = col.get("content") or "text"
|
|
281
|
+
if bt.startswith(("JSON", "Map(")):
|
|
282
|
+
content = "text" # a JSON column gets one key, below: generated keys would become hundreds of paths
|
|
283
|
+
expr, vocab = shaped_text(content, _length(model, seeds, scale), model["median"], seeds.next(), filler=filler)
|
|
284
|
+
return expr, vocab # column_expr turns it into an element of an Array, Map or JSON column (into_type)
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
TIME_SEED_BASE = 700_000
|
|
288
|
+
PERIOD_SECONDS = {"day": 86_400, "week": 7 * 86_400, "month": 30.44 * 86_400, "year": 365.25 * 86_400}
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def seconds_back(col: dict, seeds: _Seeds) -> str:
|
|
292
|
+
"""How far before now a `timestamp` row lies, in seconds: spread over `days_back` (evenly, or recent-heavy when
|
|
293
|
+
`skewed`), or, with `by_age` {unit, shares}, in the period k periods back with the share of rows the real table has
|
|
294
|
+
there (shares[k], newest first) and evenly within it."""
|
|
295
|
+
# `time_seed`: columns that hold the same moment (an event's time and the time it was indexed, filtered together by
|
|
296
|
+
# one statement) share their draws, so a row's two times agree; drawn independently, a window on both meets almost nothing
|
|
297
|
+
shared = TIME_SEED_BASE + zlib.crc32(str(col["time_seed"]).encode()) % 100_000 if col.get("time_seed") else None
|
|
298
|
+
|
|
299
|
+
def draw(k: int) -> str:
|
|
300
|
+
return _u(shared + k) if shared is not None else _u(seeds.next())
|
|
301
|
+
|
|
302
|
+
by_age = col.get("by_age") or {}
|
|
303
|
+
shares = [float(s) for s in by_age.get("shares") or []]
|
|
304
|
+
if shares and sum(shares) > 0 and by_age.get("unit") in PERIOD_SECONDS:
|
|
305
|
+
length = PERIOD_SECONDS[by_age["unit"]]
|
|
306
|
+
total, acc, arms = sum(shares), 0.0, []
|
|
307
|
+
pick = draw(0)
|
|
308
|
+
for k, s in enumerate(shares[:-1]):
|
|
309
|
+
acc += s / total
|
|
310
|
+
if s > 0:
|
|
311
|
+
arms.append(f"{pick} < {acc:.6f}, {k}")
|
|
312
|
+
period = f"multiIf({', '.join(arms)}, {len(shares) - 1})" if arms else str(len(shares) - 1)
|
|
313
|
+
return f"(({period}) + {draw(1)}) * {length:.0f}"
|
|
314
|
+
seconds = max(int(float(col.get("days_back", 30)) * 86400), 1)
|
|
315
|
+
u = draw(0)
|
|
316
|
+
if col.get("distribution") == "skewed":
|
|
317
|
+
u = f"pow({u}, 2)"
|
|
318
|
+
return f"{u} * {seconds}"
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def window_share(col: dict, hours: float) -> float | None:
|
|
322
|
+
"""The share of a `timestamp` column's generated rows that lie within the last `hours` before now (seconds_back), or
|
|
323
|
+
None for a column generated otherwise (an `expr`: only the server knows)."""
|
|
324
|
+
if col.get("kind") != "timestamp" or hours <= 0:
|
|
325
|
+
return None
|
|
326
|
+
by_age = col.get("by_age") or {}
|
|
327
|
+
shares = [float(s) for s in by_age.get("shares") or []]
|
|
328
|
+
if shares and sum(shares) > 0 and by_age.get("unit") in PERIOD_SECONDS:
|
|
329
|
+
length, total, left, out = PERIOD_SECONDS[by_age["unit"]] / 3600, sum(shares), float(hours), 0.0
|
|
330
|
+
for s in shares:
|
|
331
|
+
out += s / total * min(left / length, 1.0)
|
|
332
|
+
left -= length
|
|
333
|
+
if left <= 0:
|
|
334
|
+
break
|
|
335
|
+
return min(out, 1.0)
|
|
336
|
+
span = max(float(col.get("days_back", 30)) * 24, 1e-9)
|
|
337
|
+
f = min(hours / span, 1.0)
|
|
338
|
+
return min(f ** 0.5, 1.0) if col.get("distribution") == "skewed" else f
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def column_expr(col: dict, ch_type: str, seeds: _Seeds, realism: tuple = REALISM, scale: str = "", used: list | None = None,
|
|
342
|
+
filler: bool = False) -> str:
|
|
343
|
+
"""`scale`: an expression that multiplies a text column's length per row (a fixture's heavier rows).
|
|
344
|
+
`used`: gets "vocabulary" appended when the expression reads the phrase vocabulary."""
|
|
345
|
+
kind = col.get("kind", "")
|
|
346
|
+
bt = base_type(ch_type)
|
|
347
|
+
name = col.get("name", "?")
|
|
348
|
+
shape = col.get("content", "") if "content" in realism and "sizes" in realism and not col.get("prefix") else ""
|
|
349
|
+
# the scalar is generated for the type of one element (an Array's item, a Map's value) and into_type wraps it: an
|
|
350
|
+
# identifier `name_2` generated for a Map(String, UInt32) column was cast to UInt32 and failed the whole table
|
|
351
|
+
et = element_type(ch_type)
|
|
352
|
+
if re.match(r"\s*AggregateFunction\(", ch_type or ""):
|
|
353
|
+
# an aggregate's state is binary: text cast to it fails the whole table ("Cannot read all data"). Its empty
|
|
354
|
+
# state builds every row; the statements read the column through -Merge and still read every row.
|
|
355
|
+
return f"CAST(defaultValueOfTypeName({quote(ch_type)}) AS {ch_type})"
|
|
356
|
+
if kind == "unique":
|
|
357
|
+
expr = _from_index("number", et, col.get("prefix") or f"{name}_", shape)
|
|
358
|
+
elif kind == "key":
|
|
359
|
+
if not col.get("distinct"):
|
|
360
|
+
raise ProfileError(f"{name}: kind 'key' needs 'distinct'")
|
|
361
|
+
expr = _from_index(_index(col, seeds, col["distinct"]), et, col.get("prefix") or f"{name}_", shape)
|
|
362
|
+
elif kind == "categorical":
|
|
363
|
+
values = col.get("values") or []
|
|
364
|
+
if not values:
|
|
365
|
+
raise ProfileError(f"{name}: kind 'categorical' needs 'values'")
|
|
366
|
+
total = sum(float(v.get("weight", 1)) for v in values) or 1.0
|
|
367
|
+
r, acc, arms = _u(seeds.next()), 0.0, []
|
|
368
|
+
for v in values[:-1]:
|
|
369
|
+
acc += float(v.get("weight", 1)) / total
|
|
370
|
+
arms.append(f"{r} < {acc:.6f}, {value_expr(v['value'], ch_type)}")
|
|
371
|
+
last = value_expr(values[-1]["value"], ch_type)
|
|
372
|
+
expr = f"multiIf({', '.join(arms)}, {last})" if arms else last
|
|
373
|
+
elif kind in ("int", "float"):
|
|
374
|
+
lo, hi = float(col.get("min", 0)), float(col.get("max", 1000))
|
|
375
|
+
span = max(hi - lo, 1.0)
|
|
376
|
+
u = _u(seeds.next())
|
|
377
|
+
if col.get("distribution") == "skewed":
|
|
378
|
+
u = f"pow({u}, 4)"
|
|
379
|
+
expr = f"({lo} + {u} * {span})"
|
|
380
|
+
if kind == "int":
|
|
381
|
+
expr = f"toInt64(floor({expr}))"
|
|
382
|
+
elif kind == "timestamp":
|
|
383
|
+
ts = f"(now() - toIntervalSecond(toUInt32(floor({seconds_back(col, seeds)}))))"
|
|
384
|
+
epoch = col.get("epoch") or "s"
|
|
385
|
+
bt = base_type(et)
|
|
386
|
+
if bt.startswith("Float") or INT_TYPE.match(bt):
|
|
387
|
+
# the column stores a time as a number since the epoch: seconds, or the unit the statements read it in
|
|
388
|
+
expr = {"ms": f"toUnixTimestamp64Milli(toDateTime64({ts}, 3))", "us": f"toUnixTimestamp64Micro(toDateTime64({ts}, 6))",
|
|
389
|
+
"ns": f"toUnixTimestamp64Nano(toDateTime64({ts}, 9))"}.get(epoch, f"toUnixTimestamp({ts})")
|
|
390
|
+
elif bt.startswith("Date") and not bt.startswith("DateTime"):
|
|
391
|
+
expr = f"toDate({ts})"
|
|
392
|
+
else:
|
|
393
|
+
expr = ts
|
|
394
|
+
elif kind == "text":
|
|
395
|
+
expr, vocab = text_expr(col, ch_type, seeds, realism, scale, filler=filler)
|
|
396
|
+
if vocab and used is not None:
|
|
397
|
+
used.append("vocabulary")
|
|
398
|
+
elif kind == "constant":
|
|
399
|
+
expr = value_expr(col.get("value"), ch_type)
|
|
400
|
+
elif kind == "expr":
|
|
401
|
+
if not col.get("sql"):
|
|
402
|
+
raise ProfileError(f"{name}: kind 'expr' needs 'sql'")
|
|
403
|
+
expr = f"({col['sql']})"
|
|
404
|
+
else:
|
|
405
|
+
raise ProfileError(f"{name}: unknown generator kind '{kind}'")
|
|
406
|
+
if kind not in ("expr", "constant", "categorical"):
|
|
407
|
+
expr = into_type(expr, ch_type) # a scalar for an Array, Map or JSON column becomes one element of it
|
|
408
|
+
|
|
409
|
+
pinned = [p for p in (col.get("pinned") or []) if float(p.get("share", 0)) > 0]
|
|
410
|
+
if pinned:
|
|
411
|
+
r, acc, arms = _u(seeds.next()), 0.0, []
|
|
412
|
+
for p in pinned:
|
|
413
|
+
acc += float(p["share"])
|
|
414
|
+
arms.append(f"{r} < {acc:.6f}, CAST({value_expr(p['value'], ch_type)} AS {ch_type})")
|
|
415
|
+
expr = f"multiIf({', '.join(arms)}, CAST({expr} AS {ch_type}))"
|
|
416
|
+
nulls = float(col.get("null_fraction") or 0)
|
|
417
|
+
if nulls > 0 and ch_type.startswith(("Nullable", "LowCardinality(Nullable")):
|
|
418
|
+
expr = f"if({_u(seeds.next())} < {nulls:.6f}, NULL, {expr})"
|
|
419
|
+
return f"CAST({expr} AS {ch_type})"
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def _inner(ch_type: str) -> list[str]:
|
|
423
|
+
"""The type arguments of Array(T) or Map(K, V), split at the top-level commas."""
|
|
424
|
+
body = ch_type[ch_type.index("(") + 1:ch_type.rindex(")")]
|
|
425
|
+
parts, depth, cur = [], 0, ""
|
|
426
|
+
for ch in body:
|
|
427
|
+
depth += ch == "("
|
|
428
|
+
depth -= ch == ")"
|
|
429
|
+
if ch == "," and depth == 0:
|
|
430
|
+
parts.append(cur.strip())
|
|
431
|
+
cur = ""
|
|
432
|
+
else:
|
|
433
|
+
cur += ch
|
|
434
|
+
return parts + [cur.strip()]
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
def element_type(ch_type: str) -> str:
|
|
438
|
+
"""The type one generated scalar has inside a container column: an Array's item, a Map's value (nested containers
|
|
439
|
+
to their innermost scalar), else the column's own type."""
|
|
440
|
+
bt = base_type(ch_type)
|
|
441
|
+
if bt.startswith("Array("):
|
|
442
|
+
return element_type(_inner(bt)[0])
|
|
443
|
+
if bt.startswith("Map("):
|
|
444
|
+
return element_type(", ".join(_inner(bt)[1:]))
|
|
445
|
+
return ch_type
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
def into_type(expr: str, ch_type: str) -> str:
|
|
449
|
+
"""A generated scalar as a value of a container column: one element of an Array, one entry of a Map, one string
|
|
450
|
+
in a JSON object. CAST alone can not do it: `CAST('abc' AS Array(String))` is "Array does not start with '['"."""
|
|
451
|
+
bt = base_type(ch_type)
|
|
452
|
+
if bt.startswith("Array("):
|
|
453
|
+
return f"[{into_type(expr, _inner(bt)[0])}]"
|
|
454
|
+
if bt.startswith("Map("):
|
|
455
|
+
key, value = _inner(bt)[0], ", ".join(_inner(bt)[1:])
|
|
456
|
+
return f"map(CAST('v' AS {key}), CAST({into_type(expr, value)} AS {value}))"
|
|
457
|
+
if bt.startswith("JSON"):
|
|
458
|
+
return f"concat('{{\"v\":\"', replaceRegexpAll(toString({expr}), '[\"\\\\\\\\]', ' '), '\"}}')"
|
|
459
|
+
return expr
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
def value_expr(value, ch_type: str) -> str:
|
|
463
|
+
"""A profile value (a categorical or pinned value, a constant, a fixture value) as an expression of the column's type.
|
|
464
|
+
|
|
465
|
+
Profile values are text. For an Array or a Map column the text is read as the list or the object it spells
|
|
466
|
+
(JSON, or the single-quoted form ClickHouse prints) and written as a literal: `CAST('{...}' AS Map(String, String))`
|
|
467
|
+
is "Unsupported types to CAST AS Map". Text that spells neither becomes one element, or an empty Map."""
|
|
468
|
+
bt = base_type(ch_type)
|
|
469
|
+
if value is None or not bt.startswith(("Array(", "Map(")):
|
|
470
|
+
return literal(value, ch_type)
|
|
471
|
+
parsed = value if isinstance(value, (list, dict)) else _parse_container(str(value))
|
|
472
|
+
if bt.startswith("Array("):
|
|
473
|
+
inner = _inner(bt)[0]
|
|
474
|
+
items = parsed if isinstance(parsed, list) else ([] if str(value).strip() in ("", "[]") else [value])
|
|
475
|
+
return "[" + ", ".join(f"CAST({value_expr(x, inner)} AS {inner})" for x in items) + "]"
|
|
476
|
+
key, val = _inner(bt)[0], ", ".join(_inner(bt)[1:])
|
|
477
|
+
pairs = parsed.items() if isinstance(parsed, dict) else []
|
|
478
|
+
args = ", ".join(f"CAST({quote(k)} AS {key}), CAST({value_expr(v, val)} AS {val})" for k, v in pairs)
|
|
479
|
+
return f"CAST(map({args}) AS {bt})"
|
|
480
|
+
|
|
481
|
+
|
|
482
|
+
def _parse_container(text: str):
|
|
483
|
+
import ast
|
|
484
|
+
import json
|
|
485
|
+
for read in (json.loads, ast.literal_eval):
|
|
486
|
+
try:
|
|
487
|
+
got = read(text)
|
|
488
|
+
except (ValueError, SyntaxError, MemoryError, RecursionError):
|
|
489
|
+
continue
|
|
490
|
+
if isinstance(got, (list, dict)):
|
|
491
|
+
return got
|
|
492
|
+
return None
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
def place_fixtures(tables: list[dict]) -> dict[str, dict]:
|
|
496
|
+
"""Give every fixture id the same slice of row numbers in every table.
|
|
497
|
+
|
|
498
|
+
Returns id -> {start, width, offset, min_rows}: rows whose hash falls in [start, start + share)
|
|
499
|
+
carry the fixture, plus the `min_rows` rows from `offset`, so a combination exists even in a
|
|
500
|
+
small table. Because the slice depends only on the row number, a fixture's rows in one table
|
|
501
|
+
are the same row numbers as in another, and keys derived from `number` join."""
|
|
502
|
+
width: dict[str, float] = {}
|
|
503
|
+
least: dict[str, int] = {}
|
|
504
|
+
for t in tables:
|
|
505
|
+
for f in t.get("fixtures") or []:
|
|
506
|
+
fid = str(f.get("id") or "")
|
|
507
|
+
if not fid:
|
|
508
|
+
continue
|
|
509
|
+
width[fid] = max(width.get(fid, 0.0), min(max(float(f.get("share") or 0), 0.0), 0.5))
|
|
510
|
+
least[fid] = max(least.get(fid, 0), min(max(int(f.get("min_rows") or 1), 1), 10_000))
|
|
511
|
+
# Fixtures that share no table (directly or through another fixture) never meet on a row: each such group has the
|
|
512
|
+
# row numbers to itself. One space for all of them made forty statements on ten tables share 0.9 of every table.
|
|
513
|
+
parent: dict[str, str] = {}
|
|
514
|
+
|
|
515
|
+
def find(x: str) -> str:
|
|
516
|
+
while parent.setdefault(x, x) != x:
|
|
517
|
+
parent[x] = parent[parent[x]]
|
|
518
|
+
x = parent[x]
|
|
519
|
+
return x
|
|
520
|
+
|
|
521
|
+
for k, t in enumerate(tables):
|
|
522
|
+
ids = [str(f.get("id") or "") for f in t.get("fixtures") or [] if f.get("id")]
|
|
523
|
+
for fid in ids:
|
|
524
|
+
find(fid)
|
|
525
|
+
for fid in ids[1:]:
|
|
526
|
+
parent[find(fid)] = find(ids[0])
|
|
527
|
+
groups: dict[str, list[str]] = {}
|
|
528
|
+
for fid in sorted(width):
|
|
529
|
+
groups.setdefault(find(fid), []).append(fid)
|
|
530
|
+
out = {}
|
|
531
|
+
for members in groups.values():
|
|
532
|
+
# The slices of a group may hold 0.9 of the rows together. When its fixtures want more (many statements on one
|
|
533
|
+
# table, each with the rows of its tenant), the typical runs keep theirs first and the heavy runs (`~heavy`,
|
|
534
|
+
# production's 99th percentile) share what is left: a heavy run that wants half the table must not shrink every
|
|
535
|
+
# typical run's rows.
|
|
536
|
+
heavy = {f for f in members if f.endswith("~heavy")}
|
|
537
|
+
typical = sum(width[f] for f in members if f not in heavy)
|
|
538
|
+
rest = sum(width[f] for f in members if f in heavy)
|
|
539
|
+
if typical + rest <= 0.9:
|
|
540
|
+
scales = (1.0, 1.0)
|
|
541
|
+
elif typical <= 0.9:
|
|
542
|
+
scales = (1.0, (0.9 - typical) / rest if rest else 1.0)
|
|
543
|
+
else:
|
|
544
|
+
scales = (0.9 / typical, 0.0)
|
|
545
|
+
start, offset = 0.0, 0
|
|
546
|
+
for fid in members:
|
|
547
|
+
w = width[fid] * scales[fid in heavy]
|
|
548
|
+
out[fid] = {"start": start, "width": w, "offset": offset, "min_rows": least[fid]}
|
|
549
|
+
start += w
|
|
550
|
+
offset += least[fid]
|
|
551
|
+
return out
|
|
552
|
+
|
|
553
|
+
|
|
554
|
+
FIXTURE_SLOTS = 10_000_000
|
|
555
|
+
|
|
556
|
+
|
|
557
|
+
def _fixture_conditions(fixtures: list[dict], placed: dict[str, dict]) -> list[tuple[str, dict]]:
|
|
558
|
+
"""(condition, {column: value}) per fixture. The guaranteed rows are tested first, so they win over a hash slice."""
|
|
559
|
+
sure, sliced = [], []
|
|
560
|
+
for f in fixtures or []:
|
|
561
|
+
slot = placed.get(str(f.get("id") or ""))
|
|
562
|
+
values = {v["column"]: v["value"] for v in f.get("values") or [] if v.get("column")}
|
|
563
|
+
if not slot or not values:
|
|
564
|
+
continue
|
|
565
|
+
sure.append((f"(number >= {slot['offset']} AND number < {slot['offset'] + slot['min_rows']})", values))
|
|
566
|
+
share = min(max(float(f.get("share") or 0), 0.0), slot["width"])
|
|
567
|
+
a, b = int(slot["start"] * FIXTURE_SLOTS), int((slot["start"] + share) * FIXTURE_SLOTS)
|
|
568
|
+
if b > a:
|
|
569
|
+
sliced.append((f"(sipHash64(number) % {FIXTURE_SLOTS} >= {a} AND sipHash64(number) % {FIXTURE_SLOTS} < {b})", values))
|
|
570
|
+
return sure + sliced
|
|
571
|
+
|
|
572
|
+
|
|
573
|
+
def _size_scale(name: str, fixtures: list[dict], placed: dict[str, dict]) -> str:
|
|
574
|
+
"""An expression that is a fixture's size factor for this column on that fixture's rows and 1 elsewhere, or ""."""
|
|
575
|
+
arms = []
|
|
576
|
+
for f in fixtures or []:
|
|
577
|
+
factor = next((float(s.get("factor") or 0) for s in f.get("size_factors") or [] if s.get("column") == name), 0.0)
|
|
578
|
+
slot = placed.get(str(f.get("id") or ""))
|
|
579
|
+
if factor <= 0 or factor == 1 or not slot:
|
|
580
|
+
continue
|
|
581
|
+
share = min(max(float(f.get("share") or 0), 0.0), slot["width"])
|
|
582
|
+
a, b = int(slot["start"] * FIXTURE_SLOTS), int((slot["start"] + share) * FIXTURE_SLOTS)
|
|
583
|
+
cond = f"(number >= {slot['offset']} AND number < {slot['offset'] + slot['min_rows']})"
|
|
584
|
+
if b > a:
|
|
585
|
+
cond = f"({cond} OR (sipHash64(number) % {FIXTURE_SLOTS} >= {a} AND sipHash64(number) % {FIXTURE_SLOTS} < {b}))"
|
|
586
|
+
arms.append(f"{cond}, {factor:.4f}")
|
|
587
|
+
return f"multiIf({', '.join(arms)}, 1)" if arms else ""
|
|
588
|
+
|
|
589
|
+
|
|
590
|
+
def age_scale(col: dict, types: dict[str, str], generated: set[str]) -> str:
|
|
591
|
+
"""An expression that is the column's size factor for the age of the row (sizes.py, `width_by_age`), or "".
|
|
592
|
+
|
|
593
|
+
The age is read from the time column of the same generated row (its alias in the SELECT), in the partition's
|
|
594
|
+
periods before now, so the rows of the newest partitions get the real width of the newest partitions."""
|
|
595
|
+
factors = sizes.age_factors(col)
|
|
596
|
+
by_age = col.get("width_by_age") or {}
|
|
597
|
+
when = by_age.get("column")
|
|
598
|
+
if not factors or when not in types or when not in generated:
|
|
599
|
+
return ""
|
|
600
|
+
moment = f"toDateTime({ident(when)})" if base_type(types[when]).startswith("Date") else f"toDateTime(toInt64({ident(when)}))"
|
|
601
|
+
back = f"dateDiff('{by_age['unit']}', {moment}, now())"
|
|
602
|
+
arms = [f"{back} <= {int(up_to)}, {factor:.4f}" for up_to, factor in factors[:-1] if up_to is not None]
|
|
603
|
+
return f"multiIf({', '.join(arms)}, {factors[-1][1]:.4f})" if arms else ""
|
|
604
|
+
|
|
605
|
+
|
|
606
|
+
def _scale(col: dict, types: dict[str, str], generated: set[str], fixtures: list[dict], placed: dict[str, dict], realism: tuple) -> str:
|
|
607
|
+
"""Everything that multiplies a text column's size per row: a fixture's heavier rows, and the row's age."""
|
|
608
|
+
parts = [_size_scale(col["name"], fixtures, placed), age_scale(col, types, generated) if "sizes" in realism else ""]
|
|
609
|
+
parts = [p for p in parts if p]
|
|
610
|
+
return " * ".join(f"({p})" for p in parts) if len(parts) > 1 else "".join(parts)
|
|
611
|
+
|
|
612
|
+
|
|
613
|
+
def _enum_ok(value, ch_type: str) -> bool:
|
|
614
|
+
"""False for a value an Enum column does not list (ClickHouse refuses the whole load for it): that fixture arm is
|
|
615
|
+
left out and the table still builds."""
|
|
616
|
+
m = re.search(r"\bEnum(?:8|16)?\((.*)\)", ch_type or "")
|
|
617
|
+
if not m or value is None:
|
|
618
|
+
return True
|
|
619
|
+
labels = {x.replace("\\'", "'") for x in re.findall(r"'((?:[^'\\]|\\.)*)'\s*=", m.group(1))}
|
|
620
|
+
return not labels or str(value) in labels or (isinstance(value, int) and not isinstance(value, bool))
|
|
621
|
+
|
|
622
|
+
|
|
623
|
+
def _with_fixtures(expr: str, name: str, ch_type: str, conditions: list[tuple[str, dict]]) -> str:
|
|
624
|
+
arms = [f"{cond}, CAST({value_expr(values[name], ch_type)} AS {ch_type})" for cond, values in conditions
|
|
625
|
+
if name in values and _enum_ok(values[name], ch_type)]
|
|
626
|
+
return f"multiIf({', '.join(arms)}, {expr})" if arms else expr
|
|
627
|
+
|
|
628
|
+
|
|
629
|
+
def nested_groups(types: dict[str, str]) -> dict[str, list[str]]:
|
|
630
|
+
"""The Nested structures of a table: structure name -> its array columns, in table order.
|
|
631
|
+
|
|
632
|
+
ClickHouse stores `n Nested(a T, b U)` as the columns `n.a Array(T)` and `n.b Array(U)`, and refuses a row whose
|
|
633
|
+
arrays differ in length ("Elements 'n.a' and 'n.b' of Nested data structure 'n' (Array columns) have different array
|
|
634
|
+
sizes"). Two or more Array columns that share the part of their name before the first dot are taken as one."""
|
|
635
|
+
out: dict[str, list[str]] = {}
|
|
636
|
+
for name, t in types.items():
|
|
637
|
+
if "." in name and base_type(t).startswith("Array("):
|
|
638
|
+
out.setdefault(name.split(".", 1)[0], []).append(name)
|
|
639
|
+
return {k: v for k, v in out.items() if len(v) > 1}
|
|
640
|
+
|
|
641
|
+
|
|
642
|
+
def insert_statements(table: str, rows: int, columns: list[dict], types: dict[str, str], batches: int = 4,
|
|
643
|
+
max_batch: int = 5_000_000, fixtures: list[dict] | None = None,
|
|
644
|
+
placed: dict[str, dict] | None = None, realism: tuple = REALISM,
|
|
645
|
+
relations: list[dict] | None = None, insert_block_bytes: int = INSERT_BLOCK_BYTES,
|
|
646
|
+
filler: set[str] | None = None) -> list[str]:
|
|
647
|
+
"""INSERT statements that load `rows` rows in several batches, so the table has several parts.
|
|
648
|
+
|
|
649
|
+
`relations`: this table's relations, resolved against the loaded parents (see _relation_layer).
|
|
650
|
+
`insert_block_bytes`: what one inserted block may hold for wide rows (block_settings)."""
|
|
651
|
+
known = [c for c in columns if c["name"] in types]
|
|
652
|
+
if not known:
|
|
653
|
+
raise ProfileError(f"{table}: none of the profiled columns exist in the table")
|
|
654
|
+
conditions = _fixture_conditions(fixtures or [], placed or {})
|
|
655
|
+
named = {c["name"] for c in known}
|
|
656
|
+
extra = sorted({n for _, values in conditions for n in values if n in types and n not in named})
|
|
657
|
+
profiled = named | set(extra)
|
|
658
|
+
relations = [{**r, "always": r["column"] not in profiled} for r in relations or []
|
|
659
|
+
if r["column"] in types and all(c in types for c, _ in r.get("same") or [])]
|
|
660
|
+
# a relation's columns are written even when nobody described them: they take the parent's values
|
|
661
|
+
extra += sorted({n for r in relations for n in [r["column"]] + [c for c, _ in r.get("same") or []] if n not in profiled})
|
|
662
|
+
# the arrays of one Nested structure must have one length per row: every member of a structure one of them is
|
|
663
|
+
# written for is written, each resized to the length of the first one written (nested_groups)
|
|
664
|
+
groups = nested_groups(types)
|
|
665
|
+
written = [c["name"] for c in known] + extra
|
|
666
|
+
leaders: dict[str, str] = {}
|
|
667
|
+
for members in groups.values():
|
|
668
|
+
present = [n for n in written if n in members]
|
|
669
|
+
if not present:
|
|
670
|
+
continue
|
|
671
|
+
for n in members:
|
|
672
|
+
if n != present[0]:
|
|
673
|
+
leaders[n] = present[0]
|
|
674
|
+
extra += [n for n in members if n not in written]
|
|
675
|
+
batches = max(batches, math.ceil(rows / max_batch), 1)
|
|
676
|
+
size = math.ceil(rows / batches)
|
|
677
|
+
# Wide rows are generated in small blocks: a default block of 65,536 rows of 40 kB each is 2.6 GB in one allocation.
|
|
678
|
+
row_bytes = sum((sizes.mean_bytes(c) or 0) for c in known if c.get("kind") == "text") if "sizes" in realism else 0
|
|
679
|
+
heaviest = max((float(s.get("factor") or 1) for f in fixtures or [] for s in f.get("size_factors") or []), default=1.0)
|
|
680
|
+
row_bytes *= max(heaviest, 1.0)
|
|
681
|
+
# the time columns this INSERT writes: a text column whose size follows the row's age reads its age from one of them
|
|
682
|
+
# (an `expr` column of a date type is a time too: the profile often writes the partition's time column as an expression)
|
|
683
|
+
timed = {c["name"] for c in known if c.get("kind") == "timestamp" or (c.get("kind") == "expr" and base_type(types[c["name"]]).startswith("Date"))}
|
|
684
|
+
if "sizes" in realism:
|
|
685
|
+
row_bytes *= max((f for c in known if c.get("kind") == "text" for _, f in sizes.age_factors(c)), default=1.0)
|
|
686
|
+
sized = block_settings(row_bytes, insert_block_bytes)
|
|
687
|
+
block = (" SETTINGS " + ", ".join(f"{k} = {v}" for k, v in sized.items())) if sized else ""
|
|
688
|
+
out, offset = [], 0
|
|
689
|
+
while offset < rows:
|
|
690
|
+
n = min(size, rows - offset)
|
|
691
|
+
seeds = _Seeds(1000) # the same seeds in every batch: a value depends on the row number, not on the batch
|
|
692
|
+
used: list = []
|
|
693
|
+
values = {c["name"]: _with_fixtures(column_expr(c, types[c["name"]], seeds, realism, _scale(c, types, timed, fixtures or [], placed or {}, realism), used,
|
|
694
|
+
filler=c["name"] in (filler or ())),
|
|
695
|
+
c["name"], types[c["name"]], conditions) for c in known}
|
|
696
|
+
# a fixture column the profile did not describe still has to be written
|
|
697
|
+
values.update({x: _with_fixtures("defaultValueOfTypeName(" + quote(types[x]) + ")", x, types[x], conditions) for x in extra})
|
|
698
|
+
for member, leader in leaders.items():
|
|
699
|
+
# the alias of the structure's first array, read in the same SELECT: one length for every array of the row
|
|
700
|
+
values[member] = f"CAST(arrayResize({values[member]}, length({ident(leader)})) AS {types[member]})"
|
|
701
|
+
names = [c["name"] for c in known] + extra
|
|
702
|
+
exprs = [f"{values[x]} AS {ident(x)}" for x in names]
|
|
703
|
+
cols = ", ".join(ident(x) for x in names)
|
|
704
|
+
vocabulary = (f"WITH [{', '.join(quote(f) for f in FRAGMENTS)}] AS {FRAG}, [{', '.join(str(len(f.encode())) for f in FRAGMENTS)}] "
|
|
705
|
+
f"AS {FRAG_LENS} ") if used else ""
|
|
706
|
+
if not relations:
|
|
707
|
+
out.append(f"INSERT INTO {ident(table)} ({cols}) {vocabulary}SELECT {', '.join(exprs)} FROM numbers({offset}, {n}){block}")
|
|
708
|
+
else:
|
|
709
|
+
rows_sql = f"{vocabulary}SELECT number, {', '.join(exprs)} FROM numbers({offset}, {n})"
|
|
710
|
+
for i, rel in enumerate(relations):
|
|
711
|
+
rows_sql = _relation_layer(rows_sql, names, types, rel, RELATION_SEED + i, i)
|
|
712
|
+
out.append(f"INSERT INTO {ident(table)} ({cols}) SELECT {cols} FROM ({rows_sql}){block}")
|
|
713
|
+
offset += n
|
|
714
|
+
return out
|
|
715
|
+
|
|
716
|
+
|
|
717
|
+
RELATION_SEED = 9100
|
|
718
|
+
|
|
719
|
+
|
|
720
|
+
def as_text(expr: str) -> str:
|
|
721
|
+
"""Any scalar as a String key, NULL as '': what the relation lookup tables are keyed by."""
|
|
722
|
+
return f"ifNull(CAST({expr} AS Nullable(String)), '')"
|
|
723
|
+
|
|
724
|
+
|
|
725
|
+
def _relation_layer(inner: str, names: list[str], types: dict[str, str], rel: dict, seed: int, n: int) -> str:
|
|
726
|
+
"""One relation applied to the rows of `inner` (relations.py says what is kept and what is chosen).
|
|
727
|
+
|
|
728
|
+
`rel`: {column, group, same: [(child column, lookup column)], tables: {k, a, g, n}, total, skewed, always}. The four
|
|
729
|
+
are Join-engine tables of the parent's keys as text: `k` key -> (one, x, d1..), `a` row number -> key,
|
|
730
|
+
`g` (x, row number within x) -> key, `n` x -> how many keys. `x` is the first shared column."""
|
|
731
|
+
fk, group, t = rel["column"], rel.get("group"), rel["tables"]
|
|
732
|
+
qk, qx, qh = f"codecop_k{n}", f"codecop_x{n}", f"codecop_h{n}"
|
|
733
|
+
|
|
734
|
+
def ordinal(count: str) -> str:
|
|
735
|
+
if not rel.get("skewed"):
|
|
736
|
+
return f"({qh} % {count})"
|
|
737
|
+
u = f"(({qh} % 1000000007) / 1000000007)"
|
|
738
|
+
# both arguments Float64: `count() AS n` of a Join table is UInt64, and `n - 1` is Int64, which least() refuses beside
|
|
739
|
+
# a Float64 ("Illegal types Float64 and Int64 of arguments of function least" on a Join table)
|
|
740
|
+
return f"toUInt64(greatest(least(floor(exp({u} * log(toFloat64({count})))) - 1, toFloat64({count}) - 1), 0))"
|
|
741
|
+
|
|
742
|
+
known = f"joinGet('{t['k']}', 'one', {qk}) = 1"
|
|
743
|
+
any_ = f"joinGet('{t['a']}', 'k', {ordinal(f'toUInt64({int(rel['total'])})')})"
|
|
744
|
+
if group:
|
|
745
|
+
count = f"joinGet('{t['n']}', 'n', {qx})"
|
|
746
|
+
key = (f"multiIf({known} AND joinGet('{t['k']}', 'x', {qk}) = {qx}, {qk}, {count} > 0, "
|
|
747
|
+
f"joinGet('{t['g']}', 'k', {qx}, {ordinal(f'greatest({count}, 1)')}), {known}, {qk}, {any_})")
|
|
748
|
+
else:
|
|
749
|
+
key = f"if({known}, {qk}, {any_})"
|
|
750
|
+
chosen = f"codecop_c{n}"
|
|
751
|
+
|
|
752
|
+
def kept(name: str, value: str) -> str:
|
|
753
|
+
"""NULL keys stay NULL and keep their own shared values, unless the key was never generated (`always`)."""
|
|
754
|
+
typed = f"CAST({value} AS {types[name]})"
|
|
755
|
+
return typed if rel.get("always") else f"if(isNull({ident(fk)}), {ident(name)}, {typed})"
|
|
756
|
+
|
|
757
|
+
replaced = {fk: kept(fk, chosen)}
|
|
758
|
+
for child, lookup in rel.get("same") or []:
|
|
759
|
+
replaced[child] = kept(child, f"joinGet('{t['k']}', '{lookup}', {chosen})")
|
|
760
|
+
select = ", ".join(f"{replaced[c]} AS {ident(c)}" if c in replaced else ident(c) for c in names)
|
|
761
|
+
aliases = f"{as_text(ident(fk))} AS {qk}, cityHash64(number, {seed}) AS {qh}" + (f", {as_text(ident(group))} AS {qx}" if group else "")
|
|
762
|
+
# three levels: the row with its lookup keys, the parent chosen for it, the columns that follow the parent.
|
|
763
|
+
# The inner columns are renamed on the way out, so an alias never shadows the column it is computed from.
|
|
764
|
+
renamed = ", ".join(f"{ident(c)} AS {ident(c)}" for c in names)
|
|
765
|
+
return (f"SELECT number, {select} FROM (SELECT number, {renamed}, {key} AS {chosen} FROM "
|
|
766
|
+
f"(SELECT number, {renamed}, {aliases} FROM ({inner})))")
|