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/fidelity.py
ADDED
|
@@ -0,0 +1,671 @@
|
|
|
1
|
+
"""Does the sandbox read what production reads? The check, the grade, and the correction.
|
|
2
|
+
|
|
3
|
+
When a real workload was pulled, each matched query is known per run: rows read, bytes read, rows returned. After the
|
|
4
|
+
sandbox is loaded the same baseline is measured there and the three are compared:
|
|
5
|
+
|
|
6
|
+
close every ratio within x1.5
|
|
7
|
+
near every ratio within x3
|
|
8
|
+
off anything further
|
|
9
|
+
unchecked nothing to compare with (no real workload for this query)
|
|
10
|
+
|
|
11
|
+
A table is graded the same way against the real catalog: uncompressed bytes per row and the compression ratio.
|
|
12
|
+
|
|
13
|
+
The correction (`corrections`) changes only what the query log can teach and the catalog can not:
|
|
14
|
+
- which parameter values a query runs with: two queries that share values (the same tenant) but return very
|
|
15
|
+
different numbers of rows in production can not both be right on one tenant, so the lighter reader gets parameter
|
|
16
|
+
values of its own (`param_overrides` in the profile) and a fixture of its own;
|
|
17
|
+
- how many rows carry the query's parameter values (a fixture's share and the column's pinned share), from rows returned;
|
|
18
|
+
- how heavy those rows are compared with the table's average (a fixture's size factor on the heaviest column the
|
|
19
|
+
query reads), from bytes read per row read. A table average can not carry this: the rows one tenant owns are
|
|
20
|
+
often several times the average.
|
|
21
|
+
Rows read is not corrected directly. It follows from row width (granules), parts and the two above.
|
|
22
|
+
|
|
23
|
+
A share is only ever lowered below what the profile estimated, never raised above it. The sandbox table is smaller
|
|
24
|
+
than the real one, so returning as many rows as production does can need a tenant that owns half the table; a fix
|
|
25
|
+
that filters on the tenant then saves nothing there, and a verdict would change for a reason that is only scale.
|
|
26
|
+
A baseline that production reads more rows for than the sandbox tables hold is marked `scale_bound` instead.
|
|
27
|
+
|
|
28
|
+
Which production run is the target. The query log's sums give a mean per run, and a mean describes no run when most runs
|
|
29
|
+
are light and a few are heavy. When the pull has the spread per shape (median, 90th and 99th percentile of rows read,
|
|
30
|
+
bytes read and rows returned), the baseline is graded against the median run, the fit targets the median, and a second
|
|
31
|
+
run is built for the 99th percentile: the same query with other parameter values, on rows of their own (a fixture
|
|
32
|
+
`<finding>~heavy`), measured and graded on its own (`heavy`). Without the spread everything is against the mean, as
|
|
33
|
+
before, and the record says which it was (`graded_against`).
|
|
34
|
+
|
|
35
|
+
A target of zero. Most runs of a query often return nothing (a tenant with no activity in the bucket) and some read
|
|
36
|
+
nothing at all. A ratio to zero is infinite and says nothing, so a measure whose target is zero is not a ratio: it is
|
|
37
|
+
reported beside the ratios (`zero_targets`: production 0, what the sandbox did) and the grade is that of the other
|
|
38
|
+
measures. When every target is zero, the grade says whether the sandbox also read and returned nothing. The fit has a
|
|
39
|
+
lever for it (`empty_runs`): the typical run is given parameter values no row holds, so it reads what the key lookup
|
|
40
|
+
of a missing value reads (one granule per part, or nothing when the value sorts past every value of a key's first
|
|
41
|
+
column) and returns nothing, as production's typical run does. The variants are then also measured on the heavy run,
|
|
42
|
+
which returns rows, and their sameness is shown there (bench.combined_verdict).
|
|
43
|
+
|
|
44
|
+
Parts and marks selected. The pull gives, per shape, production's average SelectedParts and SelectedMarks per run. They
|
|
45
|
+
are two more graded measures (`selected_parts`, `selected_marks` in `ratios`, the same x1.5 / x3 bands), because rows read
|
|
46
|
+
can match for the wrong reason (eleven parts of a few rows each against production's one part of many) and a variant's
|
|
47
|
+
gain depends on how many parts and granules the baseline touched. They are graded only for the typical run and only
|
|
48
|
+
when the average describes it (`selected_target`: the mean rows read per run within x3 of the median's); otherwise the
|
|
49
|
+
average is the heavy runs' and it is reported beside the run (`selected.graded` false, `selected.not_graded` why). A
|
|
50
|
+
target of zero is a zero target as for the reads. The heavy run is never graded on them: its target is a percentile and
|
|
51
|
+
production gives no percentile of parts. The fit has a lever for parts (`part_corrections`, parts.py): the shape of a
|
|
52
|
+
table's time-ranged parts.
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
from __future__ import annotations
|
|
56
|
+
|
|
57
|
+
import copy
|
|
58
|
+
import hashlib
|
|
59
|
+
import re
|
|
60
|
+
|
|
61
|
+
from . import sizes
|
|
62
|
+
|
|
63
|
+
CLOSE, NEAR = 1.5, 3.0
|
|
64
|
+
SCALE_BOUND = 0.5 # production rows read per run over the sandbox table's rows, from which the scale explains the gap
|
|
65
|
+
SPREAD_WARNING = 10.0 # production's heaviest run over its mean run, from which the mean stops describing a run
|
|
66
|
+
GRADES = ("close", "near", "off", "unchecked")
|
|
67
|
+
METRICS = (("rows_read", "read_rows", "rows_read_per_run"), ("bytes_read", "read_bytes", "bytes_read_per_run"),
|
|
68
|
+
("rows_returned", "result_rows", "rows_returned_per_run"))
|
|
69
|
+
MIN_SHARE, MAX_SHARE = 1e-7, 0.5
|
|
70
|
+
MIN_FACTOR, MAX_FACTOR = 0.1, 10.0
|
|
71
|
+
SIZE_NEEDS_ROWS_WITHIN = 2.0
|
|
72
|
+
SPLIT_AT = 3.0 # two candidates on one fixture whose wanted row counts differ by more than this get separate values
|
|
73
|
+
UUID = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", re.I)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def ratio(sandbox, production) -> float | None:
|
|
77
|
+
"""sandbox / production. Small counts are compared with one added to each: 1 row against 2 is not "twice"."""
|
|
78
|
+
if production is None or sandbox is None:
|
|
79
|
+
return None
|
|
80
|
+
s, p = float(sandbox), float(production)
|
|
81
|
+
if p < 20 and s < 20:
|
|
82
|
+
s, p = s + 1, p + 1
|
|
83
|
+
if p <= 0 or s <= 0:
|
|
84
|
+
return None if p <= 0 and s <= 0 else (0.0 if s <= 0 else float("inf"))
|
|
85
|
+
return round(s / p, 4)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def spread(r: float | None) -> float:
|
|
89
|
+
"""How far a ratio is from 1, as a factor >= 1."""
|
|
90
|
+
if r is None:
|
|
91
|
+
return 1.0
|
|
92
|
+
if r <= 0 or r == float("inf"):
|
|
93
|
+
return float("inf")
|
|
94
|
+
return max(r, 1 / r)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def grade(ratios: list[float | None]) -> str:
|
|
98
|
+
known = [r for r in ratios if r is not None]
|
|
99
|
+
if not known:
|
|
100
|
+
return "unchecked"
|
|
101
|
+
worst = max(spread(r) for r in known)
|
|
102
|
+
return "close" if worst <= CLOSE else "near" if worst <= NEAR else "off"
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def grade_with_zeros(ratios: dict[str, float | None], zero: dict[str, dict]) -> str:
|
|
106
|
+
"""The grade of the measures with a target above zero. When every target is zero (production's typical run reads
|
|
107
|
+
and returns nothing), whether the sandbox did nothing too: close when it did, off when it read or returned anything."""
|
|
108
|
+
if any(r is not None for r in ratios.values()) or not zero:
|
|
109
|
+
return grade(list(ratios.values()))
|
|
110
|
+
return "close" if all(not (z.get("sandbox") or 0) for z in zero.values()) else "off"
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
HEAVY = "~heavy" # the finding id of a query's heavy run: "Q-001~heavy"
|
|
114
|
+
QUANTILES = ("median", "p90", "p99")
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def quantiles(production: dict | None, at: int) -> dict | None:
|
|
118
|
+
"""One quantile of production's runs as a per-run target ({rows_read_per_run, ...}), or None without the spread.
|
|
119
|
+
`at`: 0 the median, 1 the 90th percentile, 2 the 99th."""
|
|
120
|
+
sp = (production or {}).get("spread")
|
|
121
|
+
if not isinstance(sp, dict) or not all(isinstance(sp.get(name), list) and len(sp[name]) == 3 for name, _, _ in METRICS):
|
|
122
|
+
return None
|
|
123
|
+
return {theirs: sp[name][at] for name, _, theirs in METRICS}
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def target(production: dict) -> dict:
|
|
127
|
+
"""What one sandbox run is compared with: production's median run when the pull has the spread, else its mean run.
|
|
128
|
+
{rows_read_per_run, bytes_read_per_run, rows_returned_per_run, basis}. An entry that already is a quantile (a heavy
|
|
129
|
+
run's) says so in `basis` and is taken as it is."""
|
|
130
|
+
median = quantiles(production, 0)
|
|
131
|
+
if median:
|
|
132
|
+
return {**median, "basis": "median"}
|
|
133
|
+
return {**{theirs: production.get(theirs) for _, _, theirs in METRICS}, "basis": production.get("basis") or "mean"}
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
SELECTED = (("selected_parts", "selected_parts", "selected_parts_per_run"), ("selected_marks", "selected_marks", "selected_marks_per_run"))
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def selected_target(production: dict) -> tuple[dict | None, str]:
|
|
140
|
+
"""Production's average parts and marks selected per run as the typical run's target, or (None, why not).
|
|
141
|
+
|
|
142
|
+
The pull gives an average over all runs, not a median. It stands for the typical run when the runs read alike:
|
|
143
|
+
the mean rows read per run within x SPLIT_AT of the median run's. When a few heavy runs pull the mean far above the
|
|
144
|
+
median (a query whose typical run reads 16 rows and whose 99th percentile reads millions), the average marks are
|
|
145
|
+
the heavy runs' and grading the typical run against them would chase the wrong run: then reported, not graded."""
|
|
146
|
+
if production.get("selected_parts_per_run") is None:
|
|
147
|
+
return None, "the pull has no parts selected per run for this query"
|
|
148
|
+
median = quantiles(production, 0)
|
|
149
|
+
if median:
|
|
150
|
+
apart = spread(ratio(production.get("rows_read_per_run"), median.get("rows_read_per_run")))
|
|
151
|
+
if apart > SPLIT_AT:
|
|
152
|
+
return None, (f"production's mean run reads {'far more than' if apart == float('inf') else f'x{apart:.0f}'} the rows of its median run: "
|
|
153
|
+
"the average parts and marks per run are the heavy runs', not the typical run's")
|
|
154
|
+
return {"selected_parts_per_run": production.get("selected_parts_per_run"),
|
|
155
|
+
"selected_marks_per_run": production.get("selected_marks_per_run")}, ""
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def check(measurement: dict, production: dict | None, table_rows: int = 0) -> dict:
|
|
159
|
+
"""The fidelity record of one baseline: production per run, the sandbox/production ratios and the grade.
|
|
160
|
+
`table_rows`: rows in the largest sandbox table the query reads, to say when the scale alone explains a gap.
|
|
161
|
+
|
|
162
|
+
Graded against production's median run when the spread is known (`graded_against`: median), else against the mean.
|
|
163
|
+
`production` is always the mean per run; `production_typical` the median the grade used; `ratios_to_mean` the same
|
|
164
|
+
comparison against the mean, for reading beside pulls that had no spread."""
|
|
165
|
+
if not production or not measurement or not measurement.get("ok"):
|
|
166
|
+
return {"grade": "unchecked", "ratios": {}, "production": None}
|
|
167
|
+
aim = target(production)
|
|
168
|
+
ratios, zero = {}, {}
|
|
169
|
+
for name, ours, theirs in METRICS:
|
|
170
|
+
want = aim.get(theirs)
|
|
171
|
+
if want is not None and float(want) <= 0:
|
|
172
|
+
# a ratio to zero is infinite: reported as what the sandbox did, not graded (see the module's docstring)
|
|
173
|
+
ratios[name] = None
|
|
174
|
+
zero[name] = {"production": 0, "sandbox": measurement.get(ours)}
|
|
175
|
+
else:
|
|
176
|
+
ratios[name] = ratio(measurement.get(ours), want)
|
|
177
|
+
out = {"grade": grade_with_zeros(ratios, zero), "ratios": ratios, "graded_against": aim["basis"],
|
|
178
|
+
"production": {theirs: production.get(theirs) for _, _, theirs in METRICS}}
|
|
179
|
+
if zero:
|
|
180
|
+
out["zero_targets"] = zero
|
|
181
|
+
if aim["basis"] == "median":
|
|
182
|
+
out["production_typical"] = {theirs: aim[theirs] for _, _, theirs in METRICS}
|
|
183
|
+
out["production_heavy"] = quantiles(production, 2)
|
|
184
|
+
out["ratios_to_mean"] = {name: ratio(measurement.get(ours), production.get(theirs)) for name, ours, theirs in METRICS}
|
|
185
|
+
sp = production["spread"]
|
|
186
|
+
out["spread"] = {**{name: list(sp[name]) for name, _, _ in METRICS}, "method": sp.get("method", ""),
|
|
187
|
+
**({"of_executions": sp["of_executions"]} if sp.get("of_executions") is not None else {})}
|
|
188
|
+
for key in ("no_result_share", "no_read_share"):
|
|
189
|
+
if production.get(key) is not None:
|
|
190
|
+
out[key] = production[key]
|
|
191
|
+
if production.get("selected_parts_per_run") is not None and measurement.get("selected_parts") is not None:
|
|
192
|
+
# parts and marks the run selected against production's average per run: graded beside the three reads when that
|
|
193
|
+
# average describes the typical run (selected_target), else reported only
|
|
194
|
+
mine = {"parts": measurement.get("selected_parts"), "marks": measurement.get("selected_marks")}
|
|
195
|
+
theirs_ = {"parts": production.get("selected_parts_per_run"), "marks": production.get("selected_marks_per_run")}
|
|
196
|
+
aim_sel, why = selected_target(production)
|
|
197
|
+
out["selected"] = {"sandbox": mine, "production": theirs_, "ratios": {k: ratio(mine[k], theirs_[k]) for k in ("parts", "marks")},
|
|
198
|
+
"graded": aim_sel is not None, **({"not_graded": why} if why else {})}
|
|
199
|
+
if aim_sel is not None:
|
|
200
|
+
for name, ours, theirs in SELECTED:
|
|
201
|
+
want = aim_sel.get(theirs)
|
|
202
|
+
if want is None or measurement.get(ours) is None:
|
|
203
|
+
continue
|
|
204
|
+
if float(want) <= 0:
|
|
205
|
+
ratios[name] = None
|
|
206
|
+
zero[name] = {"production": 0, "sandbox": measurement.get(ours)}
|
|
207
|
+
else:
|
|
208
|
+
ratios[name] = ratio(measurement.get(ours), want)
|
|
209
|
+
out["grade"] = grade_with_zeros(ratios, zero)
|
|
210
|
+
if zero:
|
|
211
|
+
out["zero_targets"] = zero
|
|
212
|
+
if table_rows and (aim.get("rows_read_per_run") or 0) > table_rows * SCALE_BOUND:
|
|
213
|
+
# production reads about as many rows per run as the sandbox's largest table holds: rows read can not match here
|
|
214
|
+
out["scale_bound"] = True
|
|
215
|
+
top, mean = production.get("max_bytes_read_per_run"), production.get("bytes_read_per_run")
|
|
216
|
+
if top and mean:
|
|
217
|
+
# The log gives a mean per run. When one run read many times the mean, the mean mixes light and heavy runs
|
|
218
|
+
# (a query that often finds nothing and sometimes scans a table), and one sandbox run can match only one kind.
|
|
219
|
+
out["production_spread"] = round(top / mean, 1)
|
|
220
|
+
out["mean_hides_spread"] = top / mean >= SPREAD_WARNING
|
|
221
|
+
return out
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def check_table(stats: dict, real: dict | None) -> dict:
|
|
225
|
+
"""A loaded table against the real one: uncompressed bytes per row and compression ratio."""
|
|
226
|
+
if not real or not stats.get("rows") or (real.get("rows") or 0) < 1000 or not real.get("uncompressed_bytes"):
|
|
227
|
+
return {"grade": "unchecked", "ratios": {}}
|
|
228
|
+
ours_row = stats.get("uncompressed", 0) / stats["rows"]
|
|
229
|
+
real_row = real["uncompressed_bytes"] / real["rows"]
|
|
230
|
+
ratios = {"row_bytes": ratio(ours_row, real_row)}
|
|
231
|
+
if real.get("bytes_on_disk") and stats.get("bytes_on_disk"):
|
|
232
|
+
ratios["compression"] = ratio(stats.get("uncompressed", 0) / stats["bytes_on_disk"], real["uncompressed_bytes"] / real["bytes_on_disk"])
|
|
233
|
+
return {"grade": grade(list(ratios.values())), "ratios": ratios,
|
|
234
|
+
"row_bytes": round(ours_row, 1), "real_row_bytes": round(real_row, 1)}
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def _fixture_ids(fixture_id: str) -> list[str]:
|
|
238
|
+
return [p.strip() for p in str(fixture_id or "").split("+") if p.strip()]
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def heaviest_column(cand: dict, profile: dict) -> tuple[str, str] | None:
|
|
242
|
+
"""(table, column): the largest text column of the candidate's tables that its baseline reads."""
|
|
243
|
+
sql = cand.get("baseline_sql") or ""
|
|
244
|
+
star = bool(re.search(r"(?:\bSELECT\s+|\.)\*", sql, re.I))
|
|
245
|
+
best, best_size = None, 0.0
|
|
246
|
+
for t in profile.get("tables") or []:
|
|
247
|
+
if t["name"] not in cand.get("tables", []) and t["name"].split(".")[-1] not in cand.get("tables", []):
|
|
248
|
+
continue
|
|
249
|
+
for c in t.get("columns") or []:
|
|
250
|
+
if c.get("kind") != "text" or not (star or re.search(rf"\b{re.escape(c['name'])}\b", sql)):
|
|
251
|
+
continue
|
|
252
|
+
size = sizes.mean_bytes(c) or float(c.get("avg_len") or 40)
|
|
253
|
+
if size > best_size:
|
|
254
|
+
best, best_size = (t["name"], c["name"]), size
|
|
255
|
+
return best
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def alternate(value, tag: str) -> str | None:
|
|
259
|
+
"""Another value of the same shape (a different tenant id), or None when the value is not an identifier."""
|
|
260
|
+
v = str(value)
|
|
261
|
+
if not v or re.fullmatch(r"-?\d+(\.\d+)?", v) or v.lower() in ("true", "false", "null"):
|
|
262
|
+
return None
|
|
263
|
+
digest = hashlib.sha1(f"{v}/{tag}".encode()).hexdigest()
|
|
264
|
+
if UUID.match(v):
|
|
265
|
+
return v[:24] + digest[:12]
|
|
266
|
+
if re.fullmatch(r"[0-9a-f]{16,}", v):
|
|
267
|
+
return (digest * 4)[:len(v)]
|
|
268
|
+
return f"{v}-{tag.lower()}"
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def second_values(cand: dict, profile: dict, fixtures: list[dict], tag: str) -> tuple[dict, dict]:
|
|
272
|
+
"""(mapping, overrides) for a run that gets rows of its own: every value the fixtures set -> its second value, and
|
|
273
|
+
parameter -> its second value.
|
|
274
|
+
|
|
275
|
+
The parameters a fixture carries get a second value. So do the other values the fixtures set that the query does
|
|
276
|
+
not name itself: an identifier that only ties the run's rows together (a row key, a session id). Left
|
|
277
|
+
as it was, the second run's rows hold the same key as the first's, and on a deduplicating table keyed on it
|
|
278
|
+
(ReplacingMergeTree ORDER BY row_key) FINAL keeps one row of the two: one run's rows are lost. The
|
|
279
|
+
same value gets the same second value in every table, so the joins between them still hold. A value the query
|
|
280
|
+
names (status = 'active') is kept."""
|
|
281
|
+
carried = {str(v.get("value")) for f in fixtures for v in f.get("values") or []}
|
|
282
|
+
mapping, overrides = {}, {}
|
|
283
|
+
for name, value in params_of(cand, profile).items():
|
|
284
|
+
new = alternate(value, tag) if str(value) in carried else None
|
|
285
|
+
if new:
|
|
286
|
+
mapping[str(value)], overrides[name] = new, new
|
|
287
|
+
if overrides:
|
|
288
|
+
sql = cand.get("baseline_sql") or ""
|
|
289
|
+
for value in sorted(carried - set(mapping)):
|
|
290
|
+
new = alternate(value, tag) if value and value not in sql else None
|
|
291
|
+
if new:
|
|
292
|
+
mapping[value] = new
|
|
293
|
+
return mapping, overrides
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def params_of(cand: dict, profile: dict) -> dict:
|
|
297
|
+
"""The parameters a candidate is run with: its own, with the profile's overrides on top."""
|
|
298
|
+
return {**(cand.get("params") or {}), **((profile.get("param_overrides") or {}).get(cand["finding"]) or {})}
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def _wanted_rows(m: dict, p: dict) -> float | None:
|
|
302
|
+
returned = ratio(m.get("result_rows"), target(p).get("rows_returned_per_run"))
|
|
303
|
+
return None if returned in (None, 0.0, float("inf")) else 1 / returned
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def heavy_runs(candidates: list[dict], production: dict[str, dict], profile: dict) -> tuple[dict, dict]:
|
|
307
|
+
"""Give every query whose 99th-percentile run is far from its median run a second, heavy run.
|
|
308
|
+
|
|
309
|
+
Returns a copy of the profile with a fixture `<finding>~heavy` beside each such query's own fixture (the same
|
|
310
|
+
columns, other values of the same shape, a larger share of the rows) and `param_overrides` for it, and
|
|
311
|
+
{candidates, production, notes}: the heavy runs as candidates of their own (finding `<finding>~heavy`) with the 99th
|
|
312
|
+
percentile as their production target, so the fit corrects them like any other; `notes` says, per query with a
|
|
313
|
+
spread, whether a heavy run was built and why not.
|
|
314
|
+
|
|
315
|
+
The first share is the typical fixture's times how many more rows the heavy run returns; the fit only lowers it."""
|
|
316
|
+
out = copy.deepcopy(profile)
|
|
317
|
+
extra: dict = {"candidates": [], "production": {}, "notes": []}
|
|
318
|
+
for cand in candidates:
|
|
319
|
+
p = production.get(cand["finding"])
|
|
320
|
+
typical, heavy = quantiles(p, 0), quantiles(p, 2)
|
|
321
|
+
if not typical or not heavy:
|
|
322
|
+
continue
|
|
323
|
+
apart = max(spread(ratio(heavy[theirs], typical[theirs])) for _, _, theirs in METRICS)
|
|
324
|
+
if apart <= SPLIT_AT:
|
|
325
|
+
extra["notes"].append({"finding": cand["finding"], "built": False, "reason": "the 99th-percentile run is within "
|
|
326
|
+
f"x{SPLIT_AT:g} of the median run: one run stands for both"})
|
|
327
|
+
continue
|
|
328
|
+
fixtures = [(t, f) for t in out.get("tables") or [] for f in list(t.get("fixtures") or []) if cand["finding"] in _fixture_ids(f.get("id"))]
|
|
329
|
+
mapping, overrides = second_values(cand, out, [f for _, f in fixtures], f"{cand['finding']}-heavy")
|
|
330
|
+
if not overrides:
|
|
331
|
+
extra["notes"].append({"finding": cand["finding"], "built": False, "reason": "no fixture carries a parameter value that "
|
|
332
|
+
"could be given a second value (the parameters are numbers, or the profile pins none of them)"})
|
|
333
|
+
continue
|
|
334
|
+
more = ratio(heavy["rows_returned_per_run"], typical["rows_returned_per_run"])
|
|
335
|
+
more = min(max(more, 1.0), 1000.0) if more not in (None, float("inf")) else 1000.0
|
|
336
|
+
for t, f in fixtures:
|
|
337
|
+
own = copy.deepcopy(f)
|
|
338
|
+
own["id"] = cand["finding"] + HEAVY
|
|
339
|
+
for key in ("size_factors", "share_estimated"):
|
|
340
|
+
own.pop(key, None)
|
|
341
|
+
for v in own.get("values") or []:
|
|
342
|
+
v["value"] = mapping.get(str(v.get("value")), v.get("value"))
|
|
343
|
+
own["share"] = min(max(float(f.get("share") or 0) * more, MIN_SHARE), MAX_SHARE)
|
|
344
|
+
own["min_rows"] = max(int(round(int(f.get("min_rows") or 1) * more)), 1)
|
|
345
|
+
if own.get("target_rows") is not None:
|
|
346
|
+
# a statement production ran: its heavy run's rows are production's 99th percentile (bench.target_shares)
|
|
347
|
+
own["target_rows"] = int(heavy.get("rows_read_per_run") or 0)
|
|
348
|
+
t["fixtures"].append(own)
|
|
349
|
+
out.setdefault("param_overrides", {})[cand["finding"] + HEAVY] = overrides
|
|
350
|
+
extra["candidates"].append({**cand, "finding": cand["finding"] + HEAVY, "heavy_of": cand["finding"]})
|
|
351
|
+
# ranked just behind its own typical run, so a fixture the two share with a third query follows the typical one
|
|
352
|
+
extra["production"][cand["finding"] + HEAVY] = {**heavy, "basis": "p99", "executions": p.get("executions"),
|
|
353
|
+
"read_bytes": (p.get("read_bytes") or 0) * 0.99, "aggregate": p.get("aggregate")}
|
|
354
|
+
extra["notes"].append({"finding": cand["finding"], "built": True, "apart": round(apart, 1) if apart != float("inf") else None})
|
|
355
|
+
return out, extra
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
PAST_EVERY_STRING = "\U0010ffff" # sorts after every UTF-8 string: a String key value no generated row holds or passes
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def successor(value) -> str | None:
|
|
362
|
+
"""A value of the same shape that sorts right after `value` and that no generated row holds: the last hex digit of
|
|
363
|
+
an identifier counted up (a uuid stays a uuid), else the value with a suffix. None for a number or a boolean."""
|
|
364
|
+
v = str(value)
|
|
365
|
+
if not v or re.fullmatch(r"-?\d+(\.\d+)?", v) or v.lower() in ("true", "false", "null"):
|
|
366
|
+
return None
|
|
367
|
+
if UUID.match(v) or re.fullmatch(r"[0-9a-f]{16,}", v, re.I):
|
|
368
|
+
chars = list(v)
|
|
369
|
+
for i in range(len(chars) - 1, -1, -1):
|
|
370
|
+
if chars[i] == "-":
|
|
371
|
+
continue
|
|
372
|
+
digit = int(chars[i], 16)
|
|
373
|
+
if digit < 15:
|
|
374
|
+
chars[i] = format(digit + 1, "x")
|
|
375
|
+
return "".join(chars)
|
|
376
|
+
chars[i] = "0"
|
|
377
|
+
return None
|
|
378
|
+
return f"{v}-none"
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def empty_runs(candidates: list[dict], production: dict[str, dict], profile: dict,
|
|
382
|
+
string_columns: dict[str, set[str]] | None = None, sort_keys: dict[str, list[str]] | None = None) -> tuple[dict, list[dict]]:
|
|
383
|
+
"""Make the typical run of every query whose typical production run returns nothing a run that returns nothing.
|
|
384
|
+
|
|
385
|
+
The fixture of a query puts rows under its parameter values, so its run returns rows; production's median run of
|
|
386
|
+
these queries returns none (a tenant with nothing in the bucket), and a ratio to that is infinite and no fit can
|
|
387
|
+
close it. The typical run is given parameter values no row holds instead (`param_overrides`), so what it reads is
|
|
388
|
+
what the key lookup of a missing value reads, and that is graded on rows and bytes read:
|
|
389
|
+
- production's median run reads rows: the value sorts right after the fixture's (`successor`), among the values
|
|
390
|
+
the table holds, so the lookup reads the granules where it would be;
|
|
391
|
+
- production's median run reads nothing: the value sorts past every value of the column (String columns only,
|
|
392
|
+
`string_columns`: table -> its String columns; else the successor), so a key that leads with the column
|
|
393
|
+
excludes every granule. Production may read nothing for another reason (a bucket no part covers); the sandbox
|
|
394
|
+
reproduces what is read, not why.
|
|
395
|
+
Only parameters a fixture carries are changed: a time window stays. Run after `heavy_runs`, whose heavy run takes
|
|
396
|
+
the fixture values. Returns a copy of the profile and one note per query: {finding, empty, reads, params}."""
|
|
397
|
+
out = copy.deepcopy(profile)
|
|
398
|
+
notes = []
|
|
399
|
+
for cand in candidates:
|
|
400
|
+
typical = quantiles(production.get(cand["finding"]), 0)
|
|
401
|
+
nothing, why = matched_nothing(production.get(cand["finding"]))
|
|
402
|
+
if not typical or not nothing:
|
|
403
|
+
continue
|
|
404
|
+
reads_nothing = (typical.get("rows_read_per_run") or 0) <= 0
|
|
405
|
+
where: dict[str, list[tuple[str, str]]] = {}
|
|
406
|
+
for t in out.get("tables") or []:
|
|
407
|
+
for f in t.get("fixtures") or []:
|
|
408
|
+
if cand["finding"] in _fixture_ids(f.get("id")):
|
|
409
|
+
for v in f.get("values") or []:
|
|
410
|
+
where.setdefault(str(v.get("value")), []).append((t["name"], v.get("column")))
|
|
411
|
+
overrides = {}
|
|
412
|
+
params = params_of(cand, out)
|
|
413
|
+
deepest = None
|
|
414
|
+
if not reads_nothing and sort_keys:
|
|
415
|
+
# a run that reads the granule where its value would be: only the value of the deepest key column the fixture
|
|
416
|
+
# sets is missing (tenant found, user not), so the key lookup ends among the tenant's rows, as a run
|
|
417
|
+
# for a tenant's unknown user does; changing every value would land it anywhere, or past every part
|
|
418
|
+
depth = {name: max((sort_keys.get(table, []).index(col) for table, col in where.get(str(value)) or []
|
|
419
|
+
if col in sort_keys.get(table, [])), default=-1) for name, value in params.items()}
|
|
420
|
+
if depth and max(depth.values()) >= 0:
|
|
421
|
+
deepest = max(depth, key=lambda n: depth[n])
|
|
422
|
+
for name, value in params.items():
|
|
423
|
+
places = where.get(str(value))
|
|
424
|
+
if not places or (deepest is not None and name != deepest):
|
|
425
|
+
continue
|
|
426
|
+
strings = string_columns is not None and all(col in (string_columns.get(table) or set()) for table, col in places)
|
|
427
|
+
new = PAST_EVERY_STRING + str(value) if reads_nothing and strings else successor(value)
|
|
428
|
+
if new:
|
|
429
|
+
overrides[name] = new
|
|
430
|
+
if not overrides:
|
|
431
|
+
notes.append({"finding": cand["finding"], "empty": False,
|
|
432
|
+
"reason": "no fixture carries a parameter value that could be replaced by one no row holds"})
|
|
433
|
+
continue
|
|
434
|
+
out.setdefault("param_overrides", {})[cand["finding"]] = {**((out.get("param_overrides") or {}).get(cand["finding"]) or {}), **overrides}
|
|
435
|
+
notes.append({"finding": cand["finding"], "empty": True, "reads": "nothing" if reads_nothing else "rows",
|
|
436
|
+
"params": sorted(overrides), **({"because": why} if why else {})})
|
|
437
|
+
return out, notes
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
KEY_ONLY_BYTES = 8.0 # bytes per row read up to which a run read no more than one key column
|
|
441
|
+
KEY_ONLY_APART = 10.0 # ... when the 90th-percentile run reads this many times more bytes per row
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
def matched_nothing(production: dict | None) -> tuple[bool, str]:
|
|
445
|
+
"""Whether production's typical (median) run of a query found no row: (yes, why when it is not plain).
|
|
446
|
+
|
|
447
|
+
Plainly, when it returns nothing. An aggregate without groups (`SELECT count() ... WHERE tenant = ?`) returns its one
|
|
448
|
+
row anyway; that its median run found nothing shows in what it read: about one key column per row (KEY_ONLY_BYTES)
|
|
449
|
+
where the runs that find rows read many times more per row (the 90th percentile, KEY_ONLY_APART). It looked a value
|
|
450
|
+
up in the primary key, read the key's granule and stopped. Such a run is made a run that finds nothing as well."""
|
|
451
|
+
typical, wide = quantiles(production, 0), quantiles(production, 1)
|
|
452
|
+
if not typical:
|
|
453
|
+
return False, ""
|
|
454
|
+
if (typical.get("rows_returned_per_run") or 0) <= 0:
|
|
455
|
+
return True, ""
|
|
456
|
+
returned = ((production or {}).get("spread") or {}).get("rows_returned") or []
|
|
457
|
+
one_row = bool(returned) and all((r or 0) <= 1 for r in returned) # every run returns one row: its result says nothing
|
|
458
|
+
if (typical.get("rows_returned_per_run") or 0) > 1 or not ((production or {}).get("aggregate") or one_row) or not wide:
|
|
459
|
+
return False, ""
|
|
460
|
+
rows, size = float(typical.get("rows_read_per_run") or 0), float(typical.get("bytes_read_per_run") or 0)
|
|
461
|
+
rows90, size90 = float(wide.get("rows_read_per_run") or 0), float(wide.get("bytes_read_per_run") or 0)
|
|
462
|
+
if rows <= 0 or rows90 <= 0:
|
|
463
|
+
return False, ""
|
|
464
|
+
per, per90 = size / rows, size90 / rows90
|
|
465
|
+
if per <= KEY_ONLY_BYTES and per * KEY_ONLY_APART <= per90:
|
|
466
|
+
return True, (f"production's median run returned its one row of an aggregate and read {per:.1f} bytes per row, against "
|
|
467
|
+
f"{per90:,.0f} at the 90th percentile: it read the key and found no row")
|
|
468
|
+
return False, ""
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
def split_shared(ranked: list[dict], measurements: dict, production: dict, profile: dict) -> list[dict]:
|
|
472
|
+
"""Give a candidate its own parameter values when it shares a fixture with a heavier reader that needs a very
|
|
473
|
+
different number of rows. Changes `profile` in place; returns the changes."""
|
|
474
|
+
changes: list[dict] = []
|
|
475
|
+
for lead_at, lead in enumerate(ranked):
|
|
476
|
+
for other in ranked[lead_at + 1:]:
|
|
477
|
+
shared = [(t, f) for t in profile.get("tables") or [] for f in t.get("fixtures") or []
|
|
478
|
+
if {lead["finding"], other["finding"]} <= set(_fixture_ids(f.get("id")))]
|
|
479
|
+
a = _wanted_rows(measurements[lead["finding"]], production[lead["finding"]])
|
|
480
|
+
b = _wanted_rows(measurements[other["finding"]], production[other["finding"]])
|
|
481
|
+
if not shared or not a or not b or spread(a / b) <= SPLIT_AT:
|
|
482
|
+
continue
|
|
483
|
+
mapping, overrides = second_values(other, profile, [f for _, f in shared], other["finding"])
|
|
484
|
+
if not overrides:
|
|
485
|
+
continue
|
|
486
|
+
for t, f in shared:
|
|
487
|
+
own = copy.deepcopy(f)
|
|
488
|
+
own["id"] = other["finding"]
|
|
489
|
+
own.pop("size_factors", None)
|
|
490
|
+
for v in own.get("values") or []:
|
|
491
|
+
v["value"] = mapping.get(str(v.get("value")), v.get("value"))
|
|
492
|
+
f["id"] = "+".join(x for x in _fixture_ids(f.get("id")) if x != other["finding"])
|
|
493
|
+
t["fixtures"].append(own)
|
|
494
|
+
changes.append({"finding": other["finding"], "table": t["name"], "fixture": own["id"], "what": "own parameter values",
|
|
495
|
+
"from": 0.0, "to": float(own.get("share") or 0),
|
|
496
|
+
"because": f"shares its values with {lead['finding']}, which needs {spread(a / b):.0f}x "
|
|
497
|
+
f"{'fewer' if a < b else 'more'} rows"})
|
|
498
|
+
profile.setdefault("param_overrides", {})[other["finding"]] = overrides
|
|
499
|
+
return changes
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
def corrections(candidates: list[dict], measurements: dict[str, dict], production: dict[str, dict], profile: dict,
|
|
503
|
+
lever: str = "all") -> tuple[dict, list[dict]]:
|
|
504
|
+
"""A corrected copy of the profile and the list of changes, from one round of baseline measurements.
|
|
505
|
+
|
|
506
|
+
`lever`: "fixtures" (shares, sizes, own parameter values), "parts" (the shape of time-ranged parts,
|
|
507
|
+
part_corrections) or "all". The fit pulls one per round (bench.fit_to_production).
|
|
508
|
+
|
|
509
|
+
A fixture shared by several candidates ("Q-001+Q-004") follows the one that reads the most in production; a
|
|
510
|
+
candidate that needs a very different number of rows is first given values of its own (`split_shared`)."""
|
|
511
|
+
out = copy.deepcopy(profile)
|
|
512
|
+
ranked = sorted((c for c in candidates if c["finding"] in production and (measurements.get(c["finding"]) or {}).get("ok")),
|
|
513
|
+
key=lambda c: -(production[c["finding"]].get("read_bytes") or production[c["finding"]].get("bytes_read_per_run") or 0))
|
|
514
|
+
if lever == "parts":
|
|
515
|
+
return out, part_corrections(ranked, measurements, production, out)
|
|
516
|
+
changes: list[dict] = split_shared(ranked, measurements, production, out)
|
|
517
|
+
done: set[tuple[str, str]] = set()
|
|
518
|
+
for cand in ranked:
|
|
519
|
+
m, p = measurements[cand["finding"]], target(production[cand["finding"]]) # the median run when the spread is known
|
|
520
|
+
returned = ratio(m.get("result_rows"), p.get("rows_returned_per_run"))
|
|
521
|
+
want_rows = None if returned in (None, 0.0, float("inf")) or spread(returned) <= 1.2 else 1 / returned
|
|
522
|
+
per_row = per_row_prod = None
|
|
523
|
+
if m.get("read_rows") and p.get("rows_read_per_run"):
|
|
524
|
+
per_row, per_row_prod = m["read_bytes"] / m["read_rows"], p["bytes_read_per_run"] / p["rows_read_per_run"]
|
|
525
|
+
want_size = per_row_prod / per_row if per_row and per_row_prod and spread(per_row_prod / per_row) > 1.2 else None
|
|
526
|
+
# Bytes per row read says how heavy the rows are only when about as many rows are read as in production. When
|
|
527
|
+
# the sandbox reads far fewer or more (its tables are smaller, the key prunes differently), the quotient is
|
|
528
|
+
# about the row count, and "correcting" sizes with it would shrink or inflate payloads for no reason.
|
|
529
|
+
if spread(ratio(m.get("read_rows"), p.get("rows_read_per_run"))) > SIZE_NEEDS_ROWS_WITHIN:
|
|
530
|
+
want_size = None
|
|
531
|
+
heavy = heaviest_column(cand, out) if want_size else None
|
|
532
|
+
for t in out.get("tables") or []:
|
|
533
|
+
if t["name"] not in cand.get("tables", []):
|
|
534
|
+
continue
|
|
535
|
+
for f in t.get("fixtures") or []:
|
|
536
|
+
if cand["finding"] not in _fixture_ids(f.get("id")) or (t["name"], str(f.get("id"))) in done:
|
|
537
|
+
continue
|
|
538
|
+
done.add((t["name"], str(f.get("id"))))
|
|
539
|
+
# Small dimension tables are left alone: the fixture there is one configuration row, not a volume.
|
|
540
|
+
if want_rows and int(t.get("rows") or 0) >= 10_000:
|
|
541
|
+
before = float(f.get("share") or 0)
|
|
542
|
+
estimated = float(f.setdefault("share_estimated", before)) # what the profile said, kept as the ceiling
|
|
543
|
+
f["share"] = min(max(before * want_rows, MIN_SHARE), MAX_SHARE, estimated)
|
|
544
|
+
applied = f["share"] / before if before else 1.0
|
|
545
|
+
f["min_rows"] = max(int(round(int(f.get("min_rows") or 1) * applied)), 1)
|
|
546
|
+
# the same value pinned on the column puts it on rows outside the fixture too: those follow
|
|
547
|
+
values = {v.get("column"): str(v.get("value")) for v in f.get("values") or []}
|
|
548
|
+
for c in t.get("columns") or []:
|
|
549
|
+
for pin in c.get("pinned") or []:
|
|
550
|
+
if values.get(c["name"]) == str(pin.get("value")):
|
|
551
|
+
pin["share"] = min(max(float(pin.get("share") or 0) * applied, 0.0), MAX_SHARE)
|
|
552
|
+
if applied != 1.0:
|
|
553
|
+
changes.append({"finding": cand["finding"], "table": t["name"], "fixture": f.get("id"), "what": "share",
|
|
554
|
+
"from": before, "to": f["share"], "because": f"rows returned x{returned:g} of production"})
|
|
555
|
+
if heavy and heavy[0] == t["name"]:
|
|
556
|
+
factors = f.setdefault("size_factors", [])
|
|
557
|
+
entry = next((s for s in factors if s.get("column") == heavy[1]), None)
|
|
558
|
+
if entry is None:
|
|
559
|
+
entry = {"column": heavy[1], "factor": 1.0}
|
|
560
|
+
factors.append(entry)
|
|
561
|
+
before = float(entry["factor"])
|
|
562
|
+
entry["factor"] = round(min(max(before * want_size, MIN_FACTOR), MAX_FACTOR), 4)
|
|
563
|
+
changes.append({"finding": cand["finding"], "table": t["name"], "fixture": f.get("id"), "what": f"size of {heavy[1]}",
|
|
564
|
+
"from": before, "to": entry["factor"],
|
|
565
|
+
"because": f"{per_row:,.0f} bytes per row read against {per_row_prod:,.0f} in production"})
|
|
566
|
+
if lever == "all":
|
|
567
|
+
changes += part_corrections(ranked, measurements, production, out)
|
|
568
|
+
return out, changes
|
|
569
|
+
|
|
570
|
+
|
|
571
|
+
def part_corrections(ranked: list[dict], measurements: dict, production: dict, profile: dict) -> list[dict]:
|
|
572
|
+
"""The part-layout lever: change the shape of a table's time-ranged parts (`part_shape.ratio`, parts.py) when the
|
|
573
|
+
typical run selects a very different number of parts than production's runs do. Changes `profile` in place.
|
|
574
|
+
|
|
575
|
+
Only a table whose parts are cut by time has the lever (bench sets `part_shape` on it). Too many parts selected:
|
|
576
|
+
the parts become more even (a recent window meets fewer small parts at the head); too few: more skewed. Which way
|
|
577
|
+
helps depends on where the query's window falls, so this is a step the fit takes and measures, and undoes when the
|
|
578
|
+
grades get worse. A table read by several queries follows the one that reads the most in production, as fixtures do."""
|
|
579
|
+
from . import parts
|
|
580
|
+
changes, done = [], set()
|
|
581
|
+
by_name = {t["name"]: t for t in profile.get("tables") or []}
|
|
582
|
+
for cand in ranked:
|
|
583
|
+
m = measurements.get(cand["finding"]) or {}
|
|
584
|
+
fid = check(m, production[cand["finding"]])
|
|
585
|
+
r = (fid.get("ratios") or {}).get("selected_parts")
|
|
586
|
+
shaped = [by_name[n] for n in cand.get("tables") or [] if n in by_name and (by_name[n].get("part_shape") or {}).get("ratio") is not None]
|
|
587
|
+
if r is None or not shaped:
|
|
588
|
+
continue
|
|
589
|
+
t = max(shaped, key=lambda x: int(x.get("rows") or 0))
|
|
590
|
+
if t["name"] in done:
|
|
591
|
+
continue
|
|
592
|
+
done.add(t["name"]) # the heaviest reader decides, also when it is already close: a lighter one does not move it
|
|
593
|
+
if spread(r) <= CLOSE:
|
|
594
|
+
continue
|
|
595
|
+
before = parts.clamp_ratio(t["part_shape"]["ratio"])
|
|
596
|
+
after = parts.step(before, r > 1)
|
|
597
|
+
if after == before:
|
|
598
|
+
continue
|
|
599
|
+
t["part_shape"] = {**t["part_shape"], "ratio": round(after, 4), "basis": "fitted"}
|
|
600
|
+
changes.append({"finding": cand["finding"], "table": t["name"], "fixture": None, "what": "part size ratio", "from": before,
|
|
601
|
+
"to": t["part_shape"]["ratio"], "because": f"parts selected x{r:g} of production"})
|
|
602
|
+
return changes
|
|
603
|
+
|
|
604
|
+
|
|
605
|
+
# ---- CPU and memory against production -----------------------------------------------------------
|
|
606
|
+
# Graded beside the read grade, never into it: `fidelity.grade` stays the grade of rows, bytes and rows returned (and
|
|
607
|
+
# parts and marks), and `fidelity.resources` {cpu, memory} says whether the sandbox's CPU and memory behave like
|
|
608
|
+
# production's. A measure whose production figure is missing is "unchecked" and lowers nothing.
|
|
609
|
+
#
|
|
610
|
+
# memory the sandbox baseline's peak (the memory tracker's, ClickHouse only) / production's typical (p50) peak, the same
|
|
611
|
+
# bands (x1.5 close, x3 near); the heavy run against production's p99
|
|
612
|
+
# cpu milliseconds differ by machine, so CPU is graded relative to the run: factor = sandbox CPU per run / production's
|
|
613
|
+
# typical CPU per run; the machine factor is the median factor of the run's candidates whose reads are graded
|
|
614
|
+
# close; a candidate's `cpu_per_byte` = its factor / the machine factor. Fewer than
|
|
615
|
+
# `[bench] machine_factor_min_candidates` close candidates: CPU is not graded (`machine_factor.used` false).
|
|
616
|
+
|
|
617
|
+
|
|
618
|
+
def sandbox_memory(m: dict | None) -> float | None:
|
|
619
|
+
"""The sandbox run's typical peak memory: the median of the timed runs when they were kept, else the measurement's."""
|
|
620
|
+
if not m or not m.get("ok") or m.get("memory_kind") != "tracker":
|
|
621
|
+
return None
|
|
622
|
+
runs = sorted(x for x in ((m.get("runs_detail") or {}).get("memory_bytes") or []) if x is not None)
|
|
623
|
+
if runs:
|
|
624
|
+
return float(runs[len(runs) // 2])
|
|
625
|
+
return float(m["memory_bytes"]) if m.get("memory_bytes") else None
|
|
626
|
+
|
|
627
|
+
|
|
628
|
+
def cpu_factor(m: dict | None, production: dict | None) -> float | None:
|
|
629
|
+
"""sandbox CPU per run / production's typical CPU per run (both user + system, getrusage), or None."""
|
|
630
|
+
want = ((production or {}).get("cpu_ms_per_run") or {}).get("q50")
|
|
631
|
+
have = (m or {}).get("cpu_ms") if (m or {}).get("cpu_kind") == "rusage" else None
|
|
632
|
+
if not want or have is None or float(want) <= 0 or float(have) <= 0:
|
|
633
|
+
return None
|
|
634
|
+
return round(float(have) / float(want), 4)
|
|
635
|
+
|
|
636
|
+
|
|
637
|
+
def machine_factor(candidates: list[tuple[str, float | None]], min_candidates: int) -> dict:
|
|
638
|
+
"""{median, low, high, candidates, min_candidates, used} over (read grade, cpu factor) of the run's candidates: only
|
|
639
|
+
close-graded ones with a factor count. `used` false below `min_candidates`: CPU is then not graded at all."""
|
|
640
|
+
factors = sorted(f for g, f in candidates if g == "close" and f)
|
|
641
|
+
out: dict = {"candidates": len(factors), "min_candidates": int(min_candidates), "used": len(factors) >= max(int(min_candidates), 1)}
|
|
642
|
+
if factors:
|
|
643
|
+
mid = len(factors) // 2
|
|
644
|
+
out["median"] = round(factors[mid] if len(factors) % 2 else (factors[mid - 1] + factors[mid]) / 2, 4)
|
|
645
|
+
out["low"], out["high"] = round(factors[0], 4), round(factors[-1], 4)
|
|
646
|
+
return out
|
|
647
|
+
|
|
648
|
+
|
|
649
|
+
def resource_check(record: dict | None, production: dict | None, machine: dict | None) -> dict:
|
|
650
|
+
"""{ratios: {memory, memory_heavy, cpu_per_byte}, resources: {cpu, memory}, cpu_factor} for one benchmarked baseline."""
|
|
651
|
+
base = (record or {}).get("baseline") or {}
|
|
652
|
+
out: dict = {"ratios": {}, "resources": {"cpu": "unchecked", "memory": "unchecked"}}
|
|
653
|
+
mem = (production or {}).get("memory_per_run") or {}
|
|
654
|
+
have = sandbox_memory(base)
|
|
655
|
+
if have and mem.get("q50"):
|
|
656
|
+
r = ratio(have, mem["q50"])
|
|
657
|
+
out["ratios"]["memory"] = r
|
|
658
|
+
grades = [r]
|
|
659
|
+
heavy = ((record or {}).get("fidelity") or {}).get("heavy") or {}
|
|
660
|
+
hm = (heavy.get("measured") or {}).get("memory_bytes")
|
|
661
|
+
if heavy.get("built") and hm and mem.get("q99"):
|
|
662
|
+
out["ratios"]["memory_heavy"] = ratio(hm, mem["q99"])
|
|
663
|
+
grades.append(out["ratios"]["memory_heavy"])
|
|
664
|
+
out["resources"]["memory"] = grade(grades)
|
|
665
|
+
f = cpu_factor(base, production)
|
|
666
|
+
if f is not None:
|
|
667
|
+
out["cpu_factor"] = f
|
|
668
|
+
if machine and machine.get("used") and machine.get("median"):
|
|
669
|
+
out["ratios"]["cpu_per_byte"] = round(f / machine["median"], 4)
|
|
670
|
+
out["resources"]["cpu"] = grade([out["ratios"]["cpu_per_byte"]])
|
|
671
|
+
return out
|