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/advisor_bench.py
ADDED
|
@@ -0,0 +1,493 @@
|
|
|
1
|
+
"""The sandbox proof of advisor.json: each proposed index built for real, every statement it claims measured before and
|
|
2
|
+
after it, as a set.
|
|
3
|
+
|
|
4
|
+
Called by `codecop bench` (bench.run's `after_scale` hook) at the largest scale, while the table's data is loaded, after the
|
|
5
|
+
ranked candidates were measured:
|
|
6
|
+
|
|
7
|
+
1. Runnable forms. A statement the advisor read is run as the benchmark already runs it when it is a candidate
|
|
8
|
+
(ranked, observed or built for a scenario: its baseline and parameters). Otherwise, a statement from code whose
|
|
9
|
+
text has no part known only at run time and whose every placeholder is compared with a column is bound here: each
|
|
10
|
+
value is the column's value in the sandbox table's middle row (generated data, never a real value), LIMIT 100 and
|
|
11
|
+
OFFSET 0. Anything else is listed as claimed, not measured, and never counts towards a verified gain.
|
|
12
|
+
2. Before and after. Every runnable statement the index serves, and up to `max_measured_per_suggestion` statements of
|
|
13
|
+
the same table it does not serve (did they get worse? a plan can change for them too), measured without the
|
|
14
|
+
index and with it, EXPLAIN (ANALYZE, BUFFERS) as for any variant. Pages decide (bench.verdict, pages_decide); the
|
|
15
|
+
same rows are shown by the result hash with the single-statement rules (bench.Comparison: ties under ORDER BY ...
|
|
16
|
+
LIMIT are compared before the LIMIT; the text is the baseline's and the setup only adds an access path, so a plan
|
|
17
|
+
whose rows differ is "not compared", never "differs").
|
|
18
|
+
3. Write side. The same rows inserted into a copy of the table with and without the index (writecost.measure_postgres):
|
|
19
|
+
time, WAL bytes and size; blockers.insert_cost_rule decides as for any table-level variant.
|
|
20
|
+
4. Visibility map. Right after the load the table is VACUUMed, so every heap page is all-visible and an index-only
|
|
21
|
+
scan never visits the heap: that is a production table just vacuumed, not a table being written to. When a
|
|
22
|
+
statement's plan with the index is an Index Only Scan on it, the statement is measured a second time after
|
|
23
|
+
`vm_touch_share` of the table's heap pages were rewritten without VACUUM (`UPDATE ... SET c = c` on a page sample,
|
|
24
|
+
then ANALYZE), with and without the index. The verdict uses that second run (`honest_verdict`); both are reported.
|
|
25
|
+
The table is VACUUMed again afterwards.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
import re
|
|
31
|
+
import time
|
|
32
|
+
|
|
33
|
+
from . import advisor as A
|
|
34
|
+
from . import bench as bench_mod
|
|
35
|
+
from .engines.base import Measurement, QueryError, SandboxError, outside_quotes
|
|
36
|
+
|
|
37
|
+
MEASURED_KEYS = ("ok", "error", "read_rows", "read_bytes", "result_rows", "duration_ms", "shared_hit_blocks", "shared_read_blocks", "node_types")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _numbers(m: Measurement | None) -> dict | None:
|
|
41
|
+
if m is None:
|
|
42
|
+
return None
|
|
43
|
+
d = m.to_dict()
|
|
44
|
+
out = {k: d.get(k) for k in MEASURED_KEYS if k in d}
|
|
45
|
+
out["pages"] = int((d.get("read_bytes") or 0) // max(int(d.get("block_size") or 8192), 1))
|
|
46
|
+
out["error"] = (out.get("error") or "")[:300]
|
|
47
|
+
return out
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def candidate_maps(rank: dict | None) -> tuple[dict, dict]:
|
|
51
|
+
by_site, by_hash = {}, {}
|
|
52
|
+
for c in (rank or {}).get("candidates") or []:
|
|
53
|
+
if not c.get("baseline_sql") or isinstance(c.get("write"), dict):
|
|
54
|
+
continue # a write statement is measured by writebench only, inside a rolled-back transaction
|
|
55
|
+
h = (c.get("observed") or {}).get("hash")
|
|
56
|
+
if h:
|
|
57
|
+
by_hash.setdefault(str(h), c)
|
|
58
|
+
if c.get("sql_from") != "query_log" and c.get("id"):
|
|
59
|
+
by_site.setdefault(c["id"], c)
|
|
60
|
+
return by_site, by_hash
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _literal(v: str, op: str) -> str:
|
|
64
|
+
if op == "any":
|
|
65
|
+
v = "{" + '"' + str(v).replace("\\", "\\\\").replace('"', '\\"') + '"' + "}"
|
|
66
|
+
return "'" + str(v).replace("'", "''") + "'"
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def bind(sb, info: dict, loaded: set[str], cache: dict) -> tuple[dict | None, str]:
|
|
70
|
+
"""A runnable form of a statement from code: (runnable, '') or (None, why not)."""
|
|
71
|
+
if info.get("runtime_parts"):
|
|
72
|
+
return None, "runtime_parts"
|
|
73
|
+
if info.get("unbound"):
|
|
74
|
+
return None, "parameter_not_bound_to_a_column"
|
|
75
|
+
if info.get("positional", 0) > 1:
|
|
76
|
+
return None, "positional_parameters"
|
|
77
|
+
if not set(info.get("tables") or []) <= loaded:
|
|
78
|
+
return None, "table_not_loaded"
|
|
79
|
+
values: dict[str, str] = {}
|
|
80
|
+
for p, (table, col, op) in (info.get("binds") or {}).items():
|
|
81
|
+
if op == "limit":
|
|
82
|
+
values[p] = "100"
|
|
83
|
+
continue
|
|
84
|
+
if op == "offset":
|
|
85
|
+
values[p] = "0"
|
|
86
|
+
continue
|
|
87
|
+
key = (table, col)
|
|
88
|
+
if key not in cache:
|
|
89
|
+
try:
|
|
90
|
+
q = sb._q(table)
|
|
91
|
+
n = int(sb.table_stats(table).get("rows") or 0)
|
|
92
|
+
got = sb.rows(f'SELECT ("{col}")::text AS v FROM {q} WHERE "{col}" IS NOT NULL OFFSET {max(n // 2, 0)} LIMIT 1')
|
|
93
|
+
cache[key] = got[0]["v"] if got else None
|
|
94
|
+
except QueryError:
|
|
95
|
+
cache[key] = None
|
|
96
|
+
if cache[key] is None:
|
|
97
|
+
return None, "no_value_in_sandbox"
|
|
98
|
+
values[p] = cache[key] if op in ("limit", "offset") else _literal(cache[key], op)
|
|
99
|
+
text = info["text"]
|
|
100
|
+
sql, _ = A.prepare_sql(text)
|
|
101
|
+
|
|
102
|
+
def change(part: str) -> str:
|
|
103
|
+
for p, v in sorted(values.items(), key=lambda kv: -len(kv[0])):
|
|
104
|
+
if p.startswith("$"):
|
|
105
|
+
part = re.sub(re.escape(p) + r"(?!\d)", v, part)
|
|
106
|
+
elif p.startswith(":"):
|
|
107
|
+
part = re.sub(r"(?<![:\w])" + re.escape(p) + r"\b", v, part)
|
|
108
|
+
elif p == "?":
|
|
109
|
+
part = re.sub(r"(?<![\w?])\?(?![\w?|&-])", v, part)
|
|
110
|
+
return part
|
|
111
|
+
return {"sql": outside_quotes(sql, change), "params": {}, "how": "bound_here",
|
|
112
|
+
"values_from": "the sandbox table's middle row (generated data); LIMIT 100, OFFSET 0"}, ""
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def runnable_of(sb, info: dict, by_site: dict, by_hash: dict, profile: dict, loaded: set[str], cache: dict, allow_bind: bool) -> tuple[dict | None, str]:
|
|
116
|
+
from . import fidelity
|
|
117
|
+
c = by_hash.get(str(info.get("hash"))) if info.get("hash") else None
|
|
118
|
+
c = c or next((by_site[s] for s in info.get("site_ids") or [] if s in by_site), None)
|
|
119
|
+
if c is not None:
|
|
120
|
+
if not {A.short(t) for t in c.get("tables") or []} <= loaded:
|
|
121
|
+
return None, "table_not_loaded"
|
|
122
|
+
return {"sql": c["baseline_sql"], "params": fidelity.params_of(c, profile or {}), "how": "candidate", "finding": c["finding"]}, ""
|
|
123
|
+
if not allow_bind:
|
|
124
|
+
return None, "not_a_candidate"
|
|
125
|
+
return bind(sb, info, loaded, cache)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _index_only(m: Measurement | None, name: str) -> bool:
|
|
129
|
+
return bool(m and m.ok and any(s.get("node") == "Index Only Scan" and A.short(s.get("index")) == name.lower() for s in getattr(m, "scans", []) or []))
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _uses(m: Measurement | None, name: str) -> bool:
|
|
133
|
+
return bool(m and m.ok and (any(A.short(s.get("index")) == name.lower() for s in getattr(m, "scans", []) or [])
|
|
134
|
+
or name.lower() in (m.explain or "").lower()))
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _verdict(sb, base: Measurement, m: Measurement, match, compared: str, rows_only: bool) -> tuple[str, str]:
|
|
138
|
+
why = compared.removeprefix("not compared: ") if match is None else ""
|
|
139
|
+
return bench_mod.verdict(base, m, True, rows_only, sb.floor_bytes, sb.floor_rows, match=match, why=why, pages_decide=True)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def touch(sb, table: str, share: float) -> dict:
|
|
143
|
+
"""Rewrite the rows of `share` of the table's heap pages without VACUUM: their pages are no longer all-visible."""
|
|
144
|
+
q = sb._q(table)
|
|
145
|
+
cols = sb.rows(f"SELECT a.attname AS name FROM pg_attribute a WHERE a.attrelid = '{q}'::regclass AND a.attnum > 0 AND NOT a.attisdropped "
|
|
146
|
+
"AND a.attgenerated = '' AND a.attidentity = '' AND NOT EXISTS (SELECT 1 FROM pg_index i WHERE i.indrelid = a.attrelid "
|
|
147
|
+
"AND a.attnum = ANY(i.indkey)) ORDER BY a.attnum LIMIT 1")
|
|
148
|
+
if not cols:
|
|
149
|
+
cols = sb.rows(f"SELECT a.attname AS name FROM pg_attribute a WHERE a.attrelid = '{q}'::regclass AND a.attnum > 0 AND NOT a.attisdropped "
|
|
150
|
+
"AND a.attgenerated = '' AND a.attidentity = '' ORDER BY a.attnum LIMIT 1")
|
|
151
|
+
if not cols:
|
|
152
|
+
return {"touched": False, "reason": "no_column_to_rewrite"}
|
|
153
|
+
c = '"' + cols[0]["name"].replace('"', '""') + '"'
|
|
154
|
+
pct = max(min(share * 100.0, 100.0), 0.0)
|
|
155
|
+
for name in list((getattr(sb, "loaded", None) or {})):
|
|
156
|
+
if A.short(name) == A.short(table):
|
|
157
|
+
sb.loaded.pop(name, None) # rewritten rows: a later bench of the run loads it again (bench.load_tables)
|
|
158
|
+
sb.execute(f"UPDATE {q} SET {c} = {c} WHERE ctid = ANY(ARRAY(SELECT ctid FROM {q} TABLESAMPLE SYSTEM ({pct:g}) REPEATABLE (7)))")
|
|
159
|
+
sb.execute(f"ANALYZE {q}")
|
|
160
|
+
vm = sb.rows(f"SELECT relpages AS pages, relallvisible AS all_visible FROM pg_class WHERE oid = '{q}'::regclass")[0]
|
|
161
|
+
pages = int(vm.get("pages") or 0)
|
|
162
|
+
return {"touched": True, "share_setting": share, "pages": pages, "all_visible_pages": int(vm.get("all_visible") or 0),
|
|
163
|
+
"all_visible_share": round(int(vm.get("all_visible") or 0) / pages, 4) if pages else None, "column_rewritten": cols[0]["name"]}
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def run_table(sb, table: str, suggestions: list[dict], doc: dict, by_site: dict, by_hash: dict, profile: dict, loaded: set[str], runs: int,
|
|
167
|
+
cfg: dict, insert_settings: dict | None, log) -> dict[str, dict]:
|
|
168
|
+
"""Every suggestion on one loaded table: {suggestion id: record}."""
|
|
169
|
+
from . import writecost
|
|
170
|
+
infos = {i["ref"]: i for i in doc.get("statements") or []}
|
|
171
|
+
trow = next((t for t in doc.get("tables") or [] if A.short(t["table"]) == table), {})
|
|
172
|
+
cache: dict = {}
|
|
173
|
+
forms: dict[str, tuple[dict | None, str]] = {}
|
|
174
|
+
bases: dict[str, Measurement] = {}
|
|
175
|
+
compares: dict[str, bench_mod.Comparison] = {}
|
|
176
|
+
out: dict[str, dict] = {}
|
|
177
|
+
|
|
178
|
+
def form(ref: str) -> tuple[dict | None, str]:
|
|
179
|
+
if ref not in forms:
|
|
180
|
+
info = infos.get(ref)
|
|
181
|
+
forms[ref] = runnable_of(sb, info, by_site, by_hash, profile, loaded, cache, cfg["bind_code_statements"]) if info else (None, "unknown")
|
|
182
|
+
return forms[ref]
|
|
183
|
+
|
|
184
|
+
def baseline(ref: str) -> Measurement | None:
|
|
185
|
+
f, _ = form(ref)
|
|
186
|
+
if f is None:
|
|
187
|
+
return None
|
|
188
|
+
if ref not in bases:
|
|
189
|
+
bases[ref] = sb.measure(f["sql"], f["params"], runs)
|
|
190
|
+
compares[ref] = bench_mod.Comparison(sb, {"baseline_sql": f["sql"]}, bases[ref], f["params"])
|
|
191
|
+
return bases[ref]
|
|
192
|
+
|
|
193
|
+
vm_wanted: list[tuple[dict, list[str]]] = []
|
|
194
|
+
for s in suggestions:
|
|
195
|
+
started = time.monotonic()
|
|
196
|
+
served = [x["statement"] for x in s.get("serves") or []]
|
|
197
|
+
others = [r for r in trow.get("statement_refs") or [] if r not in served]
|
|
198
|
+
cap = int(cfg["max_measured_per_suggestion"])
|
|
199
|
+
refs = served[:cap] + others[:max(cap - len(served), 0)]
|
|
200
|
+
rec = {**_ident(s), "statements": [], "claimed_not_measured": []}
|
|
201
|
+
for ref in refs:
|
|
202
|
+
f, why = form(ref)
|
|
203
|
+
if f is None:
|
|
204
|
+
if ref in served:
|
|
205
|
+
rec["claimed_not_measured"].append({"statement": ref, "why": why})
|
|
206
|
+
continue
|
|
207
|
+
b = baseline(ref)
|
|
208
|
+
measured_refs = [r for r in refs if r in bases and bases[r].ok]
|
|
209
|
+
failed = [r for r in refs if r in bases and not bases[r].ok]
|
|
210
|
+
name = s["name"]
|
|
211
|
+
variant = {"sql": "", "setup_sql": s["ddl"], "same_results": True}
|
|
212
|
+
try:
|
|
213
|
+
sb.apply_setup(s["ddl"])
|
|
214
|
+
except QueryError as e:
|
|
215
|
+
rec["skip"] = "sandbox_could_not_run"
|
|
216
|
+
rec["error_class"] = _error_class(str(e))
|
|
217
|
+
out[_key(s)] = rec
|
|
218
|
+
log(f"{s['id']} {name}: the index could not be built: {str(e).splitlines()[0][:160]}")
|
|
219
|
+
continue
|
|
220
|
+
try:
|
|
221
|
+
# a partitioned table's index is a parent (relkind I) over one index per partition: their sizes add up
|
|
222
|
+
size = sb.rows(f"SELECT coalesce(sum(pg_relation_size(x.oid)), 0) AS bytes FROM pg_class c, LATERAL (SELECT c.oid UNION "
|
|
223
|
+
f"SELECT relid FROM pg_partition_tree(c.oid)) x WHERE c.relname = '{name.lower()}' AND c.relkind IN ('i', 'I')")
|
|
224
|
+
rec["index_bytes"] = int(size[0]["bytes"]) if size else None
|
|
225
|
+
afters, pending = {}, {}
|
|
226
|
+
for ref in measured_refs:
|
|
227
|
+
f, _ = form(ref)
|
|
228
|
+
m = sb.measure(f["sql"], f["params"], runs)
|
|
229
|
+
afters[ref] = m
|
|
230
|
+
pending[ref] = compares[ref].with_setup({**variant, "sql": f["sql"]}, m)
|
|
231
|
+
finally:
|
|
232
|
+
sb.undo_setup(s["ddl"])
|
|
233
|
+
index_only_refs = []
|
|
234
|
+
for ref in measured_refs:
|
|
235
|
+
f, _ = form(ref)
|
|
236
|
+
base, m = bases[ref], afters[ref]
|
|
237
|
+
match, compared = compares[ref].settle({**variant, "sql": f["sql"]}, m, pending[ref])
|
|
238
|
+
v, reason = _verdict(sb, base, m, match, compared, compares[ref].rows_only)
|
|
239
|
+
row = {"statement": ref, "serves": ref in served, "how": f["how"], **({"finding": f["finding"]} if f.get("finding") else {}),
|
|
240
|
+
**({"values_from": f["values_from"]} if f.get("values_from") else {}),
|
|
241
|
+
"before": _numbers(base), "after": _numbers(m), "verdict": v, "reason": reason, "results_match": match if m.ok else None,
|
|
242
|
+
"compared": compared, "uses_index": _uses(m, name), "index_only": _index_only(m, name),
|
|
243
|
+
# local only: what `codecop apply` confirms the index with (never uploaded)
|
|
244
|
+
"run_sql": f["sql"], "run_params": f["params"]}
|
|
245
|
+
if ref not in served and m.ok and base.read_bytes > sb.floor_bytes and m.read_bytes > cfg["regression_ratio"] * base.read_bytes:
|
|
246
|
+
row["regressed"] = True
|
|
247
|
+
row["verdict"] = "slower"
|
|
248
|
+
if row["index_only"] and ref in served:
|
|
249
|
+
index_only_refs.append(ref)
|
|
250
|
+
rec["statements"].append(row)
|
|
251
|
+
for ref in failed:
|
|
252
|
+
rec["statements"].append({"statement": ref, "serves": ref in served, "verdict": "failed", "how": form(ref)[0]["how"], "reason": bases[ref].error[:240],
|
|
253
|
+
"before": _numbers(bases[ref])})
|
|
254
|
+
if any(r.get("serves") and r.get("verdict") in ("win", "mixed") for r in rec["statements"]):
|
|
255
|
+
ic = writecost.measure_postgres(sb, sb._name(s["table"]), s["ddl"], insert_settings)
|
|
256
|
+
rec["write_cost"] = ic
|
|
257
|
+
if ic.get("measured"):
|
|
258
|
+
log(f"{s['id']} {name}: insert side x{ic.get('insert_time_ratio')} time, x{ic.get('wal_bytes_ratio')} WAL, "
|
|
259
|
+
f"x{ic.get('storage_ratio')} size over {ic['rows']:,} rows")
|
|
260
|
+
if index_only_refs and float(cfg["vm_touch_share"]) > 0:
|
|
261
|
+
vm_wanted.append((rec, index_only_refs, s))
|
|
262
|
+
rec["seconds"] = round(time.monotonic() - started, 1)
|
|
263
|
+
out[_key(s)] = rec
|
|
264
|
+
won = sum(1 for r in rec["statements"] if r.get("serves") and r["verdict"] == "win")
|
|
265
|
+
log(f"{s['id']} {name}: {won} of {len(served)} statements it serves read less "
|
|
266
|
+
f"({len(rec['claimed_not_measured'])} claimed, not measured)")
|
|
267
|
+
if vm_wanted:
|
|
268
|
+
_visibility_pass(sb, table, vm_wanted, form, compares, runs, cfg, log)
|
|
269
|
+
return out
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _visibility_pass(sb, table: str, wanted: list, form, compares, runs: int, cfg: dict, log) -> None:
|
|
273
|
+
"""The index-only claims measured again with `vm_touch_share` of the heap pages not all-visible; VACUUM after."""
|
|
274
|
+
real = sb._name(table)
|
|
275
|
+
try:
|
|
276
|
+
state = touch(sb, real, float(cfg["vm_touch_share"]))
|
|
277
|
+
except QueryError as e:
|
|
278
|
+
for rec, refs, s in wanted:
|
|
279
|
+
rec["visibility"] = {"measured": False, "reason": "server_error", "error": str(e)[:200]}
|
|
280
|
+
return
|
|
281
|
+
try:
|
|
282
|
+
touched_base: dict[str, Measurement] = {}
|
|
283
|
+
for rec, refs, s in wanted:
|
|
284
|
+
for ref in refs:
|
|
285
|
+
if ref not in touched_base:
|
|
286
|
+
f, _ = form(ref)
|
|
287
|
+
touched_base[ref] = sb.measure(f["sql"], f["params"], runs)
|
|
288
|
+
afters = {}
|
|
289
|
+
try:
|
|
290
|
+
sb.apply_setup(s["ddl"])
|
|
291
|
+
for ref in refs:
|
|
292
|
+
f, _ = form(ref)
|
|
293
|
+
afters[ref] = sb.measure(f["sql"], f["params"], runs)
|
|
294
|
+
except QueryError as e:
|
|
295
|
+
rec["visibility"] = {"measured": False, "reason": "server_error", "error": str(e)[:200]}
|
|
296
|
+
continue
|
|
297
|
+
finally:
|
|
298
|
+
sb.undo_setup(s["ddl"])
|
|
299
|
+
rec["visibility"] = {"measured": True, **state, "rule": "the verdict of an index-only read is its run with these pages not all-visible"}
|
|
300
|
+
for row in rec["statements"]:
|
|
301
|
+
if row["statement"] in afters:
|
|
302
|
+
base, m = touched_base[row["statement"]], afters[row["statement"]]
|
|
303
|
+
match = row.get("results_match")
|
|
304
|
+
v, reason = _verdict(sb, base, m, match, row.get("compared") or "", compares[row["statement"]].rows_only)
|
|
305
|
+
row["before_touched"], row["after_touched"] = _numbers(base), _numbers(m)
|
|
306
|
+
row["honest_verdict"], row["honest_reason"] = v, reason
|
|
307
|
+
row["fresh_verdict"] = row["verdict"]
|
|
308
|
+
log(f"{s['id']}: index-only reads measured again with {state.get('all_visible_share')} of the pages all-visible")
|
|
309
|
+
finally:
|
|
310
|
+
try:
|
|
311
|
+
sb.execute(f"VACUUM (ANALYZE) {sb._q(real)}")
|
|
312
|
+
except QueryError:
|
|
313
|
+
pass
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def _error_class(text: str) -> str:
|
|
317
|
+
from .blockers import error_class
|
|
318
|
+
return error_class(text, "postgres")
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def _key(s: dict) -> str:
|
|
322
|
+
"""What a record is filed under: the suggestion's fingerprint (stable across runs), its id for an older file."""
|
|
323
|
+
return s.get("fingerprint") or s["id"]
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def _ident(s: dict) -> dict:
|
|
327
|
+
return {"id": s["id"], "fingerprint": s.get("fingerprint"), "name": s.get("name"), "table": s.get("table")}
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def after_scale(doc: dict, rank: dict, runs: int, largest: float, settings: dict | None = None, insert_settings: dict | None = None,
|
|
331
|
+
log=lambda m: None, on_record=None):
|
|
332
|
+
"""The hook bench.run calls per load group and scale; it runs at the largest scale only. Its results are in
|
|
333
|
+
`hook.results` (suggestion fingerprint -> record) for `results_into`; `hook.loaded` the tables it saw built.
|
|
334
|
+
`on_record(results)` is called after each table, so a caller can keep the records written while the bench runs."""
|
|
335
|
+
cfg = A.settings_of(settings)
|
|
336
|
+
by_site, by_hash = candidate_maps(rank)
|
|
337
|
+
results: dict[str, dict] = {}
|
|
338
|
+
seen_loaded: set[str] = set()
|
|
339
|
+
budget = float(cfg.get("max_bench_seconds") or 0)
|
|
340
|
+
spent = [0.0]
|
|
341
|
+
|
|
342
|
+
def hook(sb, tables, profile, fraction, findings=None):
|
|
343
|
+
if fraction + 1e-9 < largest or getattr(sb, "engine", "") != "postgres":
|
|
344
|
+
return None
|
|
345
|
+
loaded = {A.short(t["name"]) for t in tables if t.get("ok")}
|
|
346
|
+
seen_loaded.update(loaded)
|
|
347
|
+
failed = {A.short(t["name"]): t for t in tables if not t.get("ok")}
|
|
348
|
+
by_table: dict[str, list[dict]] = {}
|
|
349
|
+
for s in doc.get("table_suggestions") or []:
|
|
350
|
+
t = A.short(s["table"])
|
|
351
|
+
if _key(s) in results:
|
|
352
|
+
continue
|
|
353
|
+
if t in failed:
|
|
354
|
+
results[_key(s)] = {**_ident(s), "skip": "sandbox_table_not_loaded", "error_class": _error_class(failed[t].get("error") or "")}
|
|
355
|
+
elif t in loaded:
|
|
356
|
+
by_table.setdefault(t, []).append(s)
|
|
357
|
+
for t, suggs in by_table.items():
|
|
358
|
+
if budget and spent[0] >= budget:
|
|
359
|
+
for s in suggs:
|
|
360
|
+
results.setdefault(_key(s), {**_ident(s), "skip": "advisor_time_budget", "error_class": "time_budget"})
|
|
361
|
+
continue
|
|
362
|
+
log(f"advisor: {len(suggs)} index suggestion(s) on {t} built and measured as a set")
|
|
363
|
+
began = time.monotonic()
|
|
364
|
+
try:
|
|
365
|
+
results.update(run_table(sb, t, suggs, doc, by_site, by_hash, profile, loaded, runs, cfg, insert_settings, log))
|
|
366
|
+
except SandboxError as e:
|
|
367
|
+
why = sb.revive() if hasattr(sb, "revive") else ""
|
|
368
|
+
for s in suggs:
|
|
369
|
+
results.setdefault(_key(s), {**_ident(s), "skip": "sandbox_could_not_run", "error_class": "server_stopped",
|
|
370
|
+
"error": (why or str(e))[:200]})
|
|
371
|
+
spent[0] += time.monotonic() - began
|
|
372
|
+
if budget and spent[0] >= budget:
|
|
373
|
+
log(f"advisor: time budget of {budget:g} s spent ([advisor] max_bench_seconds); the other suggestions are listed, not measured")
|
|
374
|
+
if on_record is not None:
|
|
375
|
+
on_record(results)
|
|
376
|
+
return None
|
|
377
|
+
hook.results = results
|
|
378
|
+
hook.loaded = seen_loaded
|
|
379
|
+
return hook
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def bench_record(results: dict[str, dict], largest: float, loaded: set[str] | None, complete: bool) -> dict:
|
|
383
|
+
"""What bench.json keeps under `advisor` for this advisor: the records of the largest scale, the tables built there
|
|
384
|
+
(a suggestion on a table not among them was never built) and whether the bench finished."""
|
|
385
|
+
return {"schema_version": A.SCHEMA_VERSION, "engine": A.ENGINE, "complete": complete,
|
|
386
|
+
"scales": [{"fraction": largest, "results": list(results.values())}],
|
|
387
|
+
"loaded": sorted(loaded) if loaded is not None else None}
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def apply_record(doc: dict, record: dict | None, insert_settings: dict | None = None) -> dict:
|
|
391
|
+
"""advisor.json with a bench record's measurements (`bench_record`, from bench.json or the record written while a
|
|
392
|
+
bench ran). Without a record every suggestion is "not benchmarked yet". A record of a bench that did not finish
|
|
393
|
+
judges what it measured; the rest stays not benchmarked."""
|
|
394
|
+
if not record:
|
|
395
|
+
return results_into(doc, {}, bench_ran=False, insert_settings=insert_settings)
|
|
396
|
+
results: dict[str, dict] = {}
|
|
397
|
+
for sc in record.get("scales") or []:
|
|
398
|
+
for r in sc.get("results") or []:
|
|
399
|
+
# a record of this version is matched by fingerprint only (ids are places in one run); an older one by its
|
|
400
|
+
# index name
|
|
401
|
+
for k in ((r.get("fingerprint"),) if r.get("fingerprint") else (r.get("name"),)):
|
|
402
|
+
if k:
|
|
403
|
+
results[k] = r
|
|
404
|
+
# a record rebuilt from an older advisor.json covers the suggestions of that file only: one it does not know was not run
|
|
405
|
+
complete = record.get("complete") is not False and record.get("from") != "advisor.json"
|
|
406
|
+
loaded = set(record["loaded"]) if complete and isinstance(record.get("loaded"), list) else None
|
|
407
|
+
return results_into(doc, results, bench_ran=complete, insert_settings=insert_settings, loaded=loaded)
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def record_of_doc(doc: dict | None) -> dict | None:
|
|
411
|
+
"""A bench record rebuilt from an advisor.json the bench wrote before bench.json kept one: each suggestion's
|
|
412
|
+
measurement, filed under its index name."""
|
|
413
|
+
if not doc or not any(s.get("measured") for s in doc.get("table_suggestions") or []):
|
|
414
|
+
return None
|
|
415
|
+
results = [{**s["measured"], "name": s.get("name"), "fingerprint": s.get("fingerprint")} for s in doc["table_suggestions"] if s.get("measured")]
|
|
416
|
+
return {"schema_version": A.SCHEMA_VERSION, "engine": A.ENGINE, "complete": bool((doc.get("bench") or {}).get("ran")),
|
|
417
|
+
"scales": [{"fraction": None, "results": results}], "loaded": None, "from": "advisor.json"}
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
def chain(*hooks):
|
|
421
|
+
"""Several after_scale hooks as one: the first one's return value is the scale's `groups`."""
|
|
422
|
+
live = [h for h in hooks if h is not None]
|
|
423
|
+
if not live:
|
|
424
|
+
return None
|
|
425
|
+
|
|
426
|
+
def hook(sb, tables, profile, fraction, findings=None):
|
|
427
|
+
first = None
|
|
428
|
+
for i, h in enumerate(live):
|
|
429
|
+
got = h(sb, tables, profile, fraction, findings=findings)
|
|
430
|
+
if i == 0:
|
|
431
|
+
first = got
|
|
432
|
+
return first
|
|
433
|
+
return hook
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
def results_into(doc: dict, results: dict[str, dict], bench_ran: bool, insert_settings: dict | None = None,
|
|
437
|
+
loaded: set[str] | None = None) -> dict:
|
|
438
|
+
"""advisor.json with each suggestion's measurements, gain, cost and verdict. `loaded`: the tables the bench built at
|
|
439
|
+
its largest scale (a suggestion on a table the profile does not describe was never built)."""
|
|
440
|
+
for s in doc.get("table_suggestions") or []:
|
|
441
|
+
rec = next((results[k] for k in (s.get("fingerprint"), s.get("name")) if k and k in results), None)
|
|
442
|
+
if rec is None and not s.get("fingerprint"):
|
|
443
|
+
rec = results.get(s["id"])
|
|
444
|
+
if rec is None and bench_ran and loaded is not None and A.short(s["table"]) not in loaded:
|
|
445
|
+
rec = {**_ident(s), "skip": "sandbox_table_not_loaded", "error_class": "not_in_profile"}
|
|
446
|
+
s["measured"] = rec
|
|
447
|
+
if rec and not rec.get("skip"):
|
|
448
|
+
rows = {r["statement"]: r for r in rec.get("statements") or []}
|
|
449
|
+
for x in s.get("serves") or []:
|
|
450
|
+
r = rows.get(x["statement"])
|
|
451
|
+
if r:
|
|
452
|
+
x.update({k: r.get(k) for k in ("before", "after", "verdict", "reason", "results_match", "index_only", "honest_verdict",
|
|
453
|
+
"before_touched", "after_touched", "how", "finding", "uses_index") if k in r})
|
|
454
|
+
x["role"] = "measured"
|
|
455
|
+
else:
|
|
456
|
+
x["role"] = "claimed"
|
|
457
|
+
x["why_not_measured"] = next((c["why"] for c in rec.get("claimed_not_measured") or [] if c["statement"] == x["statement"]), "")
|
|
458
|
+
s["not_served_checked"] = [{k: r.get(k) for k in ("statement", "before", "after", "verdict", "regressed", "uses_index")}
|
|
459
|
+
for r in rec.get("statements") or [] if not r.get("serves")]
|
|
460
|
+
s["read_gain"] = read_gain(s)
|
|
461
|
+
s["write_cost"] = rec.get("write_cost")
|
|
462
|
+
s["size"] = {"index_bytes": rec.get("index_bytes"), "at": "sandbox scale"} if rec.get("index_bytes") is not None else None
|
|
463
|
+
s["visibility"] = rec.get("visibility")
|
|
464
|
+
else:
|
|
465
|
+
for x in s.get("serves") or []:
|
|
466
|
+
x["role"] = "claimed"
|
|
467
|
+
x["why_not_measured"] = (rec or {}).get("skip") or ("no_runnable_form" if bench_ran else "bench_not_run")
|
|
468
|
+
s["verdict"] = A.verdict_of(s, rec, insert_settings, bench_ran)
|
|
469
|
+
doc["summary"] = A.summarize(doc)
|
|
470
|
+
doc["bench"] = {"ran": bench_ran}
|
|
471
|
+
return doc
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
def read_gain(s: dict) -> dict | None:
|
|
475
|
+
"""Pages before and after over the served statements that were measured (the honest run for index-only reads),
|
|
476
|
+
and the weighted share of pages saved."""
|
|
477
|
+
rows = [x for x in s.get("serves") or [] if x.get("role") == "measured" and (x.get("before") or {}).get("ok") and (x.get("after") or {}).get("ok")]
|
|
478
|
+
if not rows:
|
|
479
|
+
return None
|
|
480
|
+
before = after = 0
|
|
481
|
+
wsum = saved = 0.0
|
|
482
|
+
for x in rows:
|
|
483
|
+
b = x.get("before_touched") or x["before"]
|
|
484
|
+
a = x.get("after_touched") or x["after"]
|
|
485
|
+
before += int(b.get("pages") or 0)
|
|
486
|
+
after += int(a.get("pages") or 0)
|
|
487
|
+
if b.get("pages"):
|
|
488
|
+
wsum += float(x.get("weight") or 0)
|
|
489
|
+
saved += float(x.get("weight") or 0) * (1 - int(a.get("pages") or 0) / int(b["pages"]))
|
|
490
|
+
return {"pages_before": before, "pages_after": after, "ratio": round(after / before, 4) if before else None,
|
|
491
|
+
"weighted_share_saved": round(saved / wsum, 4) if wsum else None, "statements_measured": len(rows),
|
|
492
|
+
"statements_won": sum(1 for x in rows if (x.get("honest_verdict") or x.get("verdict")) == "win"),
|
|
493
|
+
"statements_claimed": sum(1 for x in s.get("serves") or [] if x.get("role") != "measured")}
|