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,274 @@
1
+ """How scenarios are shown: the CLI lines, the report section, and the fields the upload bundle carries.
2
+
3
+ Built from scenarios.json alone, fixed vocabularies and numbers; the report section follows the report's own style (cards,
4
+ a stacked bar, dense tables, chips), no prose blobs."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import html
9
+
10
+ from .scenarios import LABEL, RULES, SCENARIOS
11
+
12
+ RULE_LABEL = {"empty_runs": "runs mostly return nothing, the median run still reads", "key_wrapped": "key column inside a function",
13
+ "map_lookup": "map or JSON lookup where a key column exists", "no_time_bound": "no bound on the table's time key",
14
+ "reads_far_above_returns": "reads far more rows than it returns", "wide_before_limit": "wide columns read for every row of a page",
15
+ "wide_in_aggregate_before_limit": "wide columns carried through an aggregate before LIMIT",
16
+ "narrow_copy": "a narrow copy holds every column it reads", "count_next_to_page": "a count beside a paged select",
17
+ "count_over_sorted_subquery": "count over a sorted subquery"}
18
+ CHANGE_LABEL = {"filter_first_prewhere": "key predicates in PREWHERE", "probe_before_wide_read": "existence probe before the wide read",
19
+ "narrow_columns": "read fewer columns", "skip_closed_buckets": "do not re-read closed buckets",
20
+ "unwrap_key_column": "compare the bare key column", "rewrite_wrapped_predicate": "rewrite the wrapped predicate",
21
+ "compare_typed_column": "compare the typed column", "add_time_bound": "add the time bound", "skip_index": "skip index",
22
+ "projection": "projection", "sorting_key": "re-keyed copy", "late_materialization": "pick the page on the key first",
23
+ "late_materialization_aggregate": "aggregate on narrow columns, fetch wide ones for the page",
24
+ "read_narrow_copy": "read the narrow copy", "count_over_window": "one statement with count() OVER ()",
25
+ "totals_optional": "make the total optional", "drop_inner_order": "drop the ORDER BY inside the count",
26
+ "agent_variant": "agent's variant"}
27
+ PROOF_LABEL = {"sandbox": "provable in the sandbox", "needs_agent": "needs the agent (paid step)", "evidence_only": "evidence only",
28
+ "trade_off": "trade-off"}
29
+ PROOF_CLASS = {"sandbox": "verified", "needs_agent": "unverified", "evidence_only": "unverified dashed", "trade_off": "unverified dashed"}
30
+ STATE_LABEL = {"fixed": "Fixed", "blocked": "Needs another fix", "not_judged": "Could not be judged", "nothing_to_gain": "Nothing to gain"}
31
+ SHORT = {"empty_reads": "Empty runs", "key_unusable": "Key or time bound", "heavy_columns": "Heavy columns", "count_page": "Count + page"}
32
+ COLORS = {"empty_reads": "#2f5fd0", "key_unusable": "#b3261e", "heavy_columns": "#9a6700", "count_page": "#6a4fc7", "none": "#c9ccd1"}
33
+ VERIFY_LABEL = {"reads_the_same_table": "reads the same table", "keeps_every_row": "keeps every row (no filter, grouping or join)",
34
+ "same_columns": "same columns, unchanged", "complete_copy": "holds the source's rows", "same_deduplication": "same deduplication",
35
+ "view_select_unparsed": "view SELECT not parsed"}
36
+
37
+
38
+ def _e(x) -> str:
39
+ return html.escape(str(x if x is not None else ""))
40
+
41
+
42
+ def _tag(text, cls="") -> str:
43
+ return f"<span class='tag {_e(cls)}'>{_e(text)}</span>"
44
+
45
+
46
+ def human_bytes(n) -> str:
47
+ n = float(n or 0)
48
+ for unit, size in (("TB", 1e12), ("GB", 1e9), ("MB", 1e6), ("kB", 1e3)):
49
+ if abs(n) >= size:
50
+ return f"{n / size:.1f} {unit}"
51
+ return f"{n:.0f} B"
52
+
53
+
54
+ def pct(share) -> str:
55
+ if share is None:
56
+ return "-"
57
+ v = share * 100
58
+ return f"{v:.1f}%" if v >= 0.1 or v == 0 else "under 0.1%"
59
+
60
+
61
+ def place(c: dict) -> str:
62
+ st = c["statement"]
63
+ if st.get("file"):
64
+ return f"{st['file']}:{st.get('line') or 0}"
65
+ if st.get("located") == "likely":
66
+ return "production statement, possible places only"
67
+ return "production statement, place in code not found"
68
+
69
+
70
+ # ---- CLI ---------------------------------------------------------------------------------------------------------
71
+
72
+ def summary_lines(doc: dict | None, limit: int = 8) -> list[str]:
73
+ if not doc:
74
+ return []
75
+ s = doc.get("summary") or {}
76
+ by = s.get("by_scenario") or {}
77
+ out = [f"scenarios {s.get('candidates', 0)} candidates · " + " · ".join(f"{LABEL[k].lower()} {by.get(k, 0)}" for k in SCENARIOS)
78
+ + f" · bound to a runnable statement {s.get('bound', 0)} · with rule variants {s.get('with_variants', 0)}"]
79
+ for a in doc.get("accounting") or []:
80
+ parts = [f"{LABEL.get(r['scenario'], 'no scenario')} {pct(r.get('share_of_read_bytes'))}" for r in a.get("first_fit") or []]
81
+ out.append(f" each byte once ({a['engine']}, {a.get('window_hours')} h): " + " · ".join(parts))
82
+ if s.get("empty_runs_bytes_estimate"):
83
+ out.append(f" estimated read by empty runs: {human_bytes(s['empty_runs_bytes_estimate'])} (an estimate: each empty run read the median run's bytes)")
84
+ if s.get("states"):
85
+ out.append(" " + " · ".join(f"{STATE_LABEL[k]} {v}" for k, v in s["states"].items()))
86
+ for c in (doc.get("candidates") or [])[:limit]:
87
+ m = c.get("measured") or {}
88
+ o = c.get("outcome") or {}
89
+ out.append(f" {c['id']} {LABEL[c['scenario']]:<38} {pct(m.get('share_of_read_bytes')) if m else 'not measured':>12} "
90
+ f"{place(c)} [{', '.join(c['rules'])}]" + (f" {STATE_LABEL.get(o.get('state'), '')}: {o.get('reason')}" if o else ""))
91
+ return out
92
+
93
+
94
+ # ---- report ------------------------------------------------------------------------------------------------------
95
+
96
+ CSS = """
97
+ .scn-stack{display:flex;height:18px;border-radius:4px;overflow:hidden;background:var(--track);margin:8px 0}.scn-stack i{display:block;height:100%;min-width:2px}
98
+ .scn-ov td{text-align:right;font-variant-numeric:tabular-nums}.scn-ov td:first-child{text-align:left}
99
+ .scn-v{display:flex;flex-wrap:wrap;gap:4px;align-items:center}
100
+ .tag.dashed{border-style:dashed}
101
+ """
102
+
103
+
104
+ def _stack(a: dict) -> str:
105
+ total = a.get("read_bytes_total") or a.get("read_bytes_in_shapes") or 0
106
+ segs = "".join(f"<i style='background:{COLORS.get(r['scenario'], '#c9ccd1')};width:{(r['read_bytes'] / total * 100) if total else 0:.2f}%' "
107
+ f"title='{_e(LABEL.get(r['scenario'], 'No scenario'))}: {_e(human_bytes(r['read_bytes']))}'></i>" for r in a.get("first_fit") or [])
108
+ rows = "".join(f"<tr><td><span class=tag style='border-color:{COLORS.get(r['scenario'])}'>{_e(LABEL.get(r['scenario'], 'No scenario'))}</span></td>"
109
+ f"<td class=num>{pct(r.get('share_of_read_bytes'))}</td><td class=num>{_e(human_bytes(r['read_bytes']))}</td><td class=num>{r['shapes']:,}</td>"
110
+ f"<td class=num>{pct((r.get('fits') or {}).get('share_of_read_bytes')) if r['scenario'] != 'none' else '-'}</td></tr>"
111
+ for r in a.get("first_fit") or [])
112
+ order = [r["scenario"] for r in a.get("first_fit") or [] if r["scenario"] != "none"]
113
+ ov = a.get("overlap_bytes") or {}
114
+ head = "".join(f"<th class=num>{_e(SHORT[s])}</th>" for s in order)
115
+ body = "".join(f"<tr><td>{_e(LABEL[s])}</td>" + "".join(f"<td>{pct((ov.get(s) or {}).get(t, 0) / total) if total else '-'}</td>" for t in order) + "</tr>"
116
+ for s in order)
117
+ return (f"<h4>Each measured byte counted once · {_e(a['engine'])}, {_e(a.get('window_hours'))} h of query log, {a.get('shapes', 0):,} read statements with a text, {pct((a.get('read_bytes_in_shapes') or 0) / total) if total else '-'} of all bytes read</h4>"
118
+ f"<div class=scn-stack>{segs}</div><div class=wrap><table><tr><th>First scenario it fits</th><th class=num>Share</th><th class=num>Bytes</th>"
119
+ f"<th class=num>Statements</th><th class=num>It fits, overlapping</th></tr>{rows}</table></div>"
120
+ + (f"<h4>Overlap: share of measured bytes that fit both</h4><div class=wrap><table class=scn-ov><tr><th></th>{head}</tr>{body}</table></div>" if order else ""))
121
+
122
+
123
+ def _evidence_chips(c: dict) -> list[str]:
124
+ out = []
125
+ for ev in c.get("evidence") or []:
126
+ r = ev["rule"]
127
+ if r == "empty_runs":
128
+ least = ev.get("no_result_share_basis") == "at_least"
129
+ out += [_tag(f"{'at least ' if least else ''}{ev['no_result_share']:.0%} of {ev['executions']:,} runs return nothing"),
130
+ _tag(f"{ev.get('median_basis', 'median')} run reads {human_bytes(ev['median_run_bytes'])}"),
131
+ _tag(f"est. {human_bytes(ev['empty_runs_bytes_estimate'])} read by empty runs", "unverified dashed")]
132
+ if ev.get("share_of_read_bytes") is not None:
133
+ out.append(_tag(f"{ev['share_of_read_bytes']:.1%} of all bytes read"))
134
+ if ev.get("stats_note"):
135
+ out.append(_tag(ev["stats_note"], "unverified dashed"))
136
+ elif r == "reads_far_above_returns":
137
+ out.append(_tag(f"{ev['rows_read_per_run']:,.0f} rows read per run for {ev['rows_returned_per_run']:,.0f} returned"
138
+ + (f" · {ev['marks_per_run']:,.0f} marks" if ev.get("marks_per_run") else "")))
139
+ elif r == "key_wrapped":
140
+ out.append(_tag(f"{'('.join(ev['functions'])}({ev['column']}{')' * len(ev['functions'])}: {ev['in']} of {ev['table']}"))
141
+ elif r == "map_lookup":
142
+ out.append(_tag(f"lookup '{ev['lookup']}' where {ev['table']}.{ev['column']} exists" + (" in a key" if ev.get("column_in_key") else "")))
143
+ elif r == "no_time_bound":
144
+ out.append(_tag(f"{ev['table']}: no bound on {', '.join(ev['time_columns'])}" + (" (joined side)" if ev.get("joined_side") else "")))
145
+ elif r in ("wide_before_limit", "wide_in_aggregate_before_limit"):
146
+ sizes = ev.get("bytes_per_row") or {}
147
+ out.append(_tag(", ".join(f"{col} {human_bytes(sizes[col])}/row" if col in sizes else col for col in ev["wide_columns"][:4])
148
+ + (" (by type)" if "by_type" in (ev.get("sized_by") or []) else "")))
149
+ elif r == "narrow_copy":
150
+ out.append(_tag(f"{ev['copy']} (view {ev['view']}) holds its columns of {ev['table']}"))
151
+ out += [_tag("shown: " + VERIFY_LABEL.get(x, x), "verified") for x in ev.get("verified") or []]
152
+ out += [_tag("not shown: " + VERIFY_LABEL.get(x, x), "unverified dashed") for x in ev.get("not_verified") or []]
153
+ elif r == "count_next_to_page":
154
+ out.append(_tag(f"page at {str(ev.get('page_file') or '').split('/')[-1]}:{ev.get('page_line')}" + (" with OFFSET" if ev.get("page_offset") else "")))
155
+ elif r == "count_over_sorted_subquery":
156
+ out.append(_tag("ORDER BY inside the counted subquery, no LIMIT"))
157
+ return out
158
+
159
+
160
+ def _variant_chips(c: dict) -> str:
161
+ measured = {(m.get("change"), m.get("kind")): m for m in c.get("measured_variants") or []}
162
+ out = []
163
+ for v in c.get("variants") or []:
164
+ m = measured.get((v.get("change"), v.get("kind")))
165
+ label = CHANGE_LABEL.get(v.get("change"), v.get("change"))
166
+ if not m:
167
+ out.append(_tag(f"{label}: not benchmarked", "unverified"))
168
+ continue
169
+ cls = {"win": "win", "rejected": "rejected", "failed": "failed"}.get(m.get("verdict"), "mixed")
170
+ ratio = f" · bytes x{m['bytes_ratio']:g}" if m.get("bytes_ratio") is not None else ""
171
+ runs = ""
172
+ if m.get("typical") and m.get("heavy"):
173
+ runs = f" · typical {m['typical'].get('verdict')}, heavy {m['heavy'].get('verdict')}"
174
+ out.append(_tag(f"{label}: {m.get('verdict')}{ratio}{runs}", cls))
175
+ ic = m.get("insert_cost")
176
+ if ic and ic.get("measured"):
177
+ out.append(_tag(f"inserts x{ic.get('insert_time_ratio')} time, storage x{ic.get('storage_ratio')}", "verified" if ic.get("within") else "failed"))
178
+ elif v.get("table_level"):
179
+ out.append(_tag("insert side not measured", "unverified"))
180
+ for x in c.get("changes") or []:
181
+ if x["proof"] != "sandbox" and not any(v.get("change") == x["change"] for v in c.get("variants") or []):
182
+ out.append(_tag(f"{CHANGE_LABEL.get(x['change'], x['change'])}: {PROOF_LABEL[x['proof']]}", PROOF_CLASS[x["proof"]]))
183
+ return "".join(out)
184
+
185
+
186
+ TIER = {"code": "SQL in code", "orm": "ORM-translated SQL", "query_log": "observed in production"}
187
+
188
+
189
+ def html_section(doc: dict | None, limit: int = 60) -> str:
190
+ """The "Scenarios" section of report.html."""
191
+ if not doc or not doc.get("candidates"):
192
+ return ""
193
+ s = doc.get("summary") or {}
194
+ by = s.get("by_scenario") or {}
195
+ states = s.get("states") or {}
196
+ cards = "".join(f"<div class=card><b>{by.get(k, 0)}</b>{_e(LABEL[k])}</div>" for k in SCENARIOS)
197
+ cards += f"<div class=card><b>{states.get('fixed', 0)}</b>fixed (benchmark-verified)</div>"
198
+ if s.get("empty_runs_bytes_estimate"):
199
+ cards += f"<div class=card><b>{_e(human_bytes(s['empty_runs_bytes_estimate']))}</b>est. read by empty runs</div>"
200
+ st_chips = "".join(_tag(f"{STATE_LABEL[k]} {v}", k) for k, v in states.items()) if states else _tag("not benchmarked yet", "unverified")
201
+ rows = []
202
+ for c in (doc.get("candidates") or [])[:limit]:
203
+ m = c.get("measured") or {}
204
+ o = c.get("outcome") or {}
205
+ st = c["statement"]
206
+ tier = _tag(TIER.get(st["sql_from"], st["sql_from"]), "verified") + _tag(f"located: {st['located']}", "verified" if st["located"] in ("exact", "template", "tag", "site") else "unverified")
207
+ bench = c.get("bench") or {}
208
+ bound = f" · runs as <a href='#{_e(bench['finding'])}'>{_e(bench['finding'])}</a>" if bench.get("finding") else ""
209
+ rows.append(
210
+ f"<tr><td class=mono>{_e(c['id'])}</td><td><span class=tag style='border-color:{COLORS[c['scenario']]}'>{_e(LABEL[c['scenario']])}</span>"
211
+ f"<div class=muted><code>{_e(place(c))}</code>{bound}</div><div class=chips>{tier}{''.join(_tag(RULE_LABEL.get(r, r)) for r in c['rules'])}</div></td>"
212
+ f"<td class=num>{pct(m.get('share_of_read_bytes')) if m else '-'}<div class=muted>{_e(human_bytes(m.get('read_bytes'))) if m else ''}</div></td>"
213
+ f"<td><div class=chips>{''.join(_evidence_chips(c))}</div><div class='chips scn-v'>{_variant_chips(c)}</div></td>"
214
+ f"<td>{_tag(STATE_LABEL.get(o.get('state'), o.get('state') or ''), o.get('state') or '') if o else ''}"
215
+ f"<div class=muted>{_e(str(o.get('reason') or '').replace('_', ' '))}</div></td></tr>")
216
+ more = f"<p class=muted>{len(doc['candidates']) - limit} more in scenarios.json.</p>" if len(doc["candidates"]) > limit else ""
217
+ acc = "".join(_stack(a) for a in doc.get("accounting") or [])
218
+ return (f"<style>{CSS}</style><h2>Scenarios</h2><div class=cards>{cards}</div><div class=chips>{st_chips}</div>{acc}"
219
+ "<p></p><div class=wrap><table><tr><th>Id</th><th>Scenario and place</th><th class=num>Share of bytes</th><th>Evidence · variants</th>"
220
+ f"<th>State</th></tr>{''.join(rows)}</table></div>{more}"
221
+ "<p class=muted>A scenario's bytes are the bytes its statements read, not the bytes a fix saves: only a benchmark-verified win is Fixed. "
222
+ "An estimate is labelled as one; a trade-off is never counted as fixed.</p>")
223
+
224
+
225
+ # ---- upload ------------------------------------------------------------------------------------------------------
226
+
227
+ STATEMENT_KEYS = ("ref", "hash", "sql_from", "located", "engine", "site_ids", "file", "line", "symbol", "tables")
228
+ NUMBER_KEYS = ("executions", "read_bytes", "share_of_read_bytes", "window_hours", "rows_read_per_run", "rows_returned_per_run",
229
+ "bytes_read_per_run", "no_result_share", "selected_marks_per_run")
230
+ EVIDENCE_KEYS = ("rule", "table", "executions", "runs_per_hour", "no_result_share", "median_run_bytes", "median_basis", "empty_runs_bytes_estimate",
231
+ "read_bytes", "share_of_read_bytes", "rows_read_per_run", "rows_returned_per_run", "rows_read_per_row_returned", "marks_per_run",
232
+ "column", "functions", "clause", "in", "unwrappable", "lookup", "column_in_key", "time_columns", "joined_side", "table_rows",
233
+ "wide_columns", "sized_by", "bytes_per_row", "final", "copy", "view", "verified", "not_verified", "source_rows", "copy_rows",
234
+ "page_site", "page_file", "page_line", "scope", "filter_overlap", "page_offset", "definition")
235
+ VARIANT_KEYS = ("change", "kind", "verdict", "rows_ratio", "bytes_ratio", "heavy_bytes_ratio", "results_match", "typical", "heavy", "insert_cost")
236
+
237
+
238
+ def _pick(d: dict | None, keys) -> dict:
239
+ return {k: d[k] for k in keys if isinstance(d, dict) and k in d}
240
+
241
+
242
+ def for_upload(doc: dict | None) -> dict | None:
243
+ """scenarios.json for the bundle, rebuilt field by field: codes, places (file, line, symbol, site ids, already in the
244
+ inventory), short table names and numbers. No SQL text of any kind, no parameter values, no database, host, account,
245
+ application label or client name."""
246
+ if not doc or not isinstance(doc.get("candidates"), list):
247
+ return None
248
+ cands = []
249
+ for c in doc["candidates"]:
250
+ o = c.get("outcome") or {}
251
+ ev = o.get("evidence") or {}
252
+ cands.append({
253
+ "id": c.get("id"), "fingerprint": c.get("fingerprint"), "scenario": c.get("scenario"), "rules": list(c.get("rules") or []),
254
+ "statement": _pick(c.get("statement"), STATEMENT_KEYS), "also_fires_on_code": list(c.get("also_fires_on_code") or []),
255
+ "measured": _pick(c.get("measured"), NUMBER_KEYS) or None,
256
+ "evidence": [_pick(e, EVIDENCE_KEYS) for e in c.get("evidence") or []],
257
+ "changes": [_pick(x, ("change", "touches", "proof")) for x in c.get("changes") or []], "proof": c.get("proof"),
258
+ "bench": _pick(c.get("bench"), ("finding", "built", "why_not")),
259
+ "variants": [_pick(v, VARIANT_KEYS) for v in c.get("measured_variants") or []],
260
+ "outcome": {"state": o.get("state"), "reason": o.get("reason"),
261
+ "evidence": {k: ev[k] for k in ("kind", "rows_ratio", "bytes_ratio", "memory_ratio", "read_rows", "read_bytes", "result_rows",
262
+ "fidelity", "variants_on", "trade_off", "next_step", "insert_cost") if k in ev}} if o else None,
263
+ })
264
+ acc = [{**_pick(a, ("engine", "window_hours", "shapes", "read_bytes_in_shapes")),
265
+ **_pick(a, ("read_bytes_total",)), "first_fit": [{**_pick(r, ("scenario", "shapes", "executions", "read_bytes", "share_of_read_bytes")), "fits": _pick(r.get("fits"), ("shapes", "read_bytes", "share_of_read_bytes"))}
266
+ for r in a.get("first_fit") or []],
267
+ "overlap_bytes": {k: {kk: int(vv) for kk, vv in (v or {}).items()} for k, v in (a.get("overlap_bytes") or {}).items() if k in SCENARIOS}}
268
+ for a in doc.get("accounting") or []]
269
+ s = doc.get("summary") or {}
270
+ summary = {k: s[k] for k in ("statements", "unparsed", "candidates", "by_scenario", "by_rule", "by_proof", "empty_runs_bytes_estimate",
271
+ "bound", "with_variants", "runnable_built", "not_bound", "states", "reasons") if k in s}
272
+ settings = {k: v for k, v in (doc.get("settings") or {}).items() if isinstance(v, (int, float, bool, str)) or k == "order"}
273
+ return {"schema_version": doc.get("schema_version", 1), "generated_at": doc.get("generated_at"), "settings": settings,
274
+ "summary": summary, "accounting": acc, "candidates": cands, "rules": {k: list(v) for k, v in RULES.items()}}
codecop/schemacli.py ADDED
@@ -0,0 +1,67 @@
1
+ """`codecop db schema-check`: does every statement of the repository plan against the sandbox schema?
2
+
3
+ Builds the schema in a throwaway sandbox from every pulled database (db_catalog.json) and the repository's own table
4
+ definitions (inventory.json; with --with-inventory, also those of the organisation's other repositories that share
5
+ its databases), plans every site's statement with typed parameters (sandboxschema), writes schema_check_<engine>.json
6
+ and, with --mark, puts each site's result on inventory.json (`plan`, read by `codecop coverage`: a site that does not plan
7
+ stops at the plans stage with its reason and next step)."""
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ from collections import Counter
13
+ from pathlib import Path
14
+ from typing import Optional
15
+
16
+ import typer
17
+ from rich.console import Console
18
+
19
+ console = Console()
20
+
21
+
22
+ def schema_check(
23
+ path: Path = typer.Argument(Path("."), help="Repository that was scanned."),
24
+ out: Optional[Path] = typer.Option(None, "--out", help="Directory holding inventory.json (and db_catalog.json). Default: <path>/.codecop"),
25
+ engine: str = typer.Option("auto", "--engine", help="postgres, clickhouse or auto (every engine the inventory has sites of)."),
26
+ with_inventory: list[Path] = typer.Option([], "--with-inventory", help="inventory.json of another repository of the organisation "
27
+ "whose tables this one's statements read. Repeatable."),
28
+ mark: bool = typer.Option(False, "--mark", help="Write each site's result into inventory.json (`plan`), for codecop coverage."),
29
+ engine_version: Optional[str] = typer.Option(None, "--engine-version", help="Sandbox server version. Default: CodeCop's default."),
30
+ ) -> None:
31
+ """Plan every statement against a throwaway schema built from the pulled databases and the repository's definitions."""
32
+ from . import engines, sandboxschema as SS
33
+ from .realdb.facts import load as load_facts
34
+ out_dir = out or (path / ".codecop")
35
+ inv_path = out_dir / "inventory.json"
36
+ inventory = json.loads(inv_path.read_text())
37
+ catalog_path = out_dir / "db_catalog.json"
38
+ catalog = json.loads(catalog_path.read_text()) if catalog_path.exists() else None
39
+ facts = load_facts(out_dir) if catalog else None
40
+ others = [json.loads(p.read_text()) for p in with_inventory]
41
+ wanted = ["postgres", "clickhouse"] if engine == "auto" else [engine]
42
+ marked = 0
43
+ for name in wanted:
44
+ if not SS.statement_sites(inventory, name):
45
+ continue
46
+ eng = engines.get(name)
47
+ sb = eng.sandbox(engine_version or eng.default_version)
48
+ sb.start()
49
+ try:
50
+ res = SS.check(sb, name, inventory, catalog, facts, others=others,
51
+ log=lambda t: console.print(f"[dim] {t}[/dim]", highlight=False))
52
+ finally:
53
+ sb.stop()
54
+ SS.write(out_dir, res)
55
+ t = res["totals"]
56
+ n = t.get("planned", 0) + t.get("failed", 0)
57
+ console.print(f"{name}: {t.get('planned', 0):,} of {n:,} statements plan ({100 * t.get('planned', 0) / max(n, 1):.1f}%); "
58
+ f"{t.get('run_time_parts', 0):,} have run-time parts; tables built {res['build'].get('built', 0)} pulled, "
59
+ f"{res['build'].get('repository', 0)} from the repository", highlight=False)
60
+ reasons = Counter(r.get("reason") for r in res["sites"].values() if r.get("planned") is False)
61
+ for code, k in reasons.most_common():
62
+ console.print(f" {k:5d} {code}", highlight=False)
63
+ if mark:
64
+ marked += SS.mark(inventory, res)
65
+ if mark:
66
+ inv_path.write_text(json.dumps(inventory))
67
+ console.print(f"{marked:,} sites marked in {inv_path}", highlight=False)
@@ -0,0 +1,21 @@
1
+ {
2
+ "type": "object",
3
+ "required": ["areas"],
4
+ "additionalProperties": false,
5
+ "properties": {
6
+ "areas": {
7
+ "type": "array",
8
+ "items": {
9
+ "type": "object",
10
+ "required": ["path", "role", "description", "confidence"],
11
+ "additionalProperties": false,
12
+ "properties": {
13
+ "path": {"type": "string"},
14
+ "role": {"type": "string", "enum": ["app", "job", "script", "migration", "tooling", "test", "unknown"]},
15
+ "description": {"type": "string"},
16
+ "confidence": {"type": "string", "enum": ["high", "medium", "low"]}
17
+ }
18
+ }
19
+ }
20
+ }
21
+ }