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_view.py
ADDED
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
"""How the access-path advisors are shown, both engines through one view: the CLI lines and the report section.
|
|
2
|
+
|
|
3
|
+
Everything here reads the shared shape (advisors.shared: run_bundle.schema.json $defs.table_suggestion) plus each
|
|
4
|
+
advisor's table rows. Per table, one suggestion per row: the change, the statements it serves drawn as bars (what each
|
|
5
|
+
read with the change against what it read before; a dashed bar for a statement claimed but not measured), the gain
|
|
6
|
+
beside the cost (insert time with its measured spread, storage), and the state. Nothing is called a win unless the
|
|
7
|
+
sandbox verified it; a trade-off is never one."""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import html
|
|
12
|
+
|
|
13
|
+
from . import advisors
|
|
14
|
+
|
|
15
|
+
STATE_LABEL = {"fixed": "Fixed", "blocked": "Needs another fix", "not_judged": "Could not be judged", "nothing_to_gain": "Nothing to gain"}
|
|
16
|
+
STATE_ORDER = {"fixed": 0, "blocked": 1, "not_judged": 2, "nothing_to_gain": 3}
|
|
17
|
+
ENGINE_LABEL = {"clickhouse": "ClickHouse", "postgres": "PostgreSQL"}
|
|
18
|
+
KIND_LABEL = {"skip_index": "skip index", "projection": "projection", "aggregating_projection": "aggregating projection",
|
|
19
|
+
"ordering_key": "new sorting key", "dedup_on_read": "FINAL rewrite", "index": "index", "partial_index": "partial index",
|
|
20
|
+
"covering_index": "covering index (INCLUDE)", "expression_index": "expression index"}
|
|
21
|
+
RULE_LABEL = {"prewhere_keys": "key filters in PREWHERE", "filter_into_final": "filters into the FINAL subquery",
|
|
22
|
+
"per_partition_final": "FINAL per partition", "limit_1_by": "LIMIT 1 BY the key", "argmax": "argMax by the key",
|
|
23
|
+
"drop_final": "FINAL dropped"}
|
|
24
|
+
LOCALITY_LABEL = {"sorting_key": "placement: sorting key", "time_parts": "placement: parts cut by time", "profile_expression": "placement: profile expression",
|
|
25
|
+
"unique_values": "placement does not matter (unique values)", "catalog_only": "placement unknown (catalog values only)",
|
|
26
|
+
"agent_values": "placement unknown (profile values only)", "unknown": "placement unknown"}
|
|
27
|
+
REASON_WORDS = {
|
|
28
|
+
"verified": "reads less on the statements it serves, the same rows, the insert side within the limits",
|
|
29
|
+
"fix_costs_inserts": "reads less, but costs inserts above the limits: a trade-off",
|
|
30
|
+
"insert_cost_near_limit": "reads less; insert cost near the limit: the measured spread of the insert time crosses it (a trade-off)",
|
|
31
|
+
"fix_results_differ": "a statement returned other rows with it",
|
|
32
|
+
"regresses_other_statements": "another statement of the table reads more with it",
|
|
33
|
+
"no_variant_reads_less": "measured: the statements it serves read no less",
|
|
34
|
+
"engine_did_not_use_it": "the server did not use it for the statements it was built for",
|
|
35
|
+
"skip_index_locality_unknown": "could not be judged on generated data: where the column's values sit in production is not known",
|
|
36
|
+
"claimed_not_measured": "no statement it serves has a runnable form: claimed, not measured",
|
|
37
|
+
"insert_cost_not_measured": "reads less, but its insert side could not be measured",
|
|
38
|
+
"sandbox_could_not_run": "the sandbox could not build it or run a statement",
|
|
39
|
+
"sandbox_table_not_loaded": "the table could not be built in the sandbox",
|
|
40
|
+
"bench_not_run": "not benchmarked yet",
|
|
41
|
+
"a_projection_serves_it": "a projection with the same order serves the same statements, for less",
|
|
42
|
+
"already_cheap_measured": "the statements it serves already read little",
|
|
43
|
+
"not_usable_as_written": "the statements bound a column the projection does not keep: the engine can not use it",
|
|
44
|
+
"parameters_match_no_rows": "the statements it serves read nothing on the sandbox: their values match no rows there",
|
|
45
|
+
"sameness_not_shown": "reads less, the same rows not shown",
|
|
46
|
+
"measured_on_production": "Read side measured on production (simulated), insert side verified",
|
|
47
|
+
"production_floor": "counted on production: the statements already read only granules that hold their rows",
|
|
48
|
+
"production_counts_disagree": "could not be judged: the sandbox's marks and production's row counts disagree",
|
|
49
|
+
"table_too_small": "nothing to gain: the table is read whole in a few granules (counted on production's catalog, no statement sent)",
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def production_text(s: dict) -> str:
|
|
54
|
+
"""What production's counts say (realdb/locality.py), in the report's words: never a win, the spread always shown."""
|
|
55
|
+
ed = s.get("engine_detail") or {}
|
|
56
|
+
p = ed.get("production") or {}
|
|
57
|
+
if p.get("status") != "answered" or p.get("ratio") is None:
|
|
58
|
+
return ""
|
|
59
|
+
over = p.get("counted_over") or {}
|
|
60
|
+
sp = p.get("spread") or {}
|
|
61
|
+
window = (f"the last {p['window_hours']:g} h" + (" (assumed: the statement's bound is a parameter)" if "assumed" in str(p.get("window_basis")) else "")
|
|
62
|
+
if p.get("window_hours") else "any time (the statement has no time bound)")
|
|
63
|
+
where = f"{over.get('parts')} part(s), {int(over.get('rows') or 0):,} rows" + (" (not every part in scope)" if over.get("cut") else "")
|
|
64
|
+
est = " An estimate: granules from the rows per mark (the server is older than 25.8)." if p.get("estimate") else ""
|
|
65
|
+
if s["kind"] in ("projection", "aggregating_projection", "ordering_key"):
|
|
66
|
+
second = (s.get("read_gain") or {}).get("read_ratio_typical") is not None
|
|
67
|
+
return (("Production's row counts, a second opinion: " if second else "Estimate from row counts on production: ")
|
|
68
|
+
+ f"about x{p['ratio']:g} of the marks the key selects now (rows of the new key's prefix a part, rounded up to granules; "
|
|
69
|
+
f"draws x{sp.get('draw_min')}–x{sp.get('draw_max')}), over {p.get('probes')} values from {window} in {where}."
|
|
70
|
+
+ ("" if second else " Not run.") + est)
|
|
71
|
+
what_ = f"{ed.get('type')} on {ed.get('expr') or ed.get('column')}"
|
|
72
|
+
if p.get("by_rank"):
|
|
73
|
+
ranks = ", ".join(f"rank {r['rank']} ({pct(r.get('share'))} of rows): x{r['ratio']}" for r in p["by_rank"] if r.get("ratio") is not None)
|
|
74
|
+
detail = f"per value by frequency: {ranks}"
|
|
75
|
+
elif p.get("thresholds"):
|
|
76
|
+
detail = "per threshold: " + ", ".join(f"{t['threshold']}: x{t['ratio']}" for t in p["thresholds"] if t.get("ratio") is not None)
|
|
77
|
+
else:
|
|
78
|
+
detail = (f"over all {p.get('probes')}: x{p['ratio']:g}; draws x{sp.get('draw_min')}–x{sp.get('draw_max')}"
|
|
79
|
+
+ (f"; for a tenth of the values x{sp['probe_p10']} or less, for a tenth x{sp['probe_p90']} or more"
|
|
80
|
+
if sp.get("probe_p10") is not None and sp.get("probe_p90") is not None else ""))
|
|
81
|
+
floor = f" Granules that hold a matching row: x{p['floor']:g}." if p.get("floor") is not None else ""
|
|
82
|
+
return (f"Not built. Counted on production over values drawn from rows of {window} in {where}: {what_} would leave "
|
|
83
|
+
f"x{p['ratio']:g} of the granules the key selects now ({detail}).{floor} Granules, not seconds; the result depends on "
|
|
84
|
+
f"which values production asks for.{est}")
|
|
85
|
+
HYGIENE_WORDS = {"duplicate_index": "duplicate", "redundant_prefix_index": "left prefix of another", "invalid_index": "invalid (failed build)",
|
|
86
|
+
"unused_index": "no scan since statistics began"}
|
|
87
|
+
PLAN_MARK = "<!--codecop-plan:{}-->"
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _e(x) -> str:
|
|
91
|
+
return html.escape(str(x if x is not None else ""))
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _tag(text, cls="") -> str:
|
|
95
|
+
return f"<span class='tag {_e(cls)}'>{_e(text)}</span>"
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def human_bytes(n) -> str:
|
|
99
|
+
n = float(n or 0)
|
|
100
|
+
for unit, size in (("TB", 1e12), ("GB", 1e9), ("MB", 1e6), ("kB", 1e3)):
|
|
101
|
+
if abs(n) >= size:
|
|
102
|
+
return f"{n / size:.1f} {unit}"
|
|
103
|
+
return f"{n:.0f} B"
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def pct(share) -> str:
|
|
107
|
+
if share is None:
|
|
108
|
+
return "-"
|
|
109
|
+
v = share * 100
|
|
110
|
+
return f"{v:.1f}%" if v >= 0.1 or v == 0 else "under 0.1%"
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _state(s: dict) -> str:
|
|
114
|
+
return (s.get("outcome") or {}).get("state") or ""
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
# ---- the tables -----------------------------------------------------------------------------------------------------
|
|
118
|
+
|
|
119
|
+
def table_rows(stage: dict | None) -> list[dict]:
|
|
120
|
+
"""Each advisor's tables as one row shape: {engine, table, facts, statements, load, load_text}."""
|
|
121
|
+
out = []
|
|
122
|
+
for eng, doc in advisors.docs(stage):
|
|
123
|
+
weights = (doc.get("basis") or {}).get("weights") or "static"
|
|
124
|
+
for t in doc.get("tables") or []:
|
|
125
|
+
if eng == "clickhouse":
|
|
126
|
+
facts = f"key ({', '.join(t.get('sorting_key') or [])})" + (f" · partition {t['partition_key']}" if t.get("partition_key") else "")
|
|
127
|
+
n = len(t.get("statements") or [])
|
|
128
|
+
load, load_text = float(t.get("read_bytes") or 0), f"{human_bytes(t.get('read_bytes'))} read ({t.get('load_basis')})"
|
|
129
|
+
else:
|
|
130
|
+
facts = f"{len(t.get('existing_indexes') or [])} indexes known ({', '.join(t.get('index_basis') or []) or 'no source'})"
|
|
131
|
+
n = int(t.get("statements") or 0)
|
|
132
|
+
load = float(t.get("weight") or 0)
|
|
133
|
+
load_text = f"{human_bytes(load)} read (measured)" if weights == "measured" else f"weight {load:g} (static: entry points and loops)"
|
|
134
|
+
out.append({"engine": eng, "table": t["table"], "facts": facts, "statements": n, "load": load, "load_text": load_text})
|
|
135
|
+
return out
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
# ---- one suggestion -----------------------------------------------------------------------------------------------
|
|
139
|
+
|
|
140
|
+
def what(s: dict) -> str:
|
|
141
|
+
ed = s.get("engine_detail") or {}
|
|
142
|
+
k = s["kind"]
|
|
143
|
+
if s.get("engine") == "postgres":
|
|
144
|
+
out = f"{ed.get('method') or 'btree'} ({', '.join(ed.get('columns') or [])})"
|
|
145
|
+
if ed.get("include"):
|
|
146
|
+
out += f" INCLUDE ({', '.join(ed['include'])})"
|
|
147
|
+
if ed.get("where"):
|
|
148
|
+
out += f" WHERE {ed['where']}"
|
|
149
|
+
return out
|
|
150
|
+
if k == "skip_index":
|
|
151
|
+
g = ed.get("granularity_chosen")
|
|
152
|
+
return f"{ed.get('type')} on {ed.get('expr')}" + (f", granularity {g}" if g else f", granularity {'/'.join(map(str, ed.get('granularities') or []))} tried")
|
|
153
|
+
if k == "projection":
|
|
154
|
+
return f"ordered by ({', '.join(ed.get('order_by') or [])}), {len(ed.get('columns') or [])} column(s)" + (" (a full copy)" if ed.get("full_copy") else "")
|
|
155
|
+
if k == "aggregating_projection":
|
|
156
|
+
return f"GROUP BY {', '.join(ed.get('group_by') or [])}: {', '.join(ed.get('aggregates') or [])}"
|
|
157
|
+
if k == "ordering_key":
|
|
158
|
+
return f"({', '.join(ed.get('new_key') or [])}) instead of ({', '.join(ed.get('old_key') or [])})"
|
|
159
|
+
return RULE_LABEL.get(ed.get("rule"), ed.get("rule") or "")
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def gain_text(s: dict) -> str:
|
|
163
|
+
g = s.get("read_gain") or {}
|
|
164
|
+
serves = s.get("serves") or []
|
|
165
|
+
n = len(serves)
|
|
166
|
+
measured = sum(1 for sv in serves if sv.get("claimed") is False)
|
|
167
|
+
share = g.get("load_share")
|
|
168
|
+
out = f"serves {n} statement{'s' if n != 1 else ''}" + (f" covering {pct(share)} of the table's read load ({g.get('load_share_basis')})" if share is not None else "")
|
|
169
|
+
if measured:
|
|
170
|
+
out += f"; {measured} measured"
|
|
171
|
+
if g.get("read_ratio_typical") is not None:
|
|
172
|
+
out += f", reads {pct(1 - g['read_ratio_typical'])} less" + (" on the typical run" if g.get("read_ratio_heavy") is not None else "")
|
|
173
|
+
if g.get("read_ratio_heavy") is not None:
|
|
174
|
+
out += f", {pct(1 - g['read_ratio_heavy'])} less on the heavy run"
|
|
175
|
+
else:
|
|
176
|
+
out += "; claimed, not measured"
|
|
177
|
+
prod = production_text(s)
|
|
178
|
+
t = (s.get("engine_detail") or {}).get("production_trial") or {}
|
|
179
|
+
if t.get("status") == "answered" and t.get("ratio") is not None:
|
|
180
|
+
prod = (prod.rstrip(".") + ". " if prod else "") + (f"Trial on one production partition: x{t['ratio']:g} of the marks per run "
|
|
181
|
+
f"over {t.get('runs_trial')} runs after the build")
|
|
182
|
+
return f"{out}. {prod.rstrip('.')}" if prod else out
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _x(v) -> str:
|
|
186
|
+
return f"x{v:g}" if isinstance(v, (int, float)) else "x-"
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def cost_text(s: dict) -> str:
|
|
190
|
+
w = s.get("write_cost") or {}
|
|
191
|
+
if w.get("measured"):
|
|
192
|
+
rng = w.get("insert_time_ratio_range")
|
|
193
|
+
spread = isinstance(rng, list) and len(rng) == 2 and rng[0] != rng[1]
|
|
194
|
+
limit = (w.get("thresholds") or {}).get("insert_cost_max_time_ratio")
|
|
195
|
+
if w.get("near_limit") and spread:
|
|
196
|
+
head = f"insert cost near the limit: inserts {_x(rng[0])} to {_x(rng[1])} over {w.get('rounds')} rounds, the limit {_x(limit)}"
|
|
197
|
+
else:
|
|
198
|
+
head = f"inserts {_x(w.get('insert_time_ratio'))}" + (f" ({_x(rng[0])} to {_x(rng[1])} over {w.get('rounds')} rounds)" if spread else "")
|
|
199
|
+
parts = [head, f"storage {_x(w.get('storage_ratio'))}"]
|
|
200
|
+
if w.get("parts_ratio") is not None:
|
|
201
|
+
parts.append(f"parts {_x(w['parts_ratio'])}")
|
|
202
|
+
if w.get("wal_bytes_ratio") is not None:
|
|
203
|
+
parts.append(f"WAL {_x(w['wal_bytes_ratio'])}")
|
|
204
|
+
return ", ".join(parts)
|
|
205
|
+
if s["kind"] == "dedup_on_read":
|
|
206
|
+
return "no table change"
|
|
207
|
+
return "insert side not measured" + (f" ({str(w.get('reason')).replace('_', ' ')})" if w.get("reason") else "")
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def reason_text(s: dict) -> str:
|
|
211
|
+
o = s.get("outcome") or {}
|
|
212
|
+
return o.get("words") or REASON_WORDS.get(o.get("reason"), str(o.get("reason") or "").replace("_", " "))
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
CSS = """
|
|
216
|
+
.adv-bars{display:grid;grid-template-columns:auto 1fr auto;gap:2px 8px;align-items:center;font-size:12px;min-width:260px}
|
|
217
|
+
.adv-bar{height:10px;background:var(--track);border-radius:3px;overflow:hidden;position:relative}
|
|
218
|
+
.adv-bar i{display:block;height:100%;background:#2f7d4f}
|
|
219
|
+
.adv-bar.worse i{background:#b3261e}.adv-bar.claimed{background:none;border:1px dashed #9aa0a6}
|
|
220
|
+
.adv-k{font-weight:600}
|
|
221
|
+
"""
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _bars(s: dict, limit: int = 8) -> str:
|
|
225
|
+
rows = []
|
|
226
|
+
for sv in (s.get("serves") or [])[:limit]:
|
|
227
|
+
label = sv.get("finding") or (sv.get("file") and f"{str(sv['file']).split('/')[-1]}:{sv.get('line')}") or str(sv.get("statement") or "")[:18]
|
|
228
|
+
share = sv.get("weight_share")
|
|
229
|
+
m = (sv.get("measured") or {}).get("typical")
|
|
230
|
+
if m and m.get("before_bytes"):
|
|
231
|
+
r = (m.get("after_bytes") or 0) / m["before_bytes"]
|
|
232
|
+
cls = "adv-bar worse" if r > 1 else "adv-bar"
|
|
233
|
+
note = f"x{r:.2f}" + ("" if sv.get("engine_used") is not False else " (not used)")
|
|
234
|
+
title = f"{human_bytes(m.get('after_bytes'))} of {human_bytes(m['before_bytes'])}"
|
|
235
|
+
if m.get("before_pages") is not None:
|
|
236
|
+
title += f" ({m.get('after_pages')} of {m['before_pages']} pages)"
|
|
237
|
+
if (sv.get("engine_detail") or {}).get("fresh_run"):
|
|
238
|
+
title += "; index-only: the run with pages not all-visible"
|
|
239
|
+
rows.append(f"<span class=mono>{_e(label)}</span><span class='{cls}' title='{_e(title)}'>"
|
|
240
|
+
f"<i style='width:{min(r, 1) * 100:.1f}%'></i></span><span>{_e(note)} · {pct(share)}</span>")
|
|
241
|
+
else:
|
|
242
|
+
why = (sv.get("engine_detail") or {}).get("why_not_measured")
|
|
243
|
+
rows.append(f"<span class=mono>{_e(label)}</span><span class='adv-bar claimed'></span><span>claimed"
|
|
244
|
+
+ (f" ({_e(str(why).replace('_', ' '))})" if why else "") + f" · {pct(share)}</span>")
|
|
245
|
+
more = f"<span></span><span class=muted>{len(s['serves']) - limit} more</span><span></span>" if len(s.get("serves") or []) > limit else ""
|
|
246
|
+
return f"<div class=adv-bars>{''.join(rows)}{more}</div>"
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _chips(s: dict) -> str:
|
|
250
|
+
ed = s.get("engine_detail") or {}
|
|
251
|
+
out = []
|
|
252
|
+
if s["kind"] == "skip_index":
|
|
253
|
+
out.append(_tag(LOCALITY_LABEL.get(ed.get("locality_basis"), ed.get("locality_basis") or ""), "verified" if ed.get("measurable") else "unverified dashed"))
|
|
254
|
+
for t in ed.get("trials_measured") or []:
|
|
255
|
+
out.append(_tag(f"granularity {t['granularity']}: x{t['read_ratio']}" if t.get("read_ratio") is not None else f"granularity {t['granularity']}: -"))
|
|
256
|
+
if s["kind"] == "aggregating_projection" and not ed.get("usable", True):
|
|
257
|
+
out.append(_tag("bound on the raw time column", "unverified dashed"))
|
|
258
|
+
if s["kind"] == "ordering_key":
|
|
259
|
+
out.append(_tag(f"key serves {pct(ed.get('served_share_old'))} → {pct(ed.get('served_share_new'))} of the load ({ed.get('share_basis')})"))
|
|
260
|
+
if ed.get("needs_setting"):
|
|
261
|
+
out.append(_tag(f"needs {ed['needs_setting']}", "unverified"))
|
|
262
|
+
if ed.get("covering_of"):
|
|
263
|
+
out.append(_tag(f"covering form of {ed['covering_of']}: index-only reads measured with pages not all-visible"))
|
|
264
|
+
if ed.get("alternative_of"):
|
|
265
|
+
out.append(_tag(f"other column order of {ed['alternative_of']}: both measured"))
|
|
266
|
+
if ed.get("extends"):
|
|
267
|
+
out.append(_tag("extends " + ", ".join(ed["extends"])))
|
|
268
|
+
if ed.get("updated_columns"):
|
|
269
|
+
out.append(_tag("UPDATEs set " + ", ".join(ed["updated_columns"]) + ": no HOT update there", "unverified"))
|
|
270
|
+
vis = ed.get("visibility") or {}
|
|
271
|
+
if vis.get("measured") and vis.get("all_visible_share") is not None:
|
|
272
|
+
out.append(_tag(f"index-only reads measured with {pct(vis['all_visible_share'])} of the pages all-visible"))
|
|
273
|
+
worse = [o for o in s.get("others_measured") or [] if o.get("verdict") == "slower"]
|
|
274
|
+
if s.get("engine") == "postgres" and s.get("others_measured"):
|
|
275
|
+
n = len(s["others_measured"])
|
|
276
|
+
out.append(_tag(f"{n - len(worse)} of {n} other statements not worse", "failed" if worse else ""))
|
|
277
|
+
if (s.get("size") or {}).get("bytes_sandbox") is not None:
|
|
278
|
+
out.append(_tag(f"+{human_bytes(s['size']['bytes_sandbox'])} at sandbox scale"))
|
|
279
|
+
return "".join(out)
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def _row(x: dict) -> str:
|
|
283
|
+
o = x.get("outcome") or {}
|
|
284
|
+
ddl = "; ".join(x.get("ddl") or []) or (x.get("engine_detail") or {}).get("note", "")
|
|
285
|
+
state = o.get("state") or ""
|
|
286
|
+
return (f"<tr><td class=mono>{_e(x['id'])}</td><td><span class=adv-k>{_e(KIND_LABEL.get(x['kind'], x['kind']))}</span> {_e(what(x))}"
|
|
287
|
+
f"<div class=muted><code>{_e(ddl[:220])}</code></div><div class=chips>{_chips(x)}</div></td>"
|
|
288
|
+
f"<td>{_bars(x)}<div class=muted>{_e(gain_text(x))}</div></td><td>{_e(cost_text(x))}</td>"
|
|
289
|
+
f"<td>{_tag(STATE_LABEL.get(state, state), state) if state else ''}<div class=muted>{_e(reason_text(x))}</div></td></tr>"
|
|
290
|
+
f"<tr class=adv-plan><td></td><td colspan=4>{PLAN_MARK.format(_e(x['id']))}</td></tr>")
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def html_section(stage: dict | None, limit_tables: int = 25) -> str:
|
|
294
|
+
"""The "Access paths, per table" section of report.html: every engine's suggestions, one block per table."""
|
|
295
|
+
stage = advisors.wrap(stage) if stage and "engines" not in stage else stage
|
|
296
|
+
sh = advisors.shared(stage) if stage else {}
|
|
297
|
+
sugg = sh.get("table_suggestions") or []
|
|
298
|
+
hyg = sh.get("index_hygiene") or []
|
|
299
|
+
if not sugg and not hyg:
|
|
300
|
+
return ""
|
|
301
|
+
states: dict[str, int] = {}
|
|
302
|
+
for s in sugg:
|
|
303
|
+
if _state(s):
|
|
304
|
+
states[_state(s)] = states.get(_state(s), 0) + 1
|
|
305
|
+
engines = sorted({s["engine"] for s in sugg} | {h["engine"] for h in hyg}, key=advisors.ENGINES.index)
|
|
306
|
+
cards = (f"<div class=card><b>{len(sugg)}</b>suggestions</div><div class=card><b>{len({(s['engine'], s['table']) for s in sugg})}</b>tables</div>"
|
|
307
|
+
f"<div class=card><b>{states.get('fixed', 0)}</b>fixed (verified on the sandbox)</div>")
|
|
308
|
+
st_chips = "".join(_tag(f"{STATE_LABEL[k]} {states[k]}", k) for k in STATE_ORDER if states.get(k)) or _tag("not benchmarked yet", "unverified")
|
|
309
|
+
by_table: dict[tuple, list[dict]] = {}
|
|
310
|
+
for s in sugg:
|
|
311
|
+
by_table.setdefault((s["engine"], s["table"]), []).append(s)
|
|
312
|
+
hyg_by: dict[tuple, list[dict]] = {}
|
|
313
|
+
for h in hyg:
|
|
314
|
+
hyg_by.setdefault((h["engine"], h["table"]), []).append(h)
|
|
315
|
+
rows = {(t["engine"], t["table"]): t for t in table_rows(stage)}
|
|
316
|
+
keys = sorted(set(by_table) | set(hyg_by), key=lambda k: (min([STATE_ORDER.get(_state(x), 4) for x in by_table.get(k, [])] or [5]),
|
|
317
|
+
advisors.ENGINES.index(k[0]), -(rows.get(k) or {}).get("load", 0.0), k[1]))
|
|
318
|
+
blocks = []
|
|
319
|
+
for key in keys[:limit_tables]:
|
|
320
|
+
t = rows.get(key) or {"facts": "", "statements": 0, "load_text": ""}
|
|
321
|
+
mine = sorted(by_table.get(key, []), key=lambda x: (STATE_ORDER.get(_state(x), 4), x["id"]))
|
|
322
|
+
h = "".join(f"<div>{_tag(HYGIENE_WORDS.get(x['code'], x['code']), 'unverified')} <span class=mono>{_e(x.get('index'))}</span>"
|
|
323
|
+
+ (f" ({_e(x.get('same_as') or x.get('covered_by'))})" if x.get("same_as") or x.get("covered_by") else "")
|
|
324
|
+
+ (f" <span class=muted>{_e(x.get('caveat'))}</span>" if x.get("caveat") else "") + "</div>" for x in hyg_by.get(key, []))
|
|
325
|
+
blocks.append(f"<h4>{_e(key[1])} · {_e(ENGINE_LABEL.get(key[0], key[0]))} · {_e(t['facts'])} · {t['statements']} statements · {_e(t['load_text'])}</h4>"
|
|
326
|
+
+ ("<div class=wrap><table><tr><th>Id</th><th>Change</th><th>Statements it serves (read with it / before)</th><th>Cost</th>"
|
|
327
|
+
f"<th>State</th></tr>{''.join(_row(x) for x in mine)}</table></div>" if mine else "")
|
|
328
|
+
+ (f"<div class=muted><b>Evidence only</b> (index hygiene, never a fix){h}</div>" if h else ""))
|
|
329
|
+
more = f"<p class=muted>{len(keys) - limit_tables} more tables in advisor.json.</p>" if len(keys) > limit_tables else ""
|
|
330
|
+
return (f"<style>{CSS}</style><h2>Access paths, per table</h2><p class=muted>{_e(' and '.join(ENGINE_LABEL[e] for e in engines))} · rule-based, no agent</p>"
|
|
331
|
+
f"<div class=cards>{cards}</div><div class=chips>{st_chips}</div>{''.join(blocks)}{more}"
|
|
332
|
+
"<p class=muted>Each suggestion is built once on the sandbox table and every runnable statement of the table is measured with it: "
|
|
333
|
+
"the statements it serves (same rows) and the others (no regression), then its insert side. A statement with no runnable form is "
|
|
334
|
+
"claimed, not measured, and never counts toward a gain. A suggestion is fixed only when the sandbox measured it reading less with "
|
|
335
|
+
"the same rows and its insert side within the limits; an insert side over a limit, or whose measured spread crosses it, is a "
|
|
336
|
+
"trade-off. A skip index whose column's placement in the sandbox is not production's could not be judged on generated data.</p>")
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
# ---- the console --------------------------------------------------------------------------------------------------
|
|
340
|
+
|
|
341
|
+
def summary_lines(stage: dict | None, limit: int = 15) -> list[str]:
|
|
342
|
+
stage = advisors.wrap(stage) if stage and "engines" not in stage else stage
|
|
343
|
+
if not stage:
|
|
344
|
+
return []
|
|
345
|
+
sh = advisors.shared(stage)
|
|
346
|
+
out = []
|
|
347
|
+
rows = {(t["engine"], t["table"]): t for t in table_rows(stage)}
|
|
348
|
+
for eng, doc in advisors.docs(stage):
|
|
349
|
+
mine = [s for s in sh["table_suggestions"] if s["engine"] == eng]
|
|
350
|
+
tables = {s["table"] for s in mine}
|
|
351
|
+
by_kind: dict[str, int] = {}
|
|
352
|
+
states: dict[str, int] = {}
|
|
353
|
+
for s in mine:
|
|
354
|
+
by_kind[s["kind"]] = by_kind.get(s["kind"], 0) + 1
|
|
355
|
+
if _state(s):
|
|
356
|
+
states[_state(s)] = states.get(_state(s), 0) + 1
|
|
357
|
+
s = doc.get("summary") or {}
|
|
358
|
+
n_hyg = sum(1 for h in sh["index_hygiene"] if h["engine"] == eng)
|
|
359
|
+
out.append(f"advisor {ENGINE_LABEL[eng]}: {len(mine)} suggestions on {len(tables)} of {len(doc.get('tables') or [])} tables · "
|
|
360
|
+
+ " · ".join(f"{KIND_LABEL.get(k, k)} {v}" for k, v in by_kind.items())
|
|
361
|
+
+ (f" · runnable forms built {s.get('runnable_built')}" if s.get("runnable_built") is not None else "")
|
|
362
|
+
+ (f" · {n_hyg} index hygiene notes (evidence only)" if n_hyg else ""))
|
|
363
|
+
if states:
|
|
364
|
+
out.append(" " + " · ".join(f"{STATE_LABEL[k]} {states[k]}" for k in STATE_ORDER if states.get(k)))
|
|
365
|
+
shown = 0
|
|
366
|
+
for key in [k for k in rows if k[0] == eng]:
|
|
367
|
+
here = [x for x in mine if x["table"] == key[1]]
|
|
368
|
+
if not here:
|
|
369
|
+
continue
|
|
370
|
+
shown += 1
|
|
371
|
+
if shown > limit:
|
|
372
|
+
break
|
|
373
|
+
t = rows[key]
|
|
374
|
+
out.append(f" {key[1]} {t['facts']} {t['statements']} statements, {t['load_text']}")
|
|
375
|
+
for x in here[:8]:
|
|
376
|
+
o = x.get("outcome") or {}
|
|
377
|
+
out.append(f" {x['id']} {KIND_LABEL.get(x['kind'], x['kind']):<22} {what(x)[:90]}")
|
|
378
|
+
out.append(f" {gain_text(x)}; {cost_text(x)}" + (f" [{STATE_LABEL.get(o.get('state'), '')}: {o.get('reason')}]" if o else ""))
|
|
379
|
+
if len(here) > 8:
|
|
380
|
+
out.append(f" … {len(here) - 8} more in advisor.json")
|
|
381
|
+
return out
|
codecop/advisors.py
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
"""The two access-path advisors behind one stage file, one bundle shape and one bench record.
|
|
2
|
+
|
|
3
|
+
advisor.json holds one document per engine, under `engines`: the ClickHouse access-path advisor's (advisor_ch.py: skip
|
|
4
|
+
indexes, projections, a re-key, FINAL rewrites) and the PostgreSQL index advisor's (advisor.py). Each advisor keeps its
|
|
5
|
+
own document (its tables, its runnable statements, its settings); what leaves it is one shape, `$defs.table_suggestion`
|
|
6
|
+
of run_bundle.schema.json, the same for both (`table_suggestions`). An advisor.json written before both advisors shared
|
|
7
|
+
the file (one engine's document at the top) is read as that engine's.
|
|
8
|
+
|
|
9
|
+
Which statements are whose: a statement belongs to the advisor of the engine it was found for (the call site's
|
|
10
|
+
`engine`, the pull's engine). A call site with no engine belongs to an advisor only when the inventory names no other
|
|
11
|
+
engine at all: in a repository with both, it reaches neither. The engines an out dir is advised for are the engine of
|
|
12
|
+
its run (rank.json), else every engine the inventory has statements for (`codecop advise --engine` chooses).
|
|
13
|
+
|
|
14
|
+
bench.json keeps one `advisor` record: the run has one engine, so the record is that engine's advisor's (`engine`). While
|
|
15
|
+
the bench runs the record is also written to advisor_bench.json after each table, so what was measured survives a
|
|
16
|
+
sandbox that stops mid-run; a newer record there than bench.json's is the one read.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import json
|
|
22
|
+
from datetime import datetime, timezone
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
|
|
25
|
+
FILE = "advisor.json"
|
|
26
|
+
PARTIAL_FILE = "advisor_bench.json"
|
|
27
|
+
SCHEMA_VERSION = 2
|
|
28
|
+
ENGINES = ("clickhouse", "postgres")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
# ---- which statements are whose -----------------------------------------------------------------------------------
|
|
32
|
+
|
|
33
|
+
def named_engines(inventory: dict | None) -> set[str]:
|
|
34
|
+
"""Every engine some call site of the inventory names."""
|
|
35
|
+
return {str(c.get("engine")) for c in (inventory or {}).get("call_sites") or [] if c.get("engine")}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def owns(statement_engine: str | None, engine: str, inventory: dict | None) -> bool:
|
|
39
|
+
"""Whether a statement found for `statement_engine` belongs to `engine`'s advisor. No engine: only when the
|
|
40
|
+
inventory names no other engine."""
|
|
41
|
+
if statement_engine:
|
|
42
|
+
return statement_engine == engine
|
|
43
|
+
return named_engines(inventory) <= {engine}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def statement_engines(inventory: dict | None) -> list[str]:
|
|
47
|
+
"""The advisors' engines the inventory has SELECT statements for, in ENGINES order."""
|
|
48
|
+
found = set()
|
|
49
|
+
for c in (inventory or {}).get("call_sites") or []:
|
|
50
|
+
if c.get("is_test") or c.get("statement") != "select":
|
|
51
|
+
continue
|
|
52
|
+
for e in ENGINES:
|
|
53
|
+
if owns(c.get("engine"), e, inventory):
|
|
54
|
+
found.add(e)
|
|
55
|
+
return [e for e in ENGINES if e in found]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def run_engines(inventory: dict | None, rank: dict | None, requested: str | None = None) -> list[str]:
|
|
59
|
+
"""The engines to advise for: the one asked for, else the run's (rank.json), else every engine with statements."""
|
|
60
|
+
if requested:
|
|
61
|
+
return [requested] if requested in ENGINES else []
|
|
62
|
+
eng = (rank or {}).get("engine")
|
|
63
|
+
if eng:
|
|
64
|
+
return [eng] if eng in ENGINES else []
|
|
65
|
+
return statement_engines(inventory)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
# ---- the stage file -----------------------------------------------------------------------------------------------
|
|
69
|
+
|
|
70
|
+
def _engine_of(doc: dict) -> str | None:
|
|
71
|
+
eng = doc.get("engine")
|
|
72
|
+
if eng in ENGINES:
|
|
73
|
+
return eng
|
|
74
|
+
kinds = {s.get("engine") for s in doc.get("table_suggestions") or []}
|
|
75
|
+
return next((e for e in ENGINES if e in kinds), None)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def wrap(doc: dict | None) -> dict | None:
|
|
79
|
+
"""advisor.json as {schema_version, engines: {engine: document}}, whatever version wrote it."""
|
|
80
|
+
if not isinstance(doc, dict):
|
|
81
|
+
return None
|
|
82
|
+
if isinstance(doc.get("engines"), dict):
|
|
83
|
+
return {**doc, "engines": {e: d for e, d in doc["engines"].items() if e in ENGINES and isinstance(d, dict)}}
|
|
84
|
+
eng = _engine_of(doc)
|
|
85
|
+
if eng is None:
|
|
86
|
+
return None
|
|
87
|
+
return {"schema_version": SCHEMA_VERSION, "engines": {eng: doc}}
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def load(out_dir: Path) -> dict | None:
|
|
91
|
+
path = Path(out_dir) / FILE
|
|
92
|
+
if not path.exists():
|
|
93
|
+
return None
|
|
94
|
+
try:
|
|
95
|
+
return wrap(json.loads(path.read_text()))
|
|
96
|
+
except (OSError, ValueError):
|
|
97
|
+
return None
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def new() -> dict:
|
|
101
|
+
return {"schema_version": SCHEMA_VERSION, "engines": {}}
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def save(out_dir: Path, stage: dict) -> None:
|
|
105
|
+
stage = {**stage, "schema_version": SCHEMA_VERSION, "generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds")}
|
|
106
|
+
(Path(out_dir) / FILE).write_text(json.dumps(stage, indent=1, ensure_ascii=False, default=list))
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def doc_of(stage: dict | None, engine: str) -> dict | None:
|
|
110
|
+
return ((stage or {}).get("engines") or {}).get(engine)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def docs(stage: dict | None) -> list[tuple[str, dict]]:
|
|
114
|
+
got = (stage or {}).get("engines") or {}
|
|
115
|
+
return [(e, got[e]) for e in ENGINES if e in got]
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
# ---- the shared shape -----------------------------------------------------------------------------------------------
|
|
119
|
+
|
|
120
|
+
def shared(stage: dict | None, databases: set[str] | None = None) -> dict:
|
|
121
|
+
"""{table_suggestions, index_hygiene, advice}: every engine's suggestions in the one shape (no statement text, no
|
|
122
|
+
rewritten statement, no parameter values), the hygiene evidence and each advisor's summary."""
|
|
123
|
+
from . import advisor as pg, advisor_ch as ch
|
|
124
|
+
out: dict = {"table_suggestions": [], "index_hygiene": [], "advice": {}}
|
|
125
|
+
for eng, doc in docs(stage):
|
|
126
|
+
if eng == "clickhouse":
|
|
127
|
+
out["table_suggestions"] += ch.for_upload(doc) or []
|
|
128
|
+
out["advice"][eng] = {"summary": doc.get("summary") or {}}
|
|
129
|
+
else:
|
|
130
|
+
up = pg.for_upload(doc, databases) or {}
|
|
131
|
+
out["table_suggestions"] += up.get("table_suggestions") or []
|
|
132
|
+
out["index_hygiene"] += up.get("index_hygiene") or []
|
|
133
|
+
if up.get("advice"):
|
|
134
|
+
out["advice"][eng] = up["advice"]
|
|
135
|
+
return out
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def table_advice(advice: dict) -> dict:
|
|
139
|
+
"""The bundle's `table_advice` section: per engine, the advisor's summary, basis and hand-offs."""
|
|
140
|
+
return {"schema_version": SCHEMA_VERSION, "engines": advice}
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
# ---- the bench record ----------------------------------------------------------------------------------------------
|
|
144
|
+
|
|
145
|
+
def record_engine(record: dict | None) -> str | None:
|
|
146
|
+
if not isinstance(record, dict):
|
|
147
|
+
return None
|
|
148
|
+
return record.get("engine") or ("clickhouse" if record.get("scales") is not None else None)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def write_partial(out_dir: Path, record: dict) -> None:
|
|
152
|
+
"""The bench record as it stands, written while the bench runs (each table): what survives a sandbox that stops."""
|
|
153
|
+
try:
|
|
154
|
+
(Path(out_dir) / PARTIAL_FILE).write_text(json.dumps({**record, "complete": False}, ensure_ascii=False, default=list))
|
|
155
|
+
except OSError:
|
|
156
|
+
pass
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def clear_partial(out_dir: Path) -> None:
|
|
160
|
+
try:
|
|
161
|
+
(Path(out_dir) / PARTIAL_FILE).unlink()
|
|
162
|
+
except OSError:
|
|
163
|
+
pass
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def latest_record(out_dir: Path, engine: str, bench: dict | None = None) -> dict | None:
|
|
167
|
+
"""The newest bench record of `engine`'s advisor: bench.json's, or one written by a bench that did not finish
|
|
168
|
+
(advisor_bench.json, newer than bench.json's)."""
|
|
169
|
+
if bench is None and (Path(out_dir) / "bench.json").exists():
|
|
170
|
+
try:
|
|
171
|
+
bench = json.loads((Path(out_dir) / "bench.json").read_text())
|
|
172
|
+
except (OSError, ValueError):
|
|
173
|
+
bench = None
|
|
174
|
+
rec = (bench or {}).get("advisor")
|
|
175
|
+
rec = rec if record_engine(rec) == engine else None
|
|
176
|
+
path = Path(out_dir) / PARTIAL_FILE
|
|
177
|
+
if path.exists():
|
|
178
|
+
try:
|
|
179
|
+
part = json.loads(path.read_text())
|
|
180
|
+
except (OSError, ValueError):
|
|
181
|
+
part = None
|
|
182
|
+
if record_engine(part) == engine and str(part.get("started_at") or "") > str((rec or {}).get("started_at") or ""):
|
|
183
|
+
return part
|
|
184
|
+
return rec
|