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
@@ -0,0 +1,483 @@
1
+ """The concurrency schedule: N sessions of CodeCop's own, each running the same short program (the extracted statements in
2
+ the transaction's order, a think time standing in for the external call), against a sandbox database built from the
3
+ repository's schema with generated rows. No repository code runs here.
4
+
5
+ Two databases: PostgreSQL in a throwaway container (`PgDb`, pg8000 sessions over a port published on 127.0.0.1) and
6
+ SQLite in-process (`SqliteDb`, one connection per thread on a temporary file). A run records, per session, what each
7
+ statement did (lanes: run, wait, call, error, dup), errors by class (deadlock, busy, serialization, lock timeout,
8
+ unique), the scenario's own counters (duplicates, lost updates), and on PostgreSQL a sampler that reads
9
+ pg_stat_activity inside the sandbox (sessions waiting on a lock, idle in a transaction). Verdicts rest on counts and
10
+ throughput ratios; tail latencies and lock-wait shares are shown, never judged (they move several times over from run to run).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import os
16
+ import random
17
+ import shutil
18
+ import sqlite3
19
+ import statistics
20
+ import tempfile
21
+ import threading
22
+ import time
23
+ from dataclasses import dataclass, field
24
+ from typing import Any, Callable
25
+
26
+ # lanes kept for the console drawing: the first sessions, a bounded number of segments each
27
+ LANE_SESSIONS = 6
28
+ LANE_SEGMENTS = 80
29
+ # a statement that took this much longer than its program's quickest run of the same statement waited (SQLite has no
30
+ # wait sampler; its busy handler sleeps inside the statement)
31
+ WAIT_FLOOR_MS = 2.0
32
+ # a session stops after this many operations in a row failed with an error contention does not explain
33
+ STUCK_AFTER = 25
34
+
35
+
36
+ class DbError(Exception):
37
+ """A statement failed in the sandbox; `cls` is its class (deadlock, busy, serialization, lock_timeout, unique, fk, other)."""
38
+
39
+ def __init__(self, cls: str, message: str):
40
+ super().__init__(message)
41
+ self.cls = cls
42
+
43
+
44
+ # --- databases -----------------------------------------------------------------------------------------------------------
45
+
46
+ class SqliteDb:
47
+ """In-process SQLite on a temporary file. `journal_mode` and `busy_timeout_ms` are the settings under test."""
48
+
49
+ engine = "sqlite"
50
+
51
+ def __init__(self, journal_mode: str = "delete", busy_timeout_ms: int = 0, synchronous: str = "normal"):
52
+ self.journal_mode, self.busy_timeout_ms, self.synchronous = journal_mode, int(busy_timeout_ms), synchronous
53
+ self.dir = tempfile.mkdtemp(prefix="codecop-tx-")
54
+ self.path = os.path.join(self.dir, "t.db")
55
+ self.version = sqlite3.sqlite_version
56
+
57
+ def settings(self) -> dict:
58
+ return {"journal_mode": self.journal_mode, "busy_timeout_ms": self.busy_timeout_ms, "synchronous": self.synchronous}
59
+
60
+ def reset(self, setup: list[str]) -> None:
61
+ for suffix in ("", "-wal", "-shm", "-journal"):
62
+ try:
63
+ os.remove(self.path + suffix)
64
+ except OSError:
65
+ pass
66
+ c = sqlite3.connect(self.path, isolation_level=None)
67
+ c.execute(f"PRAGMA journal_mode={self.journal_mode}")
68
+ for stmt in setup:
69
+ c.execute(stmt)
70
+ c.close()
71
+
72
+ def connect(self) -> "SqliteConn":
73
+ return SqliteConn(self)
74
+
75
+ def close(self) -> None:
76
+ shutil.rmtree(self.dir, ignore_errors=True)
77
+
78
+
79
+ class SqliteConn:
80
+ def __init__(self, db: SqliteDb):
81
+ self.c = sqlite3.connect(db.path, timeout=db.busy_timeout_ms / 1000.0, isolation_level=None, check_same_thread=False)
82
+ self.rowcount = 0
83
+ for pragma in (f"PRAGMA busy_timeout={db.busy_timeout_ms}", f"PRAGMA synchronous={db.synchronous}"):
84
+ for _ in range(100):
85
+ try:
86
+ self.c.execute(pragma)
87
+ break
88
+ except sqlite3.OperationalError:
89
+ time.sleep(0.005)
90
+
91
+ def run(self, sql: str, params: dict | None = None) -> list[tuple]:
92
+ try:
93
+ cur = self.c.execute(sql, params or {})
94
+ rows = cur.fetchall()
95
+ self.rowcount = cur.rowcount
96
+ return rows
97
+ except sqlite3.IntegrityError as e:
98
+ raise DbError("unique" if "UNIQUE" in str(e) else "fk" if "FOREIGN" in str(e) else "other", str(e)) from None
99
+ except sqlite3.OperationalError as e:
100
+ text = str(e)
101
+ raise DbError("busy" if "locked" in text or "busy" in text else "other", text) from None
102
+
103
+ def begin(self, mode: str = "") -> None:
104
+ self.run(f"BEGIN {mode}".strip())
105
+
106
+ def commit(self) -> None:
107
+ self.run("COMMIT")
108
+
109
+ def rollback(self) -> None:
110
+ try:
111
+ self.c.execute("ROLLBACK")
112
+ except sqlite3.OperationalError:
113
+ pass
114
+
115
+ def close(self) -> None:
116
+ self.c.close()
117
+
118
+
119
+ PG_CODES = {"40P01": "deadlock", "40001": "serialization", "55P03": "lock_timeout", "23505": "unique", "23503": "fk",
120
+ "57014": "timeout"}
121
+
122
+
123
+ class PgDb:
124
+ """A database in the sandbox PostgreSQL container, reached with pg8000 on 127.0.0.1:<port>."""
125
+
126
+ engine = "postgres"
127
+
128
+ def __init__(self, port: int, database: str, version: str = "", server_settings: dict | None = None, host: str = "127.0.0.1"):
129
+ self.host, self.port, self.database, self.version = host, int(port), database, version
130
+ self.server_settings = dict(server_settings or {})
131
+
132
+ def settings(self) -> dict:
133
+ return dict(self.server_settings)
134
+
135
+ def _raw(self, database: str | None = None):
136
+ import pg8000.native
137
+ return pg8000.native.Connection(user="postgres", host=self.host, port=self.port, database=database or self.database, timeout=60)
138
+
139
+ def reset(self, setup: list[str]) -> None:
140
+ c = self._raw()
141
+ try:
142
+ c.run("DROP SCHEMA IF EXISTS public CASCADE")
143
+ c.run("CREATE SCHEMA public")
144
+ for stmt in setup:
145
+ c.run(stmt)
146
+ finally:
147
+ c.close()
148
+
149
+ def connect(self) -> "PgConn":
150
+ return PgConn(self)
151
+
152
+ def admin(self):
153
+ return self._raw()
154
+
155
+ def close(self) -> None:
156
+ return None
157
+
158
+
159
+ class PgConn:
160
+ def __init__(self, db: PgDb):
161
+ self.c = db._raw()
162
+ self.rowcount = 0
163
+ self.pid = self.c.run("SELECT pg_backend_pid()")[0][0]
164
+ self.c.run("SET application_name = 'codecop-tx'")
165
+
166
+ def run(self, sql: str, params: dict | None = None) -> list:
167
+ import pg8000.exceptions
168
+ try:
169
+ rows = self.c.run(sql, **(params or {}))
170
+ self.rowcount = self.c.row_count
171
+ return rows or []
172
+ except pg8000.exceptions.DatabaseError as e:
173
+ info = e.args[0] if e.args and isinstance(e.args[0], dict) else {}
174
+ code = info.get("C", "")
175
+ raise DbError(PG_CODES.get(code, "other"), f"{code} {info.get('M', str(e))[:200]}") from None
176
+
177
+ def begin(self, mode: str = "") -> None:
178
+ self.run(f"BEGIN {mode}".strip())
179
+
180
+ def commit(self) -> None:
181
+ self.run("COMMIT")
182
+
183
+ def rollback(self) -> None:
184
+ try:
185
+ self.c.run("ROLLBACK")
186
+ except Exception: # noqa: BLE001
187
+ pass
188
+
189
+ def close(self) -> None:
190
+ try:
191
+ self.c.close()
192
+ except Exception: # noqa: BLE001
193
+ pass
194
+
195
+
196
+ # --- a session and its recording -----------------------------------------------------------------------------------------
197
+
198
+ class Session:
199
+ """One of CodeCop's sessions in a run. Statements and calls are recorded as lane segments (ms since the run's start)."""
200
+
201
+ def __init__(self, db, idx: int, t0: float, keep: bool, rng: random.Random):
202
+ self.conn = db.connect()
203
+ self.idx, self.t0, self.keep, self.rng = idx, t0, keep, rng
204
+ self.segments: list[list] = []
205
+ self.stmt_ms: list[float] = []
206
+ self.acts: list[Any] = [] # what this session acted on (a claimed job, a posted run)
207
+ self.waits_ms: list[float] = [] # time to the first row of a claim, when the program says so
208
+ self.pid = getattr(self.conn, "pid", None)
209
+ # lock accounting per committed transaction: `lock_wait_ms`, from BEGIN to the end of its first statement (the
210
+ # wait for the lock a write takes, on SQLite inside BEGIN IMMEDIATE or the busy handler, on PostgreSQL inside the
211
+ # statement); `lock_hold_ms`, from the end of that statement to the end of COMMIT (what the transaction holds the
212
+ # lock across: the rest of its statements and any call inside it). Wall-clock intervals of one session's own
213
+ # program, so a busy machine stretches both sides alike and cannot move a call out of a transaction.
214
+ self.lock_wait_ms: list[float] = []
215
+ self.lock_hold_ms: list[float] = []
216
+ self._tx_begin: float | None = None
217
+ self._tx_locked: float | None = None
218
+
219
+ def _seg(self, a: float, b: float, state: str, tag: Any = None) -> None:
220
+ if self.keep and len(self.segments) < LANE_SEGMENTS:
221
+ seg = [round((a - self.t0) * 1000, 2), round((b - self.t0) * 1000, 2), state]
222
+ if tag is not None:
223
+ seg.append(tag)
224
+ self.segments.append(seg)
225
+
226
+ def q(self, sql: str, params: dict | None = None) -> list:
227
+ a = time.perf_counter()
228
+ try:
229
+ rows = self.conn.run(sql, params)
230
+ except DbError:
231
+ self._seg(a, time.perf_counter(), "error")
232
+ raise
233
+ b = time.perf_counter()
234
+ self.stmt_ms.append((b - a) * 1000)
235
+ self._seg(a, b, "run")
236
+ if self._tx_begin is not None and self._tx_locked is None:
237
+ self._tx_locked = b
238
+ return rows
239
+
240
+ @property
241
+ def rowcount(self) -> int:
242
+ return self.conn.rowcount
243
+
244
+ def begin(self, mode: str = "") -> None:
245
+ self._tx_begin, self._tx_locked = time.perf_counter(), None
246
+ self.conn.begin(mode)
247
+
248
+ def commit(self) -> None:
249
+ a = time.perf_counter()
250
+ try:
251
+ self.conn.commit()
252
+ except DbError:
253
+ self._seg(a, time.perf_counter(), "error")
254
+ self._tx_begin = self._tx_locked = None
255
+ raise
256
+ b = time.perf_counter()
257
+ if self._tx_begin is not None and self._tx_locked is not None:
258
+ self.lock_wait_ms.append((self._tx_locked - self._tx_begin) * 1000)
259
+ self.lock_hold_ms.append((b - self._tx_locked) * 1000)
260
+ self._tx_begin = self._tx_locked = None
261
+
262
+ def rollback(self) -> None:
263
+ self._tx_begin = self._tx_locked = None
264
+ self.conn.rollback()
265
+
266
+ def call(self, ms: float, act: Any = None) -> None:
267
+ """The external call's stand-in (a sleep of the think time). `act`: what the call acts on (a run posted)."""
268
+ a = time.perf_counter()
269
+ if ms > 0:
270
+ time.sleep(ms / 1000.0)
271
+ self._seg(a, time.perf_counter(), "call", act)
272
+ if act is not None:
273
+ self.acts.append(act)
274
+
275
+ def close(self) -> None:
276
+ self.conn.close()
277
+
278
+
279
+ class Sampler(threading.Thread):
280
+ """PostgreSQL only: every `every_ms`, the sandbox's client sessions waiting on a lock and idle in a transaction
281
+ (by pid). One cheap read of pg_stat_activity inside the sandbox; nothing leaves the machine."""
282
+
283
+ def __init__(self, db: PgDb, every_ms: float):
284
+ super().__init__(daemon=True)
285
+ self.db, self.every = db, every_ms / 1000.0
286
+ self.stop_ev = threading.Event()
287
+ self.samples = 0
288
+ self.lock_wait_samples = 0
289
+ self.idle_in_tx_samples = 0
290
+ self.waiting: list[tuple[float, set]] = [] # (perf_counter, pids waiting on a lock)
291
+
292
+ def run(self) -> None:
293
+ try:
294
+ c = self.db.admin()
295
+ except Exception: # noqa: BLE001
296
+ return
297
+ try:
298
+ while not self.stop_ev.is_set():
299
+ rows = c.run("SELECT pid, wait_event_type = 'Lock', state = 'idle in transaction' FROM pg_stat_activity "
300
+ "WHERE application_name = 'codecop-tx' AND pid <> pg_backend_pid()")
301
+ now = time.perf_counter()
302
+ self.samples += 1
303
+ waits = {r[0] for r in rows if r[1]}
304
+ self.lock_wait_samples += 1 if waits else 0
305
+ self.idle_in_tx_samples += 1 if any(r[2] for r in rows) else 0
306
+ self.waiting.append((now, waits))
307
+ self.stop_ev.wait(self.every)
308
+ finally:
309
+ c.close()
310
+
311
+ def stop(self) -> None:
312
+ self.stop_ev.set()
313
+ self.join(timeout=5)
314
+
315
+
316
+ # --- one run -------------------------------------------------------------------------------------------------------------
317
+
318
+ @dataclass
319
+ class Program:
320
+ """A scenario variant: `setup` statements (tables and generated rows), the per-operation `step(session, i, k)`, the
321
+ `check(conn, sessions)` that reads the final state (counters and the invariant), and how errors are handled."""
322
+ setup: list[str]
323
+ step: Callable
324
+ check: Callable
325
+ on_error: str = "count" # count: the operation fails and the session goes on; retry: run it again
326
+ max_retries: int = 20
327
+ until_empty: bool = False # step returns False when there is nothing left (a drained queue)
328
+ before_run: Callable | None = None # extra statements on a fresh database (the fix's index)
329
+
330
+
331
+ @dataclass
332
+ class RunResult:
333
+ elapsed_s: float
334
+ ops: int
335
+ errors: dict
336
+ counters: dict
337
+ state: Any
338
+ held: bool | None
339
+ samples: int = 0
340
+ lock_wait_samples: int = 0
341
+ idle_in_tx_samples: int = 0
342
+ p95_wait_ms: float | None = None
343
+ p50_wait_ms: float | None = None
344
+ lanes: dict = field(default_factory=dict)
345
+ lock_wait_ms: list = field(default_factory=list) # per committed transaction (Session.lock_wait_ms)
346
+ lock_hold_ms: list = field(default_factory=list) # per committed transaction (Session.lock_hold_ms)
347
+
348
+ @property
349
+ def throughput(self) -> float:
350
+ return self.ops / self.elapsed_s if self.elapsed_s > 0 else 0.0
351
+
352
+
353
+ def pct(xs: list[float], p: float) -> float | None:
354
+ if not xs:
355
+ return None
356
+ xs = sorted(xs)
357
+ return xs[min(len(xs) - 1, int(round(p / 100 * (len(xs) - 1))))]
358
+
359
+
360
+ def run_once(db, program: Program, *, sessions: int, operations: int, seed: int = 1, sample_ms: float = 20.0,
361
+ timeout_s: float = 120.0) -> RunResult:
362
+ """Run `program` with `sessions` sessions of `operations` operations each (or until the queue is empty)."""
363
+ db.reset(program.setup)
364
+ if program.before_run:
365
+ program.before_run(db)
366
+ errors: dict[str, int] = {}
367
+ lock = threading.Lock()
368
+ done = [0]
369
+ t0 = time.perf_counter()
370
+ deadline = t0 + timeout_s
371
+ opened = [Session(db, i, t0, i < LANE_SESSIONS, random.Random(seed * 1000 + i)) for i in range(sessions)]
372
+ sampler = Sampler(db, sample_ms) if isinstance(db, PgDb) else None
373
+ go = threading.Barrier(sessions + 1)
374
+
375
+ def body(s: Session) -> None:
376
+ go.wait()
377
+ mine, errs = 0, {}
378
+ k = 0
379
+ failing = 0 # operations in a row that failed with an error no contention explains: a broken statement
380
+ while (program.until_empty or k < operations) and time.perf_counter() < deadline:
381
+ tries = 0
382
+ more = None
383
+ while True:
384
+ try:
385
+ more = program.step(s, s.idx, k)
386
+ failing = 0
387
+ if more is False:
388
+ break
389
+ mine += 1
390
+ break
391
+ except DbError as e:
392
+ s.rollback()
393
+ errs[e.cls] = errs.get(e.cls, 0) + 1
394
+ failing = failing + 1 if e.cls in ("other", "unique", "fk") else 0
395
+ if e.cls == "other" and "first_error" not in errs:
396
+ errs["first_error"] = str(e)[:200]
397
+ tries += 1
398
+ if program.on_error != "retry" or tries > program.max_retries or failing >= STUCK_AFTER:
399
+ break
400
+ if more is False or failing >= STUCK_AFTER:
401
+ break
402
+ k += 1
403
+ with lock:
404
+ done[0] += mine
405
+ for c, n in errs.items():
406
+ if c == "first_error":
407
+ errors.setdefault("first_error", n)
408
+ else:
409
+ errors[c] = errors.get(c, 0) + n
410
+
411
+ threads = [threading.Thread(target=body, args=(s,), daemon=True) for s in opened]
412
+ for t in threads:
413
+ t.start()
414
+ if sampler:
415
+ sampler.start()
416
+ t0 = time.perf_counter()
417
+ for s in opened:
418
+ s.t0 = t0
419
+ go.wait()
420
+ for t in threads:
421
+ t.join(timeout=max(1.0, deadline - time.perf_counter() + 5))
422
+ elapsed = time.perf_counter() - t0
423
+ if sampler:
424
+ sampler.stop()
425
+ for s in opened:
426
+ s.close()
427
+ c = db.connect()
428
+ try:
429
+ counters, state, held = program.check(c, opened)
430
+ finally:
431
+ c.close()
432
+ waits = [w for s in opened for w in s.waits_ms]
433
+ lanes = _lanes(opened, sampler, t0)
434
+ return RunResult(elapsed_s=round(elapsed, 4), ops=done[0], errors=errors, counters=counters, state=state, held=held,
435
+ samples=sampler.samples if sampler else 0, lock_wait_samples=sampler.lock_wait_samples if sampler else 0,
436
+ idle_in_tx_samples=sampler.idle_in_tx_samples if sampler else 0,
437
+ p95_wait_ms=round(pct(waits, 95), 2) if waits else None,
438
+ p50_wait_ms=round(pct(waits, 50), 3) if waits else None, lanes=lanes,
439
+ lock_wait_ms=[x for s in opened for x in s.lock_wait_ms], lock_hold_ms=[x for s in opened for x in s.lock_hold_ms])
440
+
441
+
442
+ def _lanes(sessions: list[Session], sampler: Sampler | None, t0: float) -> dict:
443
+ """The drawing's lanes: each kept session's segments; a statement is `wait` when the sampler saw its session waiting
444
+ on a lock during it (PostgreSQL) or when it took WAIT_FLOOR_MS longer than the session's quickest statement (SQLite,
445
+ whose busy handler sleeps inside the statement)."""
446
+ out = []
447
+ span = 0.0
448
+ for s in sessions[:LANE_SESSIONS]:
449
+ quickest = min(s.stmt_ms) if s.stmt_ms else 0.0
450
+ segs = []
451
+ for seg in s.segments:
452
+ a, b, state = seg[0], seg[1], seg[2]
453
+ if state == "run":
454
+ if sampler is not None:
455
+ hit = any(s.pid in pids and a <= (at - t0) * 1000 <= b for at, pids in sampler.waiting)
456
+ state = "wait" if hit else "run"
457
+ elif (b - a) > quickest + WAIT_FLOOR_MS:
458
+ state = "wait"
459
+ segs.append([a, b, state] + seg[3:])
460
+ span = max(span, b)
461
+ out.append(segs)
462
+ return {"span_ms": round(span, 1), "sessions": out}
463
+
464
+
465
+ def mark_duplicates(lanes: dict) -> dict:
466
+ """Calls that acted on something another call already acted on become `dup` (a run posted twice)."""
467
+ seen: set = set()
468
+ calls = sorted((seg[0], si, gi) for si, segs in enumerate(lanes.get("sessions") or []) for gi, seg in enumerate(segs)
469
+ if seg[2] == "call" and len(seg) > 3)
470
+ for _, si, gi in calls:
471
+ seg = lanes["sessions"][si][gi]
472
+ if seg[3] in seen:
473
+ seg[2] = "dup"
474
+ seen.add(seg[3])
475
+ for segs in lanes.get("sessions") or []:
476
+ for seg in segs:
477
+ del seg[3:]
478
+ return lanes
479
+
480
+
481
+ def spread(values: list[float]) -> tuple[float, float, float]:
482
+ """(median, low, high) of the repeated runs."""
483
+ return (statistics.median(values), min(values), max(values)) if values else (0.0, 0.0, 0.0)