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
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
"""`codecop apply`: turn a verified finding into something a person can review and run.
|
|
2
|
+
|
|
3
|
+
For a fix delivered as a migration (a new sorting key, a projection, an index, a materialized view) that is a plan:
|
|
4
|
+
ordered .sql files plus plan.json, with each step's reversibility, locks, estimates and rollback. For a fix delivered
|
|
5
|
+
as a code change it is a unified diff against the repository file.
|
|
6
|
+
|
|
7
|
+
This package writes files into the out dir and nothing else. It never connects to a real database and never writes
|
|
8
|
+
to the repository. `check.py` runs a plan on the local sandbox container, which is the only place a plan ever runs.
|
|
9
|
+
|
|
10
|
+
<out>/apply/plan.json every plan, machine-readable
|
|
11
|
+
<out>/apply/Q-001/01_precheck.sql ... the steps, in order
|
|
12
|
+
<out>/apply/Q-001/rollback_*.sql how to go back, per point in the plan
|
|
13
|
+
<out>/apply/Q-001/code.diff the code change, when the SQL literal was located exactly
|
|
14
|
+
<out>/apply/check.json what `--check` saw on the sandbox
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import json
|
|
20
|
+
import re
|
|
21
|
+
import shutil
|
|
22
|
+
from datetime import datetime, timezone
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
|
|
25
|
+
from .. import __version__
|
|
26
|
+
from . import clickhouse as ch
|
|
27
|
+
from . import patch as patch_mod
|
|
28
|
+
from . import postgres as pg
|
|
29
|
+
from .clickhouse import PlanError
|
|
30
|
+
from .common import APPLY_DIR, CHECK_FILE, MIGRATION_KINDS, PLAN_FILE, bench_setup_seconds, generic_plan, normalize_sql, number, short, sql_file, step, table_sizes
|
|
31
|
+
|
|
32
|
+
__all__ = ["APPLY_DIR", "CHECK_FILE", "PLAN_FILE", "build", "choose", "load", "write"]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def choose(finding: dict, variant: int | None = None) -> tuple[dict | None, str]:
|
|
36
|
+
"""The variant to plan: the best verified one (the first win; variants are sorted best first), or the one asked for."""
|
|
37
|
+
variants = finding.get("variants") or []
|
|
38
|
+
if variant is not None:
|
|
39
|
+
if not 0 <= variant < len(variants):
|
|
40
|
+
return None, f"no variant {variant + 1}: the finding has {len(variants)}"
|
|
41
|
+
return variants[variant], ""
|
|
42
|
+
best = next((v for v in variants if v.get("verdict") == "win"), None)
|
|
43
|
+
return (best, "") if best else (None, "no variant was verified on the sandbox")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _optional(path: Path) -> dict | None:
|
|
47
|
+
return json.loads(path.read_text()) if path.exists() else None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _repo_root(findings: dict, repo: Path | None, site_file: str) -> Path | None:
|
|
51
|
+
for root in (repo, Path((findings.get("repo") or {}).get("root") or "/nonexistent")):
|
|
52
|
+
if root and (Path(root) / site_file).is_file():
|
|
53
|
+
return Path(root)
|
|
54
|
+
return None
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _generic(findings: dict, finding: dict, variant: dict, sizes_of) -> dict:
|
|
58
|
+
steps, warnings = generic_plan(findings["engine"], finding, variant)
|
|
59
|
+
if not steps:
|
|
60
|
+
raise PlanError("the variant has no setup statements")
|
|
61
|
+
undo = [u for s in reversed(steps) for u in s["undo_sql"]]
|
|
62
|
+
if findings["engine"] == "postgres":
|
|
63
|
+
steps.append(step("confirm", "Confirm the query reads less", "confirm", [pg.explain_sql(variant["sql"], finding.get("params") or {})], effect="read",
|
|
64
|
+
chips=["parameter values are the sandbox's: use real ones", "EXPLAIN ANALYZE runs the query"],
|
|
65
|
+
expect={"measure": {"sql": variant["sql"], "params": finding.get("params") or {}, **(ch.expected_read(variant) or {})}}))
|
|
66
|
+
else:
|
|
67
|
+
steps.append(ch.confirm_step(finding, variant["sql"], "the plan should read less than before", ch.expected_read(variant)))
|
|
68
|
+
table = finding["tables"][0]
|
|
69
|
+
same_query = normalize_sql(variant.get("sql", "")) == normalize_sql(finding["baseline_sql"])
|
|
70
|
+
return {"recipe": "generic", "table": table, "sizes": sizes_of(table), "estimates": {"is_estimate": True, "extra_disk_bytes": None, "duration_s": None,
|
|
71
|
+
"basis": [], "label": "", "sizes_from": sizes_of(table)["source"]},
|
|
72
|
+
"warnings": warnings, "steps": steps,
|
|
73
|
+
"rollback": [{"when": "at any point", "possible": bool(undo), "loses": "what the setup created", "sql": undo}],
|
|
74
|
+
"code": {"needs_patch": not same_query, "call_sites": [{
|
|
75
|
+
"file": finding["site"]["file"], "line": finding["site"]["line"], "symbol": finding["site"].get("symbol") or "",
|
|
76
|
+
"change": "none: the query is unchanged" if same_query else "the query changes too: see the patch"}],
|
|
77
|
+
"other_readers": [], "reader_counts": {}, "writers": []}}
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def plan_finding(findings: dict, finding: dict, variant: dict, *, catalog: dict | None, bench: dict | None, rank: dict | None,
|
|
81
|
+
inventory: dict | None, repo: Path | None) -> dict:
|
|
82
|
+
engine, kind = findings["engine"], variant["kind"]
|
|
83
|
+
entry = {
|
|
84
|
+
"finding": finding["finding"], "id": finding["id"], "title": finding["title"], "dir": re.sub(r"[^A-Za-z0-9_-]", "_", finding["finding"]) or "finding",
|
|
85
|
+
"variant": {"kind": kind, "change": variant.get("change") or kind, "verdict": variant.get("verdict"), "reason": variant.get("reason", ""),
|
|
86
|
+
"tradeoffs": variant.get("tradeoffs") or []},
|
|
87
|
+
"same_results": variant.get("same_results", True), "status": "planned", "reason": "", "recipe": "patch", "delivery": "patch",
|
|
88
|
+
"steps": [], "rollback": [], "warnings": [], "patch": None, "files": [],
|
|
89
|
+
}
|
|
90
|
+
sizes_of = lambda table: table_sizes(findings, catalog, table) # noqa: E731
|
|
91
|
+
setup_s = bench_setup_seconds(bench, rank, finding, variant)
|
|
92
|
+
if kind in MIGRATION_KINDS:
|
|
93
|
+
try:
|
|
94
|
+
if engine == "clickhouse" and kind == "ordering_key":
|
|
95
|
+
table = next((t for t in finding["tables"] if any(short(t) + "__codecop_variant" in s for s in variant.get("setup_sql") or [])),
|
|
96
|
+
finding["tables"][0])
|
|
97
|
+
body = ch.rekey_plan(findings, finding, variant, sizes_of(table), setup_s, inventory)
|
|
98
|
+
elif engine == "clickhouse" and kind in ("projection", "skip_index"):
|
|
99
|
+
body = ch.alter_plan(findings, finding, variant, sizes_of, setup_s)
|
|
100
|
+
elif engine == "postgres" and kind == "index":
|
|
101
|
+
body = pg.index_plan(findings, finding, variant, sizes_of, setup_s)
|
|
102
|
+
else:
|
|
103
|
+
body = _generic(findings, finding, variant, sizes_of)
|
|
104
|
+
except PlanError as e:
|
|
105
|
+
entry.update(status="not_planned", reason=str(e), recipe=kind, delivery="migration")
|
|
106
|
+
return entry
|
|
107
|
+
entry.update(body)
|
|
108
|
+
entry["steps"] = number(entry["steps"])
|
|
109
|
+
entry["delivery"] = "migration + patch" if body["code"]["needs_patch"] else "migration"
|
|
110
|
+
if kind == "rewrite" or (entry.get("code") or {}).get("needs_patch"):
|
|
111
|
+
sql = variant.get("sql") or ""
|
|
112
|
+
for t in finding["tables"]:
|
|
113
|
+
sql = sql.replace(f"{short(t)}__codecop_variant", short(t))
|
|
114
|
+
entry["patch"] = patch_mod.build(_repo_root(findings, repo, finding["site"]["file"]), finding, {**variant, "sql": sql})
|
|
115
|
+
if kind == "rewrite":
|
|
116
|
+
entry["code"] = {"needs_patch": True, "call_sites": [{
|
|
117
|
+
"file": finding["site"]["file"], "line": finding["site"]["line"], "symbol": finding["site"].get("symbol") or "",
|
|
118
|
+
"change": "the query changes: see the patch"}], "other_readers": [], "reader_counts": {}, "writers": []}
|
|
119
|
+
return entry
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
ADVISOR_KIND = {"skip_index": "skip_index", "projection": "projection", "aggregating_projection": "projection", "ordering_key": "ordering_key"}
|
|
123
|
+
ADVISOR_LABEL = {"skip_index": "Skip index", "projection": "Projection", "aggregating_projection": "Aggregating projection", "ordering_key": "New sorting key"}
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _served_base(findings: dict, advisor: dict | None, s: dict) -> dict:
|
|
127
|
+
"""The runnable form of the heaviest measured statement a suggestion serves: its baseline, values and place, for the
|
|
128
|
+
plan's confirm step."""
|
|
129
|
+
runnable = {c["finding"]: c for c in (advisor or {}).get("runnable") or []}
|
|
130
|
+
by_id = {f["finding"]: f for f in findings.get("findings") or []}
|
|
131
|
+
for sv in sorted(s.get("serves") or [], key=lambda x: (x.get("claimed", True), -(x.get("weight") or 0))):
|
|
132
|
+
c = by_id.get(sv.get("finding")) or runnable.get(sv.get("finding"))
|
|
133
|
+
if c and c.get("baseline_sql"):
|
|
134
|
+
return {"baseline_sql": c["baseline_sql"], "params": c.get("params") or {}, "site": c.get("site") or {"file": sv.get("file") or "", "line": sv.get("line") or 0}}
|
|
135
|
+
sv = (s.get("serves") or [{}])[0]
|
|
136
|
+
return {"baseline_sql": "", "params": {}, "site": {"file": sv.get("file") or "", "line": sv.get("line") or 0, "symbol": ""}}
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def plan_suggestion(findings: dict, s: dict, advisor: dict | None, *, catalog: dict | None, inventory: dict | None, definition: dict | None) -> dict:
|
|
140
|
+
"""The migration plan of one verified table suggestion of the access-path advisor: ADD INDEX / ADD PROJECTION then
|
|
141
|
+
MATERIALIZE partition by partition (alter_plan), or the re-key's copy, backfill and swap (rekey_plan), with the
|
|
142
|
+
mutation's estimated disk and time and the measured insert side stated."""
|
|
143
|
+
from ..scenario_sql import rename_table
|
|
144
|
+
kind = ADVISOR_KIND[s["kind"]]
|
|
145
|
+
table = s["table"]
|
|
146
|
+
base = _served_base(findings, advisor, s)
|
|
147
|
+
n = len(s.get("serves") or [])
|
|
148
|
+
finding = {"finding": s["id"], "id": s["fingerprint"], "title": f"{ADVISOR_LABEL[s['kind']]} on {table} (access-path advisor, serves {n} statement{'s' if n != 1 else ''})",
|
|
149
|
+
"tables": [table], "baseline_sql": base["baseline_sql"], "params": base["params"],
|
|
150
|
+
"site": {"file": base["site"].get("file") or "", "line": base["site"].get("line") or 0, "symbol": base["site"].get("symbol") or ""}}
|
|
151
|
+
ed = s.get("engine_detail") or {}
|
|
152
|
+
sql = base["baseline_sql"]
|
|
153
|
+
if kind == "ordering_key" and sql:
|
|
154
|
+
sql = rename_table(sql, "clickhouse", table, ed.get("copy") or f"{table}__codecop_variant") or sql
|
|
155
|
+
variant = {"kind": kind, "change": s["kind"], "verdict": "win", "reason": (s.get("outcome") or {}).get("words", ""), "setup_sql": s.get("ddl") or [],
|
|
156
|
+
"sql": sql, "storage_delta_bytes": (s.get("size") or {}).get("bytes_sandbox") or 0, "new_order_by": ed.get("new_key") or [],
|
|
157
|
+
"same_results": True, "tradeoffs": [], "scales": []}
|
|
158
|
+
entry = {"finding": s["id"], "id": s["fingerprint"], "title": finding["title"], "dir": re.sub(r"[^A-Za-z0-9_-]", "_", s["id"]),
|
|
159
|
+
"variant": {"kind": kind, "change": s["kind"], "verdict": "win", "reason": variant["reason"], "tradeoffs": []},
|
|
160
|
+
"same_results": True, "status": "planned", "reason": "", "recipe": kind, "delivery": "migration", "steps": [], "rollback": [],
|
|
161
|
+
"warnings": [], "patch": None, "files": [], "source": "access-path advisor", "table_suggestion": s["id"]}
|
|
162
|
+
f2 = findings
|
|
163
|
+
if definition and not any(d["name"] == table for d in findings.get("table_definitions") or []):
|
|
164
|
+
f2 = {**findings, "table_definitions": list(findings.get("table_definitions") or []) + [definition]}
|
|
165
|
+
sizes_of = lambda t: table_sizes(f2, catalog, t) # noqa: E731
|
|
166
|
+
try:
|
|
167
|
+
if not sql:
|
|
168
|
+
raise PlanError("no statement it serves has a runnable form here to confirm the plan with")
|
|
169
|
+
if kind == "ordering_key":
|
|
170
|
+
body = ch.rekey_plan(f2, finding, variant, sizes_of(table), ed.get("setup_s_sandbox"), inventory)
|
|
171
|
+
else:
|
|
172
|
+
body = ch.alter_plan(f2, finding, variant, sizes_of, ed.get("setup_s_sandbox"))
|
|
173
|
+
except PlanError as e:
|
|
174
|
+
entry.update(status="not_planned", reason=str(e))
|
|
175
|
+
return entry
|
|
176
|
+
entry.update(body)
|
|
177
|
+
entry["code"]["needs_patch"] = False
|
|
178
|
+
entry["steps"] = number(entry["steps"])
|
|
179
|
+
w = s.get("write_cost") or {}
|
|
180
|
+
if w.get("measured"):
|
|
181
|
+
entry["warnings"].append({"code": "insert_cost", "detail": f"measured on the sandbox: inserts x{w.get('insert_time_ratio')} time, "
|
|
182
|
+
f"storage x{w.get('storage_ratio')}, parts x{w.get('parts_ratio')}"})
|
|
183
|
+
if ed.get("needs_setting"):
|
|
184
|
+
entry["warnings"].append({"code": "table_setting", "detail": f"the table needs {ed['needs_setting']} before the projection is added"})
|
|
185
|
+
return entry
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def build(out_dir: Path, *, only: list[str] | None = None, variant: int | None = None, repo: Path | None = None) -> dict:
|
|
189
|
+
"""plan.json's content for an out dir. Reads the stage files; connects to nothing."""
|
|
190
|
+
findings = json.loads((out_dir / "findings.json").read_text())
|
|
191
|
+
from ..realdb import CATALOG_FILE
|
|
192
|
+
catalog, bench, rank, inventory = (_optional(out_dir / n) for n in (CATALOG_FILE, "bench.json", "rank.json", "inventory.json"))
|
|
193
|
+
doc = {
|
|
194
|
+
"schema_version": 1, "tool_version": __version__, "generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
|
195
|
+
"engine": findings["engine"], "engine_version": findings.get("engine_version", ""),
|
|
196
|
+
"repo": {k: (findings.get("repo") or {}).get(k, "") for k in ("name", "commit")},
|
|
197
|
+
"sizes_from": {"real_catalog": catalog is not None, "bench": bench is not None},
|
|
198
|
+
"ran_against": "nothing: these files are written for review; `codecop apply --check` runs them on the local sandbox only",
|
|
199
|
+
"plans": [], "skipped": [],
|
|
200
|
+
}
|
|
201
|
+
wanted = {w.upper() for w in only or []}
|
|
202
|
+
for f in findings["findings"]:
|
|
203
|
+
if (f.get("kind") or "query") != "query":
|
|
204
|
+
continue # another kind of finding (kinds/): its fix is a code change, handed off, never planned here
|
|
205
|
+
if wanted and f["finding"].upper() not in wanted and f["id"].upper() not in wanted:
|
|
206
|
+
continue
|
|
207
|
+
chosen, why = choose(f, variant if wanted else None)
|
|
208
|
+
if chosen is None:
|
|
209
|
+
doc["skipped"].append({"finding": f["finding"], "title": f["title"], "reason": why})
|
|
210
|
+
continue
|
|
211
|
+
doc["plans"].append(plan_finding(findings, f, chosen, catalog=catalog, bench=bench, rank=rank, inventory=inventory, repo=repo))
|
|
212
|
+
# the advisors' table suggestions, either engine (advisor.json): only a verified one gets a plan
|
|
213
|
+
from .. import advisor as advisor_pg, advisors
|
|
214
|
+
stage = advisors.load(out_dir)
|
|
215
|
+
for engine, adv in advisors.docs(stage):
|
|
216
|
+
if engine == "postgres":
|
|
217
|
+
shared = {x["fingerprint"]: x for x in (advisor_pg.for_upload(adv) or {}).get("table_suggestions") or []}
|
|
218
|
+
for s in adv.get("table_suggestions") or []:
|
|
219
|
+
if wanted and s["id"].upper() not in wanted and str(s.get("fingerprint") or "").upper() not in wanted:
|
|
220
|
+
continue
|
|
221
|
+
if engine == "clickhouse":
|
|
222
|
+
if s.get("kind") not in ADVISOR_KIND:
|
|
223
|
+
continue # a FINAL rewrite changes a statement: its rewritten text is in the suggestion
|
|
224
|
+
verified, why = s.get("verdict") == "verified", (s.get("outcome") or {}).get("reason") or s.get("verdict")
|
|
225
|
+
else:
|
|
226
|
+
v = shared.get(s.get("fingerprint")) or advisor_pg.shared(s)
|
|
227
|
+
verified, why = v["verdict"] == "verified" and (v.get("outcome") or {}).get("state") == "fixed", (v.get("outcome") or {}).get("reason")
|
|
228
|
+
if not verified:
|
|
229
|
+
if wanted:
|
|
230
|
+
doc["skipped"].append({"finding": s["id"], "title": f"{s['kind'].replace('_', ' ')} on {s['table']}",
|
|
231
|
+
"reason": f"not verified on the sandbox ({why})"})
|
|
232
|
+
continue
|
|
233
|
+
if engine == "clickhouse":
|
|
234
|
+
definition = None
|
|
235
|
+
if catalog:
|
|
236
|
+
from ..realdb import facts as facts_mod
|
|
237
|
+
got = facts_mod.load(out_dir if (out_dir / CATALOG_FILE).exists() else out_dir.parent)
|
|
238
|
+
definition = got.definition("clickhouse", s["table"]) if got else None
|
|
239
|
+
doc["plans"].append(plan_suggestion(findings, s, adv, catalog=catalog, inventory=inventory, definition=definition))
|
|
240
|
+
else:
|
|
241
|
+
doc["plans"].append(plan_index_suggestion(findings, s, adv, catalog=catalog))
|
|
242
|
+
return doc
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def plan_index_suggestion(findings: dict, s: dict, advisor: dict, *, catalog: dict | None) -> dict:
|
|
246
|
+
"""The migration plan for a verified advisor index (advisor.json): the same PostgreSQL index recipe, confirmed on the
|
|
247
|
+
served statement that saved the most pages."""
|
|
248
|
+
measured = [x for x in s.get("serves") or [] if x.get("role") == "measured" and (x.get("honest_verdict") or x.get("verdict")) == "win"]
|
|
249
|
+
best = max(measured, key=lambda x: int((x.get("before") or {}).get("pages") or 0) - int((x.get("after") or {}).get("pages") or 0))
|
|
250
|
+
rows = {r["statement"]: r for r in ((s.get("measured") or {}).get("statements") or [])}
|
|
251
|
+
run = rows.get(best["statement"]) or {}
|
|
252
|
+
sql = run.get("run_sql") or ""
|
|
253
|
+
params = run.get("run_params") or {}
|
|
254
|
+
finding = {"finding": s["id"], "id": s.get("fingerprint") or s["id"], "title": f"Index on {s['table']} serving {len(s.get('serves') or [])} statements",
|
|
255
|
+
"tables": [s["table"]], "baseline_sql": sql, "params": params,
|
|
256
|
+
"site": {"file": best.get("file") or "", "line": best.get("line") or 0, "symbol": ""}}
|
|
257
|
+
b, a = best.get("before") or {}, best.get("after") or {}
|
|
258
|
+
variant = {"kind": "index", "sql": sql, "setup_sql": s["ddl"], "verdict": "win", "reason": best.get("reason") or "",
|
|
259
|
+
"storage_delta_bytes": int((s.get("size") or {}).get("index_bytes") or 0), "tradeoffs": [],
|
|
260
|
+
"scales": [{"rows": 0, "baseline": {"ok": True, "read_rows": b.get("read_rows"), "read_bytes": b.get("read_bytes")},
|
|
261
|
+
"variant": {"ok": True, "read_rows": a.get("read_rows"), "read_bytes": a.get("read_bytes")}}]}
|
|
262
|
+
entry = {
|
|
263
|
+
"finding": s["id"], "id": s.get("fingerprint") or s["id"], "title": finding["title"], "dir": re.sub(r"[^A-Za-z0-9_-]", "_", s["id"]),
|
|
264
|
+
"variant": {"kind": "index", "change": "index (advisor)", "verdict": "win", "reason": variant["reason"], "tradeoffs": []},
|
|
265
|
+
"same_results": True, "status": "planned", "reason": "", "recipe": "index", "delivery": "migration",
|
|
266
|
+
"steps": [], "rollback": [], "warnings": [], "patch": None, "files": [], "source": "advisor",
|
|
267
|
+
"serves": [x["statement"] for x in s.get("serves") or []], "table_suggestion": s["id"],
|
|
268
|
+
}
|
|
269
|
+
if not sql:
|
|
270
|
+
entry.update(status="not_planned", reason="no runnable statement recorded for the confirm step")
|
|
271
|
+
return entry
|
|
272
|
+
try:
|
|
273
|
+
body = pg.index_plan(findings, finding, variant, lambda table: table_sizes(findings, catalog, table), None)
|
|
274
|
+
except PlanError as e:
|
|
275
|
+
entry.update(status="not_planned", reason=str(e))
|
|
276
|
+
return entry
|
|
277
|
+
entry.update(body)
|
|
278
|
+
entry["steps"] = number(entry["steps"])
|
|
279
|
+
entry["delivery"] = "migration"
|
|
280
|
+
entry["code"] = {**(entry.get("code") or {}), "needs_patch": False}
|
|
281
|
+
return entry
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def _slug(text: str) -> str:
|
|
285
|
+
return re.sub(r"[^a-z0-9]+", "_", text.lower()).strip("_")
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def write(out_dir: Path, doc: dict) -> list[Path]:
|
|
289
|
+
"""Write plan.json and each plan's files under <out>/apply/. Returns the files written."""
|
|
290
|
+
base = out_dir / APPLY_DIR
|
|
291
|
+
base.mkdir(parents=True, exist_ok=True)
|
|
292
|
+
written = []
|
|
293
|
+
for plan in doc["plans"]:
|
|
294
|
+
folder = base / plan["dir"]
|
|
295
|
+
if folder.exists():
|
|
296
|
+
shutil.rmtree(folder) # ours: only this command writes under <out>/apply/<finding>/
|
|
297
|
+
folder.mkdir(parents=True)
|
|
298
|
+
plan["files"] = []
|
|
299
|
+
total = len(plan["steps"])
|
|
300
|
+
for s in plan["steps"]:
|
|
301
|
+
(folder / s["file"]).write_text(sql_file(plan, s, total))
|
|
302
|
+
plan["files"].append(f"{plan['dir']}/{s['file']}")
|
|
303
|
+
for r in plan["rollback"]:
|
|
304
|
+
if r["possible"] and r["sql"]:
|
|
305
|
+
r["file"] = f"rollback_{_slug(r['when'])}.sql"
|
|
306
|
+
(folder / r["file"]).write_text(f"-- codecop apply · {plan['finding']} · rollback · {r['when']}\n-- loses: {r['loses']}\n\n"
|
|
307
|
+
+ "".join(x + ";\n" for x in r["sql"]))
|
|
308
|
+
plan["files"].append(f"{plan['dir']}/{r['file']}")
|
|
309
|
+
p = plan.get("patch")
|
|
310
|
+
if p:
|
|
311
|
+
if p["diff"]:
|
|
312
|
+
p["diff_file"] = "code.diff"
|
|
313
|
+
(folder / "code.diff").write_text(p["diff"])
|
|
314
|
+
plan["files"].append(f"{plan['dir']}/code.diff")
|
|
315
|
+
elif p["new_sql"]:
|
|
316
|
+
p["sql_file"] = "rewritten_query.sql"
|
|
317
|
+
(folder / "rewritten_query.sql").write_text(f"-- codecop apply · {plan['finding']} · no diff: {p['reason']}\n"
|
|
318
|
+
f"-- call site: {p['site']['file']}:{p['site']['line']}\n\n{p['new_sql'].rstrip()}\n")
|
|
319
|
+
plan["files"].append(f"{plan['dir']}/rewritten_query.sql")
|
|
320
|
+
written += [base / f for f in plan["files"]]
|
|
321
|
+
(base / PLAN_FILE).write_text(json.dumps(doc, indent=1, ensure_ascii=False))
|
|
322
|
+
return written + [base / PLAN_FILE]
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def load(out_dir: Path) -> tuple[dict | None, dict | None]:
|
|
326
|
+
"""(plan.json, check.json) of an out dir, each None when it is not there."""
|
|
327
|
+
return _optional(out_dir / APPLY_DIR / PLAN_FILE), _optional(out_dir / APPLY_DIR / CHECK_FILE)
|