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.
Files changed (222) hide show
  1. codecop/__init__.py +7 -0
  2. codecop/access.py +140 -0
  3. codecop/access_postgres.py +284 -0
  4. codecop/advisor.py +1512 -0
  5. codecop/advisor_bench.py +493 -0
  6. codecop/advisor_ch.py +2080 -0
  7. codecop/advisor_view.py +381 -0
  8. codecop/advisors.py +184 -0
  9. codecop/agent.py +221 -0
  10. codecop/agentfacts.py +745 -0
  11. codecop/apply/__init__.py +327 -0
  12. codecop/apply/check.py +344 -0
  13. codecop/apply/cli.py +162 -0
  14. codecop/apply/clickhouse.py +379 -0
  15. codecop/apply/common.py +238 -0
  16. codecop/apply/html.py +264 -0
  17. codecop/apply/patch.py +213 -0
  18. codecop/apply/postgres.py +102 -0
  19. codecop/apply/trial.py +166 -0
  20. codecop/assemble.py +104 -0
  21. codecop/baseline.py +1043 -0
  22. codecop/bench.py +2464 -0
  23. codecop/blockers.py +935 -0
  24. codecop/budget.py +980 -0
  25. codecop/catalog_profile.py +525 -0
  26. codecop/changed.py +261 -0
  27. codecop/cicmd.py +1002 -0
  28. codecop/cli.py +5421 -0
  29. codecop/client.py +729 -0
  30. codecop/coverage.py +1067 -0
  31. codecop/coverage_reasons.py +116 -0
  32. codecop/crashlog.py +70 -0
  33. codecop/datagen.py +766 -0
  34. codecop/datagen_postgres.py +630 -0
  35. codecop/datagen_sqlite.py +323 -0
  36. codecop/dbcli.py +885 -0
  37. codecop/definitions.py +457 -0
  38. codecop/discover/__init__.py +702 -0
  39. codecop/discover/arms.py +160 -0
  40. codecop/discover/base.py +234 -0
  41. codecop/discover/dialect.py +296 -0
  42. codecop/discover/elixir.py +64 -0
  43. codecop/discover/engine_go.py +320 -0
  44. codecop/discover/go.py +1947 -0
  45. codecop/discover/java.py +1528 -0
  46. codecop/discover/loops.py +1671 -0
  47. codecop/discover/named_go.py +258 -0
  48. codecop/discover/origins.py +4565 -0
  49. codecop/discover/origins_ts.py +1584 -0
  50. codecop/discover/orm_django.py +2772 -0
  51. codecop/discover/orm_django_models.py +814 -0
  52. codecop/discover/orm_django_sql.py +662 -0
  53. codecop/discover/orm_ent.py +565 -0
  54. codecop/discover/orm_ex_ecto.py +2138 -0
  55. codecop/discover/orm_go.py +2134 -0
  56. codecop/discover/orm_go_bun.py +602 -0
  57. codecop/discover/orm_go_run.py +636 -0
  58. codecop/discover/orm_go_types.py +1082 -0
  59. codecop/discover/orm_java.py +1450 -0
  60. codecop/discover/orm_jdbi.py +743 -0
  61. codecop/discover/orm_jooq.py +806 -0
  62. codecop/discover/orm_jpa.py +1307 -0
  63. codecop/discover/orm_mybatis.py +730 -0
  64. codecop/discover/orm_py.py +557 -0
  65. codecop/discover/orm_py_peewee.py +1266 -0
  66. codecop/discover/orm_py_prisma.py +298 -0
  67. codecop/discover/orm_rb_activerecord.py +1906 -0
  68. codecop/discover/orm_rust.py +1248 -0
  69. codecop/discover/orm_rust_seaorm.py +734 -0
  70. codecop/discover/orm_sqlalchemy.py +2475 -0
  71. codecop/discover/orm_stats.py +307 -0
  72. codecop/discover/orm_tables.py +29 -0
  73. codecop/discover/orm_ts.py +503 -0
  74. codecop/discover/orm_ts_drizzle.py +697 -0
  75. codecop/discover/orm_ts_knex.py +1117 -0
  76. codecop/discover/orm_ts_kysely.py +861 -0
  77. codecop/discover/orm_ts_prisma.py +1045 -0
  78. codecop/discover/orm_ts_schema.py +169 -0
  79. codecop/discover/orm_ts_sequelize.py +1401 -0
  80. codecop/discover/orm_ts_typeorm.py +1067 -0
  81. codecop/discover/probes.py +323 -0
  82. codecop/discover/python.py +595 -0
  83. codecop/discover/ruby.py +793 -0
  84. codecop/discover/rust.py +2378 -0
  85. codecop/discover/schema.py +520 -0
  86. codecop/discover/schema_ent.py +145 -0
  87. codecop/discover/schema_ts.py +420 -0
  88. codecop/discover/tsresolve.py +257 -0
  89. codecop/discover/typescript.py +1728 -0
  90. codecop/discover/xml_mapper.py +526 -0
  91. codecop/engines/__init__.py +515 -0
  92. codecop/engines/base.py +498 -0
  93. codecop/engines/clickhouse.py +1558 -0
  94. codecop/engines/pg_ddl.py +444 -0
  95. codecop/engines/pg_hints.py +137 -0
  96. codecop/engines/postgres.py +1060 -0
  97. codecop/engines/sqlite.py +742 -0
  98. codecop/families/__init__.py +3 -0
  99. codecop/families/build.py +280 -0
  100. codecop/families/cli.py +177 -0
  101. codecop/families/coverage_hook.py +62 -0
  102. codecop/families/driver.py +221 -0
  103. codecop/families/goslice.py +229 -0
  104. codecop/families/goslice_tool/go.mod +3 -0
  105. codecop/families/goslice_tool/main.go +403 -0
  106. codecop/families/holes.py +451 -0
  107. codecop/families/images/Dockerfile.go +5 -0
  108. codecop/families/images/Dockerfile.python +4 -0
  109. codecop/families/images/Dockerfile.rust +4 -0
  110. codecop/families/isolate.py +171 -0
  111. codecop/families/locate.py +270 -0
  112. codecop/families/model.py +301 -0
  113. codecop/families/plangate.py +271 -0
  114. codecop/families/tagpatch.py +174 -0
  115. codecop/fidelity.py +671 -0
  116. codecop/fixgroups.py +130 -0
  117. codecop/formerly.py +91 -0
  118. codecop/grantscript.py +254 -0
  119. codecop/groupbench.py +1375 -0
  120. codecop/groups.py +594 -0
  121. codecop/groups_view.py +186 -0
  122. codecop/heat.py +1405 -0
  123. codecop/heatcli.py +219 -0
  124. codecop/joins.py +1749 -0
  125. codecop/joins_view.py +127 -0
  126. codecop/kinds/__init__.py +507 -0
  127. codecop/kinds/calls/__init__.py +501 -0
  128. codecop/kinds/calls/extract.py +1097 -0
  129. codecop/kinds/calls/harness.py +408 -0
  130. codecop/kinds/calls/measure.py +342 -0
  131. codecop/kinds/calls/rules.py +139 -0
  132. codecop/kinds/calls/runners/RunCalls.java +167 -0
  133. codecop/kinds/calls/runners/run_go.go +141 -0
  134. codecop/kinds/calls/runners/run_node.js +186 -0
  135. codecop/kinds/calls/runners/run_python.py +319 -0
  136. codecop/kinds/calls/runners/run_rust.rs +200 -0
  137. codecop/kinds/calls/standin.py +340 -0
  138. codecop/kinds/pipeline.py +288 -0
  139. codecop/kinds/regex/__init__.py +1167 -0
  140. codecop/kinds/regex/engines/RegexHarness.java +129 -0
  141. codecop/kinds/regex/engines/run_go.go +294 -0
  142. codecop/kinds/regex/engines/run_node.js +99 -0
  143. codecop/kinds/regex/engines/run_python.py +295 -0
  144. codecop/kinds/regex/engines/run_rust.rs +149 -0
  145. codecop/kinds/regex/extract.py +1438 -0
  146. codecop/kinds/regex/harness.py +235 -0
  147. codecop/kinds/regex/measure.py +270 -0
  148. codecop/kinds/regex/shapes.py +418 -0
  149. codecop/kinds/regex/syntax.py +1721 -0
  150. codecop/kinds/testkind.py +107 -0
  151. codecop/kinds/transaction/__init__.py +228 -0
  152. codecop/kinds/transaction/bind.py +355 -0
  153. codecop/kinds/transaction/measure.py +264 -0
  154. codecop/kinds/transaction/plan.py +462 -0
  155. codecop/kinds/transaction/rules.py +540 -0
  156. codecop/kinds/transaction/sandbox.py +94 -0
  157. codecop/kinds/transaction/scenarios.py +520 -0
  158. codecop/kinds/transaction/schedule.py +483 -0
  159. codecop/kinds/transaction/shapes.py +418 -0
  160. codecop/kinds/transaction/verify.py +293 -0
  161. codecop/live.py +237 -0
  162. codecop/loopbench.py +2071 -0
  163. codecop/loopschema.py +591 -0
  164. codecop/mcpserver.py +120 -0
  165. codecop/mechanism.py +214 -0
  166. codecop/members.py +200 -0
  167. codecop/multi.py +443 -0
  168. codecop/observed.py +1868 -0
  169. codecop/parts.py +102 -0
  170. codecop/patterns.py +830 -0
  171. codecop/patterns_view.py +559 -0
  172. codecop/plangate.py +242 -0
  173. codecop/profile.py +439 -0
  174. codecop/prompts/areas.md +19 -0
  175. codecop/prompts/observed_variants.md +20 -0
  176. codecop/prompts/profile.md +60 -0
  177. codecop/prompts/profile_postgres.md +68 -0
  178. codecop/prompts/profile_sizes.md +26 -0
  179. codecop/prompts/profile_sqlite.md +69 -0
  180. codecop/prompts/rank.md +84 -0
  181. codecop/prompts/rank_postgres.md +96 -0
  182. codecop/prompts/rank_sqlite.md +94 -0
  183. codecop/prompts/scenario_variants.md +20 -0
  184. codecop/rank.py +1473 -0
  185. codecop/realdb/__init__.py +688 -0
  186. codecop/realdb/clickhouse.py +1223 -0
  187. codecop/realdb/facts.py +815 -0
  188. codecop/realdb/locality.py +964 -0
  189. codecop/realdb/locks.py +355 -0
  190. codecop/realdb/match.py +531 -0
  191. codecop/realdb/postgres.py +643 -0
  192. codecop/realdb/ratios.py +77 -0
  193. codecop/realdb/sample.py +126 -0
  194. codecop/relations.py +227 -0
  195. codecop/report.py +1854 -0
  196. codecop/resources.py +332 -0
  197. codecop/resources_view.py +266 -0
  198. codecop/rules/entry_points.toml +1013 -0
  199. codecop/rules/sinks.toml +362 -0
  200. codecop/runsonce.py +8 -0
  201. codecop/sandboxschema.py +555 -0
  202. codecop/scenario_agent.py +172 -0
  203. codecop/scenario_bind.py +507 -0
  204. codecop/scenario_sql.py +971 -0
  205. codecop/scenarios.py +675 -0
  206. codecop/scenarios_view.py +274 -0
  207. codecop/schemacli.py +67 -0
  208. codecop/schemas/areas_output.schema.json +21 -0
  209. codecop/schemas/profile_output.schema.json +362 -0
  210. codecop/schemas/rank_output.schema.json +385 -0
  211. codecop/sizes.py +200 -0
  212. codecop/sqlinfo.py +558 -0
  213. codecop/typedparams.py +576 -0
  214. codecop/verdicts.py +212 -0
  215. codecop/writebench.py +720 -0
  216. codecop/writecost.py +440 -0
  217. codecop/writes.py +1208 -0
  218. codecop-0.1.0.dist-info/METADATA +42 -0
  219. codecop-0.1.0.dist-info/RECORD +222 -0
  220. codecop-0.1.0.dist-info/WHEEL +4 -0
  221. codecop-0.1.0.dist-info/entry_points.txt +2 -0
  222. codecop-0.1.0.dist-info/licenses/LICENSE +21 -0
codecop/writecost.py ADDED
@@ -0,0 +1,440 @@
1
+ """The write side of a table-level variant: what an index, a projection or a new sorting key costs on every insert.
2
+
3
+ A table-level variant reads less, and makes every insert into the table do more. The read gain is the benchmark's
4
+ verdict (bench.verdict); the insert side is measured here, beside it, and never folded into that verdict:
5
+
6
+ 1. a source of the same rows: up to `insert_rows` rows of the loaded table (and at most `insert_sample_bytes` of
7
+ uncompressed data), copied once into a staging table, numbered;
8
+ 2. two empty tables: one with the table's own definition (`CREATE TABLE ... AS`, which keeps its indexes and
9
+ projections), one with the variant's setup applied to it (the index or projection added, or the re-keyed copy's
10
+ definition);
11
+ 3. the same rows inserted into both, in `insert_blocks` inserts, alternating baseline and variant so that a busy
12
+ server slows both alike;
13
+ 4. what each side took: insert time (sum of query_duration_ms), bytes written (query_log written_bytes), and after the
14
+ inserts the active parts and bytes on disk.
15
+
16
+ The ratios (`insert_time_ratio`, `written_bytes_ratio`, `storage_ratio`) are variant over baseline. What decides a
17
+ finding is in blockers.py (`insert_cost_rule`): a table-level variant that reads less is Fixed only when its insert side
18
+ was measured and stays within `[bench] insert_cost_max_time_ratio` and `insert_cost_max_storage_ratio`; above either it
19
+ is a trade-off ("Needs another fix", `fix_costs_inserts`), never counted as fixed. `[bench] insert_cost = false` turns the
20
+ measurement off (then a table-level win says its insert side was not measured).
21
+
22
+ PostgreSQL (`measure_postgres`, an index variant): the same harness on two empty copies made with
23
+ `CREATE TABLE ... (LIKE t INCLUDING ALL)` (the table's own indexes, defaults and identity), the variant's index added
24
+ to one. Each batch is `EXPLAIN (ANALYZE, WAL, FORMAT JSON) INSERT ... SELECT` of the same rows, alternating sides:
25
+ execution time, WAL bytes (the plan's own count; `pg_current_wal_insert_lsn` deltas when the server has no WAL option),
26
+ and after the inserts the size on disk of each copy and of the new index. The ratios and the rule are the same; the
27
+ WAL ratio is reported beside them and decides only when `insert_cost_max_wal_ratio` is set above 0 (off by default).
28
+
29
+ Insert time on PostgreSQL is noisy at this size (one index can measure well apart across runs), so a verdict near the
30
+ limit flipped from run to run. The batches are therefore repeated `insert_rounds` times (both copies emptied between
31
+ rounds; the side that goes first alternates per batch and per round): `insert_time_ratio` is the median of the rounds'
32
+ ratios and `insert_time_ratio_range` [lowest, highest] their spread. The limit decides on the whole spread: within only
33
+ when the highest round is within it, over when the lowest round is over it. When the limit lies inside the spread the
34
+ outcome is a trade-off labelled "insert cost near the limit" (`near_limit`, reason `insert_cost_near_limit`): never
35
+ fixed, so the verdict does not flip with the noise.
36
+ """
37
+
38
+ from __future__ import annotations
39
+
40
+ import re
41
+ import time
42
+ import uuid
43
+
44
+ from .engines.base import QueryError
45
+
46
+ DEFAULTS = {"insert_cost": True, "insert_rows": 200_000, "insert_sample_bytes": 256_000_000, "insert_blocks": 10,
47
+ "insert_cost_max_time_ratio": 1.5, "insert_cost_max_storage_ratio": 1.5, "insert_cost_max_wal_ratio": 0.0,
48
+ "insert_rounds": 3}
49
+ TABLE_LEVEL_KINDS = ("skip_index", "projection", "ordering_key")
50
+ PG_TABLE_LEVEL_KINDS = ("index",)
51
+ ADD = re.compile(r"^\s*ALTER\s+TABLE\s+([`\"\w.]+)\s+(ADD\s+(?:INDEX|PROJECTION)\b.*)$", re.I | re.S)
52
+ MATERIALIZE = re.compile(r"^\s*ALTER\s+TABLE\s+[`\"\w.]+\s+MATERIALIZE\s+(?:INDEX|PROJECTION)\b", re.I)
53
+ CREATE = re.compile(r"^\s*CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?([`\"\w.]+)(.*)$", re.I | re.S)
54
+ INSERT = re.compile(r"^\s*INSERT\s+INTO\b", re.I)
55
+
56
+
57
+ def settings_of(config: dict | None) -> dict:
58
+ out = dict(DEFAULTS)
59
+ for k, d in DEFAULTS.items():
60
+ v = (config or {}).get(k)
61
+ if v is None:
62
+ continue
63
+ if isinstance(d, bool):
64
+ if isinstance(v, bool):
65
+ out[k] = v
66
+ elif isinstance(v, (int, float)) and not isinstance(v, bool) and (v > 0 or (k == "insert_cost_max_wal_ratio" and v >= 0)):
67
+ out[k] = type(d)(v)
68
+ return out
69
+
70
+
71
+ def table_level(variant: dict, engine: str = "clickhouse") -> bool:
72
+ return variant.get("kind") in (PG_TABLE_LEVEL_KINDS if engine == "postgres" else TABLE_LEVEL_KINDS)
73
+
74
+
75
+ def _bare(name: str) -> str:
76
+ return name.strip("`\"").split(".")[-1]
77
+
78
+
79
+ def variant_setup(setup_sql: list[str], table: str, target: str) -> tuple[str | None, list[str]] | None:
80
+ """(CREATE for the variant table or None to copy the table's own, the ALTERs to run on it) with every name of the
81
+ table (or of the re-keyed copy) replaced by `target`. None when the setup holds something this can not replay."""
82
+ create, alters = None, []
83
+ for stmt in setup_sql or []:
84
+ s = stmt.strip().rstrip(";")
85
+ if not s:
86
+ continue
87
+ m = ADD.match(s)
88
+ if m and _bare(m.group(1)).lower() == table.lower():
89
+ alters.append(f"ALTER TABLE {target} {m.group(2)}")
90
+ continue
91
+ if MATERIALIZE.match(s) or INSERT.match(s):
92
+ continue # the table is empty; the rows are inserted after the setup
93
+ m = CREATE.match(s)
94
+ if m and create is None:
95
+ rest = re.sub(rf"(\bAS\s+)[`\"]?{re.escape(table)}[`\"]?(?=\s|$)", rf"\1{table}", m.group(2), count=1, flags=re.I)
96
+ create = f"CREATE TABLE {target}{rest}"
97
+ continue
98
+ return None
99
+ return create, alters
100
+
101
+
102
+ def measure(sb, table: str, setup_sql: list[str], settings: dict, log=lambda msg: None) -> dict:
103
+ """The insert side of one table-level variant on `table` (already loaded in the sandbox). Always returns a record:
104
+ {measured: False, reason} when it could not be measured."""
105
+ if getattr(sb, "engine", "") == "postgres":
106
+ return measure_postgres(sb, table, setup_sql, settings)
107
+ cfg = settings_of(settings)
108
+ name = _bare(table)
109
+ plan = variant_setup(setup_sql, name, "codecop_wc_var")
110
+ if plan is None:
111
+ return {"measured": False, "reason": "setup_not_replayable"}
112
+ tag = uuid.uuid4().hex[:8]
113
+ src, base, var = f"codecop_wc_src_{tag}", f"codecop_wc_base_{tag}", f"codecop_wc_var_{tag}"
114
+ create, alters = plan
115
+ create = create.replace("codecop_wc_var", var, 1) if create else None
116
+ alters = [a.replace("codecop_wc_var", var, 1) for a in alters]
117
+ try:
118
+ # a table whose unread columns hold filler (bench.ReadColumns) has a sample of rows with full content: the
119
+ # inserts are measured on it, so a filled row's cheaper compression does not make an index look dearer
120
+ full = (getattr(sb, "full_width", None) or {}).get(table) or (getattr(sb, "full_width", None) or {}).get(name)
121
+ source = full or name
122
+ stats = sb.table_stats(source)
123
+ rows = int(stats.get("rows") or 0)
124
+ if rows <= 0:
125
+ return {"measured": False, "reason": "table_empty"}
126
+ width = float(stats.get("uncompressed") or 0) / rows if rows else 0.0
127
+ n = min(rows, int(cfg["insert_rows"]), int(cfg["insert_sample_bytes"] / width) if width > 0 else rows)
128
+ n = max(n, 1)
129
+ sb.execute(f"CREATE TABLE {src} ENGINE = MergeTree ORDER BY codecop_n AS SELECT *, rowNumberInAllBlocks() AS codecop_n FROM {source} LIMIT {n}")
130
+ sb.execute(f"CREATE TABLE {base} AS {name}")
131
+ if create:
132
+ sb.execute(create)
133
+ else:
134
+ sb.execute(f"CREATE TABLE {var} AS {name}")
135
+ if alters:
136
+ sb.apply_setup(alters)
137
+ blocks = max(int(cfg["insert_blocks"]), 1)
138
+ ids = {"base": [], "var": []}
139
+ for k in range(blocks):
140
+ for side, target in (("base", base), ("var", var)):
141
+ qid = f"codecop-wc-{tag}-{side}-{k}"
142
+ sb._http(f"INSERT INTO {target} SELECT * EXCEPT codecop_n FROM {src} WHERE codecop_n % {blocks} = {k}", None,
143
+ {"query_id": qid, "log_queries": 1, "insert_deduplicate": 0, "max_insert_threads": 1, "async_insert": 0})
144
+ ids[side].append(qid)
145
+ sb._http("SYSTEM FLUSH LOGS")
146
+ out = {"measured": True, "rows": n, "blocks": blocks, "basis": "the same rows inserted into the table as it is and with the variant"}
147
+ for side, target in (("base", base), ("var", var)):
148
+ r = sb.rows("SELECT sum(query_duration_ms) AS ms, sum(written_rows) AS wrows, sum(written_bytes) AS wbytes, max(memory_usage) AS mem "
149
+ "FROM system.query_log WHERE type = 'QueryFinish' AND query_id LIKE {p:String}", {"p": f"codecop-wc-{tag}-{side}-%"})
150
+ st = sb.table_stats(target)
151
+ row = r[0] if r else {}
152
+ out["baseline" if side == "base" else "variant"] = {
153
+ "insert_ms": float(row.get("ms") or 0), "written_rows": int(row.get("wrows") or 0), "written_bytes": int(row.get("wbytes") or 0),
154
+ "memory_bytes": int(row.get("mem") or 0), "parts": int(st.get("parts") or 0), "bytes_on_disk": int(st.get("bytes_on_disk") or 0)}
155
+ b, v = out["baseline"], out["variant"]
156
+ out["insert_time_ratio"] = round(v["insert_ms"] / b["insert_ms"], 3) if b["insert_ms"] else None
157
+ out["written_bytes_ratio"] = round(v["written_bytes"] / b["written_bytes"], 3) if b["written_bytes"] else None
158
+ out["storage_ratio"] = round(v["bytes_on_disk"] / b["bytes_on_disk"], 3) if b["bytes_on_disk"] else None
159
+ out["parts_ratio"] = round(v["parts"] / b["parts"], 3) if b["parts"] else None
160
+ out["thresholds"] = {"insert_cost_max_time_ratio": cfg["insert_cost_max_time_ratio"],
161
+ "insert_cost_max_storage_ratio": cfg["insert_cost_max_storage_ratio"]}
162
+ out["within"] = within(out, cfg)
163
+ return out
164
+ except QueryError as e:
165
+ return {"measured": False, "reason": "server_error", "error": str(e)[:300]}
166
+ finally:
167
+ for t in (var, base, src):
168
+ try:
169
+ sb.execute(f"DROP TABLE IF EXISTS {t} SYNC")
170
+ except QueryError:
171
+ pass
172
+
173
+
174
+ def _time_range(rec: dict) -> tuple[float, float] | None:
175
+ """(lowest, highest) insert time ratio: the measured spread when there is one, else the one ratio."""
176
+ r = rec.get("insert_time_ratio_range")
177
+ if isinstance(r, (list, tuple)) and len(r) == 2 and all(isinstance(x, (int, float)) and not isinstance(x, bool) for x in r):
178
+ return float(min(r)), float(max(r))
179
+ t = rec.get("insert_time_ratio")
180
+ return (float(t), float(t)) if isinstance(t, (int, float)) and not isinstance(t, bool) else None
181
+
182
+
183
+ def _others_within(rec: dict, cfg: dict) -> bool:
184
+ s, w = rec.get("storage_ratio"), rec.get("wal_bytes_ratio")
185
+ wal_cap = float(cfg.get("insert_cost_max_wal_ratio") or 0)
186
+ return (s is None or s <= cfg["insert_cost_max_storage_ratio"]) and (not wal_cap or w is None or w <= wal_cap)
187
+
188
+
189
+ def within(rec: dict, cfg: dict) -> bool | None:
190
+ """Whether a measured insert side stays within the thresholds; None when it was not measured. With a measured spread
191
+ of the insert time (`insert_time_ratio_range`), within only when its highest round is."""
192
+ if not rec or not rec.get("measured"):
193
+ return None
194
+ t = _time_range(rec)
195
+ return (t is None or t[1] <= cfg["insert_cost_max_time_ratio"]) and _others_within(rec, cfg)
196
+
197
+
198
+ def near_limit(rec: dict, cfg: dict) -> bool:
199
+ """The insert time limit lies inside the measured spread (the lowest round within it, the highest over it) and nothing
200
+ else is over: a trade-off labelled "insert cost near the limit", never fixed and never flipping with the noise."""
201
+ if not rec or not rec.get("measured"):
202
+ return False
203
+ t = _time_range(rec)
204
+ limit = cfg["insert_cost_max_time_ratio"]
205
+ return t is not None and t[0] <= limit < t[1] and _others_within(rec, cfg)
206
+
207
+
208
+ def _median(xs: list[float]) -> float:
209
+ ys = sorted(xs)
210
+ m = len(ys) // 2
211
+ return round(ys[m] if len(ys) % 2 else (ys[m - 1] + ys[m]) / 2, 3)
212
+
213
+
214
+ PG_INDEX = re.compile(r'^\s*CREATE\s+(UNIQUE\s+)?INDEX\s+(?:CONCURRENTLY\s+)?(?:IF\s+NOT\s+EXISTS\s+)?(?:([\w"$]+)\s+)?ON\s+(?:ONLY\s+)?'
215
+ r'((?:"[^"]+"|[\w$]+)(?:\.(?:"[^"]+"|[\w$]+))?)', re.I)
216
+
217
+
218
+ def pg_variant_setup(setup_sql: list[str], table: str, target: str) -> list[str] | None:
219
+ """The variant's CREATE INDEX statements on `table`, rewritten onto `target` (unnamed, so the server names them).
220
+ ANALYZE, CREATE STATISTICS and CREATE EXTENSION are left out (nothing to replay on a copy). None when the setup holds
221
+ anything else: it can not be replayed on an empty copy."""
222
+ from .engines.pg_ddl import split_statements, unquote
223
+ out = []
224
+ for script in setup_sql or []:
225
+ for stmt in split_statements(script):
226
+ m = PG_INDEX.match(stmt)
227
+ if not m:
228
+ # statistics, and an extension the index needs (pg_trgm, btree_gin): the variant's own setup made it in
229
+ # this database already, so the copies have it too
230
+ if re.match(r"^\s*(ANALYZE|CREATE\s+STATISTICS|CREATE\s+EXTENSION)\b", stmt, re.I):
231
+ continue
232
+ return None
233
+ if unquote(m.group(3)).split(".")[-1].lower() != table.split(".")[-1].lower():
234
+ return None
235
+ out.append(f"CREATE {'UNIQUE ' if m.group(1) else ''}INDEX ON {target}" + stmt[m.end():])
236
+ return out or None
237
+
238
+
239
+ def index_key(table: str, setup_sql: list[str], stats: dict, cfg: dict, existing: str = "") -> tuple | None:
240
+ """What an insert-side measurement depends on: the table as loaded (its rows and size, and the indexes it has now,
241
+ names left out: the copies are made LIKE it), the index statements as they are replayed on a copy (names left out) and
242
+ the settings. Two variants (or a variant and an advisor suggestion) that add the same index to the same loaded table
243
+ are measured once (`sb.insert_cost_cache`)."""
244
+ plan = pg_variant_setup(setup_sql, table, "codecop_wc_target")
245
+ if plan is None:
246
+ return None
247
+ return (table.replace('"', "").split(".")[-1].lower(), int(stats.get("rows") or 0), int(stats.get("bytes_on_disk") or 0), existing,
248
+ tuple(sorted(" ".join(s.split()).lower() for s in plan)),
249
+ tuple(sorted((k, v) for k, v in cfg.items() if k.startswith("insert"))))
250
+
251
+
252
+ def _existing_indexes(sb, q: str) -> str:
253
+ """The table's indexes as definitions without their names, sorted: what a LIKE ... INCLUDING ALL copy carries."""
254
+ return sb._psql(f"SELECT coalesce(string_agg(d, ';' ORDER BY d), '') FROM (SELECT regexp_replace(pg_get_indexdef(indexrelid), "
255
+ f"'^CREATE (UNIQUE )?INDEX \\S+ ON ', 'CREATE \\1INDEX ON ') AS d FROM pg_index WHERE indrelid = '{q}'::regclass) x;").strip()
256
+
257
+
258
+ def release_sources(sb) -> None:
259
+ """Drop the staging copies of loaded rows the insert-side measurements share (after a load group)."""
260
+ for src in list((getattr(sb, "_wc_sources", None) or {}).values()):
261
+ try:
262
+ sb.execute(f"DROP TABLE IF EXISTS {src[0]}")
263
+ except QueryError:
264
+ pass
265
+ sb._wc_sources = {}
266
+ sb.insert_cost_cache = {}
267
+
268
+
269
+ MARK = "codecop-wc-mark"
270
+
271
+
272
+ def _round_script(blocks: int, r: int, base: str, var: str, names: str, overriding: str, src: str, wal: bool) -> tuple[str, list[str]]:
273
+ """One round of alternating batches as one psql session: per batch the WAL position, the EXPLAIN ANALYZE of the insert
274
+ and the WAL position again, each after a marker. The timings are the server's own (EXPLAIN's Execution Time, the WAL
275
+ position), so running them in one session changes nothing measured; it only saves a client round trip per statement."""
276
+ lsn = "SELECT pg_wal_lsn_diff(pg_current_wal_insert_lsn(), '0/0')::bigint;"
277
+ lines, sides = [], []
278
+ for k in range(blocks):
279
+ # alternating which side goes first, per batch and per round, so that neither always meets a cold cache or a
280
+ # fresh file extension
281
+ order = (("base", base), ("var", var)) if (k + r) % 2 == 0 else (("var", var), ("base", base))
282
+ for side, target in order:
283
+ insert = f"INSERT INTO {target} ({names}){overriding} SELECT {names} FROM {src} WHERE codecop_n % {blocks} = {k}"
284
+ lines += [f"\\echo {MARK}", lsn, f"\\echo {MARK}",
285
+ f"EXPLAIN (ANALYZE, {'WAL, ' if wal else ''}TIMING OFF, FORMAT JSON) {insert};", f"\\echo {MARK}", lsn]
286
+ sides.append(side)
287
+ return "\n".join(lines) + "\n", sides
288
+
289
+
290
+ def measure_postgres(sb, table: str, setup_sql: list[str], settings: dict | None) -> dict:
291
+ """The insert side of an index on a PostgreSQL sandbox table: the same rows into a copy with and without it. The same
292
+ index on the same loaded table is measured once per load group (`sb.insert_cost_cache`, record `same_index_as`);
293
+ the staging copy of the rows is shared by every index of the table."""
294
+ import copy as _copy
295
+ import json as _json
296
+ cfg = settings_of(settings)
297
+ tag = uuid.uuid4().hex[:8]
298
+ base, var = f"codecop_wc_base_{tag}", f"codecop_wc_var_{tag}"
299
+ plan = pg_variant_setup(setup_sql, table, var)
300
+ if plan is None:
301
+ return {"measured": False, "reason": "setup_not_replayable"}
302
+ q = sb._q(table)
303
+ try:
304
+ stats = sb.table_stats(table)
305
+ rows = int(stats.get("rows") or 0)
306
+ if rows <= 0:
307
+ return {"measured": False, "reason": "table_empty"}
308
+ key = index_key(table, setup_sql, stats, cfg, _existing_indexes(sb, q))
309
+ cache = getattr(sb, "insert_cost_cache", None)
310
+ if cache is None:
311
+ cache = sb.insert_cost_cache = {}
312
+ if key is not None and key in cache:
313
+ # the same index on the same rows, measured a moment ago: the measurement is the same one, said so
314
+ return {**_copy.deepcopy(cache[key]), "same_index_as": cache[key].get("measured_at") or "an earlier variant"}
315
+ width = float(stats.get("heap_bytes") or 0) / rows if rows else 0.0
316
+ n = max(min(rows, int(cfg["insert_rows"]), int(cfg["insert_sample_bytes"] / width) if width > 0 else rows), 1)
317
+ cols = sb.rows(f"SELECT a.attname AS name, a.attidentity AS ident FROM pg_attribute a WHERE a.attrelid = '{q}'::regclass "
318
+ "AND a.attnum > 0 AND NOT a.attisdropped AND a.attgenerated = '' ORDER BY a.attnum")
319
+ names = ", ".join('"' + c["name"].replace('"', '""') + '"' for c in cols)
320
+ overriding = " OVERRIDING SYSTEM VALUE" if any(c.get("ident") == "a" for c in cols) else ""
321
+ sources = getattr(sb, "_wc_sources", None)
322
+ if sources is None:
323
+ sources = sb._wc_sources = {}
324
+ skey = (key[0] if key else table, rows, int(stats.get("bytes_on_disk") or 0), n)
325
+ held = sources.get(skey[0])
326
+ if held is not None and held[1] != skey:
327
+ sb.execute(f"DROP TABLE IF EXISTS {held[0]}") # the table was loaded again since: a new sample of its rows
328
+ held = None
329
+ if held is None:
330
+ src = f"codecop_wc_src_{tag}"
331
+ sb.execute(f"CREATE UNLOGGED TABLE {src} AS SELECT {names}, (row_number() OVER ()) - 1 AS codecop_n FROM {q} LIMIT {n}")
332
+ # the first reader of fresh rows sets their hint bits and reads them from disk: done here, so neither side pays it
333
+ # (the staging copy is only read whole: its visibility map does not matter, so no CHECKPOINT first; the comment
334
+ # keeps the sandbox from adding one, engines/postgres.VACUUM_RE)
335
+ sb.execute(f"/* staging */ VACUUM (ANALYZE) {src}")
336
+ sources[skey[0]] = (src, skey)
337
+ else:
338
+ src = held[0]
339
+ sb.execute(f"CREATE TABLE {base} (LIKE {q} INCLUDING ALL)")
340
+ sb.execute(f"CREATE TABLE {var} (LIKE {q} INCLUDING ALL)")
341
+ for stmt in plan:
342
+ sb.execute(stmt)
343
+ blocks = max(int(cfg["insert_blocks"]), 1)
344
+ rounds = max(int(cfg["insert_rounds"]), 1)
345
+ sides = {"base": {"ms": 0.0, "wal": 0, "wal_lsn": 0}, "var": {"ms": 0.0, "wal": 0, "wal_lsn": 0}}
346
+ wal_option = True
347
+ round_ms: list[tuple[float, float]] = []
348
+ for r in range(rounds):
349
+ if r:
350
+ sb.execute(f"TRUNCATE {base}, {var}") # the same rows again into empty copies: each round is a repeat
351
+ ms = {"base": 0.0, "var": 0.0}
352
+ script, order = _round_script(blocks, r, base, var, names, overriding, src, wal_option)
353
+ try:
354
+ text = sb._psql(script)
355
+ except QueryError:
356
+ if not wal_option or r:
357
+ raise
358
+ wal_option = False # a server before 13 has no WAL option: time and the LSN delta
359
+ sb.execute(f"TRUNCATE {base}, {var}")
360
+ script, order = _round_script(blocks, r, base, var, names, overriding, src, wal_option)
361
+ text = sb._psql(script)
362
+ parts = [x.strip() for x in text.split(MARK)[1:]]
363
+ for i, side in enumerate(order):
364
+ before, out, after = parts[3 * i], parts[3 * i + 1], parts[3 * i + 2]
365
+ p = _json.loads(out)[0]
366
+ ms[side] += float(p.get("Execution Time") or 0)
367
+ sides[side]["ms"] += float(p.get("Execution Time") or 0)
368
+ sides[side]["wal"] += int((p.get("Plan") or {}).get("WAL Bytes") or 0)
369
+ sides[side]["wal_lsn"] += max(int(after or 0) - int(before or 0), 0)
370
+ round_ms.append((ms["base"], ms["var"]))
371
+ sizes = sb.rows(f"SELECT pg_total_relation_size('{base}'::regclass) AS base, pg_total_relation_size('{var}'::regclass) AS var, "
372
+ f"pg_indexes_size('{var}'::regclass) - pg_indexes_size('{base}'::regclass) AS index_bytes")[0]
373
+ out = {"measured": True, "engine": "postgres", "rows": n, "blocks": blocks, "rounds": rounds,
374
+ "basis": "the same rows inserted into two empty copies of the table, one with the index, in alternating batches, "
375
+ "repeated per round"}
376
+ for side, label, size in (("base", "baseline", int(sizes["base"])), ("var", "variant", int(sizes["var"]))):
377
+ wal = sides[side]["wal"] if sides[side]["wal"] else sides[side]["wal_lsn"]
378
+ out[label] = {"insert_ms": round(sides[side]["ms"], 2), "wal_bytes": wal, "bytes_on_disk": size}
379
+ out["wal_from"] = "explain_wal" if sides["base"]["wal"] else "wal_lsn_delta"
380
+ b, v = out["baseline"], out["variant"]
381
+ out["index_bytes"] = int(sizes["index_bytes"] or 0)
382
+ ratios = [round(vm / bm, 3) for bm, vm in round_ms if bm]
383
+ out["insert_time_ratios"] = ratios
384
+ out["insert_time_ratio"] = _median(ratios) if ratios else None
385
+ out["insert_time_ratio_range"] = [min(ratios), max(ratios)] if ratios else None
386
+ out["wal_bytes_ratio"] = round(v["wal_bytes"] / b["wal_bytes"], 3) if b["wal_bytes"] else None
387
+ out["storage_ratio"] = round(v["bytes_on_disk"] / b["bytes_on_disk"], 3) if b["bytes_on_disk"] else None
388
+ out["thresholds"] = {"insert_cost_max_time_ratio": cfg["insert_cost_max_time_ratio"],
389
+ "insert_cost_max_storage_ratio": cfg["insert_cost_max_storage_ratio"],
390
+ "insert_cost_max_wal_ratio": cfg["insert_cost_max_wal_ratio"]}
391
+ out["within"] = within(out, cfg)
392
+ out["near_limit"] = near_limit(out, cfg)
393
+ out["measured_at"] = time.strftime("%H:%M:%S")
394
+ if key is not None:
395
+ cache[key] = _copy.deepcopy(out)
396
+ return out
397
+ except (QueryError, ValueError, KeyError, IndexError) as e:
398
+ return {"measured": False, "reason": "server_error", "error": str(e)[:300]}
399
+ finally:
400
+ for t in (var, base):
401
+ try:
402
+ sb.execute(f"DROP TABLE IF EXISTS {t}")
403
+ except QueryError:
404
+ pass
405
+
406
+
407
+ def measure_findings(sb, rank: dict, findings: list[dict], settings: dict | None, log=lambda msg: None) -> int:
408
+ """Measure the insert side of every table-level variant that read less (verdict win or mixed) in `findings` (one
409
+ scale's bench records), in place: `insert_cost` on the variant's record. Returns how many were measured."""
410
+ cfg = settings_of(settings)
411
+ engine = getattr(sb, "engine", "")
412
+ if not cfg["insert_cost"] or engine not in ("clickhouse", "postgres"):
413
+ return 0
414
+ cands = {c["finding"]: c for c in rank.get("candidates") or []}
415
+ done = 0
416
+ started = time.monotonic()
417
+ for f in findings:
418
+ c = cands.get(f.get("finding"))
419
+ if c is None or not (f.get("baseline") or {}).get("ok"):
420
+ continue
421
+ for rec in f.get("variants") or []:
422
+ i = rec.get("index", 0)
423
+ v = c["variants"][i] if i < len(c.get("variants") or []) else {}
424
+ if not table_level(v, engine) or rec.get("verdict") not in ("win", "mixed"):
425
+ continue
426
+ table = next((t for t in c.get("tables") or [] if any(re.search(rf"\b{re.escape(_bare(t))}\b", s) for s in v.get("setup_sql") or [])), None)
427
+ if table is None:
428
+ rec["insert_cost"] = {"measured": False, "reason": "table_not_found_in_setup"}
429
+ continue
430
+ rec["insert_cost"] = measure(sb, table, v.get("setup_sql") or [], cfg, log)
431
+ done += rec["insert_cost"].get("measured", False)
432
+ ic = rec["insert_cost"]
433
+ if ic.get("measured"):
434
+ log(f"{f['finding']} variant {i + 1} ({v['kind']}): insert side x{ic.get('insert_time_ratio')} time, "
435
+ f"x{ic.get('storage_ratio')} storage over {ic['rows']:,} rows in {ic['blocks']} inserts")
436
+ else:
437
+ log(f"{f['finding']} variant {i + 1} ({v['kind']}): insert side not measured ({ic.get('reason')})")
438
+ if done:
439
+ log(f"insert side of {done} table-level variant(s) measured in {time.monotonic() - started:.0f}s")
440
+ return done