codecop 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (222) hide show
  1. codecop/__init__.py +7 -0
  2. codecop/access.py +140 -0
  3. codecop/access_postgres.py +284 -0
  4. codecop/advisor.py +1512 -0
  5. codecop/advisor_bench.py +493 -0
  6. codecop/advisor_ch.py +2080 -0
  7. codecop/advisor_view.py +381 -0
  8. codecop/advisors.py +184 -0
  9. codecop/agent.py +221 -0
  10. codecop/agentfacts.py +745 -0
  11. codecop/apply/__init__.py +327 -0
  12. codecop/apply/check.py +344 -0
  13. codecop/apply/cli.py +162 -0
  14. codecop/apply/clickhouse.py +379 -0
  15. codecop/apply/common.py +238 -0
  16. codecop/apply/html.py +264 -0
  17. codecop/apply/patch.py +213 -0
  18. codecop/apply/postgres.py +102 -0
  19. codecop/apply/trial.py +166 -0
  20. codecop/assemble.py +104 -0
  21. codecop/baseline.py +1043 -0
  22. codecop/bench.py +2464 -0
  23. codecop/blockers.py +935 -0
  24. codecop/budget.py +980 -0
  25. codecop/catalog_profile.py +525 -0
  26. codecop/changed.py +261 -0
  27. codecop/cicmd.py +1002 -0
  28. codecop/cli.py +5421 -0
  29. codecop/client.py +729 -0
  30. codecop/coverage.py +1067 -0
  31. codecop/coverage_reasons.py +116 -0
  32. codecop/crashlog.py +70 -0
  33. codecop/datagen.py +766 -0
  34. codecop/datagen_postgres.py +630 -0
  35. codecop/datagen_sqlite.py +323 -0
  36. codecop/dbcli.py +885 -0
  37. codecop/definitions.py +457 -0
  38. codecop/discover/__init__.py +702 -0
  39. codecop/discover/arms.py +160 -0
  40. codecop/discover/base.py +234 -0
  41. codecop/discover/dialect.py +296 -0
  42. codecop/discover/elixir.py +64 -0
  43. codecop/discover/engine_go.py +320 -0
  44. codecop/discover/go.py +1947 -0
  45. codecop/discover/java.py +1528 -0
  46. codecop/discover/loops.py +1671 -0
  47. codecop/discover/named_go.py +258 -0
  48. codecop/discover/origins.py +4565 -0
  49. codecop/discover/origins_ts.py +1584 -0
  50. codecop/discover/orm_django.py +2772 -0
  51. codecop/discover/orm_django_models.py +814 -0
  52. codecop/discover/orm_django_sql.py +662 -0
  53. codecop/discover/orm_ent.py +565 -0
  54. codecop/discover/orm_ex_ecto.py +2138 -0
  55. codecop/discover/orm_go.py +2134 -0
  56. codecop/discover/orm_go_bun.py +602 -0
  57. codecop/discover/orm_go_run.py +636 -0
  58. codecop/discover/orm_go_types.py +1082 -0
  59. codecop/discover/orm_java.py +1450 -0
  60. codecop/discover/orm_jdbi.py +743 -0
  61. codecop/discover/orm_jooq.py +806 -0
  62. codecop/discover/orm_jpa.py +1307 -0
  63. codecop/discover/orm_mybatis.py +730 -0
  64. codecop/discover/orm_py.py +557 -0
  65. codecop/discover/orm_py_peewee.py +1266 -0
  66. codecop/discover/orm_py_prisma.py +298 -0
  67. codecop/discover/orm_rb_activerecord.py +1906 -0
  68. codecop/discover/orm_rust.py +1248 -0
  69. codecop/discover/orm_rust_seaorm.py +734 -0
  70. codecop/discover/orm_sqlalchemy.py +2475 -0
  71. codecop/discover/orm_stats.py +307 -0
  72. codecop/discover/orm_tables.py +29 -0
  73. codecop/discover/orm_ts.py +503 -0
  74. codecop/discover/orm_ts_drizzle.py +697 -0
  75. codecop/discover/orm_ts_knex.py +1117 -0
  76. codecop/discover/orm_ts_kysely.py +861 -0
  77. codecop/discover/orm_ts_prisma.py +1045 -0
  78. codecop/discover/orm_ts_schema.py +169 -0
  79. codecop/discover/orm_ts_sequelize.py +1401 -0
  80. codecop/discover/orm_ts_typeorm.py +1067 -0
  81. codecop/discover/probes.py +323 -0
  82. codecop/discover/python.py +595 -0
  83. codecop/discover/ruby.py +793 -0
  84. codecop/discover/rust.py +2378 -0
  85. codecop/discover/schema.py +520 -0
  86. codecop/discover/schema_ent.py +145 -0
  87. codecop/discover/schema_ts.py +420 -0
  88. codecop/discover/tsresolve.py +257 -0
  89. codecop/discover/typescript.py +1728 -0
  90. codecop/discover/xml_mapper.py +526 -0
  91. codecop/engines/__init__.py +515 -0
  92. codecop/engines/base.py +498 -0
  93. codecop/engines/clickhouse.py +1558 -0
  94. codecop/engines/pg_ddl.py +444 -0
  95. codecop/engines/pg_hints.py +137 -0
  96. codecop/engines/postgres.py +1060 -0
  97. codecop/engines/sqlite.py +742 -0
  98. codecop/families/__init__.py +3 -0
  99. codecop/families/build.py +280 -0
  100. codecop/families/cli.py +177 -0
  101. codecop/families/coverage_hook.py +62 -0
  102. codecop/families/driver.py +221 -0
  103. codecop/families/goslice.py +229 -0
  104. codecop/families/goslice_tool/go.mod +3 -0
  105. codecop/families/goslice_tool/main.go +403 -0
  106. codecop/families/holes.py +451 -0
  107. codecop/families/images/Dockerfile.go +5 -0
  108. codecop/families/images/Dockerfile.python +4 -0
  109. codecop/families/images/Dockerfile.rust +4 -0
  110. codecop/families/isolate.py +171 -0
  111. codecop/families/locate.py +270 -0
  112. codecop/families/model.py +301 -0
  113. codecop/families/plangate.py +271 -0
  114. codecop/families/tagpatch.py +174 -0
  115. codecop/fidelity.py +671 -0
  116. codecop/fixgroups.py +130 -0
  117. codecop/formerly.py +91 -0
  118. codecop/grantscript.py +254 -0
  119. codecop/groupbench.py +1375 -0
  120. codecop/groups.py +594 -0
  121. codecop/groups_view.py +186 -0
  122. codecop/heat.py +1405 -0
  123. codecop/heatcli.py +219 -0
  124. codecop/joins.py +1749 -0
  125. codecop/joins_view.py +127 -0
  126. codecop/kinds/__init__.py +507 -0
  127. codecop/kinds/calls/__init__.py +501 -0
  128. codecop/kinds/calls/extract.py +1097 -0
  129. codecop/kinds/calls/harness.py +408 -0
  130. codecop/kinds/calls/measure.py +342 -0
  131. codecop/kinds/calls/rules.py +139 -0
  132. codecop/kinds/calls/runners/RunCalls.java +167 -0
  133. codecop/kinds/calls/runners/run_go.go +141 -0
  134. codecop/kinds/calls/runners/run_node.js +186 -0
  135. codecop/kinds/calls/runners/run_python.py +319 -0
  136. codecop/kinds/calls/runners/run_rust.rs +200 -0
  137. codecop/kinds/calls/standin.py +340 -0
  138. codecop/kinds/pipeline.py +288 -0
  139. codecop/kinds/regex/__init__.py +1167 -0
  140. codecop/kinds/regex/engines/RegexHarness.java +129 -0
  141. codecop/kinds/regex/engines/run_go.go +294 -0
  142. codecop/kinds/regex/engines/run_node.js +99 -0
  143. codecop/kinds/regex/engines/run_python.py +295 -0
  144. codecop/kinds/regex/engines/run_rust.rs +149 -0
  145. codecop/kinds/regex/extract.py +1438 -0
  146. codecop/kinds/regex/harness.py +235 -0
  147. codecop/kinds/regex/measure.py +270 -0
  148. codecop/kinds/regex/shapes.py +418 -0
  149. codecop/kinds/regex/syntax.py +1721 -0
  150. codecop/kinds/testkind.py +107 -0
  151. codecop/kinds/transaction/__init__.py +228 -0
  152. codecop/kinds/transaction/bind.py +355 -0
  153. codecop/kinds/transaction/measure.py +264 -0
  154. codecop/kinds/transaction/plan.py +462 -0
  155. codecop/kinds/transaction/rules.py +540 -0
  156. codecop/kinds/transaction/sandbox.py +94 -0
  157. codecop/kinds/transaction/scenarios.py +520 -0
  158. codecop/kinds/transaction/schedule.py +483 -0
  159. codecop/kinds/transaction/shapes.py +418 -0
  160. codecop/kinds/transaction/verify.py +293 -0
  161. codecop/live.py +237 -0
  162. codecop/loopbench.py +2071 -0
  163. codecop/loopschema.py +591 -0
  164. codecop/mcpserver.py +120 -0
  165. codecop/mechanism.py +214 -0
  166. codecop/members.py +200 -0
  167. codecop/multi.py +443 -0
  168. codecop/observed.py +1868 -0
  169. codecop/parts.py +102 -0
  170. codecop/patterns.py +830 -0
  171. codecop/patterns_view.py +559 -0
  172. codecop/plangate.py +242 -0
  173. codecop/profile.py +439 -0
  174. codecop/prompts/areas.md +19 -0
  175. codecop/prompts/observed_variants.md +20 -0
  176. codecop/prompts/profile.md +60 -0
  177. codecop/prompts/profile_postgres.md +68 -0
  178. codecop/prompts/profile_sizes.md +26 -0
  179. codecop/prompts/profile_sqlite.md +69 -0
  180. codecop/prompts/rank.md +84 -0
  181. codecop/prompts/rank_postgres.md +96 -0
  182. codecop/prompts/rank_sqlite.md +94 -0
  183. codecop/prompts/scenario_variants.md +20 -0
  184. codecop/rank.py +1473 -0
  185. codecop/realdb/__init__.py +688 -0
  186. codecop/realdb/clickhouse.py +1223 -0
  187. codecop/realdb/facts.py +815 -0
  188. codecop/realdb/locality.py +964 -0
  189. codecop/realdb/locks.py +355 -0
  190. codecop/realdb/match.py +531 -0
  191. codecop/realdb/postgres.py +643 -0
  192. codecop/realdb/ratios.py +77 -0
  193. codecop/realdb/sample.py +126 -0
  194. codecop/relations.py +227 -0
  195. codecop/report.py +1854 -0
  196. codecop/resources.py +332 -0
  197. codecop/resources_view.py +266 -0
  198. codecop/rules/entry_points.toml +1013 -0
  199. codecop/rules/sinks.toml +362 -0
  200. codecop/runsonce.py +8 -0
  201. codecop/sandboxschema.py +555 -0
  202. codecop/scenario_agent.py +172 -0
  203. codecop/scenario_bind.py +507 -0
  204. codecop/scenario_sql.py +971 -0
  205. codecop/scenarios.py +675 -0
  206. codecop/scenarios_view.py +274 -0
  207. codecop/schemacli.py +67 -0
  208. codecop/schemas/areas_output.schema.json +21 -0
  209. codecop/schemas/profile_output.schema.json +362 -0
  210. codecop/schemas/rank_output.schema.json +385 -0
  211. codecop/sizes.py +200 -0
  212. codecop/sqlinfo.py +558 -0
  213. codecop/typedparams.py +576 -0
  214. codecop/verdicts.py +212 -0
  215. codecop/writebench.py +720 -0
  216. codecop/writecost.py +440 -0
  217. codecop/writes.py +1208 -0
  218. codecop-0.1.0.dist-info/METADATA +42 -0
  219. codecop-0.1.0.dist-info/RECORD +222 -0
  220. codecop-0.1.0.dist-info/WHEEL +4 -0
  221. codecop-0.1.0.dist-info/entry_points.txt +2 -0
  222. codecop-0.1.0.dist-info/licenses/LICENSE +21 -0
codecop/groups_view.py ADDED
@@ -0,0 +1,186 @@
1
+ """Scan groups for people: console lines and the report.html section (groups.py, groupbench.py)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import html
6
+
7
+ from .groupbench import STATE_WORDS, WORDS
8
+ from .patterns_view import human_bytes, pct
9
+ from .formerly import code as _code # next-step codes stored before the rename
10
+
11
+ KIND_TEXT = {"shared_scan": "Statements that read the same rows", "repeated_read": "One statement reads a CTE or subquery twice"}
12
+ CONF_TEXT = {"code_path_traced": "run together: code path traced", "code_path_guessed": "run together: code path guessed",
13
+ "counts_agree": "run together: run counts agree in the log", "one_statement": "one statement"}
14
+ CONF_CLASS = {"code_path_traced": "verified", "one_statement": "verified", "counts_agree": "unverified", "code_path_guessed": "unverified"}
15
+ SOURCE_TEXT = {"loop": "same loop body", "entry_point": "same entry point", "function": "same function", "counts": "run counts agree",
16
+ "one_statement": "one statement"}
17
+ ROLE_TEXT = {"aggregate": "aggregate", "count": "count", "page": "page of rows", "rows": "rows"}
18
+ FROM_TEXT = {"code": "SQL in code", "orm": "ORM translation", "query_log": "statement production ran"}
19
+ STATE_CLASS = {"fixed": "verified", "blocked": "failed", "not_judged": "unverified", "nothing_to_gain": ""}
20
+ RULE_TEXT = {"one_select_all_aggregates": "all aggregates in one SELECT", "merged_group_by": "one GROUP BY",
21
+ "conditional_aggregates": "conditional aggregates", "grouping_sets": "GROUPING SETS", "materialize_once": "computed once",
22
+ "agent": "written by the agent"}
23
+ NOTE_TEXT = {"members_shared_with_other_groups": "a member is in another group too", "member_not_located_in_code": "a member has no place in code",
24
+ "members_on_several_engines": "members on several engines"}
25
+
26
+ CSS = """
27
+ .grp{display:grid;grid-template-columns:minmax(0,2.3fr) 28px minmax(0,1fr) 28px minmax(0,1.3fr);gap:6px;align-items:stretch;margin:8px 0}
28
+ .grp .box{border:1px solid var(--line,#d0d4da);border-radius:8px;padding:8px 10px;background:var(--panel);min-width:0}
29
+ .grp .arrow{display:flex;align-items:center;justify-content:center;color:var(--muted);font-size:18px}
30
+ .grp-m{display:grid;grid-template-columns:minmax(0,1fr) auto auto auto;gap:3px 10px;font-size:12.5px;align-items:center}
31
+ .grp-m .h{color:var(--muted);font-size:10.5px;text-transform:uppercase;letter-spacing:.04em}
32
+ .grp-m>span{min-width:0;overflow-wrap:anywhere}.grp-m .n{text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap}
33
+ .grp .big{font-size:15px;font-weight:600}.grp .k{color:var(--muted);font-size:11px;text-transform:uppercase;letter-spacing:.04em}
34
+ .grp-s{display:grid;grid-template-columns:auto minmax(0,1fr) auto;gap:2px 8px;font-size:12.5px;align-items:center;margin-top:4px}
35
+ .grp-s .n{text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap}
36
+ .ok{color:var(--good,#1a7f37)}.no{color:var(--bad,#cf222e)}.unk{color:var(--muted)}
37
+ @media (max-width:760px){.grp{grid-template-columns:minmax(0,1fr)}.grp .arrow{transform:rotate(90deg);height:18px}}
38
+ """
39
+
40
+
41
+ def _e(x) -> str:
42
+ return html.escape(str(x if x is not None else ""))
43
+
44
+
45
+ def _tag(text, cls="") -> str:
46
+ return f"<span class='tag {_e(cls)}'>{_e(text)}</span>"
47
+
48
+
49
+ def _bar(share, cls="read") -> str:
50
+ w = min(100.0, max(share or 0, 0) * 100)
51
+ return f"<span class=mini><span class=track style='display:block'><span class='fill {cls}' style='display:block;width:{w:.1f}%'></span></span></span>"
52
+
53
+
54
+ def place(m: dict) -> str:
55
+ if m.get("file"):
56
+ return f"{m.get('symbol') or ''} {m['file'].split('/')[-1]}:{m.get('line')}".strip()
57
+ return "no place in code"
58
+
59
+
60
+ def summary_lines(data: dict | None, limit: int = 10) -> list[str]:
61
+ if not data:
62
+ return ["groups no inventory"]
63
+ s = data.get("summary") or {}
64
+ out = [f"groups {s.get('groups', 0)} scan groups · " + " · ".join(f"{KIND_TEXT[k].lower()} {n}" for k, n in (s.get("by_kind") or {}).items())]
65
+ if s.get("by_confidence"):
66
+ out.append(" " + " · ".join(f"{CONF_TEXT.get(k, k)} {n}" for k, n in s["by_confidence"].items()))
67
+ if s.get("share_of_read_bytes_once") is not None:
68
+ out.append(f" members read {pct(s['share_of_read_bytes_once'])} of all bytes in the window, each shape once")
69
+ o = data.get("outcomes") or {}
70
+ if o.get("states"):
71
+ out.append(" " + " · ".join(f"{STATE_WORDS[k].lower()} {n}" for k, n in o["states"].items()))
72
+ for g in (data.get("groups") or [])[:limit]:
73
+ m = g.get("measured") or {}
74
+ filt = ", ".join(p["text"] for p in g.get("shared_filter") or [])[:90]
75
+ out.append(f" {g['id']} {g['table']} · {g['member_count']} member(s) · {CONF_TEXT.get(g['confidence'], g['confidence'])}"
76
+ + (f" · {pct(m.get('share_of_read_bytes'))} of bytes" if m else ""))
77
+ out.append(" " + (f"filter: {filt}" if filt else f"{(g.get('repeated') or {}).get('what', '')} "
78
+ f"{(g.get('repeated') or {}).get('name', '')} read {(g.get('repeated') or {}).get('reads', '')} times")
79
+ + (f" · {STATE_WORDS[g['outcome']['state']].lower()}: {g['outcome']['reason'].replace('_', ' ')}" if g.get("outcome") else ""))
80
+ return out
81
+
82
+
83
+ def _check(v) -> str:
84
+ return {True: "<span class=ok title='reproduced'>✓</span>", False: "<span class=no title='not reproduced'>✗</span>"}.get(
85
+ v, "<span class=unk title='not shown'>?</span>")
86
+
87
+
88
+ def _saving_rows(rec: dict) -> str:
89
+ rows = []
90
+ for which in ("typical", "heavy"):
91
+ r = rec.get(which) or {}
92
+ b, m = r.get("baseline") or {}, r.get("measurement") or {}
93
+ if not b:
94
+ continue
95
+ for key, label, fmt in (("read_bytes", "bytes", human_bytes), ("read_rows", "rows", lambda n: f"{int(n or 0):,}"),
96
+ ("memory_bytes", "peak memory", human_bytes), ("selected_marks", "marks", lambda n: f"{int(n or 0):,}")):
97
+ bv, mv = b.get(key) or 0, m.get(key) or 0
98
+ if not bv and not mv:
99
+ continue
100
+ share = (mv / bv) if bv else None
101
+ rows.append(f"<span class=k>{_e(which)} {_e(label)}</span><span>{_bar(share if share is not None else 0, 'fill')}</span>"
102
+ f"<span class=n>{_e(fmt(bv))} → {_e(fmt(mv))}{(' (' + pct(share) + ')') if share is not None else ''}</span>")
103
+ return f"<div class=grp-s>{''.join(rows)}</div>" if rows else ""
104
+
105
+
106
+ def _card(g: dict) -> str:
107
+ o = g.get("outcome") or {}
108
+ m = g.get("measured") or {}
109
+ total = m.get("read_bytes") or 0
110
+ result = g.get("result") or {}
111
+ variants = g.get("variants") or []
112
+ best_i = (o.get("evidence") or {}).get("variant")
113
+ recs = result.get("variants") or []
114
+ rec = recs[best_i] if best_i is not None and best_i < len(recs) else (recs[0] if recs else None)
115
+ var = variants[rec["index"]] if rec and rec.get("index") is not None and rec["index"] < len(variants) else (variants[0] if variants else None)
116
+ reproduced = (rec or {}).get("members_reproduced") or {}
117
+ replaced = set((var or {}).get("replaces") or [])
118
+ rows = ["<span class=h>Member</span><span class='h n'>Runs</span><span class='h n'>Bytes read</span><span class='h n'>Same rows</span>"]
119
+ for mem in g.get("members") or []:
120
+ mm = mem.get("measured") or {}
121
+ share = (mm.get("read_bytes") or 0) / total if total else None
122
+ chips = _tag(ROLE_TEXT.get(mem.get("role"), mem.get("role"))) + _tag(FROM_TEXT.get(mem.get("sql_from"), mem.get("sql_from")))
123
+ if mem.get("sql_from") == "query_log":
124
+ chips += _tag(f"located: {mem.get('located')}", "verified" if mem.get("located") in ("exact", "template", "tag") else "unverified")
125
+ if mem.get("shared_with"):
126
+ chips += _tag("also in " + ", ".join(mem["shared_with"][:3]), "dashed")
127
+ same = _check(reproduced.get(mem["key"])) if mem["key"] in replaced and rec else "<span class=muted>-</span>"
128
+ rows.append(f"<span class=mono>{_e(place(mem))} {chips}</span><span class=n>{mm.get('executions', 0):,}</span>"
129
+ f"<span class=n>{_bar(share) if share is not None else ''}{_e(human_bytes(mm.get('read_bytes'))) if mm else '-'}</span>"
130
+ f"<span class=n>{same}</span>")
131
+ filt = "".join(_tag(p["text"], "verified" if p.get("equality") else "") for p in g.get("shared_filter") or [])
132
+ rep = g.get("repeated") or {}
133
+ scan = (f"<div class=k>Shared scan</div><div class='big mono'>{_e(g['table'])}</div>"
134
+ + (f"<div class=chips>{filt}</div>" if filt else "")
135
+ + (f"<div class=chips>{_tag(rep.get('what', '') + ' ' + rep.get('name', '') + ' read ' + str(rep.get('reads')) + '×')}</div>" if rep else "")
136
+ + (f"<div class=chips>{''.join(_tag('also ' + t) for t in g['also_tables'][:4])}</div>" if g.get("also_tables") else "")
137
+ + (f"<div class=muted>{_e(pct(m.get('share_of_read_bytes')))} of all bytes · {_e(human_bytes(total))}</div>" if m else ""))
138
+ if var:
139
+ before, after = len(var.get("replaces") or []), 1 + len(var.get("setup") or [])
140
+ combined = (f"<div class=k>Combined</div><div class=big>{before} → {after} statement{'s' if after != 1 else ''}</div>"
141
+ f"<div class=chips>{_tag(RULE_TEXT.get(var.get('rule'), var.get('rule')))}"
142
+ f"{_tag(STATE_WORDS.get(o.get('state'), ''), STATE_CLASS.get(o.get('state'), ''))}</div>"
143
+ + (_saving_rows(rec) if rec else "<div class=muted>not measured yet</div>")
144
+ + f"<details><summary class=muted>statement</summary><pre class=mono style='white-space:pre-wrap;font-size:11.5px'>"
145
+ + _e("\n".join((var.get("setup") or []) + [var.get("sql") or ""])) + "</pre></details>")
146
+ else:
147
+ combined = (f"<div class=k>Combined</div><div class=chips>{_tag(STATE_WORDS.get(o.get('state'), ''), STATE_CLASS.get(o.get('state'), ''))}</div>"
148
+ f"<div class=muted>{_e(WORDS.get(o.get('reason'), ''))}</div>")
149
+ run = "".join(_tag(SOURCE_TEXT.get(r["source"], r["source"]) + (f": {r.get('name') or r.get('function') or ''}" if r.get("name") or r.get("function") else ""))
150
+ for r in (g.get("run_together") or [])[:3])
151
+ chips = (_tag(CONF_TEXT.get(g["confidence"], g["confidence"]), CONF_CLASS.get(g["confidence"], "")) + run
152
+ + "".join(_tag(NOTE_TEXT.get(n, n), "dashed") for n in g.get("notes") or []) + "".join(_tag(x) for x in g.get("labels") or []))
153
+ nxt = f"<p class=muted>Next: {_e((_code(o.get('next_step')) or '').replace('_', ' '))} · hand-off: <code>codecop handoff {_e(g['id'])}</code></p>" if o else ""
154
+ return (f"<section class=finding id='{_e(g['id'])}'><header><h3>{_e(g['id'])} · {_e(KIND_TEXT.get(g['kind'], g['kind']))}</h3>"
155
+ f"<span class='muted mono'>{_e(g['fingerprint'])}</span></header><div class=chips>{chips}</div>"
156
+ f"<div class=grp><div class=box><div class=grp-m>{''.join(rows)}</div></div><div class=arrow>→</div><div class=box>{scan}</div>"
157
+ f"<div class=arrow>→</div><div class=box>{combined}</div></div>{nxt}</section>")
158
+
159
+
160
+ def html_section(data: dict | None, detail: int = 30) -> str:
161
+ """The "Statements that read the same rows" section: a table of every group and a drawing of the first `detail`."""
162
+ if not data or not data.get("groups"):
163
+ return ""
164
+ s = data.get("summary") or {}
165
+ o = (data.get("outcomes") or {}).get("states") or {}
166
+ groups = data["groups"]
167
+ rows = []
168
+ for g in groups:
169
+ m = g.get("measured") or {}
170
+ oc = g.get("outcome") or {}
171
+ rows.append(f"<tr><td><a href='#{_e(g['id'])}'>{_e(g['id'])}</a></td><td class=mono>{_e(g['table'])}</td>"
172
+ f"<td class=num>{g['member_count']}</td><td>{_tag(CONF_TEXT.get(g['confidence'], g['confidence']), CONF_CLASS.get(g['confidence'], ''))}</td>"
173
+ f"<td class=num>{(_bar(m.get('share_of_read_bytes')) + _e(pct(m.get('share_of_read_bytes')))) if m else '<span class=muted>not measured</span>'}</td>"
174
+ f"<td>{_tag(STATE_WORDS.get(oc.get('state'), '-'), STATE_CLASS.get(oc.get('state'), '')) if oc else ''}"
175
+ f"<span class=muted> {_e((oc.get('reason') or '').replace('_', ' '))}</span></td></tr>")
176
+ cards = "".join(_card(g) for g in groups[:detail])
177
+ more = f"<p class=muted>Drawn for the first {detail} groups.</p>" if len(groups) > detail else ""
178
+ return (f"<style>{CSS}</style><h2>Statements that read the same rows</h2>"
179
+ f"<div class=cards><div class=card><b>{s.get('groups', 0)}</b>scan groups</div>"
180
+ + (f"<div class=card><b>{_e(pct(s.get('share_of_read_bytes_once')))}</b>of all bytes read by their members, each shape once</div>"
181
+ if s.get("share_of_read_bytes_once") is not None else "")
182
+ + "".join(f"<div class=card><b>{n}</b>{_e(STATE_WORDS[k].lower())}</div>" for k, n in o.items() if n)
183
+ + "</div><div class=wrap><table><tr><th>Id</th><th>Shared table</th><th class=num>Members</th><th>Run together</th>"
184
+ "<th class=num>Share of bytes read</th><th>State</th></tr>" + "".join(rows) + "</table></div>"
185
+ "<p class=muted>A group is a candidate until its combined statement is measured: fixed only when it reads less and every member it "
186
+ "replaces is reproduced from its result. The change is in the application: one call instead of several.</p>" + more + cards)