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/writebench.py
ADDED
|
@@ -0,0 +1,720 @@
|
|
|
1
|
+
"""Benchmark one write candidate (writes.py) on a loaded sandbox: values, baseline, variants, same final state.
|
|
2
|
+
|
|
3
|
+
Every run leaves the sandbox's rows as they were:
|
|
4
|
+
|
|
5
|
+
PostgreSQL each run is `BEGIN; EXPLAIN (ANALYZE, BUFFERS, WAL) <write>; ROLLBACK`: rows scanned and pages touched by
|
|
6
|
+
the plan's nodes, rows changed (the ModifyTable's input), WAL bytes, time. The final state is read inside a
|
|
7
|
+
transaction of its own: after the write, a hash of every written table's rows (columns a default fills
|
|
8
|
+
from a sequence, a clock or a random generator left out: they differ from run to run by design) and of
|
|
9
|
+
the RETURNING output, then ROLLBACK.
|
|
10
|
+
SQLite the same through a writable measuring connection: BEGIN, the write, its pages and full-scan steps, the
|
|
11
|
+
final-state hash, ROLLBACK.
|
|
12
|
+
ClickHouse no transactions: an INSERT runs into an empty copy of the table (`CREATE TABLE ... AS`), a mutation
|
|
13
|
+
(`ALTER TABLE ... UPDATE / DELETE`, a lightweight DELETE) on a full copy; rows and bytes read and written,
|
|
14
|
+
time, from system.query_log; the copy is dropped after.
|
|
15
|
+
|
|
16
|
+
Values (writes.py `slots`) are chosen here, once per candidate, from the sandbox's rows: a WHERE value from rows that
|
|
17
|
+
meet the write's other conditions (`probe_sql`), tried on up to `probe_rows` rows until the write changes one; a written
|
|
18
|
+
value copied from a row of the table, a fresh one for a column that holds one value per row. The record has the shape
|
|
19
|
+
bench.bench_candidate returns, with `baseline.write` holding what only a write has.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import hashlib
|
|
25
|
+
import json
|
|
26
|
+
import re
|
|
27
|
+
import uuid
|
|
28
|
+
from datetime import datetime, timezone
|
|
29
|
+
|
|
30
|
+
from .engines.base import Measurement, QueryError, SandboxError
|
|
31
|
+
from . import writes as W
|
|
32
|
+
|
|
33
|
+
PG_VOLATILE_DEFAULT = re.compile(r"nextval|now\(|clock_timestamp|statement_timestamp|transaction_timestamp|current_timestamp|"
|
|
34
|
+
r"localtimestamp|current_date|random|uuid|gen_random", re.I)
|
|
35
|
+
MARK = "@@codecopw@@"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def bench_write(sb, cand: dict, runs: int, log=lambda msg: None, on_event=lambda name, label, counts: None,
|
|
39
|
+
settings: dict | None = None, floors: tuple[int, int] = (0, 0)) -> dict:
|
|
40
|
+
engine = getattr(sb, "engine", "") or ("postgres" if hasattr(sb, "_psql") else "")
|
|
41
|
+
cfg = W.settings_of(settings)
|
|
42
|
+
impl = {"postgres": PgWrites, "sqlite": SqliteWrites, "clickhouse": ChWrites}.get(engine)
|
|
43
|
+
out = {"finding": cand["finding"], "baseline": Measurement(ok=False).to_dict(), "variants": [], "write": True}
|
|
44
|
+
if impl is None:
|
|
45
|
+
out["baseline"]["error"] = f"writes are not benchmarked on {engine or 'this engine'}"
|
|
46
|
+
return out
|
|
47
|
+
w = impl(sb, cand, cfg, log)
|
|
48
|
+
try:
|
|
49
|
+
base = w.baseline(runs)
|
|
50
|
+
except QueryError as e: # anything the server refused before a measurement (QueryError is a SandboxError: first)
|
|
51
|
+
base = {"ok": False, "error": str(e)[:1500], "write": {"stage": w.stage}}
|
|
52
|
+
out["baseline"] = base
|
|
53
|
+
on_event("baseline", f"{cand['finding']} write baseline {'measured' if base.get('ok') else 'failed'}",
|
|
54
|
+
{"finding": cand["finding"], "ok": bool(base.get("ok")), "read_rows": base.get("read_rows"), "read_bytes": base.get("read_bytes"),
|
|
55
|
+
"duration_ms": base.get("duration_ms"), "variants": len(cand.get("variants") or [])})
|
|
56
|
+
if not base.get("ok"):
|
|
57
|
+
log(f"{cand['finding']}: [red]write baseline failed[/red] ({w.stage}) {str(base.get('error'))[:200]}")
|
|
58
|
+
return out
|
|
59
|
+
wd = base.get("write") or {}
|
|
60
|
+
log(f"{cand['finding']} ({wd.get('kind')}): changed {wd.get('affected_rows', 0):,} rows, scanned {base.get('read_rows', 0):,}, "
|
|
61
|
+
f"{base.get('read_bytes', 0) // 1024} kB of pages" + (f", WAL {wd['wal_bytes']:,} B" if wd.get("wal_bytes") is not None else ""))
|
|
62
|
+
from .bench import verdict
|
|
63
|
+
bm = _as_measurement(base)
|
|
64
|
+
for i, v in enumerate(cand.get("variants") or []):
|
|
65
|
+
rec = {"index": i, "kind": v.get("kind"), "setup_error": "", "storage_delta_bytes": 0, "setup_s": 0.0, "rule": v.get("rule")}
|
|
66
|
+
try:
|
|
67
|
+
m, same, compared = w.variant(v, runs)
|
|
68
|
+
except QueryError as e:
|
|
69
|
+
rec.update(verdict="failed", reason=f"setup failed: {str(e)[:240]}", measurement=None, setup_error=str(e)[:500])
|
|
70
|
+
out["variants"].append(rec)
|
|
71
|
+
continue
|
|
72
|
+
vm = _as_measurement(m)
|
|
73
|
+
rec["verdict"], rec["reason"] = verdict(bm, vm, v.get("same_results", True), False, floors[0], floors[1], match=same,
|
|
74
|
+
why=compared if same is None else "", pages_decide=getattr(sb, "pages_decide", False),
|
|
75
|
+
# a write returns no rows: its sameness is the final table state, shown or not
|
|
76
|
+
empty_shown=same is True)
|
|
77
|
+
if same is False:
|
|
78
|
+
rec["reason"] = f"the final table state differs from the baseline's ({compared})"
|
|
79
|
+
rec.update(compared=compared, results_match=same, measurement=m, same_final_state=same)
|
|
80
|
+
out["variants"].append(rec)
|
|
81
|
+
log(f"{cand['finding']} variant {i + 1} ({v.get('kind')}): {rec['verdict']}: {rec['reason'][:200]}")
|
|
82
|
+
return out
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _as_measurement(d: dict) -> Measurement:
|
|
86
|
+
return Measurement(ok=bool(d.get("ok")), error=d.get("error") or "", read_rows=int(d.get("read_rows") or 0),
|
|
87
|
+
read_bytes=int(d.get("read_bytes") or 0), result_rows=int(d.get("result_rows") or 0),
|
|
88
|
+
duration_ms=float(d.get("duration_ms") or 0), result_hash=d.get("result_hash") or "")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
# ---------------------------------------------------------------------------- values
|
|
92
|
+
|
|
93
|
+
def _fresh(value, typ: str, k: int):
|
|
94
|
+
t = (typ or "").lower()
|
|
95
|
+
if t == "uuid" or (isinstance(value, str) and re.fullmatch(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", value or "")):
|
|
96
|
+
return str(uuid.UUID(int=(0xF0F0 << 112) + k))
|
|
97
|
+
if re.match(r"^(?:small|big)?int|^integer|^numeric|^decimal|^serial|^bigserial|^int\d|^u?int", t) or isinstance(value, int) and not isinstance(value, bool):
|
|
98
|
+
return 900_000_000 + k
|
|
99
|
+
if value is None:
|
|
100
|
+
return f"codecop-new-{k}"
|
|
101
|
+
return f"{value}-codecop{k}"
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _default(typ: str, clock: str):
|
|
105
|
+
t = (typ or "").lower().strip()
|
|
106
|
+
if t.endswith("[]"):
|
|
107
|
+
return []
|
|
108
|
+
if re.match(r"^(?:small|big)?int|^integer|^numeric|^decimal|^real|^double|^float|^u?int|^float", t):
|
|
109
|
+
return 1
|
|
110
|
+
if t.startswith("bool"):
|
|
111
|
+
return True
|
|
112
|
+
if t == "uuid":
|
|
113
|
+
return "00000000-0000-4000-8000-000000000001"
|
|
114
|
+
if t.startswith(("timestamp", "date", "datetime")):
|
|
115
|
+
return clock or "2026-01-01 00:00:00"
|
|
116
|
+
if t.startswith("interval"):
|
|
117
|
+
return "1 day"
|
|
118
|
+
if t in ("json", "jsonb"):
|
|
119
|
+
return {}
|
|
120
|
+
# "qopt": a neutral text value, kept from before the rename (formerly qopt) so the data stays the same
|
|
121
|
+
return "qopt"
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def choose_values(cand: dict, types: dict[str, str], rows_of, fresh_base: dict[str, int], clock: str, cfg: dict,
|
|
125
|
+
probe_rows: list[dict] | None = None, probe_index: int = 0) -> tuple[dict, dict]:
|
|
126
|
+
"""$n -> value, and how each was chosen. `rows_of(table) -> list of rows`; `probe_rows`: rows meeting the write's other
|
|
127
|
+
conditions (its target's WHERE values come from row `probe_index` of them)."""
|
|
128
|
+
wd = cand["write"]
|
|
129
|
+
slots = wd.get("slots") or {}
|
|
130
|
+
unique = {c.lower() for c in wd.get("unique") or []} | {c.lower() for c in wd.get("conflict") or []}
|
|
131
|
+
target = W.bare(wd.get("target") or "")
|
|
132
|
+
values, how = {}, {}
|
|
133
|
+
k = 0
|
|
134
|
+
for pname, typ in types.items():
|
|
135
|
+
s = slots.get(pname) or {"role": "other"}
|
|
136
|
+
role, col, table = s.get("role"), (s.get("column") or "").lower(), W.bare(s.get("table") or "")
|
|
137
|
+
if role == "limit":
|
|
138
|
+
values[pname], how[pname] = int(cfg["limit_value"]), "limit"
|
|
139
|
+
continue
|
|
140
|
+
if role == "where" and col:
|
|
141
|
+
src = probe_rows if (table == target and probe_rows) else rows_of(table)
|
|
142
|
+
if s.get("array") or (typ or "").endswith("[]"):
|
|
143
|
+
vals = [_get(r, col) for r in (src or [])[:int(cfg["array_items"])] if _get(r, col) is not None]
|
|
144
|
+
values[pname], how[pname] = vals, f"{len(vals)} values of {table}.{col} from the sandbox's rows"
|
|
145
|
+
continue
|
|
146
|
+
row = (src or [])[min(probe_index, len(src) - 1)] if src else None
|
|
147
|
+
if row is not None and _has(row, col):
|
|
148
|
+
values[pname], how[pname] = _get(row, col), f"{table}.{col} of a row the write's other conditions select"
|
|
149
|
+
continue
|
|
150
|
+
if role in ("insert", "set") and col:
|
|
151
|
+
src = rows_of(table or target)
|
|
152
|
+
row = src[len(src) // 2] if src else None
|
|
153
|
+
base = _get(row, col) if row is not None else None
|
|
154
|
+
if col in unique:
|
|
155
|
+
k += 1
|
|
156
|
+
values[pname], how[pname] = _fresh(base, typ, fresh_base.get(pname, 0) + k), f"a new value for {table or target}.{col} (one per row)"
|
|
157
|
+
continue
|
|
158
|
+
if row is not None and _has(row, col):
|
|
159
|
+
values[pname], how[pname] = base, f"copied from a row of {table or target}"
|
|
160
|
+
continue
|
|
161
|
+
values[pname], how[pname] = _default(typ, clock), f"a value of type {typ}"
|
|
162
|
+
return values, how
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _has(row: dict, col: str) -> bool:
|
|
166
|
+
return any(k.lower() == col for k in row)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _get(row: dict | None, col: str):
|
|
170
|
+
if not row:
|
|
171
|
+
return None
|
|
172
|
+
for k, v in row.items():
|
|
173
|
+
if k.lower() == col:
|
|
174
|
+
return v
|
|
175
|
+
return None
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
# ---------------------------------------------------------------------------- PostgreSQL
|
|
179
|
+
|
|
180
|
+
def pg_literal(value, typ: str) -> str:
|
|
181
|
+
t = (typ or "text").strip()
|
|
182
|
+
if value is None:
|
|
183
|
+
return f"CAST(NULL AS {t})"
|
|
184
|
+
if isinstance(value, bool):
|
|
185
|
+
text = "true" if value else "false"
|
|
186
|
+
elif isinstance(value, (dict,)) or (isinstance(value, list) and t in ("json", "jsonb")):
|
|
187
|
+
text = json.dumps(value)
|
|
188
|
+
elif isinstance(value, list):
|
|
189
|
+
if t in ("json", "jsonb"):
|
|
190
|
+
text = json.dumps(value)
|
|
191
|
+
else:
|
|
192
|
+
def item(x):
|
|
193
|
+
if x is None:
|
|
194
|
+
return "NULL"
|
|
195
|
+
if isinstance(x, (dict, list)):
|
|
196
|
+
x = json.dumps(x)
|
|
197
|
+
return '"' + str(x).replace("\\", "\\\\").replace('"', '\\"') + '"'
|
|
198
|
+
text = "{" + ",".join(item(x) for x in value) + "}"
|
|
199
|
+
else:
|
|
200
|
+
text = str(value)
|
|
201
|
+
return f"CAST('{text.replace(chr(39), chr(39) * 2)}' AS {t})"
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def render(sql: str, values: dict, types: dict, literal=pg_literal) -> str:
|
|
205
|
+
def one(m: re.Match) -> str:
|
|
206
|
+
name = "p" + m.group(1)
|
|
207
|
+
if name not in values:
|
|
208
|
+
return m.group(0)
|
|
209
|
+
return literal(values[name], types.get(name) or "")
|
|
210
|
+
return re.sub(r"\$(\d+)\b", one, sql)
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _modify_nodes(node: dict, out: list[dict]) -> None:
|
|
214
|
+
if node.get("Node Type") == "ModifyTable":
|
|
215
|
+
out.append(node)
|
|
216
|
+
for c in node.get("Plans") or []:
|
|
217
|
+
_modify_nodes(c, out)
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
class PgWrites:
|
|
221
|
+
def __init__(self, sb, cand: dict, cfg: dict, log):
|
|
222
|
+
self.sb, self.cand, self.cfg, self.log = sb, cand, cfg, log
|
|
223
|
+
self.sql = cand["baseline_sql"].strip().rstrip(";")
|
|
224
|
+
self.stage = "prepare"
|
|
225
|
+
self.cache = getattr(sb, "_codecop_write_cache", None)
|
|
226
|
+
if self.cache is None:
|
|
227
|
+
self.cache = sb._codecop_write_cache = {"rows": {}, "cols": {}}
|
|
228
|
+
self.values: dict = {}
|
|
229
|
+
self.types: dict = {}
|
|
230
|
+
self.how: dict = {}
|
|
231
|
+
self.tried = 0
|
|
232
|
+
self.prelude = "" # statements run first inside every measuring transaction (rolled back with it)
|
|
233
|
+
|
|
234
|
+
# what the server says the parameters are
|
|
235
|
+
def param_types(self) -> dict[str, str]:
|
|
236
|
+
n = sorted({int(x) for x in re.findall(r"\$(\d+)\b", self.sql)})
|
|
237
|
+
if not n:
|
|
238
|
+
return {}
|
|
239
|
+
for _ in range(len(n) + 1):
|
|
240
|
+
try:
|
|
241
|
+
text = self.sb._psql(self.sb.SESSION + f"PREPARE codecop_w AS {self.sb.frozen(self.sql)};\n"
|
|
242
|
+
"SELECT array_to_json(parameter_types::text[]) FROM pg_prepared_statements WHERE name = 'codecop_w';\n").strip()
|
|
243
|
+
break
|
|
244
|
+
except QueryError as e:
|
|
245
|
+
# a parameter the server cannot type from where it stands (`$3 IS NULL OR ...`): typed from its column, else text
|
|
246
|
+
m = re.search(r"could not determine data type of parameter \$(\d+)", str(e))
|
|
247
|
+
if not m:
|
|
248
|
+
raise
|
|
249
|
+
k = m.group(1)
|
|
250
|
+
col = ((self.cand["write"].get("slots") or {}).get(f"p{k}") or {})
|
|
251
|
+
typ = self._column_type(col) or "text"
|
|
252
|
+
self.sql = re.sub(rf"\${k}\b(?!\s*::)", f"${k}::{typ}", self.sql)
|
|
253
|
+
else:
|
|
254
|
+
raise QueryError("parameter types could not be determined")
|
|
255
|
+
got = json.loads(text.splitlines()[-1]) if text else []
|
|
256
|
+
return {f"p{i + 1}": t for i, t in enumerate(got) if i + 1 in n}
|
|
257
|
+
|
|
258
|
+
def _column_type(self, slot: dict) -> str:
|
|
259
|
+
if not slot.get("table") or not slot.get("column"):
|
|
260
|
+
return ""
|
|
261
|
+
try:
|
|
262
|
+
types = self.sb.column_types(slot["table"])
|
|
263
|
+
except QueryError:
|
|
264
|
+
return ""
|
|
265
|
+
return next((t for c, t in types.items() if c.lower() == slot["column"].lower()), "")
|
|
266
|
+
|
|
267
|
+
def rows_of(self, table: str) -> list[dict]:
|
|
268
|
+
key = W.bare(table)
|
|
269
|
+
if key in self.cache["rows"]:
|
|
270
|
+
return self.cache["rows"][key]
|
|
271
|
+
name = next((t for t in self.cand.get("tables") or [] if W.bare(t) == key), table)
|
|
272
|
+
try:
|
|
273
|
+
q = self.sb._q(name) if hasattr(self.sb, "_q") else name
|
|
274
|
+
got = self.sb.rows(f"SELECT * FROM {q} OFFSET (SELECT count(*) / 3 FROM {q}) LIMIT 40")
|
|
275
|
+
if not got:
|
|
276
|
+
got = self.sb.rows(f"SELECT * FROM {q} LIMIT 40")
|
|
277
|
+
except QueryError:
|
|
278
|
+
got = []
|
|
279
|
+
self.cache["rows"][key] = got
|
|
280
|
+
return got
|
|
281
|
+
|
|
282
|
+
def volatile(self, table: str) -> list[str]:
|
|
283
|
+
key = W.bare(table)
|
|
284
|
+
if key in self.cache["cols"]:
|
|
285
|
+
return self.cache["cols"][key]
|
|
286
|
+
try:
|
|
287
|
+
self.sb.column_types(table)
|
|
288
|
+
meta = (getattr(self.sb, "_meta", {}) or {}).get(self.sb._name(table)) or {}
|
|
289
|
+
except QueryError:
|
|
290
|
+
meta = {}
|
|
291
|
+
out = sorted(n for n, c in meta.items() if c.get("identity") or c.get("generated") or PG_VOLATILE_DEFAULT.search(str(c.get("default") or "")))
|
|
292
|
+
self.cache["cols"][key] = out
|
|
293
|
+
return out
|
|
294
|
+
|
|
295
|
+
def explain(self, sql: str, n: int) -> list[dict]:
|
|
296
|
+
script = self.sb.SESSION + "".join(
|
|
297
|
+
f"BEGIN;\n{self.prelude}\\echo {MARK}\nEXPLAIN (ANALYZE, BUFFERS, WAL, TIMING OFF, FORMAT JSON) {sql};\nROLLBACK;\n" for _ in range(n))
|
|
298
|
+
chunks = [c.strip() for c in self.sb._psql(script).split(MARK)[1:]]
|
|
299
|
+
return [json.loads(c)[0] for c in chunks if c]
|
|
300
|
+
|
|
301
|
+
def read(self, plans: list[dict]) -> dict:
|
|
302
|
+
from .engines.postgres import walk_plan, plan_text
|
|
303
|
+
timed = plans[1:] or plans
|
|
304
|
+
best = min(timed, key=lambda p: float(p.get("Execution Time") or 0))
|
|
305
|
+
root = best["Plan"]
|
|
306
|
+
scans: list[dict] = []
|
|
307
|
+
walk_plan(root, scans, {})
|
|
308
|
+
mods: list[dict] = []
|
|
309
|
+
_modify_nodes(root, mods)
|
|
310
|
+
affected = 0
|
|
311
|
+
for mnode in mods:
|
|
312
|
+
ch = (mnode.get("Plans") or [{}])[0]
|
|
313
|
+
affected += int(round(float(ch.get("Actual Rows") or 0) * float(ch.get("Actual Loops") or 1)))
|
|
314
|
+
if mnode.get("Tuples Inserted") is not None:
|
|
315
|
+
affected = max(affected, int(mnode.get("Tuples Inserted") or 0) + int(mnode.get("Conflicting Tuples") or 0))
|
|
316
|
+
bs = getattr(self.sb, "block_size", 8192)
|
|
317
|
+
hit, readb = int(root.get("Shared Hit Blocks") or 0), int(root.get("Shared Read Blocks") or 0)
|
|
318
|
+
trig = best.get("Triggers") or []
|
|
319
|
+
return {"ok": True, "error": "", "read_rows": sum(s["rows"] for s in scans), "read_bytes": (hit + readb) * bs,
|
|
320
|
+
"result_rows": int(round(float(root.get("Actual Rows") or 0))), "duration_ms": float(best.get("Execution Time") or 0),
|
|
321
|
+
"runs": [float(p.get("Execution Time") or 0) for p in timed], "explain": plan_text(root), "scans": scans,
|
|
322
|
+
"node_types": sorted({s["node"] for s in scans}), "shared_hit_blocks": hit, "shared_read_blocks": readb,
|
|
323
|
+
"rows_removed": sum(s["removed"] for s in scans),
|
|
324
|
+
"write": {"kind": self.cand["write"]["kind"], "affected_rows": affected, "wal_bytes": int(root.get("WAL Bytes") or 0),
|
|
325
|
+
"wal_records": int(root.get("WAL Records") or 0), "wal_fpi": int(root.get("WAL FPI") or 0),
|
|
326
|
+
"dirtied_blocks": int(root.get("Shared Dirtied Blocks") or 0), "written_blocks": int(root.get("Shared Written Blocks") or 0),
|
|
327
|
+
"trigger_ms": round(sum(float(t.get("Time") or 0) for t in trig), 3),
|
|
328
|
+
"relations": sorted({m.get("Relation Name") for m in mods if m.get("Relation Name")}),
|
|
329
|
+
"operations": sorted({m.get("Operation") for m in mods if m.get("Operation")})}}
|
|
330
|
+
|
|
331
|
+
def digest(self, sql: str) -> tuple[str | None, str]:
|
|
332
|
+
"""(hash of the final state of every written table and of the RETURNING output, how it was compared)."""
|
|
333
|
+
wd = self.cand["write"]
|
|
334
|
+
tables = [t for t in self.cand.get("tables") or [] if W.bare(t) == W.bare(wd.get("target") or "")] or [wd.get("target")]
|
|
335
|
+
parts = []
|
|
336
|
+
ret = ""
|
|
337
|
+
if wd.get("returning") and not re.match(r"^\s*WITH\b", sql, re.I):
|
|
338
|
+
vol = sorted({c for t in tables for c in self.volatile(t)})
|
|
339
|
+
arr = "ARRAY[" + ",".join("'" + c.replace("'", "''") + "'" for c in vol) + "]::text[]" if vol else "ARRAY[]::text[]"
|
|
340
|
+
ret = (f"\\echo {MARK}\nWITH codecop_w AS ({sql}) SELECT count(*) || ':' || coalesce(sum(hashtextextended((to_jsonb(codecop_w) - {arr})::text, 0)), 0) "
|
|
341
|
+
"FROM codecop_w;\n")
|
|
342
|
+
else:
|
|
343
|
+
ret = f"\\echo {MARK}\n\\o /dev/null\n{sql};\n\\o\n\\echo -\n"
|
|
344
|
+
for t in tables:
|
|
345
|
+
vol = self.volatile(t)
|
|
346
|
+
arr = "ARRAY[" + ",".join("'" + c.replace("'", "''") + "'" for c in vol) + "]::text[]" if vol else "ARRAY[]::text[]"
|
|
347
|
+
q = self.sb._q(t)
|
|
348
|
+
parts.append(f"\\echo {MARK}\nSELECT count(*) || ':' || coalesce(sum(hashtextextended((to_jsonb(r) - {arr})::text, 0)), 0) FROM {q} r;\n")
|
|
349
|
+
script = self.sb.SESSION + "BEGIN;\n" + self.prelude + ret + "".join(parts) + "ROLLBACK;\n"
|
|
350
|
+
out = [c.strip() for c in self.sb._psql(script).split(MARK)[1:]]
|
|
351
|
+
how = ("final rows of " + ", ".join(W.bare(t) for t in tables) + (" and the RETURNING output" if wd.get("returning") and ret.startswith(f"\\echo {MARK}\nWITH") else "")
|
|
352
|
+
+ " (columns a sequence, clock or random default fills left out)")
|
|
353
|
+
return hashlib.sha1("|".join(out).encode()).hexdigest()[:16], how
|
|
354
|
+
|
|
355
|
+
def baseline(self, runs: int) -> dict:
|
|
356
|
+
self.stage = "prepare"
|
|
357
|
+
self.types = self.param_types()
|
|
358
|
+
clock = getattr(self.sb, "clock", "") or ""
|
|
359
|
+
wd = self.cand["write"]
|
|
360
|
+
probe: list[dict] | None = None
|
|
361
|
+
has_where = any((wd.get("slots") or {}).get(p, {}).get("role") == "where" for p in self.types)
|
|
362
|
+
if wd.get("probe_sql") and has_where:
|
|
363
|
+
self.stage = "values"
|
|
364
|
+
other = {p: _default(t, clock) for p, t in self.types.items() if (wd.get("slots") or {}).get(p, {}).get("role") != "where"}
|
|
365
|
+
try:
|
|
366
|
+
probe = self.sb.rows(self.sb.frozen(render(wd["probe_sql"], other, self.types)) + f" LIMIT {int(self.cfg['probe_rows'])}")
|
|
367
|
+
except QueryError:
|
|
368
|
+
probe = None
|
|
369
|
+
fresh = {}
|
|
370
|
+
if any((wd.get("slots") or {}).get(p, {}).get("column", "").lower() in {c.lower() for c in wd.get("unique") or []} for p in self.types):
|
|
371
|
+
fresh = {p: 0 for p in self.types}
|
|
372
|
+
tries = max(1, min(int(self.cfg["probe_rows"]), len(probe) if probe else (int(self.cfg["probe_rows"]) if has_where else 1)))
|
|
373
|
+
chosen = None
|
|
374
|
+
self.stage = "baseline"
|
|
375
|
+
for i in range(tries):
|
|
376
|
+
values, how = choose_values(self.cand, self.types, self.rows_of, fresh, clock, self.cfg, probe, i)
|
|
377
|
+
text = self.sb.frozen(render(self.sql, values, self.types))
|
|
378
|
+
try:
|
|
379
|
+
got = self.read(self.explain(text, 1))
|
|
380
|
+
except QueryError as e:
|
|
381
|
+
if self.prelude or "no unique or exclusion constraint matching the ON CONFLICT" not in str(e) or not wd.get("conflict"):
|
|
382
|
+
raise
|
|
383
|
+
# the sandbox built the table's unique key as a plain index (its generated rows repeat values): inside the
|
|
384
|
+
# rolled-back transaction, one row per conflict key is kept and the key made unique, as production has it
|
|
385
|
+
t = self.sb._q(wd["target"])
|
|
386
|
+
cols = ", ".join('"' + c.replace('"', '""') + '"' for c in wd["conflict"])
|
|
387
|
+
# one pass with a window (a self-join on IS NOT DISTINCT FROM is a nested loop: minutes on 200,000 rows)
|
|
388
|
+
self.prelude = (f"DELETE FROM {t} WHERE ctid IN (SELECT ctid FROM (SELECT ctid, row_number() OVER (PARTITION BY {cols}) "
|
|
389
|
+
f"AS codecop_rn FROM {t}) codecop_d WHERE codecop_rn > 1);\n"
|
|
390
|
+
f"CREATE UNIQUE INDEX codecop_w_conflict ON {t} ({cols});\n")
|
|
391
|
+
got = self.read(self.explain(text, 1))
|
|
392
|
+
self.tried = i + 1
|
|
393
|
+
chosen = (values, how, text, got)
|
|
394
|
+
if got["write"]["affected_rows"] > 0 or not has_where or probe == []:
|
|
395
|
+
break
|
|
396
|
+
values, how, text, got = chosen
|
|
397
|
+
if got["write"]["affected_rows"] == 0 and has_where and wd.get("row_conditions"):
|
|
398
|
+
# no generated row meets the write's other conditions (`completed_at IS NULL` on data where it never is): the
|
|
399
|
+
# row its values come from is given them, inside the rolled-back transaction, as a rule fixture would
|
|
400
|
+
slots = wd.get("slots") or {}
|
|
401
|
+
ident = [(s["column"], pg_literal(values[p], self.types.get(p) or "")) for p, s in slots.items()
|
|
402
|
+
if p in values and s.get("role") == "where" and s.get("op") == "eq" and not s.get("array")
|
|
403
|
+
and W.bare(s.get("table") or "") == W.bare(wd.get("target") or "")]
|
|
404
|
+
if ident:
|
|
405
|
+
t = self.sb._q(wd["target"])
|
|
406
|
+
sets = ", ".join(f'"{c["column"]}" = {c["value"]}' for c in wd["row_conditions"])
|
|
407
|
+
where = " AND ".join(f'"{c}" = {v}' for c, v in ident)
|
|
408
|
+
pre = self.prelude + f"UPDATE {t} SET {sets} WHERE ctid = (SELECT ctid FROM {t} WHERE {where} LIMIT 1);\n"
|
|
409
|
+
old, self.prelude = self.prelude, pre
|
|
410
|
+
try:
|
|
411
|
+
got2 = self.read(self.explain(text, 1))
|
|
412
|
+
except QueryError:
|
|
413
|
+
got2 = None
|
|
414
|
+
if got2 is not None and got2["write"]["affected_rows"] > 0:
|
|
415
|
+
how = {**how, "_row": "the row was given the write's other conditions (" + ", ".join(
|
|
416
|
+
f"{c['column']} = {c['value']}" for c in wd["row_conditions"]) + ") inside the rolled-back transaction"}
|
|
417
|
+
else:
|
|
418
|
+
self.prelude = old
|
|
419
|
+
self.values, self.how, self.text = values, how, text
|
|
420
|
+
m = self.read(self.explain(text, runs + 1))
|
|
421
|
+
h, compared = self.digest(text)
|
|
422
|
+
self.base_hash = h
|
|
423
|
+
m["result_hash"] = h or ""
|
|
424
|
+
m["write"].update(params_used={k: _short(v) for k, v in values.items()}, params_how=how, tried=self.tried,
|
|
425
|
+
predicate_params=has_where, state_hash=h, state_compared=compared, sql_run=text[:4000])
|
|
426
|
+
return m
|
|
427
|
+
|
|
428
|
+
def variant(self, v: dict, runs: int) -> tuple[dict, bool | None, str]:
|
|
429
|
+
sb = self.sb
|
|
430
|
+
try:
|
|
431
|
+
sb.apply_setup(v.get("setup_sql") or [])
|
|
432
|
+
text = sb.frozen(render(v.get("sql") or self.sql, self.values, self.types))
|
|
433
|
+
m = self.read(self.explain(text, runs + 1))
|
|
434
|
+
h, compared = self.digest(text)
|
|
435
|
+
finally:
|
|
436
|
+
sb.undo_setup(v.get("setup_sql") or [])
|
|
437
|
+
m["result_hash"] = h or ""
|
|
438
|
+
if h and self.base_hash and h != self.base_hash:
|
|
439
|
+
# the baseline's own state again: when it is not what it was, the state is not repeatable and nothing is compared
|
|
440
|
+
again, _ = self.digest(self.text)
|
|
441
|
+
if again != self.base_hash:
|
|
442
|
+
return m, None, "not compared: the baseline's final state differs between two runs (a value the database fills per run)"
|
|
443
|
+
return m, (None if not h or not self.base_hash else h == self.base_hash), compared
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
def _short(v):
|
|
447
|
+
if isinstance(v, str) and len(v) > 120:
|
|
448
|
+
return v[:117] + "..."
|
|
449
|
+
if isinstance(v, (dict, list)):
|
|
450
|
+
t = json.dumps(v, default=str)
|
|
451
|
+
return t if len(t) <= 120 else t[:117] + "..."
|
|
452
|
+
return v
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
# ---------------------------------------------------------------------------- SQLite
|
|
456
|
+
|
|
457
|
+
def sqlite_literal(value, typ: str = "") -> str:
|
|
458
|
+
if value is None:
|
|
459
|
+
return "NULL"
|
|
460
|
+
if isinstance(value, bool):
|
|
461
|
+
return "1" if value else "0"
|
|
462
|
+
if isinstance(value, (int, float)):
|
|
463
|
+
return repr(value)
|
|
464
|
+
if isinstance(value, (dict, list)):
|
|
465
|
+
value = json.dumps(value)
|
|
466
|
+
return "'" + str(value).replace("'", "''") + "'"
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
class SqliteWrites:
|
|
470
|
+
"""SQLite: the write runs on a writable measuring connection inside BEGIN ... ROLLBACK."""
|
|
471
|
+
|
|
472
|
+
def __init__(self, sb, cand: dict, cfg: dict, log):
|
|
473
|
+
self.sb, self.cand, self.cfg, self.log = sb, cand, cfg, log
|
|
474
|
+
self.sql = cand["baseline_sql"].strip().rstrip(";")
|
|
475
|
+
self.stage = "prepare"
|
|
476
|
+
self.meter = getattr(sb, "_codecop_write_meter", None)
|
|
477
|
+
self.values, self.types, self.how = {}, {}, {}
|
|
478
|
+
|
|
479
|
+
def _meter(self):
|
|
480
|
+
if self.meter is None:
|
|
481
|
+
from .engines import sqlite as S
|
|
482
|
+
m = S.Meter.__new__(S.Meter)
|
|
483
|
+
m.lib, m.version = S._library()
|
|
484
|
+
import ctypes
|
|
485
|
+
m.db = ctypes.c_void_p()
|
|
486
|
+
path = getattr(self.sb, "path", None) or getattr(self.sb, "db_path", None)
|
|
487
|
+
rc = m.lib.sqlite3_open_v2(str(path).encode(), ctypes.byref(m.db), 2, None) # SQLITE_OPEN_READWRITE
|
|
488
|
+
if rc != 0:
|
|
489
|
+
raise SandboxError(f"SQLite sandbox: could not open a writable measuring connection (code {rc})")
|
|
490
|
+
m._timer = None
|
|
491
|
+
self.meter = self.sb._codecop_write_meter = m
|
|
492
|
+
return self.meter
|
|
493
|
+
|
|
494
|
+
def rows_of(self, table: str) -> list[dict]:
|
|
495
|
+
try:
|
|
496
|
+
return self.sb.rows(f'SELECT * FROM "{W.bare(table)}" LIMIT 40 OFFSET (SELECT count(*) / 3 FROM "{W.bare(table)}")')
|
|
497
|
+
except QueryError:
|
|
498
|
+
return []
|
|
499
|
+
|
|
500
|
+
def _types(self) -> dict[str, str]:
|
|
501
|
+
out = {}
|
|
502
|
+
for n in sorted({int(x) for x in re.findall(r"\$(\d+)\b", self.sql)}):
|
|
503
|
+
s = (self.cand["write"].get("slots") or {}).get(f"p{n}") or {}
|
|
504
|
+
typ = ""
|
|
505
|
+
if s.get("column") and s.get("table"):
|
|
506
|
+
try:
|
|
507
|
+
info = self.sb.rows(f"SELECT type FROM pragma_table_info('{W.bare(s['table'])}') WHERE lower(name) = lower('{s['column']}')")
|
|
508
|
+
typ = (info[0]["type"] if info else "") or ""
|
|
509
|
+
except QueryError:
|
|
510
|
+
typ = ""
|
|
511
|
+
out[f"p{n}"] = typ.lower() or "text"
|
|
512
|
+
return out
|
|
513
|
+
|
|
514
|
+
def run_once(self, text: str, state: bool) -> dict:
|
|
515
|
+
m = self._meter()
|
|
516
|
+
t = float(getattr(self.sb, "statement_timeout_s", 60))
|
|
517
|
+
m.run("BEGIN", t)
|
|
518
|
+
try:
|
|
519
|
+
before = self._changes(m)
|
|
520
|
+
got = m.run(text, t)
|
|
521
|
+
affected = self._changes(m) - before
|
|
522
|
+
h = self._state(m) if state else None
|
|
523
|
+
finally:
|
|
524
|
+
m.run("ROLLBACK", t)
|
|
525
|
+
page = getattr(self.sb, "page_size", 4096)
|
|
526
|
+
return {"ok": True, "error": "", "read_rows": got.full_scan_rows, "read_bytes": got.pages * page, "result_rows": got.rows,
|
|
527
|
+
"duration_ms": round(got.ms, 3), "pages": got.pages, "vm_steps": got.vm_steps,
|
|
528
|
+
"write": {"kind": self.cand["write"]["kind"], "affected_rows": max(affected, 0)}, "result_hash": h or ""}
|
|
529
|
+
|
|
530
|
+
def _changes(self, m) -> int:
|
|
531
|
+
fn = getattr(m.lib, "sqlite3_total_changes", None)
|
|
532
|
+
return int(fn(m.db)) if fn else 0
|
|
533
|
+
|
|
534
|
+
def _state(self, m) -> str:
|
|
535
|
+
t = W.bare(self.cand["write"].get("target") or "")
|
|
536
|
+
import ctypes
|
|
537
|
+
lib = m.lib
|
|
538
|
+
stmt = ctypes.c_void_p()
|
|
539
|
+
sql = f'SELECT count(*), total(length(quote("{t}".rowid)) ) FROM "{t}"'
|
|
540
|
+
cols_sql = f"SELECT group_concat('quote(\"' || name || '\")', '||'',''||') FROM pragma_table_info('{t}')"
|
|
541
|
+
try:
|
|
542
|
+
expr = self.sb.rows(cols_sql)
|
|
543
|
+
expr = list(expr[0].values())[0] if expr else None
|
|
544
|
+
except QueryError:
|
|
545
|
+
expr = None
|
|
546
|
+
sql = f'SELECT {expr} FROM "{t}" ORDER BY 1' if expr else f'SELECT count(*) FROM "{t}"'
|
|
547
|
+
raw = sql.encode()
|
|
548
|
+
if lib.sqlite3_prepare_v2(m.db, raw, len(raw), ctypes.byref(stmt), None) != 0:
|
|
549
|
+
return ""
|
|
550
|
+
h = hashlib.sha1()
|
|
551
|
+
lib.sqlite3_column_text.restype = ctypes.c_char_p
|
|
552
|
+
try:
|
|
553
|
+
while lib.sqlite3_step(stmt) == 100:
|
|
554
|
+
h.update(lib.sqlite3_column_text(stmt, 0) or b"")
|
|
555
|
+
h.update(b"\n")
|
|
556
|
+
finally:
|
|
557
|
+
lib.sqlite3_finalize(stmt)
|
|
558
|
+
return h.hexdigest()[:16]
|
|
559
|
+
|
|
560
|
+
def baseline(self, runs: int) -> dict:
|
|
561
|
+
self.types = self._types()
|
|
562
|
+
wd = self.cand["write"]
|
|
563
|
+
has_where = any((wd.get("slots") or {}).get(p, {}).get("role") == "where" for p in self.types)
|
|
564
|
+
probe = None
|
|
565
|
+
if wd.get("probe_sql") and has_where:
|
|
566
|
+
other = {p: _default(t, "") for p, t in self.types.items() if (wd.get("slots") or {}).get(p, {}).get("role") != "where"}
|
|
567
|
+
try:
|
|
568
|
+
probe = self.sb.rows(render(wd["probe_sql"], other, self.types, sqlite_literal) + f" LIMIT {int(self.cfg['probe_rows'])}")
|
|
569
|
+
except QueryError:
|
|
570
|
+
probe = None
|
|
571
|
+
self.stage = "baseline"
|
|
572
|
+
tries = max(1, min(int(self.cfg["probe_rows"]), len(probe) if probe else (int(self.cfg["probe_rows"]) if has_where else 1)))
|
|
573
|
+
for i in range(tries):
|
|
574
|
+
values, how = choose_values(self.cand, self.types, self.rows_of, {p: 0 for p in self.types}, "", self.cfg, probe, i)
|
|
575
|
+
text = self.sb.frozen(render(self.sql, values, self.types, sqlite_literal))
|
|
576
|
+
got = self.run_once(text, False)
|
|
577
|
+
if got["write"]["affected_rows"] > 0 or not has_where:
|
|
578
|
+
break
|
|
579
|
+
self.values, self.how, self.text = values, how, text
|
|
580
|
+
timed = [self.run_once(text, False) for _ in range(max(runs, 1))]
|
|
581
|
+
m = timed[-1]
|
|
582
|
+
m["runs"] = [t["duration_ms"] for t in timed]
|
|
583
|
+
m["duration_ms"] = min(m["runs"])
|
|
584
|
+
m["result_hash"] = self.run_once(text, True)["result_hash"]
|
|
585
|
+
m["write"].update(params_used={k: _short(v) for k, v in values.items()}, params_how=how, tried=i + 1, predicate_params=has_where,
|
|
586
|
+
state_hash=m["result_hash"], state_compared=f"final rows of {W.bare(wd.get('target') or '')}", sql_run=text[:4000])
|
|
587
|
+
return m
|
|
588
|
+
|
|
589
|
+
def variant(self, v: dict, runs: int) -> tuple[dict, bool | None, str]:
|
|
590
|
+
try:
|
|
591
|
+
self.sb.apply_setup(v.get("setup_sql") or [])
|
|
592
|
+
text = self.sb.frozen(render(v.get("sql") or self.sql, self.values, self.types, sqlite_literal))
|
|
593
|
+
timed = [self.run_once(text, False) for _ in range(max(runs, 1))]
|
|
594
|
+
h = self.run_once(text, True)["result_hash"]
|
|
595
|
+
finally:
|
|
596
|
+
self.sb.undo_setup(v.get("setup_sql") or [])
|
|
597
|
+
m = timed[-1]
|
|
598
|
+
m["runs"] = [t["duration_ms"] for t in timed]
|
|
599
|
+
m["result_hash"] = h
|
|
600
|
+
base = self.run_once(self.text, True)["result_hash"]
|
|
601
|
+
return m, (h == base if h and base else None), f"final rows of {W.bare(self.cand['write'].get('target') or '')}"
|
|
602
|
+
|
|
603
|
+
|
|
604
|
+
# ---------------------------------------------------------------------------- ClickHouse
|
|
605
|
+
|
|
606
|
+
def ch_literal(value, typ: str = "") -> str:
|
|
607
|
+
if value is None:
|
|
608
|
+
return "NULL"
|
|
609
|
+
if isinstance(value, bool):
|
|
610
|
+
return "true" if value else "false"
|
|
611
|
+
if isinstance(value, (int, float)):
|
|
612
|
+
return repr(value)
|
|
613
|
+
if isinstance(value, list):
|
|
614
|
+
return "[" + ", ".join(ch_literal(x) for x in value) + "]"
|
|
615
|
+
if isinstance(value, dict):
|
|
616
|
+
value = json.dumps(value)
|
|
617
|
+
return "'" + str(value).replace("\\", "\\\\").replace("'", "\\'") + "'"
|
|
618
|
+
|
|
619
|
+
|
|
620
|
+
class ChWrites:
|
|
621
|
+
"""ClickHouse: no transactions. An INSERT runs into an empty copy of its table; a mutation on a full copy."""
|
|
622
|
+
|
|
623
|
+
def __init__(self, sb, cand: dict, cfg: dict, log):
|
|
624
|
+
self.sb, self.cand, self.cfg, self.log = sb, cand, cfg, log
|
|
625
|
+
self.sql = cand["baseline_sql"].strip().rstrip(";")
|
|
626
|
+
self.stage = "prepare"
|
|
627
|
+
self.values, self.types, self.how = {}, {}, {}
|
|
628
|
+
|
|
629
|
+
def rows_of(self, table: str) -> list[dict]:
|
|
630
|
+
try:
|
|
631
|
+
return self.sb.rows(f"SELECT * FROM {table} LIMIT 40")
|
|
632
|
+
except QueryError:
|
|
633
|
+
return []
|
|
634
|
+
|
|
635
|
+
def _types(self) -> dict[str, str]:
|
|
636
|
+
out = {}
|
|
637
|
+
wd = self.cand["write"]
|
|
638
|
+
cols = {}
|
|
639
|
+
try:
|
|
640
|
+
for r in self.sb.rows(f"SELECT name, type FROM system.columns WHERE table = '{W.bare(wd['target'])}'"):
|
|
641
|
+
cols[r["name"].lower()] = r["type"]
|
|
642
|
+
except QueryError:
|
|
643
|
+
pass
|
|
644
|
+
for n in sorted({int(x) for x in re.findall(r"\$(\d+)\b", self.sql)}):
|
|
645
|
+
s = (wd.get("slots") or {}).get(f"p{n}") or {}
|
|
646
|
+
out[f"p{n}"] = cols.get((s.get("column") or "").lower()) or "String"
|
|
647
|
+
return out
|
|
648
|
+
|
|
649
|
+
def _copy(self, full: bool) -> str:
|
|
650
|
+
t = self.cand["write"]["target"]
|
|
651
|
+
name = f"codecop_w_{W.bare(t)}_{uuid.uuid4().hex[:6]}"
|
|
652
|
+
db = t.split(".")[0] + "." if "." in t else ""
|
|
653
|
+
self.sb.execute(f"CREATE TABLE {db}{name} AS {t}")
|
|
654
|
+
if full:
|
|
655
|
+
self.sb.execute(f"INSERT INTO {db}{name} SELECT * FROM {t}")
|
|
656
|
+
return db + name
|
|
657
|
+
|
|
658
|
+
def _run(self, text: str, runs: int) -> dict:
|
|
659
|
+
t = self.cand["write"]["target"]
|
|
660
|
+
tag = uuid.uuid4().hex[:12]
|
|
661
|
+
kind = self.cand["write"]["kind"]
|
|
662
|
+
logged = []
|
|
663
|
+
affected = 0
|
|
664
|
+
for i in range(max(runs, 1)):
|
|
665
|
+
copy = self._copy(full=kind == "ch_mutation")
|
|
666
|
+
try:
|
|
667
|
+
body = re.sub(rf"(?<![\w.`\"]){re.escape(t)}(?![\w`\"])", copy, text, count=1)
|
|
668
|
+
settings = {"query_id": f"codecopw-{tag}-{i}", "log_queries": 1, "mutations_sync": 2,
|
|
669
|
+
"max_partitions_per_insert_block": 0}
|
|
670
|
+
self.sb._http(body, None, settings)
|
|
671
|
+
rows = self.sb.rows(f"SELECT count() AS n FROM {copy}")
|
|
672
|
+
affected = int(rows[0]["n"]) if rows and kind != "ch_mutation" else affected
|
|
673
|
+
finally:
|
|
674
|
+
self.sb.execute(f"DROP TABLE IF EXISTS {copy} SYNC")
|
|
675
|
+
self.sb._http("SYSTEM FLUSH LOGS")
|
|
676
|
+
logged = self.sb.rows("SELECT query_id, read_rows, read_bytes, written_rows, written_bytes, query_duration_ms, memory_usage "
|
|
677
|
+
"FROM system.query_log WHERE type = 'QueryFinish' AND query_id LIKE {p:String} ORDER BY query_id",
|
|
678
|
+
{"p": f"codecopw-{tag}-%"})
|
|
679
|
+
if not logged:
|
|
680
|
+
return {"ok": False, "error": "the write did not appear in system.query_log", "write": {"kind": kind}}
|
|
681
|
+
best = min(logged, key=lambda r: int(r["query_duration_ms"]))
|
|
682
|
+
return {"ok": True, "error": "", "read_rows": int(best["read_rows"]), "read_bytes": int(best["read_bytes"]), "result_rows": 0,
|
|
683
|
+
"duration_ms": float(best["query_duration_ms"]), "runs": [float(r["query_duration_ms"]) for r in logged],
|
|
684
|
+
"memory_bytes": max(int(r["memory_usage"]) for r in logged),
|
|
685
|
+
"write": {"kind": kind, "affected_rows": int(best.get("written_rows") or 0) or affected,
|
|
686
|
+
"written_rows": int(best.get("written_rows") or 0), "written_bytes": int(best.get("written_bytes") or 0),
|
|
687
|
+
"copy": "full copy" if kind == "ch_mutation" else "empty copy"}}
|
|
688
|
+
|
|
689
|
+
def baseline(self, runs: int) -> dict:
|
|
690
|
+
self.types = self._types()
|
|
691
|
+
values, how = choose_values(self.cand, self.types, self.rows_of, {p: 0 for p in self.types}, "", self.cfg, None, 0)
|
|
692
|
+
self.values, self.how = values, how
|
|
693
|
+
self.stage = "baseline"
|
|
694
|
+
text = render(self.sql, values, self.types, ch_literal)
|
|
695
|
+
if self.cand["write"].get("kind") == "insert_batch":
|
|
696
|
+
# the driver sends the rows: one block of the table's own rows stands for them (`[writes] limit_value` rows)
|
|
697
|
+
t = self.cand["write"]["target"]
|
|
698
|
+
cols = re.search(r"\(([^()]*)\)\s*$", self.sql.strip())
|
|
699
|
+
pick = cols.group(1) if cols else "*"
|
|
700
|
+
text = f"INSERT INTO {t}{' (' + pick + ')' if cols else ''} SELECT {pick} FROM {t} LIMIT {int(self.cfg['limit_value'])}"
|
|
701
|
+
self.how["_rows"] = f"a block of {int(self.cfg['limit_value'])} of the table's own rows stands for the rows the client sends"
|
|
702
|
+
if re.search(r"\{\w+\s*:\s*[^{}]+\}", text):
|
|
703
|
+
def fill(m):
|
|
704
|
+
typ = m.group(2)
|
|
705
|
+
return ch_literal(_default(typ, ""))
|
|
706
|
+
text = re.sub(r"\{(\w+)\s*:\s*([^{}]+)\}", fill, text)
|
|
707
|
+
self.text = self.sb.frozen(text) if hasattr(self.sb, "frozen") else text
|
|
708
|
+
m = self._run(self.text, runs)
|
|
709
|
+
if m.get("ok"):
|
|
710
|
+
m["write"].update(params_used={k: _short(v) for k, v in values.items()}, params_how=how, predicate_params=False,
|
|
711
|
+
state_compared="rows written to the copy", sql_run=self.text[:4000])
|
|
712
|
+
return m
|
|
713
|
+
|
|
714
|
+
def variant(self, v: dict, runs: int) -> tuple[dict, bool | None, str]:
|
|
715
|
+
m = self._run(render(v.get("sql") or self.sql, self.values, self.types, ch_literal), runs)
|
|
716
|
+
return m, None, "not compared: ClickHouse write variants are measured on copies"
|
|
717
|
+
|
|
718
|
+
|
|
719
|
+
def stamp() -> str:
|
|
720
|
+
return datetime.now(timezone.utc).isoformat(timespec="seconds")
|