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,355 @@
1
+ """The repository's own statements, bound to generated rows, for the schedule (`statements = extracted`).
2
+
3
+ `named(sql)` rewrites every placeholder ($1, ?, %s, %(name)s, :name, @name) to `:pN` / `:name`, which both pg8000
4
+ and sqlite3 bind. `analyze(sql)` reads, with sqlglot, what each placeholder is compared with (`s.account_id = $1` ->
5
+ column account_id of the table aliased s), the LIMIT placeholder, the literal filters (`status IN ('a', 'b')`,
6
+ `x IS NULL`, `y <> 'deleted'`), the joins and anti-joins. `seed(...)` writes the tables' definitions and rows so that
7
+ every candidate row satisfies the statement's filters: all items of one queue share the filter values, the key is
8
+ unique, joined parent tables get one row each.
9
+
10
+ A statement that cannot be bound (an unknown placeholder, a table with no definition) makes the scenario fall back to
11
+ modelled statements on the same table names; the finding then says `statements: modelled`.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import re
17
+
18
+ import sqlglot
19
+ from sqlglot import exp
20
+
21
+ PH = re.compile(r"\$(\d+)|%\((\w+)\)s|%s|(?<![:\w])\?(\d*)|(?<![:\w]):([A-Za-z_]\w*)|(?<![@\w])@([A-Za-z_]\w*)")
22
+ LITERAL_OR_COMMENT = re.compile(r"'(?:[^']|'')*'|--[^\n]*|\"(?:[^\"]|\"\")*\"")
23
+
24
+
25
+ class Unbound(Exception):
26
+ """The statement cannot be replayed as written."""
27
+
28
+
29
+ def named(sql: str) -> tuple[str, list[str]]:
30
+ """(the text with :pN placeholders, the placeholder names in order of first use)."""
31
+ order: list[str] = []
32
+ count = [0]
33
+ spans = [(m.start(), m.end()) for m in LITERAL_OR_COMMENT.finditer(sql)]
34
+
35
+ def inside(i: int) -> bool:
36
+ return any(a <= i < b for a, b in spans)
37
+
38
+ def repl(m: re.Match) -> str:
39
+ if inside(m.start()):
40
+ return m.group(0)
41
+ if m.group(1):
42
+ name = f"p{m.group(1)}"
43
+ elif m.group(2):
44
+ name = m.group(2)
45
+ elif m.group(3) is not None and m.group(0).startswith("?"):
46
+ if m.group(3):
47
+ name = f"p{m.group(3)}"
48
+ else:
49
+ count[0] += 1
50
+ name = f"p{count[0]}"
51
+ elif m.group(4):
52
+ name = m.group(4)
53
+ elif m.group(5):
54
+ name = m.group(5)
55
+ else: # %s
56
+ count[0] += 1
57
+ name = f"p{count[0]}"
58
+ if name not in order:
59
+ order.append(name)
60
+ return f":{name}"
61
+ out = PH.sub(repl, sql)
62
+ # `:p1::uuid` is fine for the drivers; sqlite has no `::` casts
63
+ return out, order
64
+
65
+
66
+ def parse(sql: str, engine: str):
67
+ try:
68
+ return sqlglot.parse_one(sql, read="postgres" if engine == "postgres" else "sqlite")
69
+ except Exception as e: # noqa: BLE001
70
+ raise Unbound(f"does not parse: {str(e)[:120]}") from None
71
+
72
+
73
+ def _table_of(col: exp.Column, aliases: dict[str, str], default: str) -> str:
74
+ q = col.table
75
+ return aliases.get(q, q) if q else default
76
+
77
+
78
+ def analyze(sql: str, engine: str) -> dict:
79
+ """{tables, aliases, main, params{name: {table, column, op}}, limit, filters[{table, column, op, value}], joins[(t1, c1,
80
+ t2, c2, kind)], anti[{table, column}], lock, kind, set_columns, returning}."""
81
+ tree = parse(sql, engine)
82
+ aliases: dict[str, str] = {}
83
+ tables: list[str] = []
84
+ for t in tree.find_all(exp.Table):
85
+ name = ".".join(p for p in (t.db, t.name) if p)
86
+ if name not in tables:
87
+ tables.append(name)
88
+ aliases[t.alias_or_name] = name
89
+ main = ""
90
+ if isinstance(tree, (exp.Insert, exp.Update, exp.Delete)):
91
+ tgt = tree.this if not isinstance(tree.this, exp.Schema) else tree.this.this
92
+ if isinstance(tgt, exp.Table):
93
+ main = ".".join(p for p in (tgt.db, tgt.name) if p)
94
+ elif isinstance(tree, exp.Select):
95
+ f = tree.args.get("from") or tree.args.get("from_")
96
+ if f is not None and isinstance(f.this, exp.Table):
97
+ main = ".".join(p for p in (f.this.db, f.this.name) if p)
98
+ params: dict[str, dict] = {}
99
+ filters: list[dict] = []
100
+ joins: list[tuple] = []
101
+ anti: list[dict] = []
102
+ for node in tree.find_all(exp.Placeholder):
103
+ name = str(node.this)
104
+ par = node.parent
105
+ while isinstance(par, (exp.Cast, exp.Paren, exp.Anonymous)) and par.parent is not None:
106
+ par = par.parent
107
+ if isinstance(par, exp.Limit):
108
+ params[name] = {"limit": True}
109
+ continue
110
+ if isinstance(par, (exp.EQ, exp.NEQ, exp.GT, exp.GTE, exp.LT, exp.LTE, exp.In, exp.Any)) or isinstance(par, exp.ArrayContains):
111
+ if isinstance(par, exp.Any):
112
+ par = par.parent
113
+ col = next((c for c in par.find_all(exp.Column)), None)
114
+ if col is not None:
115
+ params[name] = {"table": _table_of(col, aliases, main), "column": col.name, "op": type(par).__name__.lower()}
116
+ continue
117
+ if isinstance(par, exp.Tuple) or isinstance(par, exp.Values):
118
+ params[name] = {"values": True}
119
+ continue
120
+ if isinstance(par, (exp.Select,)) and isinstance(tree, exp.Insert):
121
+ params[name] = {"select_value": True}
122
+ continue
123
+ params.setdefault(name, {"unknown": True})
124
+ where = tree.args.get("where")
125
+ if where is not None:
126
+ for node in where.find_all(exp.Is, exp.EQ, exp.NEQ, exp.In, exp.GT, exp.Not):
127
+ if isinstance(node, exp.Is) and isinstance(node.this, exp.Column):
128
+ null_check = isinstance(node.expression, exp.Null)
129
+ negated = isinstance(node.parent, exp.Not) or bool(node.args.get("negate")) # sqlglot 30: Is(negate=True)
130
+ filters.append({"table": _table_of(node.this, aliases, main), "column": node.this.name,
131
+ "op": "is_not_null" if negated else "is_null" if null_check else "is"})
132
+ elif isinstance(node, exp.Not) and isinstance(node.this, exp.Is):
133
+ continue
134
+ elif isinstance(node, (exp.EQ, exp.NEQ)) and isinstance(node.this, exp.Column) and isinstance(node.expression, (exp.Literal, exp.Boolean)):
135
+ v = node.expression
136
+ filters.append({"table": _table_of(node.this, aliases, main), "column": node.this.name,
137
+ "op": "eq" if isinstance(node, exp.EQ) else "neq",
138
+ "value": v.this if isinstance(v, exp.Literal) else bool(v.this), "string": isinstance(v, exp.Literal) and v.is_string})
139
+ elif isinstance(node, exp.In) and isinstance(node.this, exp.Column):
140
+ vals = [e.this for e in node.expressions if isinstance(e, exp.Literal)]
141
+ if vals:
142
+ filters.append({"table": _table_of(node.this, aliases, main), "column": node.this.name, "op": "in", "value": vals[0],
143
+ "string": True})
144
+ elif isinstance(node, exp.GT) and isinstance(node.this, exp.Column) and "now" in node.expression.sql().lower() + node.expression.sql().lower().replace("current_timestamp", "now"):
145
+ filters.append({"table": _table_of(node.this, aliases, main), "column": node.this.name, "op": "recent"})
146
+ for j in tree.find_all(exp.Join):
147
+ on = j.args.get("on")
148
+ if on is None:
149
+ continue
150
+ for eq in on.find_all(exp.EQ):
151
+ a, b = eq.this, eq.expression
152
+ if isinstance(a, exp.Column) and isinstance(b, exp.Column):
153
+ joins.append((_table_of(a, aliases, main), a.name, _table_of(b, aliases, main), b.name, (j.args.get("side") or "").lower()))
154
+ # anti-join: LEFT JOIN m ON .. WHERE m.c IS NULL
155
+ left = {jt for (t1, _, t2, _, side) in joins if side == "left" for jt in (t1, t2)}
156
+ for flt in filters:
157
+ if flt["op"] == "is_null" and flt["table"] in left and flt["table"] != main:
158
+ anti.append({"table": flt["table"], "column": flt["column"]})
159
+ for sub in tree.find_all(exp.Exists):
160
+ if isinstance(sub.parent, exp.Not):
161
+ t = next(sub.find_all(exp.Table), None)
162
+ if t is not None:
163
+ anti.append({"table": ".".join(p for p in (t.db, t.name) if p), "column": "", "not_exists": True})
164
+ lock = ""
165
+ for lk in tree.find_all(exp.Lock):
166
+ lock = "skip_locked" if lk.args.get("wait") is False and "SKIP" in lk.sql().upper() else \
167
+ "nowait" if lk.args.get("wait") is True else ("for_share" if not lk.args.get("update") else "for_update")
168
+ if not lock:
169
+ up = sql.upper()
170
+ lock = "skip_locked" if "SKIP LOCKED" in up else "nowait" if "NOWAIT" in up else "for_update" if re.search(r"\bFOR\s+(NO\s+KEY\s+)?UPDATE\b", up) \
171
+ else "for_share" if re.search(r"\bFOR\s+(KEY\s+)?SHARE\b", up) else ""
172
+ set_cols = []
173
+ if isinstance(tree, exp.Update):
174
+ for e in tree.expressions:
175
+ if isinstance(e, exp.EQ) and isinstance(e.this, exp.Column):
176
+ set_cols.append({"column": e.this.name, "expr": e.expression.sql(dialect="postgres"),
177
+ "param": str(e.expression.this) if isinstance(e.expression, exp.Placeholder) else ""})
178
+ insert_cols = []
179
+ if isinstance(tree, exp.Insert) and isinstance(tree.this, exp.Schema):
180
+ insert_cols = [c.name for c in tree.this.expressions if isinstance(c, exp.Identifier) or isinstance(c, exp.Column)]
181
+ select_cols = []
182
+ if isinstance(tree, exp.Select):
183
+ for e in tree.expressions:
184
+ c = e.this if isinstance(e, exp.Alias) else e
185
+ if not isinstance(c, exp.Column): # `id::text AS id`: the column under the cast
186
+ inner = list(c.find_all(exp.Column)) if isinstance(c, (exp.Cast, exp.Paren)) else []
187
+ c = inner[0] if len(inner) == 1 else c
188
+ select_cols.append({"table": _table_of(c, aliases, main) if isinstance(c, exp.Column) else "", "column": c.name if isinstance(c, exp.Column) else ""})
189
+ return {"sql": sql, "kind": tree.key, "tables": tables, "aliases": aliases, "main": main, "params": params, "filters": filters, "joins": joins,
190
+ "anti": anti, "lock": lock, "set": set_cols, "insert_columns": insert_cols, "select_columns": select_cols,
191
+ "returning": tree.args.get("returning") is not None, "on_conflict": tree.args.get("conflict") is not None}
192
+
193
+
194
+ # --- table definitions and rows --------------------------------------------------------------------------------------------
195
+
196
+ TYPE_FAMILY = [
197
+ ("uuid", re.compile(r"\buuid\b", re.I)), ("bool", re.compile(r"\bbool", re.I)),
198
+ ("time", re.compile(r"timestamp|\bdate\b|\btime\b|datetime", re.I)), ("json", re.compile(r"json", re.I)),
199
+ ("int", re.compile(r"int|serial|numeric|decimal|real|double|float", re.I)), ("bytes", re.compile(r"bytea|blob", re.I)),
200
+ ("array", re.compile(r"\[\]|array", re.I)),
201
+ ]
202
+
203
+
204
+ def family(type_text: str) -> str:
205
+ for name, pat in TYPE_FAMILY:
206
+ if pat.search(type_text or ""):
207
+ return name
208
+ return "text"
209
+
210
+
211
+ def literal(value, fam: str, engine: str) -> str:
212
+ """A constant of a column's family, as SQL."""
213
+ if value is None:
214
+ return "NULL"
215
+ if fam == "uuid" and engine == "postgres":
216
+ return f"'{value}'::uuid"
217
+ if fam == "int":
218
+ return str(int(value)) if str(value).lstrip("-").isdigit() else "1"
219
+ if fam == "bool":
220
+ return "true" if value in (True, "true", "t", 1, "1") else "false"
221
+ return "'" + str(value).replace("'", "''") + "'"
222
+
223
+
224
+ def unique_expr(fam: str, engine: str, salt: str = "") -> str:
225
+ """A per-row unique value of a column family, from the series column x."""
226
+ if fam == "uuid":
227
+ return f"md5('{salt}' || x::text)::uuid" if engine == "postgres" else f"'{salt}' || x"
228
+ if fam == "int":
229
+ return "x"
230
+ if fam == "time":
231
+ return "now() - (x || ' seconds')::interval" if engine == "postgres" else "datetime('now', '-' || x || ' seconds')"
232
+ if fam == "json":
233
+ return "'{}'" if engine == "sqlite" else "'{}'::jsonb"
234
+ if fam == "bool":
235
+ return "false"
236
+ if fam == "bytes":
237
+ return "'x'" if engine == "sqlite" else "'\\x00'::bytea"
238
+ if fam == "array":
239
+ return "'{}'"
240
+ return f"'{salt}' || x"
241
+
242
+
243
+ def default_value(fam: str, engine: str) -> str:
244
+ return {"uuid": "'00000000-0000-0000-0000-0000000000aa'" + ("::uuid" if engine == "postgres" else ""), "int": "0",
245
+ "time": "now()" if engine == "postgres" else "datetime('now')", "json": "'{}'", "bool": "false",
246
+ "bytes": "'x'" if engine == "sqlite" else "'\\x00'::bytea", "array": "'{}'"}.get(fam, "'v'")
247
+
248
+
249
+ CONST_UUID = "00000000-0000-0000-0000-0000000000{:02d}"
250
+
251
+
252
+ def const_for(fam: str, n: int):
253
+ return {"uuid": CONST_UUID.format(n), "int": n, "bool": True, "time": None}.get(fam, f"c{n}")
254
+
255
+
256
+ def strip_fks(create_sql: str) -> str:
257
+ """The definition without foreign keys (the generated rows keep the joins consistent themselves) and with
258
+ IF NOT EXISTS on its table."""
259
+ s = re.sub(r",\s*(?:CONSTRAINT\s+\"?\w+\"?\s+)?FOREIGN\s+KEY\s*\([^)]*\)\s*REFERENCES\s+[\w.\"]+\s*(?:\([^)]*\))?(?:\s+(?:ON\s+(?:DELETE|UPDATE)\s+(?:CASCADE|RESTRICT|NO\s+ACTION|SET\s+NULL|SET\s+DEFAULT)|DEFERRABLE|INITIALLY\s+\w+|MATCH\s+\w+|NOT\s+VALID))*",
260
+ "", create_sql, flags=re.I)
261
+ s = re.sub(r"\s+REFERENCES\s+[\w.\"]+\s*(?:\([^)]*\))?(?:\s+(?:ON\s+(?:DELETE|UPDATE)\s+(?:CASCADE|RESTRICT|NO\s+ACTION|SET\s+NULL|SET\s+DEFAULT)|DEFERRABLE|INITIALLY\s+\w+|MATCH\s+\w+))*",
262
+ "", s, flags=re.I)
263
+ return s
264
+
265
+
266
+ def columns_of(create_sql: str, name: str) -> list[dict]:
267
+ """[{name, type, not_null, default, pk}] of the CREATE TABLE in `create_sql` (the first one for `name`)."""
268
+ from ...rank import _columns
269
+ got = _columns(create_sql or "", name)
270
+ out = []
271
+ pk_cols = set()
272
+ m = re.search(r"PRIMARY\s+KEY\s*\(([^)]*)\)", create_sql or "", re.I)
273
+ if m:
274
+ pk_cols = {c.strip().strip('"').lower() for c in m.group(1).split(",")}
275
+ for col, text in (got[1] if got else {}).items():
276
+ words = text.split()
277
+ typ = " ".join(w for w in words[1:4] if not re.match(r"^(?:PRIMARY|NOT|NULL|DEFAULT|UNIQUE|REFERENCES|CHECK|COLLATE|GENERATED|CONSTRAINT)$", w, re.I))
278
+ out.append({"name": col, "type": typ, "family": family(typ), "not_null": bool(re.search(r"\bNOT\s+NULL\b|\bPRIMARY\s+KEY\b", text, re.I)),
279
+ "default": bool(re.search(r"\bDEFAULT\b|\bserial\b|\bGENERATED\b|\bIDENTITY\b", text, re.I)),
280
+ "pk": bool(re.search(r"\bPRIMARY\s+KEY\b", text, re.I)) or col.lower() in pk_cols,
281
+ "generated": bool(re.search(r"\bGENERATED\s+ALWAYS\s+AS\s*\(", text, re.I))})
282
+ return out
283
+
284
+
285
+ def definition(name: str, inventory: dict, catalog: dict | None, engine: str) -> dict | None:
286
+ """{name, create_sql, columns, source}: the catalog's definition when pulled, else the repository's."""
287
+ bare = name.split(".")[-1].lower()
288
+ for conn in ((catalog or {}).get("connections") or {}).values():
289
+ if (conn.get("engine") or "") != engine:
290
+ continue
291
+ for t in conn.get("tables") or []:
292
+ if str(t.get("name", "")).lower() == bare and t.get("create_sql"):
293
+ sql = t["create_sql"]
294
+ return {"name": t["name"], "create_sql": sql, "columns": columns_of(sql, t["name"]), "source": "catalog",
295
+ "indexes": [i.get("definition") for i in t.get("indexes") or [] if i.get("definition")]}
296
+ from ...loopschema import definition as repo_definition
297
+ d = repo_definition(inventory or {}, name, engine)
298
+ if not d or not d.get("create_sql"):
299
+ return None
300
+ return {"name": d["name"], "create_sql": d["create_sql"], "columns": columns_of(d["create_sql"], d["name"]), "source": "repository",
301
+ "indexes": []}
302
+
303
+
304
+ def create_statements(d: dict, engine: str) -> list[str]:
305
+ """The definition's statements, foreign keys left out, CREATE SCHEMA when the name has one."""
306
+ out = []
307
+ if "." in d["name"] and engine == "postgres":
308
+ out.append(f'CREATE SCHEMA IF NOT EXISTS "{d["name"].split(".")[0]}"')
309
+ for stmt in re.split(r";\s*(?:\n|$)", strip_fks(d["create_sql"])):
310
+ s = stmt.strip()
311
+ if not s or s.startswith("--"):
312
+ continue
313
+ if re.match(r"^(CREATE\s+(UNIQUE\s+)?INDEX|CREATE\s+TABLE|ALTER\s+TABLE\s+\S+\s+ADD\s+(CONSTRAINT|PRIMARY|UNIQUE))", s, re.I):
314
+ s = re.sub(r"\bCONCURRENTLY\s+", "", s, flags=re.I)
315
+ if re.match(r"^ALTER", s, re.I) and re.search(r"FOREIGN\s+KEY|CHECK\s*\(", s, re.I):
316
+ continue
317
+ if engine == "postgres" and re.match(r"^CREATE\s+TABLE", s, re.I):
318
+ s = re.sub(r"\bPARTITION\s+BY\s+\w+\s*\([^)]*\)\s*$", "", s, flags=re.I)
319
+ out.append(s)
320
+ return out
321
+
322
+
323
+ def seed_rows(d: dict, engine: str, n: int, consts: dict[str, object], *, unique: set[str], nulls: set[str], recent: set[str],
324
+ salt: str = "q") -> str:
325
+ """INSERT .. SELECT of n rows: `consts` columns get that value in every row, `unique` columns a per-row value, `nulls`
326
+ NULL, `recent` a recent time; other NOT NULL columns without a default get a constant of their type."""
327
+ from .scenarios import series
328
+ cols, vals = [], []
329
+ for c in d["columns"]:
330
+ name, fam = c["name"], c["family"]
331
+ if c.get("generated"):
332
+ continue
333
+ low = name.lower()
334
+ if low in consts:
335
+ cols.append(name)
336
+ vals.append(literal(consts[low], fam, engine))
337
+ elif low in unique or c["pk"] and not c["default"]:
338
+ cols.append(name)
339
+ vals.append(unique_expr(fam, engine, salt))
340
+ elif low in nulls:
341
+ continue
342
+ elif low in recent:
343
+ cols.append(name)
344
+ vals.append(unique_expr("time", engine))
345
+ elif c["not_null"] and not c["default"]:
346
+ cols.append(name)
347
+ vals.append(default_value(fam, engine))
348
+ if not cols:
349
+ raise Unbound(f"no columns to fill in {d['name']}")
350
+ q = ", ".join('"' + c + '"' for c in cols)
351
+ return f'INSERT INTO {quote(d["name"])} ({q}) SELECT {", ".join(vals)} FROM {series(engine, n)}'
352
+
353
+
354
+ def quote(name: str) -> str:
355
+ return ".".join('"' + p.replace('"', "") + '"' for p in str(name).split("."))
@@ -0,0 +1,264 @@
1
+ """Measuring one scenario: before and with the fix, repeated runs interleaved, the counts and the throughput of each run,
2
+ the spread, the final-state check, the worker curve, and the verdict. Counts and throughput ratios decide; tail
3
+ latencies and lock-wait shares are shown with `verdict: False`.
4
+
5
+ A call inside a transaction is judged on the time each transaction holds its lock (`lock_hold_ms`, median per committed
6
+ transaction), not on throughput: on a busy machine the throughput gain can fall inside the spread of two runs, so the
7
+ same code would be called "no gain" one run and "fixed" the next, a state that follows the machine's load. The hold is the mechanism itself, measured on each side (the call's wall time inside it before the fix,
8
+ the commit only after), and the other sessions' measured wait for the lock (`lock_wait_ms`) says whether holding it
9
+ cost anyone anything: no wait before the fix is nothing to gain. Throughput is still measured and shown; a fix measured
10
+ slower beyond the spread is still not a win."""
11
+
12
+ from __future__ import annotations
13
+
14
+ import statistics
15
+ from typing import Callable
16
+
17
+ from .. import measure as k_measure, outcome as k_outcome, proof as k_proof, sameness as k_sameness
18
+ from .scenarios import VERDICT, WORKER_SENSITIVE, Scenario
19
+ from .schedule import WAIT_FLOOR_MS, RunResult, mark_duplicates, run_once
20
+
21
+ CORRECTNESS = ("duplicates", "lost_updates", "deadlocks", "busy_errors", "failed_writes")
22
+ DEFAULTS = {"runs": 3, "workers": [1, 2], "min_gain": 1.2, "sample_ms": 20.0, "timeout_s": 120.0, "seed": 1}
23
+
24
+
25
+ def metrics(scn: Scenario, r: RunResult, sessions: int) -> dict:
26
+ """The numbers of one run, by measure code."""
27
+ out: dict = {}
28
+ c = r.counters
29
+ if scn.code == "queue_claim":
30
+ out["throughput"] = (c.get("done") or 0) / r.elapsed_s if r.elapsed_s else 0
31
+ out["duplicates"] = c.get("duplicates", 0)
32
+ elif scn.code == "poll_then_mark":
33
+ out["duplicates"] = c.get("duplicates", 0)
34
+ out["throughput"] = (c.get("items") or 0) / r.elapsed_s if r.elapsed_s else 0
35
+ elif scn.code == "fk_without_index":
36
+ out["delete_ms"] = r.p50_wait_ms or 0
37
+ out["throughput"] = r.throughput
38
+ elif scn.code == "call_in_transaction":
39
+ out["throughput"] = r.throughput
40
+ out["failed_writes"] = sum(v for v in r.errors.values() if isinstance(v, int))
41
+ if r.lock_hold_ms:
42
+ out["lock_hold_ms"] = round(statistics.median(r.lock_hold_ms), 3)
43
+ out["lock_wait_ms"] = round(statistics.fmean(r.lock_wait_ms), 3)
44
+ elif scn.code == "read_modify_write":
45
+ applied = int(c.get("sum") or 0)
46
+ out["lost_updates"] = max(0, r.ops - applied)
47
+ out["throughput"] = r.throughput
48
+ elif scn.code == "lock_order":
49
+ out["deadlocks"] = r.errors.get("deadlock", 0)
50
+ out["throughput"] = r.throughput
51
+ elif scn.code == "sqlite_deferred_begin":
52
+ out["busy_errors"] = r.errors.get("busy", 0)
53
+ out["throughput"] = (c.get("sum") or 0) / r.elapsed_s if r.elapsed_s else 0
54
+ elif scn.code == "sqlite_no_wal_timeout":
55
+ out["failed_writes"] = max(0, int(c.get("expected") or 0) - int(c.get("landed") or 0))
56
+ out["throughput"] = (c.get("landed") or 0) / r.elapsed_s if r.elapsed_s else 0
57
+ if r.samples:
58
+ out["lock_wait_share"] = round(100.0 * r.lock_wait_samples / r.samples, 1)
59
+ out["idle_in_tx_share"] = round(100.0 * r.idle_in_tx_samples / r.samples, 1)
60
+ if r.p95_wait_ms is not None and scn.code in ("queue_claim", "fk_without_index"):
61
+ out["p95_wait_ms"] = r.p95_wait_ms
62
+ return out
63
+
64
+
65
+ def run_variant(scn: Scenario, variant: str, make_db: Callable, *, sessions: int, cfg: dict, seed: int) -> RunResult:
66
+ db = make_db(scn.db_settings.get(variant) or scn.db_settings.get("before") or {})
67
+ try:
68
+ return run_once(db, scn.variants[variant], sessions=sessions, operations=scn.operations, seed=seed,
69
+ sample_ms=float(cfg["sample_ms"]), timeout_s=float(cfg["timeout_s"]))
70
+ finally:
71
+ db.close()
72
+
73
+
74
+ def measure(scn: Scenario, make_db: Callable, settings: dict | None = None, log=None) -> dict:
75
+ """Run the scenario. Returns {runs: {variant: [metrics...]}, results: {variant: [RunResult]}, lanes, workers, state,
76
+ held, ...}. `make_db(settings)` gives a fresh database for one run (SqliteDb, or PgDb in the sandbox)."""
77
+ cfg = {**DEFAULTS, **(settings or {})}
78
+ runs = max(1, int(cfg["runs"]))
79
+ by: dict[str, list[dict]] = {v: [] for v in scn.variants}
80
+ raw: dict[str, list[RunResult]] = {v: [] for v in scn.variants}
81
+ for rep in range(runs):
82
+ for v in scn.variants: # interleaved: before, after, before, after ...
83
+ r = run_variant(scn, v, make_db, sessions=scn.sessions, cfg=cfg, seed=int(cfg["seed"]) + rep)
84
+ raw[v].append(r)
85
+ by[v].append(metrics(scn, r, scn.sessions))
86
+ if log:
87
+ log(f" {scn.code} {v} run {rep + 1}: " + ", ".join(f"{k} {round(x, 2)}" for k, x in by[v][-1].items()))
88
+ workers = []
89
+ if scn.code in WORKER_SENSITIVE:
90
+ for n in sorted({int(x) for x in cfg["workers"] if int(x) >= 1 and int(x) < scn.sessions}):
91
+ point = {"n": n}
92
+ for v in ("before", "after"):
93
+ r = run_variant(scn, v, make_db, sessions=n, cfg=cfg, seed=int(cfg["seed"]))
94
+ point[v] = round(metrics(scn, r, n).get(scn.verdict, 0), 3)
95
+ workers.append(point)
96
+ workers.append({"n": scn.sessions, "before": median(by["before"], scn.verdict), "after": median(by["after"], scn.verdict)})
97
+ lanes = {}
98
+ for v in ("before", "after"):
99
+ if raw[v]:
100
+ lanes[v] = mark_duplicates(raw[v][0].lanes) if scn.code in ("poll_then_mark", "queue_claim") else _strip(raw[v][0].lanes)
101
+ return {"runs": by, "results": raw, "workers": workers, "lanes": lanes, "cfg": cfg}
102
+
103
+
104
+ def _strip(lanes: dict) -> dict:
105
+ for segs in lanes.get("sessions") or []:
106
+ for seg in segs:
107
+ del seg[3:]
108
+ return lanes
109
+
110
+
111
+ def values(rows: list[dict], key: str) -> list[float]:
112
+ return [float(r[key]) for r in rows if r.get(key) is not None]
113
+
114
+
115
+ def median(rows: list[dict], key: str) -> float:
116
+ xs = values(rows, key)
117
+ return round(statistics.median(xs), 3) if xs else 0.0
118
+
119
+
120
+ MEASURE_META = {
121
+ # code: (unit, better, verdict)
122
+ "throughput": ("ops/s", "higher", True), "duplicates": ("count", "lower", True), "lost_updates": ("count", "lower", True),
123
+ "deadlocks": ("count", "lower", True), "busy_errors": ("count", "lower", True), "failed_writes": ("count", "lower", True),
124
+ "delete_ms": ("ms", "lower", True), "lock_wait_share": ("%", "lower", False), "idle_in_tx_share": ("%", "lower", False),
125
+ "p95_wait_ms": ("ms", "lower", False), "lock_hold_ms": ("ms", "lower", True), "lock_wait_ms": ("ms", "lower", False),
126
+ }
127
+
128
+
129
+ def build_measures(scn: Scenario, m: dict, fix_variant: str = "after") -> list[dict]:
130
+ """The proof's measures, the verdict's first."""
131
+ before, after = m["runs"]["before"], m["runs"][fix_variant]
132
+ keys = [scn.verdict] + [k for k in ("throughput", "duplicates", "lost_updates", "deadlocks", "busy_errors", "failed_writes",
133
+ "delete_ms", "p95_wait_ms", "lock_wait_ms", "lock_wait_share", "idle_in_tx_share")
134
+ if k != scn.verdict and any(k in r for r in before + after)]
135
+ out = []
136
+ for k in keys:
137
+ b, a = values(before, k), values(after, k)
138
+ if not b or not a:
139
+ continue
140
+ unit, better, verdict = MEASURE_META[k]
141
+ if (k in CORRECTNESS or not verdict) and k != scn.verdict and not any(b) and not any(a):
142
+ continue # an error class that never happened, a share that stayed 0: not a measure
143
+ judged = verdict and (k == scn.verdict or k == "throughput")
144
+ out.append(k_measure(k, unit, statistics.median(b), statistics.median(a), better=better,
145
+ of=scn.of if k in CORRECTNESS and scn.of else None,
146
+ spread_before=(min(b), max(b)), spread_after=(min(a), max(a)), runs=len(b), verdict=judged))
147
+ return out
148
+
149
+
150
+ def judge(scn: Scenario, m: dict, kind: str = "transaction") -> dict:
151
+ """{fix_variant, state, reason, held, evidence}: counts first; throughput only beyond the spread; a fix whose final
152
+ state differs from a serial execution is a trade-off; a correctness fix that costs throughput is a trade-off."""
153
+ cfg = m["cfg"]
154
+ gain_min = float(cfg["min_gain"])
155
+ best = None
156
+ for v in [x for x in scn.variants if x != "before"]:
157
+ res = _judge_one(scn, m, v, gain_min)
158
+ rank = {"fixed": 0, "blocked": 1, "nothing_to_gain": 2, "not_judged": 3}[res["state"]]
159
+ if best is None or rank < best[0]:
160
+ best = (rank, res)
161
+ return best[1]
162
+
163
+
164
+ def _held(scn: Scenario, m: dict, variant: str) -> tuple[bool | None, str]:
165
+ """Did the fix leave the state a serial execution leaves? Scenarios with an invariant say so per run; the others
166
+ compare the fix's final state with the run before the fix (same seed, same operations)."""
167
+ rs = m["results"][variant]
168
+ if scn.code == "read_modify_write":
169
+ ok = all(int(r.counters.get("sum") or 0) == r.ops for r in rs)
170
+ return ok, f"{len(rs)} runs: sum equals the updates made" if ok else "the sum differs from the updates made"
171
+ if scn.code in ("fk_without_index", "call_in_transaction"):
172
+ b = [r.state for r in m["results"]["before"]]
173
+ ok = all(r.state == b[i] for i, r in enumerate(rs) if i < len(b))
174
+ return ok, f"{len(rs)} runs: final rows equal to the run without the fix, per seed"
175
+ if scn.code == "lock_order" and any(r.held is None for r in rs):
176
+ want = scn.sessions * scn.operations
177
+ ok = all(r.ops == want for r in rs)
178
+ return ok, f"{len(rs)} runs: every transaction committed once (after retries)"
179
+ held = [r.held for r in rs]
180
+ if any(h is None for h in held):
181
+ return None, ""
182
+ return all(held), f"{len(rs)} runs: {scn.invariant}"
183
+
184
+
185
+ def _judge_one(scn: Scenario, m: dict, variant: str, gain_min: float) -> dict:
186
+ before, after = m["runs"]["before"], m["runs"][variant]
187
+ held, basis = _held(scn, m, variant)
188
+ key = scn.verdict
189
+ b, a = values(before, key), values(after, key)
190
+ tb, ta = values(before, "throughput"), values(after, "throughput")
191
+ ev = {"verdict_measure": key, "before": round(statistics.median(b), 3) if b else None,
192
+ "after": round(statistics.median(a), 3) if a else None}
193
+ if key in CORRECTNESS:
194
+ if not any(b):
195
+ return {"variant": variant, "state": "nothing_to_gain", "reason": "transaction.not_reproduced", "held": held, "basis": basis, "evidence": ev}
196
+ if any(a):
197
+ return {"variant": variant, "state": "blocked", "reason": "no_gain_measured", "held": held, "basis": basis, "evidence": ev}
198
+ if held is False:
199
+ return {"variant": variant, "state": "blocked", "reason": "fix_results_differ", "held": held, "basis": basis, "evidence": ev}
200
+ # the same work done on both sides (every update or act ran; errors would make the side before the fix finish
201
+ # early on less work): only then can a slower fix be called a trade-off on throughput. Not on SQLite: there the
202
+ # throughput of both sides is set by its busy handler's sleeps (the ratio of
203
+ # the two sides moves with the machine's load, so the same SQLite correctness fix can read "fixed" one run and a
204
+ # trade-off the next), so a SQLite throughput ratio is never a claim either way.
205
+ same_work = key in ("lost_updates", "duplicates") and scn.engine != "sqlite"
206
+ if same_work and tb and ta and max(ta) < min(tb) and statistics.median(ta) * gain_min < statistics.median(tb):
207
+ ev["throughput_ratio"] = round(statistics.median(ta) / statistics.median(tb), 3)
208
+ return {"variant": variant, "state": "blocked", "reason": "transaction.fix_costs_throughput", "held": held, "basis": basis, "evidence": ev}
209
+ return {"variant": variant, "state": "fixed", "reason": "verified", "held": held, "basis": basis, "evidence": ev}
210
+ # a speed measure: beyond the spread and by at least min_gain
211
+ better_higher = key == "throughput"
212
+ if not b or not a:
213
+ return {"variant": variant, "state": "not_judged", "reason": "sandbox_could_not_run", "held": held, "basis": basis, "evidence": ev}
214
+ mb, ma = statistics.median(b), statistics.median(a)
215
+ if key == "lock_hold_ms":
216
+ # holding the lock longer costs only when another session waited for it; a fix measured slower is no win
217
+ waits = values(before, "lock_wait_ms")
218
+ ev["lock_wait_ms_before"] = round(statistics.median(waits), 3) if waits else None
219
+ if not waits or max(waits) <= WAIT_FLOOR_MS:
220
+ return {"variant": variant, "state": "nothing_to_gain", "reason": "transaction.not_reproduced", "held": held, "basis": basis, "evidence": ev}
221
+ if tb and ta and max(ta) < min(tb) and statistics.median(ta) * gain_min < statistics.median(tb):
222
+ ev["throughput_ratio"] = round(statistics.median(ta) / statistics.median(tb), 3)
223
+ return {"variant": variant, "state": "blocked", "reason": "no_gain_measured", "held": held, "basis": basis, "evidence": ev}
224
+ if better_higher:
225
+ gained = min(a) > max(b) and ma >= mb * gain_min
226
+ else:
227
+ gained = max(a) < min(b) and ma * gain_min <= mb
228
+ ev["ratio"] = round(ma / mb, 4) if mb else None
229
+ if not gained:
230
+ waits = values(before, "lock_wait_share")
231
+ quiet = waits and max(waits) == 0
232
+ return {"variant": variant, "state": "nothing_to_gain" if quiet else "blocked",
233
+ "reason": "transaction.not_reproduced" if quiet else "no_gain_measured", "held": held, "basis": basis, "evidence": ev}
234
+ if held is False:
235
+ return {"variant": variant, "state": "blocked", "reason": "fix_results_differ", "held": held, "basis": basis, "evidence": ev}
236
+ return {"variant": variant, "state": "fixed", "reason": "verified", "held": held, "basis": basis, "evidence": ev}
237
+
238
+
239
+ def proof_of(scn: Scenario, m: dict, verdict: dict, runtime: dict, inputs: dict | None = None) -> dict:
240
+ v = verdict["variant"]
241
+ rs = m["results"][v]
242
+ same = k_sameness("same_final_state", verdict.get("held"), compared=len(rs), differed=0 if verdict.get("held") else
243
+ (len(rs) if verdict.get("held") is False else None), basis=(verdict.get("basis") or scn.compared)[:120])
244
+ sched = {"sessions": scn.sessions, "think_ms": scn.think_ms, "on_error": scn.variants[v].on_error,
245
+ "invariant": scn.invariant[:60], "statements": scn.statements, "runs": len(rs)}
246
+ if scn.items:
247
+ sched["operations"] = scn.items
248
+ else:
249
+ sched["operations"] = scn.sessions * scn.operations
250
+ if scn.hot_rows:
251
+ sched["hot_rows"] = scn.hot_rows
252
+ if scn.batch:
253
+ sched["batch"] = scn.batch
254
+ if m.get("workers"):
255
+ sched["workers"] = ", ".join(str(p["n"]) for p in m["workers"])
256
+ return k_proof(source="sandbox", measures=build_measures(scn, m, v), same=same, runtime=runtime, schedule=sched,
257
+ inputs=inputs or {"family": "generated rows", "typical": scn.compared[:60], "observed": "not measured"})
258
+
259
+
260
+ def outcome_of(verdict: dict, kind: str = "transaction") -> dict:
261
+ return k_outcome(kind, verdict["state"], verdict["reason"], source="sandbox", evidence=verdict.get("evidence") or {})
262
+
263
+
264
+ __all__ = ["measure", "judge", "proof_of", "outcome_of", "build_measures", "VERDICT"]