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/resources.py
ADDED
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
"""CPU, memory, time, spill and result size of a variant against its baseline, measured in the sandbox.
|
|
2
|
+
|
|
3
|
+
What transfers from a sandbox to production is a ratio on the same sandbox, not an absolute:
|
|
4
|
+
a laptop's milliseconds are not a cluster's. So each variant is run beside its baseline `resource_runs` times
|
|
5
|
+
(`[bench]`, default 5) after both were measured once, and every measure is a ratio of medians with the range of the
|
|
6
|
+
runs:
|
|
7
|
+
|
|
8
|
+
ratio = median(variant) / median(baseline) low = min(variant) / median(baseline) high = max(variant) / median(baseline)
|
|
9
|
+
|
|
10
|
+
The runs are interleaved (B V B V ...) when the variant needs no setup, so drift on a shared machine hits both. A
|
|
11
|
+
variant with a setup (an index, a projection) can not run beside a baseline that must not see it: its runs are taken
|
|
12
|
+
while the setup is there and the baseline's right after it is undone (`interleaved: false`).
|
|
13
|
+
|
|
14
|
+
Per engine (verified on ClickHouse 24.8, 25.8, 26.6 and PostgreSQL 15, 16, 17; see each engine's `sample`):
|
|
15
|
+
|
|
16
|
+
ClickHouse CPU = UserTimeMicroseconds + SystemTimeMicroseconds of the run (getrusage); memory = the memory tracker's
|
|
17
|
+
peak (memory_usage); threads pinned with max_threads ([bench] resource_threads); spill = External*
|
|
18
|
+
PostgreSQL CPU = user + system from log_statement_stats (getrusage of the backend), the plain statement, repeated in
|
|
19
|
+
one session below resource_min_cpu_ms; memory = the plan's sort and hash memory (EXPLAIN, one figure,
|
|
20
|
+
`plan_nodes`, never called peak memory); spill = temp blocks written x block size
|
|
21
|
+
SQLite CPU work = VM steps (exact); memory = the library's high-water mark during the run
|
|
22
|
+
|
|
23
|
+
CPU or memory never make a win. They can take one away: a variant that reads less and uses more than a limit is a
|
|
24
|
+
trade-off (`judge`): above `memory_trade_off_ratio` and at least `memory_trade_off_min_bytes` more, or above
|
|
25
|
+
`cpu_trade_off_ratio` and at least `cpu_trade_off_min_ms` more. A limit inside the range of the runs is
|
|
26
|
+
`near_limit` (also a trade-off). CPU measured beside other containers (`noisy`) is never judged.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
import time
|
|
32
|
+
|
|
33
|
+
from .engines.base import median
|
|
34
|
+
|
|
35
|
+
DEFAULTS: dict = {
|
|
36
|
+
"resources": True, # measure the resource profile of every measured variant
|
|
37
|
+
"resource_runs": 5, # runs of each side, after the measurement both already had
|
|
38
|
+
"resource_threads": 4, # ClickHouse: max_threads of every measured run (0: the server's default)
|
|
39
|
+
"resource_min_cpu_ms": 5.0, # PostgreSQL: a statement under this CPU is repeated in one session and divided
|
|
40
|
+
"resource_max_repeats": 50, # ... at most this many times
|
|
41
|
+
"resource_budget_s": 120.0, # the runs of one variant on one run kind take at most about this long (fewer runs, at least 3)
|
|
42
|
+
"resource_max_statements": 500, # a group's or a loop's side of more statements than this: its CPU runs are not taken
|
|
43
|
+
"pg_work_mem": "", # PostgreSQL: work_mem of measured statements ('' = production's when pulled, else the server's)
|
|
44
|
+
"pg_hash_mem_multiplier": 0.0, # ... and hash_mem_multiplier (0 = production's when pulled, else the server's)
|
|
45
|
+
"machine_factor_min_candidates": 3, # close-graded candidates needed before CPU is graded against production
|
|
46
|
+
"memory_trade_off_ratio": 2.0, # a win whose variant holds more than this times the memory ...
|
|
47
|
+
"memory_trade_off_min_bytes": 64_000_000, # ... and at least this much more, is a trade-off
|
|
48
|
+
"cpu_trade_off_ratio": 1.5, # a win whose variant burns more than this times the CPU ...
|
|
49
|
+
"cpu_trade_off_min_ms": 50.0, # ... and at least this much more per run, is a trade-off
|
|
50
|
+
}
|
|
51
|
+
MEASURES = ("cpu", "memory", "time", "spill", "result")
|
|
52
|
+
STATES = ("within", "over", "near_limit", "not_judged")
|
|
53
|
+
NEIGHBOUR_TTL_S = 60.0
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def settings_of(bench: dict | None) -> dict:
|
|
57
|
+
"""The resource settings of `[bench]` over the defaults. A value of the wrong type is ignored."""
|
|
58
|
+
out = dict(DEFAULTS)
|
|
59
|
+
for key, default in DEFAULTS.items():
|
|
60
|
+
value = (bench or {}).get(key)
|
|
61
|
+
if value is None:
|
|
62
|
+
continue
|
|
63
|
+
if isinstance(default, bool):
|
|
64
|
+
out[key] = bool(value)
|
|
65
|
+
elif isinstance(default, (int, float)) and isinstance(value, (int, float)) and not isinstance(value, bool) and value >= 0:
|
|
66
|
+
out[key] = type(default)(value)
|
|
67
|
+
elif isinstance(default, str) and isinstance(value, (str, int)):
|
|
68
|
+
out[key] = str(value)
|
|
69
|
+
return out
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def configure(sb, cfg: dict, production_settings: dict | None = None) -> dict:
|
|
73
|
+
"""Give the sandbox the run settings the profile needs, and return what was set (recorded in bench.json `resources`).
|
|
74
|
+
`production_settings`: PostgreSQL's pulled pg.check.settings ({work_mem_kb, hash_mem_multiplier}) when there are."""
|
|
75
|
+
said: dict = {"runs": int(cfg["resource_runs"])}
|
|
76
|
+
if hasattr(sb, "resource_threads"):
|
|
77
|
+
sb.resource_threads = int(cfg["resource_threads"]) or None
|
|
78
|
+
said["threads"] = sb.threads_for_run() if hasattr(sb, "threads_for_run") else sb.resource_threads
|
|
79
|
+
if hasattr(sb, "resource_min_cpu_ms"):
|
|
80
|
+
sb.resource_min_cpu_ms = float(cfg["resource_min_cpu_ms"])
|
|
81
|
+
sb.resource_max_repeats = max(int(cfg["resource_max_repeats"]), 1)
|
|
82
|
+
if hasattr(sb, "set_work_mem"):
|
|
83
|
+
prod = production_settings or {}
|
|
84
|
+
work_mem = cfg["pg_work_mem"] or (prod.get("work_mem_kb") and int(prod["work_mem_kb"])) or None
|
|
85
|
+
multiplier = cfg["pg_hash_mem_multiplier"] or prod.get("hash_mem_multiplier") or None
|
|
86
|
+
sb.set_work_mem(work_mem, multiplier)
|
|
87
|
+
said["work_mem"] = getattr(sb, "work_mem", None) or "server default"
|
|
88
|
+
said["work_mem_from"] = "[bench] pg_work_mem" if cfg["pg_work_mem"] else "production (pg.check.settings)" if work_mem else "server"
|
|
89
|
+
if getattr(sb, "hash_mem_multiplier", None):
|
|
90
|
+
said["hash_mem_multiplier"] = sb.hash_mem_multiplier
|
|
91
|
+
return said
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def noisy(sb) -> bool:
|
|
95
|
+
"""Whether other containers run beside the sandbox now (bench.memory.neighbours): CPU and time are then not the
|
|
96
|
+
sandbox's own. Asked at most once a minute."""
|
|
97
|
+
if not hasattr(sb, "neighbours") and not (getattr(sb, "runtime", None) and getattr(sb, "name", None)):
|
|
98
|
+
return False # in-process (SQLite): no container, nothing beside it to tell
|
|
99
|
+
seen = getattr(sb, "_noisy_seen", None)
|
|
100
|
+
if seen and time.monotonic() - seen[0] < NEIGHBOUR_TTL_S:
|
|
101
|
+
return seen[1]
|
|
102
|
+
try:
|
|
103
|
+
if hasattr(sb, "neighbours"):
|
|
104
|
+
value = bool((sb.neighbours() or {}).get("containers"))
|
|
105
|
+
else: # a container sandbox without its own count: the other running containers, names not kept
|
|
106
|
+
import subprocess
|
|
107
|
+
names = subprocess.run([sb.runtime, "ps", "--format", "{{.Names}}"], capture_output=True, text=True, timeout=60).stdout.split()
|
|
108
|
+
value = any(n != sb.name for n in names)
|
|
109
|
+
except Exception: # a runtime that can not list containers is no evidence either way
|
|
110
|
+
value = False
|
|
111
|
+
sb._noisy_seen = (time.monotonic(), value)
|
|
112
|
+
return value
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def runs_for(cfg: dict, base_ms: float, var_ms: float) -> int:
|
|
116
|
+
"""How many runs of each side fit the budget: resource_runs, fewer for slow statements, never under 3."""
|
|
117
|
+
wanted = max(int(cfg["resource_runs"]), 1)
|
|
118
|
+
per_pair = max(float(base_ms or 0) + float(var_ms or 0), 1.0)
|
|
119
|
+
fit = int(float(cfg["resource_budget_s"]) * 1000 / per_pair)
|
|
120
|
+
return max(min(wanted, fit), min(3, wanted))
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def interleaved(sb, base_sql: str, var_sql: str, params: dict | None, n: int) -> tuple[list[dict], list[dict]]:
|
|
124
|
+
got = sb.sample([pair for _ in range(n) for pair in ((base_sql, params), (var_sql, params))])
|
|
125
|
+
return got[0::2], got[1::2]
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def alone(sb, sql: str, params: dict | None, n: int) -> list[dict]:
|
|
129
|
+
return sb.sample([(sql, params)] * n)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def many_vs_one(sb, before: list[tuple[str, dict | None]], after: list[tuple[str, dict | None]], base_m: dict, var_m: dict,
|
|
133
|
+
cfg: dict | None = None) -> dict:
|
|
134
|
+
"""The resource profile of a group's members (or a loop's per-item statements) against the statement(s) that replace
|
|
135
|
+
them: each run is every `before` statement then every `after` one, interleaved run by run, CPU and time summed per
|
|
136
|
+
side; memory is the measurements' (the largest a side held). Judged like a candidate's (`judge`), never a win of its
|
|
137
|
+
own. Not taken (`{measured: False, why}`) when the sandbox has no CPU sampling or a side has more statements than
|
|
138
|
+
`resource_max_statements`."""
|
|
139
|
+
cfg = cfg or getattr(sb, "resource_cfg", None) or {}
|
|
140
|
+
if not cfg or not hasattr(sb, "sample"):
|
|
141
|
+
return {"measured": False, "why": "no_cpu_sampling"}
|
|
142
|
+
cap = int(cfg.get("resource_max_statements") or DEFAULTS["resource_max_statements"])
|
|
143
|
+
if len(before) > cap or len(after) > cap:
|
|
144
|
+
return {"measured": False, "why": "too_many_statements", "statements": max(len(before), len(after)), "resource_max_statements": cap}
|
|
145
|
+
n = runs_for(cfg, float(base_m.get("duration_ms") or 0), float(var_m.get("duration_ms") or 0))
|
|
146
|
+
got = sb.sample([s for _ in range(n) for s in list(before) + list(after)])
|
|
147
|
+
if not got or not all(g for g in got):
|
|
148
|
+
return {"measured": False, "why": "sampling_failed"}
|
|
149
|
+
per = len(before) + len(after)
|
|
150
|
+
|
|
151
|
+
def side(run: list[dict], kind: str) -> dict:
|
|
152
|
+
return {"cpu_ms": round(sum(float(x.get("cpu_ms") or 0) for x in run), 3), "duration_ms": round(sum(float(x.get("duration_ms") or 0) for x in run), 3),
|
|
153
|
+
"cpu_kind": kind}
|
|
154
|
+
kind = "rusage" if getattr(sb, "engine", "") == "postgres" else ""
|
|
155
|
+
base_runs = [side(got[i * per:i * per + len(before)], kind) for i in range(n)]
|
|
156
|
+
var_runs = [side(got[i * per + len(before):(i + 1) * per], kind) for i in range(n)]
|
|
157
|
+
res = profile(base_runs, var_runs, base_m, var_m, interleave=True, is_noisy=noisy(sb))
|
|
158
|
+
res["judged"] = judge(res, cfg)
|
|
159
|
+
res["statements"] = {"before": len(before), "after": len(after)}
|
|
160
|
+
return res
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _measure_key(cpu_kind: str) -> str:
|
|
164
|
+
return "vm_steps" if cpu_kind == "vm_steps" else "cpu_ms"
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def pair(base_runs: list[dict], var_runs: list[dict], key: str, base_m: dict | None = None, var_m: dict | None = None,
|
|
168
|
+
fallback: str = "") -> dict | None:
|
|
169
|
+
"""{ratio, low, high, runs, before, after} of one measure: medians of the runs (or the two measurements' `fallback`
|
|
170
|
+
field when no run counts it: one figure each, `runs` 1). None when neither side counts it."""
|
|
171
|
+
b = [float(r[key]) for r in base_runs if r.get(key) is not None]
|
|
172
|
+
v = [float(r[key]) for r in var_runs if r.get(key) is not None]
|
|
173
|
+
if not b or not v:
|
|
174
|
+
if fallback and base_m and var_m and base_m.get(fallback) is not None and var_m.get(fallback) is not None:
|
|
175
|
+
b, v = [float(base_m[fallback])], [float(var_m[fallback])]
|
|
176
|
+
else:
|
|
177
|
+
return None
|
|
178
|
+
before, after = median(b), median(v)
|
|
179
|
+
out = {"before": round(before, 3), "after": round(after, 3), "runs": min(len(b), len(v))}
|
|
180
|
+
if before > 0:
|
|
181
|
+
out.update(ratio=round(after / before, 4), low=round(min(v) / before, 4), high=round(max(v) / before, 4))
|
|
182
|
+
else:
|
|
183
|
+
out.update(ratio=None if after > 0 else 1.0, low=None if after > 0 else 1.0, high=None if after > 0 else 1.0)
|
|
184
|
+
out["before_low"], out["before_high"] = round(min(b), 3), round(max(b), 3)
|
|
185
|
+
return out
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def profile(base_runs: list[dict], var_runs: list[dict], base_m: dict, var_m: dict, *, interleave: bool, is_noisy: bool) -> dict:
|
|
189
|
+
"""The resource profile of one variant on one run kind (typical or heavy)."""
|
|
190
|
+
# PostgreSQL's measurement (EXPLAIN) counts no CPU; its resource runs do (log_statement_stats): CPU time then
|
|
191
|
+
cpu_kind = var_m.get("cpu_kind") or base_m.get("cpu_kind") or ("rusage" if any(r.get("cpu_ms") is not None for r in base_runs) else "")
|
|
192
|
+
out: dict = {"runs": min(len(base_runs), len(var_runs)), "interleaved": interleave, "noisy": is_noisy,
|
|
193
|
+
"cpu_kind": cpu_kind, "memory_kind": var_m.get("memory_kind") or base_m.get("memory_kind") or ""}
|
|
194
|
+
for name, key, fallback in (("cpu", _measure_key(cpu_kind), ""), ("memory", "memory_bytes", "memory_bytes"),
|
|
195
|
+
("time", "duration_ms", ""), ("spill", "spill_bytes", "spill_bytes"), ("result", "result_bytes", "result_bytes")):
|
|
196
|
+
got = pair(base_runs, var_runs, key, base_m, var_m, fallback)
|
|
197
|
+
if got is not None:
|
|
198
|
+
out[name] = got
|
|
199
|
+
if "spill" in out:
|
|
200
|
+
out["spill"]["spills_before"] = out["spill"]["before"] > 0
|
|
201
|
+
out["spill"]["spills_after"] = out["spill"]["after"] > 0
|
|
202
|
+
threads = [r["threads"] for r in var_runs if r.get("threads")]
|
|
203
|
+
if threads:
|
|
204
|
+
out["threads"] = max(threads)
|
|
205
|
+
return out
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _state(m: dict | None, limit: float, floor: float) -> str:
|
|
209
|
+
"""within | over | near_limit for one measure against (ratio limit, absolute floor of the increase)."""
|
|
210
|
+
if not m or m.get("ratio") is None or m.get("low") is None:
|
|
211
|
+
return "not_judged"
|
|
212
|
+
before = float(m["before"])
|
|
213
|
+
if m["low"] > limit and float(m["after"]) - before >= floor:
|
|
214
|
+
return "over"
|
|
215
|
+
if m["high"] > limit and m["high"] * before - before >= floor:
|
|
216
|
+
return "near_limit"
|
|
217
|
+
return "within"
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def judge(res: dict, cfg: dict) -> dict:
|
|
221
|
+
"""Whether a variant's memory or CPU takes a read-side win away: per measure within | over | near_limit |
|
|
222
|
+
not_judged, the worse of the typical and the heavy run, with the thresholds used."""
|
|
223
|
+
out: dict = {}
|
|
224
|
+
for name, limit, floor in (("memory", "memory_trade_off_ratio", "memory_trade_off_min_bytes"),
|
|
225
|
+
("cpu", "cpu_trade_off_ratio", "cpu_trade_off_min_ms")):
|
|
226
|
+
states = []
|
|
227
|
+
for run in (res, res.get("heavy")):
|
|
228
|
+
if not run:
|
|
229
|
+
continue
|
|
230
|
+
if name == "cpu" and (run.get("noisy") or run.get("cpu_kind") != "rusage"):
|
|
231
|
+
states.append("not_judged") # beside other containers, or VM steps: not a CPU time to judge
|
|
232
|
+
continue
|
|
233
|
+
states.append(_state(run.get(name), float(cfg[limit]), float(cfg[floor])))
|
|
234
|
+
decided = [s for s in states if s != "not_judged"]
|
|
235
|
+
out[name] = max(decided, key=("within", "near_limit", "over").index) if decided else "not_judged"
|
|
236
|
+
out["thresholds"] = {k: cfg[k] for k in ("memory_trade_off_ratio", "memory_trade_off_min_bytes", "cpu_trade_off_ratio",
|
|
237
|
+
"cpu_trade_off_min_ms")}
|
|
238
|
+
return out
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def fact(res: dict, cfg: dict) -> str:
|
|
242
|
+
"""A stated fact for a variant that read the same: it holds less memory or burns less CPU than the baseline by
|
|
243
|
+
the trade-off ratio, over every run, and by at least the floor. `less_memory`, `less_cpu`, `less_memory_and_cpu` or ''.
|
|
244
|
+
Never a win."""
|
|
245
|
+
got = []
|
|
246
|
+
for name, limit, floor in (("memory", "memory_trade_off_ratio", "memory_trade_off_min_bytes"),
|
|
247
|
+
("cpu", "cpu_trade_off_ratio", "cpu_trade_off_min_ms")):
|
|
248
|
+
m = res.get(name)
|
|
249
|
+
if not m or m.get("high") is None or (name == "cpu" and (res.get("noisy") or res.get("cpu_kind") != "rusage")):
|
|
250
|
+
continue
|
|
251
|
+
if m["high"] * float(cfg[limit]) < 1.0 and float(m["before"]) - float(m["after"]) >= float(cfg[floor]):
|
|
252
|
+
got.append(name)
|
|
253
|
+
return "less_" + "_and_".join(got) if got else ""
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def baseline_fields(runs: list[dict], cpu_kind: str) -> dict:
|
|
257
|
+
"""The baseline measurement's resource fields from every run it had beside its variants (pooled)."""
|
|
258
|
+
runs = [r for r in runs if r]
|
|
259
|
+
if not runs:
|
|
260
|
+
return {}
|
|
261
|
+
out: dict = {}
|
|
262
|
+
for key in ("cpu_ms", "cpu_user_ms", "cpu_system_ms", "io_wait_ms"):
|
|
263
|
+
value = median([r.get(key) for r in runs])
|
|
264
|
+
if value is not None:
|
|
265
|
+
out[key] = round(value, 3)
|
|
266
|
+
out["runs_detail"] = {k: [r.get(k) for r in runs] for k in ("cpu_ms", "memory_bytes", "duration_ms")}
|
|
267
|
+
cpu_kind = cpu_kind or ("rusage" if "cpu_ms" in out else "")
|
|
268
|
+
if cpu_kind:
|
|
269
|
+
out["cpu_kind"] = cpu_kind
|
|
270
|
+
return out
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
# ---- what findings.json and an upload carry ----------------------------------------------------------------------
|
|
274
|
+
CPU_KINDS = ("rusage", "vm_steps")
|
|
275
|
+
MEMORY_KINDS = ("tracker", "plan_nodes", "highwater")
|
|
276
|
+
FACTS = ("less_memory", "less_cpu", "less_memory_and_cpu")
|
|
277
|
+
PAIR_KEYS = ("ratio", "low", "high", "runs", "before", "after", "before_low", "before_high")
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def _num(v):
|
|
281
|
+
if isinstance(v, bool) or not isinstance(v, (int, float)) or v != v or v in (float("inf"), float("-inf")):
|
|
282
|
+
return None
|
|
283
|
+
return v
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def for_upload(res: dict | None) -> dict | None:
|
|
287
|
+
"""A variant's resource profile as findings.json and an upload carry it: numbers and fixed words, rebuilt field by
|
|
288
|
+
field (an error text from the sandbox, or anything else under these keys, is not passed through)."""
|
|
289
|
+
if not isinstance(res, dict) or res.get("error"):
|
|
290
|
+
return {"measured": False} if isinstance(res, dict) else None
|
|
291
|
+
if res.get("skipped"):
|
|
292
|
+
# the variant read no less than its baseline: its CPU and memory runs could change no verdict (bench.py)
|
|
293
|
+
return {"measured": False, "skipped": "reads_no_less" if res.get("skipped") == "reads_no_less" else "other"}
|
|
294
|
+
|
|
295
|
+
def one(run: dict) -> dict:
|
|
296
|
+
out: dict = {"runs": _num(run.get("runs")), "interleaved": bool(run.get("interleaved")), "noisy": bool(run.get("noisy")),
|
|
297
|
+
"cpu_kind": run.get("cpu_kind") if run.get("cpu_kind") in CPU_KINDS else "",
|
|
298
|
+
"memory_kind": run.get("memory_kind") if run.get("memory_kind") in MEMORY_KINDS else ""}
|
|
299
|
+
for name in MEASURES:
|
|
300
|
+
m = run.get(name)
|
|
301
|
+
if isinstance(m, dict):
|
|
302
|
+
out[name] = {k: _num(m.get(k)) for k in PAIR_KEYS if k in m}
|
|
303
|
+
if name == "spill":
|
|
304
|
+
out[name].update({k: bool(m.get(k)) for k in ("spills_before", "spills_after") if k in m})
|
|
305
|
+
if _num(run.get("threads")) is not None:
|
|
306
|
+
out["threads"] = run["threads"]
|
|
307
|
+
return out
|
|
308
|
+
|
|
309
|
+
out = {"measured": True, **one(res)}
|
|
310
|
+
if isinstance(res.get("heavy"), dict):
|
|
311
|
+
out["heavy"] = one(res["heavy"])
|
|
312
|
+
judged = res.get("judged")
|
|
313
|
+
if isinstance(judged, dict):
|
|
314
|
+
out["judged"] = {k: judged[k] for k in ("memory", "cpu") if judged.get(k) in STATES}
|
|
315
|
+
if isinstance(judged.get("thresholds"), dict):
|
|
316
|
+
out["judged"]["thresholds"] = {k: _num(v) for k, v in judged["thresholds"].items() if k in DEFAULTS}
|
|
317
|
+
if res.get("fact") in FACTS:
|
|
318
|
+
out["fact"] = res["fact"]
|
|
319
|
+
return out
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def cost_of(res: dict) -> dict:
|
|
323
|
+
"""`variants[].resource_cost` {within, near_limit, reason, memory, cpu}: whether the variant's memory and CPU stay
|
|
324
|
+
within the trade-off limits; `reason` is the outcome code a read-side win would get from them (blockers.py), '' when
|
|
325
|
+
within. `within` is null when neither measure could be judged."""
|
|
326
|
+
j = res.get("judged") or {}
|
|
327
|
+
states = [j.get(k) for k in ("memory", "cpu") if j.get(k) in STATES and j.get(k) != "not_judged"]
|
|
328
|
+
reason = "fix_costs_memory" if j.get("memory") == "over" else "fix_costs_cpu" if j.get("cpu") == "over" \
|
|
329
|
+
else "resource_cost_near_limit" if "near_limit" in states else ""
|
|
330
|
+
return {"within": (not reason) if states else None, "near_limit": "near_limit" in states, "reason": reason,
|
|
331
|
+
"memory": j.get("memory") or "not_judged", "cpu": j.get("cpu") or "not_judged",
|
|
332
|
+
**({"thresholds": j["thresholds"]} if j.get("thresholds") else {})}
|
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
"""The resource profile of a finding as rows: one row per resource, the measure that
|
|
2
|
+
decides first, then CPU, peak memory, time, spill and result. Each row has what production measured, what the sandbox
|
|
3
|
+
measured for the change against today (a ratio of medians with the range of the runs, and the two absolutes it came
|
|
4
|
+
from), and whether the sandbox behaves like production for that measure. The HTML report, the CLI table and the
|
|
5
|
+
hand-off text draw these rows; none of them is prose.
|
|
6
|
+
|
|
7
|
+
A missing fact is said ("not in this pull", "not counted by this server"), never a blank and never a zero. PostgreSQL's
|
|
8
|
+
sandbox memory is "sort and hash memory (plan nodes)", never peak memory; SQLite's CPU is "VM steps". Time is shown and
|
|
9
|
+
never estimated. An estimate (production x the sandbox ratio) is made by default, per resource only where that resource
|
|
10
|
+
is graded close or near (`[report] production_estimate = false` turns it off); it is never a saving and never summed.
|
|
11
|
+
PostgreSQL without pg_stat_kcache: busy time (run time minus disk waits) stands in the CPU row, never called CPU.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
ENGINE_LABEL = {"clickhouse": "ClickHouse", "postgres": "PostgreSQL", "sqlite": "SQLite"}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def size(n) -> str:
|
|
20
|
+
"""Decimal bytes: 3.1 MB, 17.3 TB."""
|
|
21
|
+
if n is None:
|
|
22
|
+
return "-"
|
|
23
|
+
n = float(n)
|
|
24
|
+
for unit, step in (("TB", 1e12), ("GB", 1e9), ("MB", 1e6), ("kB", 1e3)):
|
|
25
|
+
if abs(n) >= step:
|
|
26
|
+
return f"{n / step:.1f} {unit}"
|
|
27
|
+
return f"{n:.0f} B"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def ms(n) -> str:
|
|
31
|
+
if n is None:
|
|
32
|
+
return "-"
|
|
33
|
+
n = float(n)
|
|
34
|
+
return f"{n / 1000:.1f} s" if n >= 10_000 else f"{n:.0f} ms" if n >= 10 else f"{n:.1f} ms" if n >= 1 else f"{n:.2f} ms"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def count(n) -> str:
|
|
38
|
+
if n is None:
|
|
39
|
+
return "-"
|
|
40
|
+
n = float(n)
|
|
41
|
+
for unit, step in (("B", 1e9), ("M", 1e6), ("K", 1e3)):
|
|
42
|
+
if abs(n) >= step:
|
|
43
|
+
return f"{n / step:.1f}{unit}"
|
|
44
|
+
return f"{n:,.0f}"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def hours(seconds) -> str:
|
|
48
|
+
return "-" if seconds is None else f"{float(seconds) / 3600:.1f} h"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def ratio(r) -> str:
|
|
52
|
+
if r is None:
|
|
53
|
+
return "-"
|
|
54
|
+
return f"x{r:.3g}" if r < 10 else f"x{r:.0f}"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def best_variant(f: dict) -> dict | None:
|
|
58
|
+
"""The change the profile is drawn for: the first measured win, else the first variant with a resource profile."""
|
|
59
|
+
vs = [v for v in f.get("variants") or [] if (v.get("resources") or {}).get("measured")]
|
|
60
|
+
return next((v for v in vs if v.get("verdict") == "win"), vs[0] if vs else None)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _pair(m: dict | None, fmt) -> str:
|
|
64
|
+
if not m or m.get("before") is None:
|
|
65
|
+
return ""
|
|
66
|
+
return f"{fmt(m['before'])} -> {fmt(m['after'])}"
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def rows(f: dict, engine: str) -> list[dict]:
|
|
70
|
+
"""[{key, resource, qualifier, production, sandbox: {ratio, low, high, runs, pair} | None, sandbox_note, grade, grade_ratio,
|
|
71
|
+
estimate}] for one finding. `production` is a list of short lines; `sandbox_note` says why there is no sandbox pair."""
|
|
72
|
+
real = f.get("real") or {}
|
|
73
|
+
fid = f.get("fidelity") or {}
|
|
74
|
+
grades = fid.get("resources") or {}
|
|
75
|
+
est = f.get("resource_estimate") or {}
|
|
76
|
+
v = best_variant(f)
|
|
77
|
+
res = (v or {}).get("resources") or {}
|
|
78
|
+
last = ((v or {}).get("scales") or [None])[-1] or {}
|
|
79
|
+
b, m = last.get("baseline") or {}, last.get("variant") or {}
|
|
80
|
+
pulled = bool(real)
|
|
81
|
+
out = []
|
|
82
|
+
# the measure that decides: bytes (ClickHouse), buffers (PostgreSQL), pages (SQLite)
|
|
83
|
+
deciding = {"clickhouse": "Bytes read", "postgres": "Buffers touched", "sqlite": "Pages read"}.get(engine, "Bytes read")
|
|
84
|
+
read_ratio = (m["read_bytes"] / b["read_bytes"]) if b.get("read_bytes") and m.get("read_bytes") is not None else None
|
|
85
|
+
days = (real.get("window_hours") or 0) / 24
|
|
86
|
+
prod_read = [f"{size(real['read_bytes'] / days)} a day ({real.get('share_of_read_bytes', 0):.1%})"] if real.get("read_bytes") and days else \
|
|
87
|
+
[f"{size(real['read_bytes'])} since the reset"] if real.get("read_bytes") else []
|
|
88
|
+
out.append({"key": "read", "resource": deciding, "qualifier": "decides", "production": prod_read or ["No pull" if not pulled else "Not in this pull"],
|
|
89
|
+
"sandbox": {"ratio": read_ratio, "low": read_ratio, "high": read_ratio, "runs": None,
|
|
90
|
+
"pair": f"{size(b.get('read_bytes'))} -> {size(m.get('read_bytes'))}"} if read_ratio is not None else None,
|
|
91
|
+
"grade": fid.get("grade"), "grade_ratio": (fid.get("ratios") or {}).get("bytes_read"),
|
|
92
|
+
"estimate": est.get("read_bytes_per_day")})
|
|
93
|
+
# CPU
|
|
94
|
+
cpu = real.get("cpu") or {}
|
|
95
|
+
if engine == "sqlite":
|
|
96
|
+
prod_cpu, label, qual = ["No production side"], "CPU work", "VM steps"
|
|
97
|
+
elif cpu:
|
|
98
|
+
prod_cpu = [f"typical {ms(cpu.get('typical_ms'))} · p95 {ms(cpu.get('p95_ms'))}" if cpu.get("typical_ms") is not None
|
|
99
|
+
else f"average {ms(cpu.get('mean_ms'))}"]
|
|
100
|
+
if cpu.get("seconds_per_day") is not None:
|
|
101
|
+
prod_cpu.append(f"{hours(cpu['seconds_per_day'])} a day" + (f" ({cpu['share']:.1%})" if cpu.get("share") is not None else "")
|
|
102
|
+
+ (f" · {cpu['cores']:.2f} cores" if cpu.get("cores") is not None else ""))
|
|
103
|
+
label, qual = "CPU time", "user + system"
|
|
104
|
+
elif engine == "postgres" and real.get("busy_ms_per_run") is not None:
|
|
105
|
+
# pg_stat_statements counts no CPU: busy time (run time - disk waits) is an upper bound of CPU, never CPU itself
|
|
106
|
+
per_day = real.get("executions_per_day") or ((real.get("executions") or 0) * 24 / real["window_hours"] if real.get("window_hours") else None)
|
|
107
|
+
prod_cpu = [f"average {ms(real['busy_ms_per_run'])} a run" + (f" · {hours(real['busy_ms_per_run'] * per_day / 1000)} a day" if per_day else ""),
|
|
108
|
+
"pg_stat_statements does not count CPU (pg_stat_kcache does)"]
|
|
109
|
+
label, qual = "Busy time", "upper bound of CPU, includes lock waits"
|
|
110
|
+
else:
|
|
111
|
+
prod_cpu = ["No pull" if not pulled else "Not counted by this server · needs pg_stat_kcache" if engine == "postgres" else "Not in this pull"]
|
|
112
|
+
label, qual = "CPU time", "user + system"
|
|
113
|
+
c = res.get("cpu")
|
|
114
|
+
fmt = count if res.get("cpu_kind") == "vm_steps" else ms
|
|
115
|
+
if label == "Busy time":
|
|
116
|
+
# the sandbox's own CPU is not compared with a production busy time: the sandbox's time stands beside it
|
|
117
|
+
c, fmt = res.get("time"), ms
|
|
118
|
+
out.append({"key": "busy" if label == "Busy time" else "cpu", "resource": label, "qualifier": qual, "production": prod_cpu,
|
|
119
|
+
"sandbox": {**{k: c.get(k) for k in ("ratio", "low", "high", "runs")}, "pair": _pair(c, fmt) + (" (time)" if label == "Busy time" else "")} if c else None,
|
|
120
|
+
"sandbox_note": "" if c else "Not measured in the sandbox", "noisy": bool(res.get("noisy")),
|
|
121
|
+
"grade": None if label == "Busy time" else grades.get("cpu"), "grade_ratio": None if label == "Busy time" else (fid.get("ratios") or {}).get("cpu_per_byte"),
|
|
122
|
+
"estimate": None if label == "Busy time" else est.get("cpu_seconds_per_day"),
|
|
123
|
+
"not_judged": None if label == "Busy time" else (est.get("not_judged") or {}).get("cpu")})
|
|
124
|
+
# memory
|
|
125
|
+
mem = real.get("memory") or {}
|
|
126
|
+
if mem:
|
|
127
|
+
prod_mem = [f"typical {size(mem.get('typical_bytes'))} · p95 {size(mem.get('p95_bytes'))}" if mem.get("typical_bytes") is not None
|
|
128
|
+
else f"mean {size(mem.get('mean_bytes'))}"]
|
|
129
|
+
prod_mem.append(f"max {size(mem.get('max_bytes'))}" + (f" · {mem['limit_stops']:,} stopped at the memory limit" if mem.get("limit_stops") else ""))
|
|
130
|
+
else:
|
|
131
|
+
prod_mem = ["No pull" if not pulled else "Not counted by PostgreSQL" if engine == "postgres" else "No production side" if engine == "sqlite"
|
|
132
|
+
else "Not in this pull"]
|
|
133
|
+
mk = res.get("memory_kind") or ""
|
|
134
|
+
label = {"plan_nodes": "Sort and hash memory", "highwater": "Memory high-water"}.get(mk, "Peak memory")
|
|
135
|
+
qual = {"plan_nodes": "plan nodes, not a peak", "highwater": "library, one run"}.get(mk, "a peak, not a sum")
|
|
136
|
+
mm = res.get("memory")
|
|
137
|
+
out.append({"key": "memory", "resource": label, "qualifier": qual, "production": prod_mem,
|
|
138
|
+
"sandbox": {**{k: mm.get(k) for k in ("ratio", "low", "high", "runs")}, "pair": _pair(mm, size)
|
|
139
|
+
+ (f", {res['threads']} threads" if res.get("threads") else "")} if mm else None,
|
|
140
|
+
"sandbox_note": "" if mm else "Not measured in the sandbox",
|
|
141
|
+
"grade": grades.get("memory"), "grade_ratio": (fid.get("ratios") or {}).get("memory"),
|
|
142
|
+
"estimate": est.get("memory_typical_bytes"), "estimate_max": est.get("memory_max_bytes"),
|
|
143
|
+
"not_judged": (est.get("not_judged") or {}).get("memory")})
|
|
144
|
+
# time: shown, never estimated
|
|
145
|
+
t = real.get("time") or {}
|
|
146
|
+
prod_t = [f"typical {ms(t.get('typical_ms'))} · p95 {ms(t.get('p95_ms') if t.get('p95_ms') is not None else real.get('p95_ms'))}"
|
|
147
|
+
if t.get("typical_ms") is not None else f"average {ms(real.get('avg_ms'))}" if real.get("avg_ms") is not None else "No pull"]
|
|
148
|
+
if t.get("max_ms") is not None:
|
|
149
|
+
prod_t.append(f"max {ms(t['max_ms'])}")
|
|
150
|
+
tt = res.get("time")
|
|
151
|
+
out.append({"key": "time", "resource": "Time", "qualifier": "wall, never estimated", "production": prod_t,
|
|
152
|
+
"sandbox": {**{k: tt.get(k) for k in ("ratio", "low", "high", "runs")}, "pair": _pair(tt, ms)} if tt else None,
|
|
153
|
+
"sandbox_note": "" if tt else "Not measured in the sandbox", "noisy": bool(res.get("noisy")), "grade": None, "estimate": None})
|
|
154
|
+
# spill
|
|
155
|
+
sp = real.get("spill") or {}
|
|
156
|
+
prod_s = [f"{sp['runs_share']:.1%} of runs" + (f" · {size(sp.get('bytes_per_day'))} a day" if sp.get("bytes_per_day") is not None else "")] if sp else \
|
|
157
|
+
[f"{size(real['temp_bytes_per_run'])} a run to temp files"] if real.get("temp_bytes_per_run") is not None else ["Not in this pull" if pulled else "No pull"]
|
|
158
|
+
ss = res.get("spill")
|
|
159
|
+
spill_text = None
|
|
160
|
+
if ss:
|
|
161
|
+
spill_text = ("no spill" if not ss.get("spills_before") and not ss.get("spills_after") else
|
|
162
|
+
f"spills {size(ss.get('before'))} -> {size(ss.get('after'))}")
|
|
163
|
+
out.append({"key": "spill", "resource": "Spill to disk", "qualifier": "sort or aggregation", "production": prod_s,
|
|
164
|
+
"sandbox": {**{k: ss.get(k) for k in ("ratio", "low", "high", "runs")}, "pair": spill_text} if ss else None,
|
|
165
|
+
"sandbox_note": "" if ss else "Not measured in the sandbox", "grade": None, "estimate": None})
|
|
166
|
+
rr = res.get("result")
|
|
167
|
+
if rr:
|
|
168
|
+
out.append({"key": "result", "resource": "Result sent", "qualifier": "bytes", "production": ["Not in this pull"],
|
|
169
|
+
"sandbox": {**{k: rr.get(k) for k in ("ratio", "low", "high", "runs")}, "pair": _pair(rr, size)}, "grade": None, "estimate": None})
|
|
170
|
+
return out
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def judged_words(v: dict | None) -> str:
|
|
174
|
+
"""What the resource judgement says of a change, in words for people: never 'blocked'."""
|
|
175
|
+
j = ((v or {}).get("resources") or {}).get("judged") or {}
|
|
176
|
+
res = (v or {}).get("resources") or {}
|
|
177
|
+
said = []
|
|
178
|
+
for k, word in (("memory", "the memory"), ("cpu", "the CPU")):
|
|
179
|
+
r = (res.get(k) or {}).get("ratio")
|
|
180
|
+
if j.get(k) == "over":
|
|
181
|
+
said.append(f"reads less, holds {ratio(r)} {word}: a trade-off" if k == "memory" else f"reads less, uses {ratio(r)} {word}: a trade-off")
|
|
182
|
+
elif j.get(k) == "near_limit":
|
|
183
|
+
said.append(f"{word} is near the limit (the runs' range crosses it): a trade-off")
|
|
184
|
+
fact = res.get("fact")
|
|
185
|
+
if fact:
|
|
186
|
+
said.append({"less_memory": "reads the same, holds less memory", "less_cpu": "reads the same, uses less CPU",
|
|
187
|
+
"less_memory_and_cpu": "reads the same, holds less memory and uses less CPU"}[fact] + " (a fact, not a win)")
|
|
188
|
+
return "; ".join(said)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def handoff(f: dict, engine: str) -> str:
|
|
192
|
+
"""The hand-off text of one finding: pasted elsewhere, so the one place with sentences. A line
|
|
193
|
+
whose facts are missing is left out, never blanked."""
|
|
194
|
+
site = f.get("site") or {}
|
|
195
|
+
lines = [f"{f['finding']} {site.get('file', '')}:{site.get('line', '')} ({ENGINE_LABEL.get(engine, engine)}, "
|
|
196
|
+
f"table{'s' if len(f.get('tables') or []) > 1 else ''} {', '.join(f.get('tables') or [])})"]
|
|
197
|
+
v = best_variant(f) or next((x for x in f.get("variants") or [] if x.get("verdict") == "win"), None)
|
|
198
|
+
if v:
|
|
199
|
+
verified = v.get("verdict") == "win"
|
|
200
|
+
lines.append(f"Change: {v.get('change') or v.get('kind')}. " + ("Verified in the sandbox: same rows." if verified else
|
|
201
|
+
f"Not a verified win ({str(v.get('verdict')).replace('_', ' ')})."))
|
|
202
|
+
words = judged_words(v)
|
|
203
|
+
if words:
|
|
204
|
+
lines.append(words[0].upper() + words[1:] + ".")
|
|
205
|
+
profile = rows(f, engine)
|
|
206
|
+
parts = []
|
|
207
|
+
for r in profile:
|
|
208
|
+
s = r.get("sandbox")
|
|
209
|
+
if not s or s.get("ratio") is None and not s.get("pair"):
|
|
210
|
+
continue
|
|
211
|
+
if r["key"] == "spill":
|
|
212
|
+
parts.append(s.get("pair") or "")
|
|
213
|
+
continue
|
|
214
|
+
name = {"read": "bytes read" if engine == "clickhouse" else "buffers" if engine == "postgres" else "pages", "cpu": "CPU" if r["qualifier"] != "VM steps" else "VM steps",
|
|
215
|
+
"busy": "time",
|
|
216
|
+
"memory": r["resource"].lower(), "time": "time", "result": "result sent"}[r["key"]]
|
|
217
|
+
runs = f", {s['runs']} runs, {ratio(s.get('low'))} to {ratio(s.get('high'))}" if s.get("runs") and s.get("runs") > 1 and r["key"] in ("cpu", "memory", "time", "busy") else ""
|
|
218
|
+
parts.append(f"{name} {ratio(s.get('ratio'))} ({s.get('pair')}{runs})")
|
|
219
|
+
if parts:
|
|
220
|
+
lines.append("Sandbox, one run, fix against today: " + " | ".join(p for p in parts if p))
|
|
221
|
+
real = f.get("real") or {}
|
|
222
|
+
if real:
|
|
223
|
+
window = f"{real['window_hours']:g} h" if real.get("window_hours") else "since the statistics reset"
|
|
224
|
+
prod = [f"{real.get('executions', 0):,} runs"]
|
|
225
|
+
if real.get("read_bytes"):
|
|
226
|
+
prod.append(f"{size(real['read_bytes'])} read ({real.get('share_of_read_bytes', 0):.1%})")
|
|
227
|
+
cpu = real.get("cpu") or {}
|
|
228
|
+
if cpu.get("seconds_per_day") is not None:
|
|
229
|
+
prod.append(f"CPU {hours(cpu['seconds_per_day'])} a day" + (f" ({cpu['share']:.1%}, {cpu.get('cores', 0):.2f} cores)" if cpu.get("share") is not None else ""))
|
|
230
|
+
elif cpu.get("mean_ms") is not None:
|
|
231
|
+
prod.append(f"CPU {ms(cpu['mean_ms'])} a run on average")
|
|
232
|
+
elif real.get("busy_ms_per_run") is not None and engine == "postgres":
|
|
233
|
+
prod.append(f"busy time {ms(real['busy_ms_per_run'])} a run (run time minus disk waits: an upper bound of CPU, includes lock waits; not CPU)")
|
|
234
|
+
mem = real.get("memory") or {}
|
|
235
|
+
if mem.get("typical_bytes") is not None:
|
|
236
|
+
prod.append(f"peak memory typical {size(mem['typical_bytes'])}, p95 {size(mem.get('p95_bytes'))}, max {size(mem.get('max_bytes'))}")
|
|
237
|
+
elif mem.get("max_bytes") is not None:
|
|
238
|
+
prod.append(f"peak memory mean {size(mem.get('mean_bytes'))}, max {size(mem['max_bytes'])}")
|
|
239
|
+
if mem.get("limit_stops"):
|
|
240
|
+
prod.append(f"{mem['limit_stops']:,} runs stopped at the memory limit")
|
|
241
|
+
lines.append(f"Production today, {window}: " + " | ".join(prod))
|
|
242
|
+
est = f.get("resource_estimate")
|
|
243
|
+
if isinstance(est, dict):
|
|
244
|
+
if est.get("judged"):
|
|
245
|
+
bits = []
|
|
246
|
+
if est.get("read_bytes_per_day"):
|
|
247
|
+
bits.append(f"{size(est['read_bytes_per_day']['value'])} read")
|
|
248
|
+
if est.get("cpu_seconds_per_day"):
|
|
249
|
+
c = est["cpu_seconds_per_day"]
|
|
250
|
+
bits.append(f"{hours(c['value'])} CPU a day ({hours(c['low'])} to {hours(c['high'])})")
|
|
251
|
+
tail = f"; typical peak about {size(est['memory_typical_bytes']['value'])}" if est.get("memory_typical_bytes") else ""
|
|
252
|
+
if bits or tail:
|
|
253
|
+
window = f"{est['window_hours']:g} h window" if est.get("window_hours") else "the pull's span"
|
|
254
|
+
lines.append(f"Estimate in production with the fix (sandbox graded {est['grade']}, {window}): about " + " and ".join(bits) + f"{tail}.")
|
|
255
|
+
basis = [f"{n} {size(x['from']) if 'bytes' in k else hours(x['from'])} x {x['ratio']:.2g}" for k, n in
|
|
256
|
+
(("read_bytes_per_day", "read"), ("cpu_seconds_per_day", "CPU"), ("memory_typical_bytes", "memory"))
|
|
257
|
+
for x in [est.get(k)] if x and x.get("from") is not None and x.get("ratio") is not None]
|
|
258
|
+
if basis:
|
|
259
|
+
lines.append("Basis: production x the sandbox ratio (" + ", ".join(basis) + ").")
|
|
260
|
+
lines.append("An estimate is production x the sandbox ratio. It is not a measurement and not a saving. Measure again after the change: codecop db pull.")
|
|
261
|
+
nj = est.get("not_judged") or {}
|
|
262
|
+
if nj:
|
|
263
|
+
lines.append("Not judged: " + ", ".join(f"{'CPU' if k == 'cpu' else 'memory'} ({str(v).replace('_', ' ')})" for k, v in sorted(nj.items())) + ".")
|
|
264
|
+
elif est.get("why") in ("graded_off", "not_graded"):
|
|
265
|
+
lines.append("Estimate in production with the fix: not judged (the sandbox is not like production for this query).")
|
|
266
|
+
return "\n".join(lines) + "\n"
|