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/fixgroups.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""Findings that share one fix: "2 indexes fix 16 call sites" instead of 25 verified findings.
|
|
2
|
+
|
|
3
|
+
The same rule the console uses: a finding's fix is its verified variant (else its first);
|
|
4
|
+
two findings share it only when it is the same text-defined change: the same index (engine, table, method, columns and
|
|
5
|
+
their order, include, predicate, uniqueness), the same new sorting key of the same table, the same layout statements
|
|
6
|
+
(the object's own name aside) or the same rewritten statement (spacing aside). Never by similarity. Only a proven
|
|
7
|
+
finding counts as a proven call site (`proof_state`: verified, and its outcome says Fixed).
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import re
|
|
13
|
+
|
|
14
|
+
from .access_postgres import new_index
|
|
15
|
+
|
|
16
|
+
INDEX_KINDS = {"index", "btree_index", "covering_index", "partial_index", "expression_index"}
|
|
17
|
+
ORDER_KINDS = {"ordering_key", "sorting_key"}
|
|
18
|
+
LAYOUT_KINDS = {"skip_index", "projection", "partition_key", "partitioning", "materialized_view", "column_type"}
|
|
19
|
+
TRADE_OFF_REASONS = {"fix_costs_inserts", "insert_cost_near_limit", "fix_costs_memory", "fix_costs_cpu", "resource_cost_near_limit"}
|
|
20
|
+
_NAME = re.compile(r"\bADD\s+(INDEX|PROJECTION)\s+(?:IF\s+NOT\s+EXISTS\s+)?[`\"\w.]+", re.I)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _flat(text) -> str:
|
|
24
|
+
return " ".join(str(text).split())
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _norm(text) -> str:
|
|
28
|
+
return re.sub(r"\s+", "", str(text).replace('"', "")).lower()
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def fix_variant(f: dict) -> dict | None:
|
|
32
|
+
variants = [v for v in f.get("variants") or [] if isinstance(v, dict)]
|
|
33
|
+
return next((v for v in variants if v.get("verdict") == "win"), variants[0] if variants else None)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def fix_of(f: dict, engine: str = "") -> dict | None:
|
|
37
|
+
"""{key, label, text} of a finding's fix, or None when it is not written down well enough to compare."""
|
|
38
|
+
v = fix_variant(f)
|
|
39
|
+
if v is None:
|
|
40
|
+
return None
|
|
41
|
+
engine = engine or str(f.get("engine") or "")
|
|
42
|
+
kind = str(v.get("kind") or "")
|
|
43
|
+
setup = [s for s in v.get("setup_sql") or [] if isinstance(s, str) and s.strip()]
|
|
44
|
+
if kind in INDEX_KINDS:
|
|
45
|
+
ix = v.get("new_index") if isinstance(v.get("new_index"), dict) else new_index(setup)
|
|
46
|
+
if ix and ix.get("columns"):
|
|
47
|
+
table = str(ix.get("table") or "").replace('"', "").rsplit(".", 1)[-1]
|
|
48
|
+
key = "|".join(("index", engine, table.lower(), _norm(ix.get("method") or "btree"),
|
|
49
|
+
",".join(_norm(c) for c in ix["columns"]), ",".join(sorted(_norm(c) for c in ix.get("include") or [])),
|
|
50
|
+
_norm(ix.get("where") or ""), "unique" if ix.get("unique") else ""))
|
|
51
|
+
stmt = next((s for s in setup if re.search(r"\bCREATE\s+(UNIQUE\s+)?INDEX\b", s, re.I)), "")
|
|
52
|
+
return {"key": key, "label": "Unique index" if ix.get("unique") else "Index", "table": table,
|
|
53
|
+
"text": _flat(stmt) or f"CREATE INDEX ON {table} ({', '.join(map(str, ix['columns']))})"}
|
|
54
|
+
if kind in ORDER_KINDS:
|
|
55
|
+
order = [_flat(c) for c in v.get("new_order_by") or [] if str(c).strip()]
|
|
56
|
+
tables = [t for t in f.get("tables") or [] if isinstance(t, str)]
|
|
57
|
+
if order and len(tables) == 1:
|
|
58
|
+
return {"key": f"order|{engine}|{tables[0].lower()}|{','.join(c.lower() for c in order)}", "label": "New sorting key",
|
|
59
|
+
"table": tables[0], "text": f"ORDER BY ({', '.join(order)}) on {tables[0]}"}
|
|
60
|
+
return None
|
|
61
|
+
if kind in LAYOUT_KINDS or kind in INDEX_KINDS:
|
|
62
|
+
norm = [_NAME.sub(lambda m: "ADD " + m.group(1), _flat(s)).lower() for s in setup
|
|
63
|
+
if not re.match(r"(?i)\s*alter\s+table\s+\S+\s+materialize\s+", s)]
|
|
64
|
+
if not norm:
|
|
65
|
+
return None
|
|
66
|
+
return {"key": f"layout|{engine}|{kind}|{' ; '.join(norm)}", "label": kind.replace("_", " ").capitalize(), "table": "",
|
|
67
|
+
"text": "; ".join(_flat(s) for s in setup)[:400]}
|
|
68
|
+
sql = v.get("sql") if isinstance(v.get("sql"), str) else ""
|
|
69
|
+
if sql.strip():
|
|
70
|
+
return {"key": f"rewrite|{engine}|{_flat(sql)}", "label": "Same rewrite", "table": "", "text": _flat(sql)[:400]}
|
|
71
|
+
return None
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def is_trade_off(f: dict) -> bool:
|
|
75
|
+
o = f.get("outcome") if isinstance(f.get("outcome"), dict) else {}
|
|
76
|
+
ev = o.get("evidence") if isinstance(o.get("evidence"), dict) else {}
|
|
77
|
+
return o.get("reason") in TRADE_OFF_REASONS or ev.get("trade_off") is True
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
WRITE_COST_UNKNOWN_REASONS = {"insert_cost_not_measured"}
|
|
81
|
+
PROOF_WORDS = {"proven": "Verified win", "trade_off": "Trade-off", "write_cost_unknown": "Reads less, write cost not measured",
|
|
82
|
+
"blocked": "Needs another fix", "not_judged": "Could not be judged", "nothing_to_gain": "Nothing to gain",
|
|
83
|
+
"unverified": "Not verified"}
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def proof_state(f: dict) -> str:
|
|
87
|
+
"""proven, trade_off, write_cost_unknown, blocked, not_judged, nothing_to_gain or unverified: the one rule every
|
|
88
|
+
"verified fix" count of the CLI uses (the summary, report.html, the pull-request comment). A finding is proven only
|
|
89
|
+
when the sandbox verified its best variant (status verified) and its own outcome says Fixed (or it has none); a
|
|
90
|
+
trade-off is never proven; reads verified with the insert side not measured is its own state."""
|
|
91
|
+
o = f.get("outcome") if isinstance(f.get("outcome"), dict) else {}
|
|
92
|
+
state = o.get("state") if isinstance(o.get("state"), str) else ""
|
|
93
|
+
if f.get("status") == "verified":
|
|
94
|
+
if is_trade_off(f):
|
|
95
|
+
return "trade_off"
|
|
96
|
+
if not state or state == "fixed":
|
|
97
|
+
return "proven"
|
|
98
|
+
if o.get("reason") in WRITE_COST_UNKNOWN_REASONS:
|
|
99
|
+
return "write_cost_unknown"
|
|
100
|
+
return state if state in ("blocked", "not_judged", "nothing_to_gain") else "unverified"
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def place(f: dict) -> tuple:
|
|
104
|
+
site = f.get("site") if isinstance(f.get("site"), dict) else {}
|
|
105
|
+
file, line = site.get("file") or f.get("file"), site.get("line") if site else f.get("line")
|
|
106
|
+
return (file, line) if file else ("#", f.get("finding") or f.get("id") or id(f))
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def summary(findings: list[dict], engine: str = "") -> dict:
|
|
110
|
+
"""{fixes, call_sites, findings, shared}: the proven fixes (`proof_state` proven), the distinct call sites they
|
|
111
|
+
were proven at, the proven findings behind them, and each fix proven at two call sites or more
|
|
112
|
+
({label, text, sites: [(file, line)]}), most call sites first."""
|
|
113
|
+
groups: dict[str, dict] = {}
|
|
114
|
+
for f in findings:
|
|
115
|
+
if proof_state(f) != "proven":
|
|
116
|
+
continue
|
|
117
|
+
fix = fix_of(f, engine)
|
|
118
|
+
key = fix["key"] if fix else f"#{id(f)}"
|
|
119
|
+
g = groups.setdefault(key, {**(fix or {"label": "", "text": ""}), "sites": [], "n": 0})
|
|
120
|
+
g["n"] += 1
|
|
121
|
+
if place(f) not in g["sites"]:
|
|
122
|
+
g["sites"].append(place(f))
|
|
123
|
+
shared = sorted((g for g in groups.values() if len(g["sites"]) > 1), key=lambda g: -len(g["sites"]))
|
|
124
|
+
return {"fixes": len(groups), "call_sites": len({p for g in groups.values() for p in g["sites"]}),
|
|
125
|
+
"findings": sum(g["n"] for g in groups.values()), "shared": shared}
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def words(fixes: int, sites: int) -> str:
|
|
129
|
+
"""'3 fixes · 18 call sites'"""
|
|
130
|
+
return f"{fixes:,} fix{'es' if fixes != 1 else ''} · {sites:,} call site{'s' if sites != 1 else ''}"
|
codecop/formerly.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""The names the product had before it was renamed (formerly qopt), still read in this one place during the switch.
|
|
2
|
+
|
|
3
|
+
Read here, never written:
|
|
4
|
+
* environment: `CODECOP_X` is read; where it is unset or empty and `QOPT_X` is set, the old value is used (copied
|
|
5
|
+
into os.environ once, when the package is imported), and stderr says once which old names are still in use;
|
|
6
|
+
* a repository's `qopt.toml` when it has no `codecop.toml`;
|
|
7
|
+
* ~/.config/qopt (settings, credentials.json) when ~/.config/codecop does not exist yet, and a token stored in the
|
|
8
|
+
OS keychain under the old service name `qopt`. `logout` also removes that old token, so it cannot come back.
|
|
9
|
+
An old out dir (`.qopt/`) is skipped by discovery like the new one; a scan writes `.codecop/`.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import logging
|
|
15
|
+
import os
|
|
16
|
+
from collections.abc import MutableMapping
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
log = logging.getLogger("codecop.formerly")
|
|
20
|
+
|
|
21
|
+
PREFIX = "CODECOP_"
|
|
22
|
+
OLD_PREFIX = "QOPT_"
|
|
23
|
+
OLD_CONFIG_FILE = "qopt.toml"
|
|
24
|
+
OLD_CONFIG_DIR = Path.home() / ".config" / "qopt"
|
|
25
|
+
OLD_KEYRING_SERVICE = "qopt"
|
|
26
|
+
OLD_OUT_DIR = ".qopt"
|
|
27
|
+
_warned: set[str] = set()
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _once(key: str, message: str, *args) -> None:
|
|
31
|
+
if key not in _warned:
|
|
32
|
+
_warned.add(key)
|
|
33
|
+
log.warning(message, *args)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def environ(env: MutableMapping[str, str]) -> MutableMapping[str, str]:
|
|
37
|
+
"""Fill each unset or empty `CODECOP_X` of `env` from `QOPT_X`, in place, and return it."""
|
|
38
|
+
used = []
|
|
39
|
+
for key, value in list(env.items()):
|
|
40
|
+
if key.startswith(OLD_PREFIX) and value != "":
|
|
41
|
+
new = PREFIX + key[len(OLD_PREFIX):]
|
|
42
|
+
if not env.get(new):
|
|
43
|
+
env[new] = value
|
|
44
|
+
used.append(key)
|
|
45
|
+
if used:
|
|
46
|
+
_once("env:" + ",".join(sorted(used)), "codecop: deprecated environment variables (the product was renamed "
|
|
47
|
+
"from qopt): %s; rename each to its CODECOP_ name", ", ".join(sorted(used)))
|
|
48
|
+
return env
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def repo_config(root: Path) -> Path:
|
|
52
|
+
"""The repository's codecop.toml, or its qopt.toml when only that exists."""
|
|
53
|
+
path = Path(root) / "codecop.toml"
|
|
54
|
+
old = Path(root) / OLD_CONFIG_FILE
|
|
55
|
+
if not path.exists() and old.exists():
|
|
56
|
+
_once("toml:" + str(old), "codecop: reading %s; rename it to codecop.toml (the product was renamed from qopt)", old)
|
|
57
|
+
return old
|
|
58
|
+
return path
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def config_file_to_read(directory: Path, name: str) -> Path:
|
|
62
|
+
"""`directory/name`, or the same file in ~/.config/qopt when only that one exists (the default directory only)."""
|
|
63
|
+
path = directory / name
|
|
64
|
+
old = OLD_CONFIG_DIR / name
|
|
65
|
+
if not path.exists() and not os.environ.get("CODECOP_CONFIG_DIR") and old.is_file():
|
|
66
|
+
return old
|
|
67
|
+
return path
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def old_credentials(directory: Path) -> Path | None:
|
|
71
|
+
"""The credentials file of ~/.config/qopt, when the default directory is in use and it exists (logout removes a
|
|
72
|
+
server from it, so a token stored before the rename does not come back; nothing is ever added to it)."""
|
|
73
|
+
old = OLD_CONFIG_DIR / "credentials.json"
|
|
74
|
+
return old if not os.environ.get("CODECOP_CONFIG_DIR") and old.is_file() and old != directory / "credentials.json" else None
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
# Stored codes written before the rename. Out dirs and uploads made then still hold them; whatever reads a next step
|
|
78
|
+
# or a variant's source maps it here, so an old file reads like a new one.
|
|
79
|
+
OLD_CODES = {"none_qopt_side": "none_codecop_side", "run_qopt_bench": "run_codecop_bench",
|
|
80
|
+
"run_qopt_bench_for_that_engine": "run_codecop_bench_for_that_engine"}
|
|
81
|
+
OLD_SOURCES = {"qopt": "codecop"}
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def code(value):
|
|
85
|
+
"""A stored next-step code as it is written now (an old one mapped, anything else unchanged)."""
|
|
86
|
+
return OLD_CODES.get(value, value) if isinstance(value, str) else value
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def source(value):
|
|
90
|
+
"""A stored variant source as it is written now (`qopt` -> `codecop`)."""
|
|
91
|
+
return OLD_SOURCES.get(value, value) if isinstance(value, str) else value
|
codecop/grantscript.py
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
"""`codecop db grant-script`: the statements a database owner runs to give CodeCop a minimal read-only account.
|
|
2
|
+
|
|
3
|
+
It only prints. It never connects, never reads an env file, and holds no password: the owner fills in
|
|
4
|
+
`<password>`.
|
|
5
|
+
|
|
6
|
+
What is granted is derived from the statements this tool sends (realdb/clickhouse.py and
|
|
7
|
+
realdb/postgres.py), so the two cannot drift: a system table a statement starts to read shows up in the
|
|
8
|
+
ClickHouse script on its own, and a PostgreSQL relation nobody has classified here fails a test.
|
|
9
|
+
Tiers: check + A (catalog) + B (aggregated query log) always; D (sampling, reads table data) only on request.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import re
|
|
15
|
+
from typing import Optional
|
|
16
|
+
|
|
17
|
+
import typer
|
|
18
|
+
|
|
19
|
+
from .realdb import Statement
|
|
20
|
+
|
|
21
|
+
DEFAULT_ACCOUNT = "codecop_reader"
|
|
22
|
+
PLACEHOLDER = "<password>"
|
|
23
|
+
TIERS = ("check", "A", "B")
|
|
24
|
+
IDENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]*\Z")
|
|
25
|
+
SYSTEM_TABLE = re.compile(r"\bsystem\.([a-z_][a-z0-9_]*)", re.I)
|
|
26
|
+
PG_RELATION = re.compile(r"\b(?:FROM|JOIN)\s+(pg_[a-z0-9_]+)\b", re.I)
|
|
27
|
+
|
|
28
|
+
# How the PostgreSQL relations the statements read become readable.
|
|
29
|
+
# everyone readable by any role, nothing to grant
|
|
30
|
+
# all_stats shows other roles' rows only to a member of pg_read_all_stats
|
|
31
|
+
# table_select shows a row only for a column the role may SELECT
|
|
32
|
+
PG_READS = {
|
|
33
|
+
"pg_roles": "everyone", "pg_class": "everyone", "pg_namespace": "everyone", "pg_extension": "everyone", "pg_inherits": "everyone",
|
|
34
|
+
"pg_attribute": "everyone", "pg_attrdef": "everyone", "pg_index": "everyone", "pg_constraint": "everyone", "pg_type": "everyone",
|
|
35
|
+
"pg_enum": "everyone", "pg_database": "everyone", "pg_stat_user_tables": "everyone", "pg_stat_user_indexes": "everyone",
|
|
36
|
+
"pg_stat_statements_info": "everyone",
|
|
37
|
+
# the resource statements (pg.check.settings, pg.workload.temp): readable by every account
|
|
38
|
+
"pg_settings": "everyone", "pg_stat_database": "everyone",
|
|
39
|
+
# pg.workload.kcache: other accounts' statements, as pg_stat_statements (verified with pg_read_all_stats on 17 + kcache 2.3.2)
|
|
40
|
+
"pg_stat_kcache": "all_stats",
|
|
41
|
+
"pg_stat_statements": "all_stats",
|
|
42
|
+
"pg_stats": "table_select",
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class GrantError(ValueError):
|
|
47
|
+
pass
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def statements(engine: str, tiers: tuple[str, ...] = TIERS) -> list[Statement]:
|
|
51
|
+
if engine == "clickhouse":
|
|
52
|
+
from .realdb.clickhouse import STATEMENTS
|
|
53
|
+
else:
|
|
54
|
+
from .realdb.postgres import STATEMENTS
|
|
55
|
+
return [s for s in STATEMENTS.values() if s.tier in tiers]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def clickhouse_needs(tiers: tuple[str, ...] = TIERS) -> dict:
|
|
59
|
+
"""What the ClickHouse statements read: system tables, whether any goes through every replica, and the largest limits."""
|
|
60
|
+
stmts = statements("clickhouse", tiers)
|
|
61
|
+
tables = sorted({t.lower() for s in stmts for t in SYSTEM_TABLE.findall(s.sql)})
|
|
62
|
+
fields = ("seconds", "rows_to_read", "bytes_to_read", "result_rows", "memory_bytes", "threads")
|
|
63
|
+
return {"system_tables": tables, "remote": any("clusterAllReplicas(" in s.sql for s in stmts),
|
|
64
|
+
"limits": {f: max(getattr(s.limits, f) for s in stmts) for f in fields}}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def postgres_needs(tiers: tuple[str, ...] = TIERS) -> dict:
|
|
68
|
+
"""The catalog relations the PostgreSQL statements read, and what each kind asks for."""
|
|
69
|
+
stmts = statements("postgres", tiers)
|
|
70
|
+
relations = sorted({r.lower() for s in stmts for r in PG_RELATION.findall(s.sql)})
|
|
71
|
+
unknown = [r for r in relations if r not in PG_READS]
|
|
72
|
+
return {"relations": relations, "unknown": unknown,
|
|
73
|
+
"all_stats": any(PG_READS.get(r) == "all_stats" for r in relations),
|
|
74
|
+
"table_select": any(PG_READS.get(r) == "table_select" for r in relations),
|
|
75
|
+
"seconds": max(s.limits.seconds for s in stmts)}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _account(name: str) -> str:
|
|
79
|
+
if not IDENT.match(name or ""):
|
|
80
|
+
raise GrantError(f"Account name `{name}` must be a plain identifier (letters, digits, underscore).")
|
|
81
|
+
return name
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _names(values: list[str], what: str) -> list[str]:
|
|
85
|
+
for v in values:
|
|
86
|
+
if not v or any(c in v for c in "`\"'\\;\n") or len(v) > 128:
|
|
87
|
+
raise GrantError(f"{what} name `{v}` has characters this script will not quote.")
|
|
88
|
+
return list(dict.fromkeys(values))
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def clickhouse_script(account: str = DEFAULT_ACCOUNT, databases: list[str] | None = None, *, sample: bool = False,
|
|
92
|
+
profile: bool = True, cluster: bool = True, on_cluster: str = "") -> str:
|
|
93
|
+
account = _account(account)
|
|
94
|
+
dbs = _names(databases or [], "Database")
|
|
95
|
+
if on_cluster and not IDENT.match(on_cluster):
|
|
96
|
+
raise GrantError(f"Cluster name `{on_cluster}` must be a plain identifier.")
|
|
97
|
+
need = clickhouse_needs()
|
|
98
|
+
oc = f" ON CLUSTER {on_cluster}" if on_cluster else ""
|
|
99
|
+
scopes = [f"`{d}`.*" for d in dbs] or ["*.*"]
|
|
100
|
+
lim = need["limits"]
|
|
101
|
+
out = [
|
|
102
|
+
"-- CodeCop read-only account for ClickHouse. Printed by `codecop db grant-script`: nothing was connected to or run.",
|
|
103
|
+
"-- Run as an account with access management. Replace <password> before running.",
|
|
104
|
+
f"-- Allows: the capability check, the catalog (tier A) and the aggregated query log (tier B){', and sampling (tier D)' if sample else ''}.",
|
|
105
|
+
"",
|
|
106
|
+
]
|
|
107
|
+
if profile:
|
|
108
|
+
out += [
|
|
109
|
+
"-- readonly = 2: the server refuses every write for this account, whatever the client sends, and readonly cannot be",
|
|
110
|
+
"-- switched off. A session may lower a limit, never raise it past MAX. The limits are the largest any CodeCop statement asks for.",
|
|
111
|
+
"-- (Not readonly = 1: that refuses every setting, and CodeCop sets a time limit on each request.)",
|
|
112
|
+
f"CREATE SETTINGS PROFILE IF NOT EXISTS {account}_profile{oc} SETTINGS",
|
|
113
|
+
" readonly = 2,",
|
|
114
|
+
f" max_execution_time = {lim['seconds']} MAX {lim['seconds']},",
|
|
115
|
+
f" max_rows_to_read = {lim['rows_to_read']} MAX {lim['rows_to_read']},",
|
|
116
|
+
f" max_bytes_to_read = {lim['bytes_to_read']} MAX {lim['bytes_to_read']},",
|
|
117
|
+
f" max_result_rows = {lim['result_rows']} MAX {lim['result_rows']},",
|
|
118
|
+
f" max_memory_usage = {lim['memory_bytes']} MAX {lim['memory_bytes']},",
|
|
119
|
+
f" max_threads = {lim['threads']} MAX {lim['threads']};",
|
|
120
|
+
"",
|
|
121
|
+
]
|
|
122
|
+
out += [
|
|
123
|
+
f"CREATE USER IF NOT EXISTS {account}{oc} IDENTIFIED WITH sha256_password BY '{PLACEHOLDER}'"
|
|
124
|
+
+ (f" SETTINGS PROFILE '{account}_profile'" if profile else "") + ";",
|
|
125
|
+
"-- Optional: add `HOST IP '<address>'` to the statement above to accept this account from one address only.",
|
|
126
|
+
"",
|
|
127
|
+
"-- Tier A. SHOW makes names, definitions and columns visible in system.tables and system.columns. It reads no table data.",
|
|
128
|
+
]
|
|
129
|
+
out += [f"GRANT{oc} SHOW DATABASES, SHOW TABLES, SHOW COLUMNS, SHOW DICTIONARIES ON {scope} TO {account};" for scope in scopes]
|
|
130
|
+
out += ["", "-- The system tables CodeCop's statements read (each lists only what the SHOW grants above make visible)."]
|
|
131
|
+
out += [f"GRANT{oc} SELECT ON system.{t} TO {account};" for t in need["system_tables"]]
|
|
132
|
+
if need["remote"] and cluster:
|
|
133
|
+
out += ["", "-- Tier B on a cluster: the query log is read from every replica with clusterAllReplicas().",
|
|
134
|
+
"-- On a single server leave this out (--single-server). Servers before 25.7: GRANT REMOTE ON *.* instead.",
|
|
135
|
+
f"GRANT{oc} READ ON REMOTE TO {account};"]
|
|
136
|
+
if sample:
|
|
137
|
+
out += ["", "-- Tier D (`codecop db pull --sample`): reads table data, capped, for column statistics.",
|
|
138
|
+
*(["-- With the read-only profile CodeCop cannot send its own smaller row cap: a table larger than max_rows_to_read is refused."]
|
|
139
|
+
if profile else [])]
|
|
140
|
+
out += [f"GRANT{oc} SELECT ON {scope} TO {account};" for scope in scopes]
|
|
141
|
+
else:
|
|
142
|
+
out += ["", "-- No SELECT on your tables: this account cannot read a row of data. `--sample` adds that grant."]
|
|
143
|
+
out += ["", "-- To remove it all:",
|
|
144
|
+
f"-- DROP USER IF EXISTS {account}{oc};" + (f" DROP SETTINGS PROFILE IF EXISTS {account}_profile{oc};" if profile else "")]
|
|
145
|
+
return "\n".join(out) + "\n"
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def postgres_script(account: str = DEFAULT_ACCOUNT, databases: list[str] | None = None, schemas: list[str] | None = None, *,
|
|
149
|
+
sample: bool = False) -> str:
|
|
150
|
+
account = _account(account)
|
|
151
|
+
dbs = _names(databases or [], "Database")
|
|
152
|
+
schema_names = _names(schemas or ["public"], "Schema")
|
|
153
|
+
need = postgres_needs()
|
|
154
|
+
if need["unknown"]:
|
|
155
|
+
raise GrantError("A statement reads " + ", ".join(need["unknown"]) + ", which grantscript.PG_READS does not classify yet.")
|
|
156
|
+
q = lambda name: '"' + name + '"' # noqa: E731
|
|
157
|
+
out = [
|
|
158
|
+
"-- CodeCop read-only account for PostgreSQL. Printed by `codecop db grant-script`: nothing was connected to or run.",
|
|
159
|
+
"-- Run with psql as a role that may create roles and owns (or may grant on) the schemas below. Replace <password>.",
|
|
160
|
+
f"-- Allows: the capability check, the catalog (tier A) and pg_stat_statements (tier B){', and sampling (tier D)' if sample else ''}.",
|
|
161
|
+
"",
|
|
162
|
+
f"CREATE ROLE {account} LOGIN PASSWORD '{PLACEHOLDER}'",
|
|
163
|
+
" NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS CONNECTION LIMIT 3;",
|
|
164
|
+
"",
|
|
165
|
+
"-- Defaults for every session of this account. A session can change them; the missing privileges below are the guard.",
|
|
166
|
+
f"ALTER ROLE {account} SET default_transaction_read_only = on;",
|
|
167
|
+
f"ALTER ROLE {account} SET statement_timeout = '{need['seconds']}s';",
|
|
168
|
+
f"ALTER ROLE {account} SET lock_timeout = '2s';",
|
|
169
|
+
f"ALTER ROLE {account} SET idle_in_transaction_session_timeout = '60s';",
|
|
170
|
+
]
|
|
171
|
+
if need["all_stats"]:
|
|
172
|
+
out += ["",
|
|
173
|
+
"-- Tier B. pg_read_all_stats, not pg_monitor: pg_stat_statements hides other roles' statements without it.",
|
|
174
|
+
"-- pg_monitor adds pg_read_all_settings and pg_stat_scan_tables (functions that lock and scan tables); CodeCop uses neither.",
|
|
175
|
+
f"GRANT pg_read_all_stats TO {account};"]
|
|
176
|
+
for db in dbs or [""]:
|
|
177
|
+
out += ["", f"\\connect {q(db)}" if db else "-- Run what follows in each database CodeCop should read (grants on schemas are per database)."]
|
|
178
|
+
if db:
|
|
179
|
+
out.append(f"GRANT CONNECT ON DATABASE {q(db)} TO {account};")
|
|
180
|
+
if need["table_select"]:
|
|
181
|
+
out += ["-- Tier A. pg_stats shows planner statistics only for columns the role may SELECT; no predefined role lifts that.",
|
|
182
|
+
"-- CodeCop selects n_distinct, null_frac, avg_width and correlation, never the columns that hold sample values."]
|
|
183
|
+
if not sample:
|
|
184
|
+
out.append("-- No USAGE on the schema is granted, so its rows stay unreadable. The exception is `public`: every role has "
|
|
185
|
+
"USAGE there by default.")
|
|
186
|
+
for s in schema_names:
|
|
187
|
+
if sample:
|
|
188
|
+
out.append(f"GRANT USAGE ON SCHEMA {q(s)} TO {account};")
|
|
189
|
+
if need["table_select"] or sample:
|
|
190
|
+
out.append(f"GRANT SELECT ON ALL TABLES IN SCHEMA {q(s)} TO {account};")
|
|
191
|
+
out.append(f"ALTER DEFAULT PRIVILEGES IN SCHEMA {q(s)} GRANT SELECT ON TABLES TO {account}; "
|
|
192
|
+
"-- tables the role running this creates later")
|
|
193
|
+
if need["all_stats"]:
|
|
194
|
+
out.append("-- pg_stat_statements must be installed here: CREATE EXTENSION IF NOT EXISTS pg_stat_statements; "
|
|
195
|
+
"(and listed in shared_preload_libraries)")
|
|
196
|
+
if sample:
|
|
197
|
+
out += ["", "-- Tier D (`codecop db pull --sample`) reads table rows: that is what USAGE on the schema adds above."]
|
|
198
|
+
out += ["",
|
|
199
|
+
"-- Not changed here because it would change every role: PUBLIC may create temporary tables in a database by default.",
|
|
200
|
+
"-- To close that too: REVOKE TEMPORARY ON DATABASE <database> FROM PUBLIC;",
|
|
201
|
+
"-- PostgreSQL 14 and older also let PUBLIC create objects in schema public: REVOKE CREATE ON SCHEMA public FROM PUBLIC;",
|
|
202
|
+
"",
|
|
203
|
+
"-- To remove it all (in each database, then once):",
|
|
204
|
+
f"-- DROP OWNED BY {account}; DROP ROLE IF EXISTS {account};"]
|
|
205
|
+
return "\n".join(out) + "\n"
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def script(engine: str, **options) -> str:
|
|
209
|
+
key = {"pg": "postgres", "postgresql": "postgres", "ch": "clickhouse"}.get((engine or "").lower(), (engine or "").lower())
|
|
210
|
+
if key == "clickhouse":
|
|
211
|
+
options.pop("schemas", None)
|
|
212
|
+
return clickhouse_script(**options)
|
|
213
|
+
if key == "postgres":
|
|
214
|
+
for k in ("profile", "cluster", "on_cluster"):
|
|
215
|
+
options.pop(k, None)
|
|
216
|
+
return postgres_script(**options)
|
|
217
|
+
raise GrantError("--engine must be clickhouse or postgres.")
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def hint(rows) -> str:
|
|
221
|
+
"""One line for `codecop db check`, when an account it looked at could write. `rows`: (connection, capabilities, error)."""
|
|
222
|
+
writable = sorted({conn.engine for conn, cap, _ in rows if cap and cap.get("account_can_write")})
|
|
223
|
+
if not writable:
|
|
224
|
+
return ""
|
|
225
|
+
return ("An account here could write. A read-only one: " +
|
|
226
|
+
" / ".join(f"`codecop db grant-script --engine {e}`" for e in writable) + " (prints the statements, runs nothing).")
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def print_hint(rows, console) -> None:
|
|
230
|
+
text = hint(rows)
|
|
231
|
+
if text:
|
|
232
|
+
console.print(text, highlight=False)
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def grant_script(
|
|
236
|
+
engine: str = typer.Option(..., "--engine", help="clickhouse or postgres."),
|
|
237
|
+
account: str = typer.Option(DEFAULT_ACCOUNT, "--account", help="Name of the account to create."),
|
|
238
|
+
database: list[str] = typer.Option([], "--database", help="Database CodeCop may read. Repeatable. Default: all (ClickHouse), "
|
|
239
|
+
"or 'the one you run it in' (PostgreSQL)."),
|
|
240
|
+
schema: list[str] = typer.Option([], "--schema", help="PostgreSQL schema whose tables CodeCop may describe. Repeatable. Default: public."),
|
|
241
|
+
sample: bool = typer.Option(False, "--sample/--no-sample", help="Also grant what the optional sampling tier (`db pull --sample`) needs: "
|
|
242
|
+
"reading table data."),
|
|
243
|
+
profile: bool = typer.Option(True, "--profile/--no-profile", help="ClickHouse: create a read-only settings profile with limits for the account."),
|
|
244
|
+
cluster: bool = typer.Option(True, "--cluster/--single-server", help="ClickHouse: allow reading the query log from every replica."),
|
|
245
|
+
on_cluster: Optional[str] = typer.Option(None, "--on-cluster", help="ClickHouse: add ON CLUSTER <name> to every statement."),
|
|
246
|
+
) -> None:
|
|
247
|
+
"""Print the statements that create a minimal read-only account for CodeCop. Connects to nothing, runs nothing."""
|
|
248
|
+
try:
|
|
249
|
+
text = script(engine, account=account, databases=database, schemas=schema, sample=sample, profile=profile, cluster=cluster,
|
|
250
|
+
on_cluster=on_cluster or "")
|
|
251
|
+
except GrantError as e:
|
|
252
|
+
typer.echo(str(e), err=True)
|
|
253
|
+
raise typer.Exit(2)
|
|
254
|
+
typer.echo(text, nl=False)
|