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,520 @@
1
+ """The canonical contention scenarios: for each, the program CodeCop's sessions run before the fix and with it, the final
2
+ state it reads, and the invariant a serial execution keeps. Statements come from `bind.py` (the repository's own
3
+ statements, bound to generated rows: `statements = extracted`) or, when they cannot be bound, are modelled on the
4
+ shape's tables and columns (`statements = modelled`). Every scenario says what it compares.
5
+
6
+ Scenario codes (the finding's `scenario`): queue_claim, poll_then_mark, fk_without_index, call_in_transaction,
7
+ read_modify_write, lock_order, sqlite_deferred_begin, sqlite_no_wal_timeout.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import hashlib
13
+ import re
14
+ from dataclasses import dataclass, field
15
+
16
+ from .schedule import DbError, Program
17
+
18
+ CODES = ("queue_claim", "poll_then_mark", "fk_without_index", "call_in_transaction", "read_modify_write", "lock_order",
19
+ "sqlite_deferred_begin", "sqlite_no_wal_timeout")
20
+ # the measure the verdict rests on, per scenario, and the harm the scenario can show
21
+ VERDICT = {"queue_claim": "throughput", "poll_then_mark": "duplicates", "fk_without_index": "delete_ms",
22
+ "call_in_transaction": "lock_hold_ms", "read_modify_write": "lost_updates", "lock_order": "deadlocks",
23
+ "sqlite_deferred_begin": "busy_errors", "sqlite_no_wal_timeout": "failed_writes"}
24
+ HARM = {"queue_claim": "speed", "poll_then_mark": "correctness", "fk_without_index": "speed", "call_in_transaction": "speed",
25
+ "read_modify_write": "correctness", "lock_order": "both", "sqlite_deferred_begin": "correctness",
26
+ "sqlite_no_wal_timeout": "correctness"}
27
+ # a scenario whose wrong result needs two workers at once: measured at 1, 2 and k workers
28
+ WORKER_SENSITIVE = {"poll_then_mark", "read_modify_write", "lock_order", "queue_claim", "sqlite_deferred_begin",
29
+ "sqlite_no_wal_timeout", "call_in_transaction"}
30
+ SKIP = re.compile(r"\bSKIP\s+LOCKED\b|\bNOWAIT\b", re.I)
31
+
32
+
33
+ @dataclass
34
+ class Scenario:
35
+ code: str
36
+ engine: str
37
+ variants: dict # name -> Program ("before", "after", optionally "after_lock")
38
+ invariant: str
39
+ statements: str = "modelled" # extracted | modelled
40
+ sessions: int = 8
41
+ operations: int = 20
42
+ think_ms: float = 20.0
43
+ hot_rows: int | None = None
44
+ batch: int | None = None
45
+ items: int | None = None
46
+ db_settings: dict = field(default_factory=dict) # variant -> SqliteDb settings (journal_mode, busy_timeout_ms)
47
+ fix: dict = field(default_factory=dict) # {change, before, after}
48
+ tradeoff: str = ""
49
+ compared: str = "" # what the final-state check compares, in a few words
50
+ of: int | None = None # the whole a count is out of (operations in all)
51
+
52
+ @property
53
+ def verdict(self) -> str:
54
+ return VERDICT[self.code]
55
+
56
+ @property
57
+ def harm(self) -> str:
58
+ return HARM[self.code]
59
+
60
+
61
+ def series(engine: str, n: int) -> str:
62
+ """A FROM item with one column `x` = 1..n."""
63
+ if engine == "postgres":
64
+ return f"generate_series(1, {int(n)}) AS g(x)"
65
+ return f"(WITH RECURSIVE g(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM g WHERE x < {int(n)}) SELECT x FROM g) AS g"
66
+
67
+
68
+ def _first(rows):
69
+ """The first column of the first row; None when the key selects no row (a key the fixture did not write)."""
70
+ return rows[0][0] if rows and rows[0] else None
71
+
72
+
73
+ def qi(name: str) -> str:
74
+ """A quoted identifier (schema.table kept as two)."""
75
+ return ".".join('"' + p.replace('"', '') + '"' for p in str(name).split("."))
76
+
77
+
78
+ def session_keys(s, f: dict, default: list) -> list:
79
+ """The hot rows' keys: generated keys (a uuid, say) are read once per session from the seeded table."""
80
+ if f.get("keys_sql"):
81
+ if getattr(s, "_keys", None) is None:
82
+ s._keys = [r[0] for r in s.conn.run(f["keys_sql"])]
83
+ return s._keys
84
+ return default
85
+
86
+
87
+ def digest(rows) -> str:
88
+ return hashlib.sha256(repr(rows).encode()).hexdigest()[:12]
89
+
90
+
91
+ # --- 1. a queue claimed with FOR UPDATE: waits behind each other; SKIP LOCKED lets them pass ----------------------------
92
+
93
+ def queue_claim(f: dict) -> Scenario:
94
+ """`f`: engine postgres; table, key, status column and its pending/done values; claim_sql (the repository's claim
95
+ with :params bound) and done_sql (:id), or modelled ones; items, sessions, think_ms (the job's work inside the claim)."""
96
+ t, key, st = f.get("table") or "codecop_jobs", f.get("key") or "id", f.get("status_col") or "status"
97
+ pending, done = f.get("pending") or "pending", f.get("done") or "done"
98
+ items = int(f.get("items") or 200)
99
+ setup = f.get("setup") or [
100
+ f"CREATE TABLE {qi(t)} ({qi(key)} bigint PRIMARY KEY, {qi(st)} text NOT NULL, codecop_worker int, codecop_attempts int NOT NULL DEFAULT 0)",
101
+ f"INSERT INTO {qi(t)} ({qi(key)}, {qi(st)}) SELECT x, '{pending}' FROM {series('postgres', items)}",
102
+ f"CREATE INDEX ON {qi(t)} ({qi(st)}, {qi(key)})"]
103
+ claim = f.get("claim_sql") or f"SELECT {qi(key)} FROM {qi(t)} WHERE {qi(st)} = '{pending}' ORDER BY {qi(key)} LIMIT 1 FOR UPDATE"
104
+ claim_params = f.get("claim_params") or {}
105
+ done_sql = f.get("done_sql") or f"UPDATE {qi(t)} SET {qi(st)} = '{done}' WHERE {qi(key)} = :id"
106
+ fixed = add_skip_locked(claim)
107
+ think = float(f.get("think_ms") if f.get("think_ms") is not None else 5)
108
+ kidx = int(f.get("key_index") or 0)
109
+ done_params = dict(f.get("done_params") or {})
110
+ count_done = f.get("count_done_sql") or f"SELECT count(*) FROM {qi(t)} WHERE {qi(st)} = '{done}'"
111
+
112
+ def program(sql: str) -> Program:
113
+ def step(s, i, k):
114
+ s.begin()
115
+ import time as _t
116
+ a = _t.perf_counter()
117
+ rows = s.q(sql, claim_params)
118
+ s.waits_ms.append((_t.perf_counter() - a) * 1000)
119
+ if not rows:
120
+ s.rollback()
121
+ return False
122
+ item = rows[0][kidx]
123
+ s.call(think, act=item)
124
+ s.q(done_sql, {**done_params, "id": item})
125
+ s.commit()
126
+ return True
127
+
128
+ def check(c, sessions):
129
+ n = c.run(count_done)[0][0]
130
+ acts = [a for s in sessions for a in s.acts]
131
+ dups = len(acts) - len(set(acts))
132
+ return {"done": n, "duplicates": dups, "items": items}, n, n == items and dups == 0
133
+ return Program(setup=setup, step=step, check=check, until_empty=True)
134
+
135
+ return Scenario("queue_claim", "postgres", {"before": program(claim), "after": program(fixed)},
136
+ invariant="every job done exactly once", statements="extracted" if f.get("claim_sql") else "modelled",
137
+ sessions=int(f.get("sessions") or 8), think_ms=think, items=items, of=items,
138
+ fix={"change": "skip_locked", "before": claim, "after": fixed},
139
+ tradeoff="Jobs are taken a little out of order: a row another worker holds is passed over, not waited for.",
140
+ compared="jobs done, and each job done once")
141
+
142
+
143
+ def add_skip_locked(sql: str) -> str:
144
+ if SKIP.search(sql):
145
+ return sql
146
+ m = re.search(r"\bFOR\s+(?:NO\s+KEY\s+)?UPDATE(?:\s+OF\s+[\w\".,\s]+?)?(?=\s*(?:;|$|\)))", sql, re.I)
147
+ if not m:
148
+ return sql.rstrip().rstrip(";") + " FOR UPDATE SKIP LOCKED"
149
+ return sql[:m.end()] + " SKIP LOCKED" + sql[m.end():]
150
+
151
+
152
+ # --- 2. poll, act, then mark: two pollers act on the same item ----------------------------------------------------------
153
+
154
+ def poll_then_mark(f: dict) -> Scenario:
155
+ """`f`: select_sql (:params) returning candidates, item_index (the column holding the item's key), mark_sql with
156
+ :item, claim_sql (the mark as a claim: changes a row only when the item was not marked yet; INSERT .. ON CONFLICT DO
157
+ NOTHING is one already), count_marked_sql, setup, items, batch, think_ms (the act: a post, a send)."""
158
+ engine = f.get("engine") or "postgres"
159
+ items = int(f.get("items") or 100)
160
+ batch = int(f.get("batch") or 20)
161
+ t = f.get("table") or "codecop_items"
162
+ setup = f.get("setup") or [
163
+ f"CREATE TABLE {qi(t)} (id integer PRIMARY KEY, delivered_at text)",
164
+ f"INSERT INTO {qi(t)} (id) SELECT x FROM {series(engine, items)}"]
165
+ select = f.get("select_sql") or f"SELECT id FROM {qi(t)} WHERE delivered_at IS NULL ORDER BY id LIMIT :batch"
166
+ params = dict(f.get("select_params") or {"batch": batch})
167
+ idx = int(f.get("item_index") or 0)
168
+ mark = f.get("mark_sql") or f"UPDATE {qi(t)} SET delivered_at = 'x' WHERE id = :item"
169
+ claim = f.get("claim_sql") or f"UPDATE {qi(t)} SET delivered_at = 'x' WHERE id = :item AND delivered_at IS NULL"
170
+ mark_params = dict(f.get("mark_params") or {})
171
+ counted = f.get("count_marked_sql") or f"SELECT count(*) FROM {qi(t)} WHERE delivered_at IS NOT NULL"
172
+ think = float(f.get("think_ms") if f.get("think_ms") is not None else 20)
173
+ idle_polls = int(f.get("idle_polls") or 2)
174
+
175
+ def program(claim_first: bool) -> Program:
176
+ def step(s, i, k):
177
+ rows = s.q(select, params)
178
+ if not rows:
179
+ s.rng_idle = getattr(s, "rng_idle", 0) + 1
180
+ if s.rng_idle >= idle_polls:
181
+ return False
182
+ s.call(think / 2)
183
+ return True
184
+ s.rng_idle = 0
185
+ for r in rows:
186
+ item = r[idx]
187
+ if claim_first:
188
+ s.q(claim, {**mark_params, "item": item})
189
+ if s.rowcount == 1:
190
+ s.call(think, act=item)
191
+ else:
192
+ s.call(think, act=item)
193
+ s.q(mark, {**mark_params, "item": item})
194
+ return True
195
+
196
+ def check(c, sessions):
197
+ marked = c.run(counted)[0][0]
198
+ acts = [a for s in sessions for a in s.acts]
199
+ dups = len(acts) - len(set(acts))
200
+ return ({"acts": len(acts), "duplicates": dups, "marked": marked, "items": items},
201
+ (marked, len(set(acts))), dups == 0 and len(set(acts)) == items and marked == items)
202
+ return Program(setup=setup, step=step, check=check, until_empty=True)
203
+
204
+ return Scenario("poll_then_mark", engine, {"before": program(False), "after": program(True)},
205
+ invariant="every item acted on exactly once, and marked", statements="extracted" if f.get("select_sql") else "modelled",
206
+ sessions=int(f.get("sessions") or 2), think_ms=think, batch=batch, items=items, of=items,
207
+ fix={"change": "claim_first", "before": f"{select}\n-- act (post, send) on each row\n{mark}",
208
+ "after": f"{select}\n{claim} -- claim first; act only when it changed a row"},
209
+ tradeoff="An item claimed and then failed is marked but not done: the act needs a retry or a lease "
210
+ "(at most once instead of at least once).",
211
+ compared="items acted on, items marked, acts per item")
212
+
213
+
214
+ # --- 3. foreign key without an index: a parent delete scans the child table ---------------------------------------------
215
+
216
+ def fk_without_index(f: dict) -> Scenario:
217
+ """`f`: parent (table, key), child (table, fk column), parents, children, deleters, inserters, delete_sql (:id)."""
218
+ p, pk = f.get("parent") or "codecop_parent", f.get("parent_key") or "id"
219
+ c, fk = f.get("child") or "codecop_child", f.get("fk") or "parent_id"
220
+ parents, children = int(f.get("parents") or 4000), int(f.get("children") or 60000)
221
+ survivors = parents // 2
222
+ on_delete = f.get("on_delete") or "CASCADE"
223
+ setup = f.get("setup") or [
224
+ f"CREATE TABLE {qi(p)} ({qi(pk)} bigint PRIMARY KEY, name text)",
225
+ f"CREATE TABLE {qi(c)} (codecop_id bigserial PRIMARY KEY, {qi(fk)} bigint NOT NULL REFERENCES {qi(p)} ({qi(pk)}) ON DELETE {on_delete}, body text)",
226
+ f"INSERT INTO {qi(p)} SELECT x, 'p' || x FROM generate_series(1, {parents}) AS g(x)",
227
+ f"INSERT INTO {qi(c)} ({qi(fk)}, body) SELECT 1 + (x % {survivors}), md5(x::text) FROM generate_series(1, {children}) AS g(x)",
228
+ f"ANALYZE {qi(p)}", f"ANALYZE {qi(c)}"]
229
+ delete = f.get("delete_sql") or f"DELETE FROM {qi(p)} WHERE {qi(pk)} = :id"
230
+ insert = f.get("insert_sql") or f"INSERT INTO {qi(c)} ({qi(fk)}, body) VALUES (:pid, 'new')"
231
+ sessions = int(f.get("sessions") or 6)
232
+ deleters = max(1, sessions // 3)
233
+ ops = int(f.get("operations") or 30)
234
+ index = f"CREATE INDEX ON {qi(c)} ({qi(fk)})"
235
+ count = (f"SELECT (SELECT count(*) FROM {qi(p)}), (SELECT count(*) FROM {qi(c)}), "
236
+ f"(SELECT md5(coalesce(string_agg({qi(fk)}::text || ':' || n::text, ',' ORDER BY {qi(fk)}), '')) FROM "
237
+ f"(SELECT {qi(fk)}, count(*) n FROM {qi(c)} GROUP BY 1) s)")
238
+
239
+ def program(with_index: bool) -> Program:
240
+ def step(s, i, k):
241
+ if i < deleters:
242
+ pid = survivors + 1 + i * ops + k # childless parents: the delete only scans the children
243
+ if pid > parents:
244
+ return False
245
+ import time as _t
246
+ a = _t.perf_counter()
247
+ s.q(delete, {"id": pid})
248
+ s.waits_ms.append((_t.perf_counter() - a) * 1000)
249
+ else:
250
+ s.q(insert, {"pid": 1 + (i * 7919 + k * 104729) % survivors})
251
+ s.call(2)
252
+ return True
253
+
254
+ def check(cn, sessions):
255
+ r = cn.run(count)[0]
256
+ return {"parents": r[0], "children": r[1]}, (r[0], r[1], r[2]), None
257
+
258
+ return Program(setup=setup, step=step, check=check,
259
+ before_run=(lambda db: _admin_run(db, [index, f"ANALYZE {qi(c)}"])) if with_index else None)
260
+
261
+ return Scenario("fk_without_index", "postgres", {"before": program(False), "after": program(True)},
262
+ invariant="parent and child rows equal to the run without the index", statements="extracted" if f.get("delete_sql") else "modelled",
263
+ sessions=sessions, operations=ops, think_ms=2,
264
+ fix={"change": "index_foreign_key", "before": f"-- {c}.{fk} references {p}.{pk}: no index starts with {fk}",
265
+ "after": index.replace("CREATE INDEX ON", "CREATE INDEX CONCURRENTLY ON")},
266
+ tradeoff="Every insert and update of the child writes one more index entry; the index takes disk.",
267
+ compared="parent rows, child rows, children per parent")
268
+
269
+
270
+ def _admin_run(db, statements: list[str]) -> None:
271
+ c = db.connect()
272
+ try:
273
+ for s in statements:
274
+ c.run(s)
275
+ finally:
276
+ c.close()
277
+
278
+
279
+ # --- 4. a transaction held open across an external call -----------------------------------------------------------------
280
+
281
+ def call_in_transaction(f: dict) -> Scenario:
282
+ """`f`: write_sql (:k the hot row's key) and the table's setup with hot_rows rows; think_ms (the call)."""
283
+ engine = f.get("engine") or "postgres"
284
+ t, key, col = f.get("table") or "codecop_accounts", f.get("key") or "id", f.get("col") or "balance"
285
+ hot = int(f.get("hot_rows") or 2)
286
+ setup = f.get("setup") or [f"CREATE TABLE {qi(t)} ({qi(key)} integer PRIMARY KEY, {qi(col)} bigint NOT NULL DEFAULT 0)",
287
+ f"INSERT INTO {qi(t)} ({qi(key)}) SELECT x FROM {series(engine, hot)}"]
288
+ write = f.get("write_sql") or f"UPDATE {qi(t)} SET {qi(col)} = {qi(col)} + 1 WHERE {qi(key)} = :k"
289
+ keys = f.get("keys") or list(range(1, hot + 1))
290
+ params = dict(f.get("write_params") or {})
291
+ think = float(f.get("think_ms") if f.get("think_ms") is not None else 50)
292
+ begin_mode = f.get("begin_mode") or ""
293
+ final = f.get("final_sql") or f"SELECT * FROM {qi(t)} ORDER BY 1"
294
+ time_cols = f.get("time_columns") or []
295
+
296
+ def program(inside: bool) -> Program:
297
+ def step(s, i, k):
298
+ ks = session_keys(s, f, keys)
299
+ row = ks[(i + k) % len(ks)]
300
+ if not inside:
301
+ s.call(think)
302
+ s.begin(begin_mode)
303
+ s.q(write, {**params, "k": row})
304
+ if inside:
305
+ s.call(think)
306
+ s.commit()
307
+ return True
308
+
309
+ def check(c, sessions):
310
+ rows = c.run(final)
311
+ keep = _drop_columns(rows, f.get("final_columns") or [], time_cols)
312
+ return {"rows": len(rows)}, digest(keep), None
313
+ return Program(setup=setup, step=step, check=check, on_error=f.get("on_error") or "count")
314
+
315
+ return Scenario("call_in_transaction", engine, {"before": program(True), "after": program(False)},
316
+ invariant="the same final rows as the run with the call inside", statements="extracted" if f.get("write_sql") else "modelled",
317
+ sessions=int(f.get("sessions") or 8), operations=int(f.get("operations") or 10), think_ms=think, hot_rows=hot,
318
+ fix={"change": "call_outside_transaction", "before": f.get("fix_before") or f"BEGIN\n{write}\n-- external call\nCOMMIT",
319
+ "after": f.get("fix_after") or f"-- external call\nBEGIN\n{write}\nCOMMIT"},
320
+ tradeoff="The call's effect no longer rolls back with the transaction; when both must happen or neither, "
321
+ "record the call in an outbox row instead.",
322
+ compared="final rows of the table (time columns left out)")
323
+
324
+
325
+ def _drop_columns(rows: list, names: list[str], drop: list[str]) -> list:
326
+ if not names or not drop:
327
+ return [tuple(r) for r in rows]
328
+ keep = [i for i, n in enumerate(names) if n not in drop]
329
+ return [tuple(r[i] for i in keep) for r in rows]
330
+
331
+
332
+ # --- 5. read, compute, write back -----------------------------------------------------------------------------------------
333
+
334
+ def read_modify_write(f: dict) -> Scenario:
335
+ """`f`: read_sql (:k) returning the value, write_sql (:k, :v) writing it back, atomic_sql (:k, :delta), table setup
336
+ with hot_rows rows whose value column starts at 0, sum_sql reading the values' sum."""
337
+ engine = f.get("engine") or "postgres"
338
+ t, key, col = f.get("table") or "codecop_wallets", f.get("key") or "id", f.get("col") or "balance"
339
+ hot = int(f.get("hot_rows") or 2)
340
+ setup = f.get("setup") or [f"CREATE TABLE {qi(t)} ({qi(key)} integer PRIMARY KEY, {qi(col)} bigint NOT NULL)",
341
+ f"INSERT INTO {qi(t)} ({qi(key)}, {qi(col)}) SELECT x, 0 FROM {series(engine, hot)}"]
342
+ read = f.get("read_sql") or f"SELECT {qi(col)} FROM {qi(t)} WHERE {qi(key)} = :k"
343
+ write = f.get("write_sql") or f"UPDATE {qi(t)} SET {qi(col)} = :v WHERE {qi(key)} = :k"
344
+ atomic = f.get("atomic_sql") or f"UPDATE {qi(t)} SET {qi(col)} = {qi(col)} + :delta WHERE {qi(key)} = :k"
345
+ total = f.get("sum_sql") or f"SELECT coalesce(sum({qi(col)}), 0) FROM {qi(t)}"
346
+ keys = f.get("keys") or list(range(1, hot + 1))
347
+ params = dict(f.get("params") or {})
348
+ think = float(f.get("think_ms") if f.get("think_ms") is not None else 1)
349
+ sessions, ops = int(f.get("sessions") or 8), int(f.get("operations") or 50)
350
+
351
+ def program(mode: str) -> Program:
352
+ def step(s, i, k):
353
+ ks = session_keys(s, f, keys)
354
+ row = ks[(i + k) % len(ks)]
355
+ if mode == "naive":
356
+ v = _first(s.q(read, {**params, "k": row}))
357
+ s.call(think)
358
+ s.q(write, {**params, "k": row, "v": (v or 0) + 1})
359
+ elif mode == "atomic":
360
+ s.call(think)
361
+ s.q(atomic, {**params, "k": row, "delta": 1})
362
+ else: # lock the row first: SELECT ... FOR UPDATE in a transaction
363
+ s.begin()
364
+ v = _first(s.q(read.rstrip().rstrip(";") + " FOR UPDATE", {**params, "k": row}))
365
+ s.call(think)
366
+ s.q(write, {**params, "k": row, "v": (v or 0) + 1})
367
+ s.commit()
368
+ return True
369
+
370
+ def check(c, sessions_):
371
+ got = int(c.run(total)[0][0] or 0)
372
+ return {"sum": got}, got, None
373
+ return Program(setup=setup, step=step, check=check, on_error="retry" if mode == "for_update" else "count")
374
+
375
+ variants = {"before": program("naive"), "after": program("atomic")}
376
+ if engine == "postgres":
377
+ variants["after_lock"] = program("for_update")
378
+ return Scenario("read_modify_write", engine, variants,
379
+ invariant="the sum of the values equals the updates made", statements="extracted" if f.get("read_sql") else "modelled",
380
+ sessions=sessions, operations=ops, think_ms=think, hot_rows=hot, of=sessions * ops,
381
+ fix={"change": "atomic_update", "before": f"{read}\n-- compute in the application\n{write}", "after": atomic},
382
+ tradeoff="The new value must be expressible in SQL (an increment, a capped sum); otherwise lock the row "
383
+ "(SELECT ... FOR UPDATE) or check a version column.",
384
+ compared="sum of the values against the number of updates")
385
+
386
+
387
+ # --- 6. two transactions lock the same rows in opposite orders -----------------------------------------------------------
388
+
389
+ def lock_order(f: dict) -> Scenario:
390
+ """`f`: steps_a and steps_b: lists of (sql with :k, which key: 'first' | 'second'), the table setup with `rows` rows."""
391
+ t, key, col = f.get("table") or "codecop_inventory", f.get("key") or "id", f.get("col") or "qty"
392
+ rows = int(f.get("rows") or 6)
393
+ setup = f.get("setup") or [f"CREATE TABLE {qi(t)} ({qi(key)} integer PRIMARY KEY, {qi(col)} bigint NOT NULL DEFAULT 0)",
394
+ f"INSERT INTO {qi(t)} ({qi(key)}) SELECT x FROM generate_series(1, {rows}) AS g(x)"]
395
+ upd = f.get("update_sql") or f"UPDATE {qi(t)} SET {qi(col)} = {qi(col)} + 1 WHERE {qi(key)} = :k"
396
+ total = f.get("sum_sql") or f"SELECT coalesce(sum({qi(col)}), 0) FROM {qi(t)}"
397
+ gap = float(f.get("think_ms") if f.get("think_ms") is not None else 2)
398
+ sessions, ops = int(f.get("sessions") or 8), int(f.get("operations") or 40)
399
+ keys = f.get("keys") or list(range(1, rows + 1))
400
+ params = dict(f.get("params") or {})
401
+
402
+ def program(ordered: bool) -> Program:
403
+ def step(s, i, k):
404
+ a, b = s.rng.sample(session_keys(s, f, keys), 2)
405
+ if ordered:
406
+ a, b = sorted((a, b))
407
+ s.begin()
408
+ s.q(upd, {**params, "k": a})
409
+ s.call(gap)
410
+ s.q(upd, {**params, "k": b})
411
+ s.commit()
412
+ return True
413
+
414
+ def check(c, sessions_):
415
+ got = int(c.run(total)[0][0] or 0)
416
+ return {"sum": got}, got, (got == 2 * sessions * ops) if not f.get("update_sql") else None
417
+ return Program(setup=setup, step=step, check=check, on_error="retry", max_retries=50)
418
+
419
+ return Scenario("lock_order", "postgres", {"before": program(False), "after": program(True)},
420
+ invariant="every transfer applied once (after retries)", statements="extracted" if f.get("update_sql") else "modelled",
421
+ sessions=sessions, operations=ops, think_ms=gap, hot_rows=rows, of=sessions * ops,
422
+ fix={"change": "consistent_lock_order", "before": f.get("fix_before") or "-- rows locked in the order the request names them\n"
423
+ f"{upd} -- k = a\n{upd} -- k = b",
424
+ "after": f.get("fix_after") or f"-- lock in key order: (a, b) = sorted((a, b))\n{upd} -- k = a\n{upd} -- k = b"},
425
+ tradeoff="None in the result; the code must sort the keys (or the tables) before the first write.",
426
+ compared="sum of the rows against the transfers made")
427
+
428
+
429
+ # --- 7. SQLite: a deferred BEGIN that reads, then writes ------------------------------------------------------------------
430
+
431
+ def sqlite_deferred_begin(f: dict) -> Scenario:
432
+ """`f`: read_sql, write_sql (:v, :k) on a counter-like table (sqlite), journal_mode and busy_timeout_ms as the
433
+ repository opens the database (WAL and 5 s when it sets them)."""
434
+ t, key, col = f.get("table") or "codecop_counter", f.get("key") or "id", f.get("col") or "v"
435
+ setup = f.get("setup") or [f"CREATE TABLE {qi(t)} ({qi(key)} integer PRIMARY KEY, {qi(col)} integer NOT NULL)",
436
+ f"INSERT INTO {qi(t)} VALUES (1, 0)"]
437
+ read = f.get("read_sql") or f"SELECT {qi(col)} FROM {qi(t)} WHERE {qi(key)} = :k"
438
+ write = f.get("write_sql") or f"UPDATE {qi(t)} SET {qi(col)} = :v WHERE {qi(key)} = :k"
439
+ total = f.get("sum_sql") or f"SELECT coalesce(sum({qi(col)}), 0) FROM {qi(t)}"
440
+ sessions, ops = int(f.get("sessions") or 4), int(f.get("operations") or 100)
441
+ think = float(f.get("think_ms") if f.get("think_ms") is not None else 0.5)
442
+ settings = {"journal_mode": f.get("journal_mode") or "wal", "busy_timeout_ms": int(f.get("busy_timeout_ms") if f.get("busy_timeout_ms") is not None else 5000)}
443
+
444
+ def program(mode: str) -> Program:
445
+ def step(s, i, k):
446
+ s.begin(mode)
447
+ try:
448
+ v = s.q(read, {"k": 1})[0][0]
449
+ s.call(think)
450
+ s.q(write, {"k": 1, "v": (v or 0) + 1})
451
+ s.commit()
452
+ except DbError:
453
+ s.rollback()
454
+ raise
455
+ return True
456
+
457
+ def check(c, sessions_):
458
+ got = int(c.run(total)[0][0] or 0)
459
+ return {"sum": got}, got, got == sessions * ops
460
+ return Program(setup=setup, step=step, check=check)
461
+
462
+ return Scenario("sqlite_deferred_begin", "sqlite", {"before": program("DEFERRED"), "after": program("IMMEDIATE")},
463
+ invariant="every write landed (the counter equals the writes)", statements="extracted" if f.get("read_sql") else "modelled",
464
+ sessions=sessions, operations=ops, think_ms=think, of=sessions * ops,
465
+ db_settings={"before": settings, "after": settings},
466
+ fix={"change": "begin_immediate", "before": f"BEGIN\n{read}\n{write}\nCOMMIT", "after": f"BEGIN IMMEDIATE\n{read}\n{write}\nCOMMIT"},
467
+ tradeoff="The write lock is taken at BEGIN: writers queue for the busy timeout instead of failing; readers in WAL are not affected.",
468
+ compared="counter against the writes made")
469
+
470
+
471
+ # --- 8. SQLite opened without WAL or a busy timeout: writers fail while readers read --------------------------------------
472
+
473
+ def sqlite_no_wal_timeout(f: dict) -> Scenario:
474
+ """`f`: write statements (insert_sql, :k), a read (read_sql), the repository's journal_mode and busy_timeout_ms."""
475
+ t = f.get("table") or "codecop_events"
476
+ setup = f.get("setup") or [f"CREATE TABLE {qi(t)} (id integer PRIMARY KEY, k integer, body text)",
477
+ f"INSERT INTO {qi(t)} (k, body) SELECT x % 100, 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' FROM {series('sqlite', 30000)}"]
478
+ insert = f.get("insert_sql") or f"INSERT INTO {qi(t)} (k, body) VALUES (:k, 'w')"
479
+ read = f.get("read_sql") or f"SELECT k, count(*), sum(length(body)) FROM {qi(t)} GROUP BY k"
480
+ writers, readers = int(f.get("writers") or 4), int(f.get("readers") or 4)
481
+ ops = int(f.get("operations") or 60)
482
+ count = f.get("count_sql") or f"SELECT count(*) FROM {qi(t)} WHERE body = 'w'"
483
+ before = {"journal_mode": f.get("journal_mode") or "delete", "busy_timeout_ms": int(f.get("busy_timeout_ms") or 0)}
484
+ after = {"journal_mode": "wal", "busy_timeout_ms": int(f.get("fix_busy_timeout_ms") or 5000)}
485
+
486
+ def program() -> Program:
487
+ def step(s, i, k):
488
+ if i < writers:
489
+ s.q(insert, {"k": 1000 + i})
490
+ s.call(1)
491
+ else:
492
+ s.q(read)
493
+ return True
494
+
495
+ def check(c, sessions_):
496
+ got = int(c.run(count)[0][0] or 0)
497
+ expected = sum(1 for s in sessions_ if s.idx < writers) * ops
498
+ return {"landed": got, "expected": expected}, got, got == expected
499
+ return Program(setup=setup, step=step, check=check)
500
+
501
+ return Scenario("sqlite_no_wal_timeout", "sqlite", {"before": program(), "after": program()},
502
+ invariant="every write landed", statements="extracted" if f.get("insert_sql") else "modelled",
503
+ sessions=writers + readers, operations=ops, think_ms=1, of=writers * ops,
504
+ db_settings={"before": before, "after": after},
505
+ fix={"change": "wal_and_busy_timeout", "before": f"PRAGMA journal_mode={before['journal_mode']}; PRAGMA busy_timeout={before['busy_timeout_ms']}",
506
+ "after": f"PRAGMA journal_mode=WAL; PRAGMA busy_timeout={after['busy_timeout_ms']}"},
507
+ tradeoff="WAL keeps a -wal file beside the database and needs shared memory (not on a network file system).",
508
+ compared="rows written against the writes made")
509
+
510
+
511
+ BUILDERS = {"queue_claim": queue_claim, "poll_then_mark": poll_then_mark, "fk_without_index": fk_without_index,
512
+ "call_in_transaction": call_in_transaction, "read_modify_write": read_modify_write, "lock_order": lock_order,
513
+ "sqlite_deferred_begin": sqlite_deferred_begin, "sqlite_no_wal_timeout": sqlite_no_wal_timeout}
514
+
515
+
516
+ def build(code: str, facts: dict) -> Scenario:
517
+ scn = BUILDERS[code](facts)
518
+ if facts.get("statements") in ("extracted", "schema", "modelled"):
519
+ scn.statements = facts["statements"] # what the planner bound: the repository's text, its schema, or a model
520
+ return scn