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,3 @@
1
+ """Statement families: every statement a run-time-built call site can send."""
2
+
3
+ from .model import BASES, BASIS_LABEL, rollup # noqa: F401
@@ -0,0 +1,280 @@
1
+ """families.json: every source of a statement merged into the family of each run-time-built call site.
2
+
3
+ Sources, in order of evidence: production shapes placed on the site (any repository of the
4
+ organisation, tags, fragments; accumulated over pull snapshots), the static family (role-typed filling and arms), the
5
+ builder evaluated in isolation (pure slice, agent-written driver), and the statement the agent wrote when no driver was
6
+ possible. Same normalised text -> one variant, strongest basis. Then whether each variant plans (a plan gate's result,
7
+ when one ran) and its outcome (findings of a baseline pass, when one ran), and the roll-up to the site.
8
+
9
+ Stage files read from the out dir: inventory.json, db_workload.json (optional), families_snapshots.json (kept here),
10
+ families_evaluated.json (isolated runs), families_plan.json (plan gate), findings.json (outcomes).
11
+ Written: families.json.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import re
18
+ from collections import Counter
19
+ from datetime import datetime, timezone
20
+ from pathlib import Path
21
+
22
+ from . import holes, model
23
+
24
+ FILE = "families.json"
25
+ SNAPSHOTS = "families_snapshots.json"
26
+ EVALUATED = "families_evaluated.json"
27
+ PLAN = "families_plan.json"
28
+ D_STATEMENTS = ("select", "insert", "update", "delete", "unknown", None)
29
+ PH = re.compile(r"«([^»]*)»")
30
+
31
+
32
+ def now() -> str:
33
+ return datetime.now(timezone.utc).isoformat(timespec="seconds")
34
+
35
+
36
+ def load(path: Path, default=None):
37
+ try:
38
+ return json.loads(Path(path).read_text())
39
+ except (OSError, ValueError):
40
+ return default
41
+
42
+
43
+ def is_built(site: dict) -> bool:
44
+ """A non-test query or write site whose SQL is only partly known before it runs (or not at all)."""
45
+ if site.get("is_test") or site.get("role") == "test" or site.get("kind") == "sql_file" and "«" not in (site.get("sql") or ""):
46
+ return False
47
+ if site.get("statement") not in D_STATEMENTS:
48
+ return False
49
+ sql = site.get("sql") or ""
50
+ return "«" in sql or not sql.strip() or site.get("resolution") in ("unresolved", "parameter") or bool(
51
+ re.search(r"\{\{.*?\}\}|\{%.*?%\}|…", sql, re.S))
52
+
53
+
54
+ def mechanism(site: dict) -> str:
55
+ """The mechanism class of a run-time-built site (mechanism.py owns the full classification)."""
56
+ sql = site.get("sql") or ""
57
+ if not sql.strip() or site.get("resolution") in ("unresolved", "parameter"):
58
+ return "assembled_across_functions"
59
+ roles = Counter(model.template_parts(sql) and [p["role"] for p in model.template_parts(sql)])
60
+ if roles.get("table") or roles.get("column"):
61
+ return "table_or_column_from_a_variable"
62
+ if roles.get("list"):
63
+ return "loop_built_lists"
64
+ if roles.get("predicate") or roles.get("tail") or roles.get("order") or roles.get("cte") or any(
65
+ p["expr"].startswith("or:") for p in model.template_parts(sql)):
66
+ return "conditional_fragments"
67
+ if set(roles) <= {"value"}:
68
+ return "template_values_only"
69
+ return "conditional_fragments"
70
+
71
+
72
+ # ---- production snapshots -------------------------------------------------------------------------------------
73
+
74
+ def accumulate(out_dir: Path, workload: dict | None) -> dict:
75
+ """Fold this pull into families_snapshots.json and return the accumulated connections per engine.
76
+
77
+ A pull of pg_stat_statements is cumulative since its `since`: a later pull with the same `since` replaces the
78
+ earlier one. Pulls with a different `since` (a new reset, a ClickHouse window) add up, so a family keeps the
79
+ variants an earlier window saw."""
80
+ path = Path(out_dir) / SNAPSHOTS
81
+ store = load(path, {}) or {}
82
+ store.setdefault("schema_version", 1)
83
+ engines = store.setdefault("engines", {})
84
+ for engine, conn in ((workload or {}).get("connections") or {}).items():
85
+ if not conn.get("queries"):
86
+ continue
87
+ e = engines.setdefault(engine, {"snapshots": {}})
88
+ key = str(conn.get("since") or conn.get("window", {}).get("from") or (workload or {}).get("generated_at") or now())
89
+ e["snapshots"][key] = {"pulled_at": (workload or {}).get("generated_at") or now(), "since": conn.get("since", ""),
90
+ "queries": [q for q in conn["queries"] if q.get("text")],
91
+ "meta": {k: conn.get(k) for k in ("engine", "source", "version", "window_hours", "top") if k in conn}}
92
+ path.write_text(json.dumps(store))
93
+ out = {}
94
+ for engine, e in engines.items():
95
+ merged: dict[str, dict] = {}
96
+ for snap in e["snapshots"].values():
97
+ for q in snap["queries"]:
98
+ m = merged.get(q["hash"])
99
+ if m is None:
100
+ merged[q["hash"]] = {**q, "snapshots": 1}
101
+ else:
102
+ for k in ("executions", "read_bytes", "read_rows", "total_ms"):
103
+ m[k] = int(m.get(k) or 0) + int(q.get(k) or 0)
104
+ m["snapshots"] += 1
105
+ m["rank_by_bytes"] = min(int(m.get("rank_by_bytes") or 10**9), int(q.get("rank_by_bytes") or 10**9))
106
+ m["tags"] = (m.get("tags") or []) + [t for t in q.get("tags") or [] if t not in (m.get("tags") or [])]
107
+ latest = max(e["snapshots"].values(), key=lambda s: s["pulled_at"])
108
+ out[engine] = {**latest["meta"], "engine": engine, "since": min(s["since"] or "" for s in e["snapshots"].values()),
109
+ "snapshots": len(e["snapshots"]), "queries": list(merged.values())}
110
+ return out
111
+
112
+
113
+ # ---- the build ----------------------------------------------------------------------------------------------
114
+
115
+ def build(out_dir: Path, *, root: Path | None = None, org: dict[str, dict] | None = None, settings: dict | None = None,
116
+ fragments: bool = True, log=lambda msg: None) -> dict:
117
+ """Write families.json for the scan in `out_dir`. `org`: {name: {"inventory": dict, "root": Path|None}} of the other
118
+ repositories of the organisation (the scanned one is added as `own`)."""
119
+ out_dir = Path(out_dir)
120
+ cfg = settings or {}
121
+ inv = load(out_dir / "inventory.json")
122
+ if not inv:
123
+ raise FileNotFoundError(f"no inventory.json in {out_dir}")
124
+ root = Path(root or inv.get("repo", {}).get("root") or ".")
125
+ own = inv.get("repo", {}).get("name") or "own"
126
+ sites = [s for s in inv.get("call_sites") or [] if is_built(s)]
127
+ log(f"{len(sites)} run-time-built call sites")
128
+ fams: dict[str, dict] = {}
129
+ src = holes.Source(root)
130
+ for s in sites:
131
+ f = model.family(s, mechanism=mechanism(s), parts=model.template_parts(s.get("sql")))
132
+ if "«" in (s.get("sql") or ""):
133
+ vs, fails = holes.fill(s, src, cfg.get("holes"))
134
+ for v in vs:
135
+ model.merge(f["variants"], v)
136
+ for why in fails:
137
+ model.add_unbuilt(f, "static filling", "run_time_part_not_resolved", why)
138
+ elif not (s.get("sql") or "").strip():
139
+ model.add_unbuilt(f, "any", "no_statement_text", s.get("expr") or "")
140
+ fams[s["id"]] = f
141
+ # production: every pulled statement of every engine placed on a site of any repository of the organisation
142
+ production = {}
143
+ workload = load(out_dir / "db_workload.json")
144
+ conns = accumulate(out_dir, workload)
145
+ if conns:
146
+ from .locate import FragmentIndex, place
147
+ inventories = {own: inv, **{n: o["inventory"] for n, o in (org or {}).items() if o.get("inventory")}}
148
+ roots = {own: root, **{n: Path(o["root"]) for n, o in (org or {}).items() if o.get("root")}}
149
+ index = FragmentIndex(roots, cfg.get("locate")) if fragments else None
150
+ for engine, conn in conns.items():
151
+ pl = place(engine, conn, inventories, index, own=own, settings=cfg.get("locate"))
152
+ production[engine] = {"located": pl["located"], "snapshots": conn.get("snapshots", 1), "since": conn.get("since", ""),
153
+ "builders": pl["builders"], "queries": pl["queries"]}
154
+ by_id = {s["id"]: s for s in inv.get("call_sites") or []}
155
+ for sid, rows in pl["by_site"].items():
156
+ if sid not in fams:
157
+ continue # a site with complete text: its statement is already the code's
158
+ for r in rows:
159
+ v = model.variant(r["text"], "production", condition="seen in production", source=f"production:{r['grade']}",
160
+ production={"hashes": [r["hash"]], "executions": r["executions"], "read_bytes": r["read_bytes"],
161
+ "how": r["grade"]})
162
+ model.merge(fams[sid]["variants"], v)
163
+ for key, b in pl["builders"].items():
164
+ fam = model.family({"id": "B:" + key, "file": b["file"], "line": 0, "symbol": b["fn"], "engine": engine},
165
+ mechanism="builder", template="", kind="builder")
166
+ qs = {q["hash"]: q for q in conn["queries"]}
167
+ for h in b["hashes"]:
168
+ q = qs[h]
169
+ model.merge(fam["variants"], model.variant(q["text"], "production", condition="seen in production",
170
+ source="production:fragment",
171
+ production={"hashes": [h], "executions": int(q.get("executions") or 0),
172
+ "read_bytes": int(q.get("read_bytes") or 0), "how": "fragment"}))
173
+ fam["inherited_by"] = [s["id"] for s in by_id.values() if s.get("file") == b["file"] and not s.get("is_test")
174
+ and re.split(r"[.:]+", s.get("symbol") or "")[-1] == b["fn"]]
175
+ fams[fam["site"]["id"]] = fam
176
+ # builders evaluated in isolation (slice, driver) and statements the agent wrote
177
+ for row in (load(out_dir / EVALUATED, {}) or {}).get("sites", []):
178
+ f = fams.get(row.get("site_id"))
179
+ if f is None:
180
+ continue
181
+ for v in row.get("variants") or []:
182
+ model.merge(f["variants"], model.variant(v["sql"], v["basis"], condition=v.get("condition", ""), source=v.get("source", "")))
183
+ for u in row.get("unbuilt") or []:
184
+ model.add_unbuilt(f, u.get("condition", ""), u.get("reason", ""), u.get("detail", ""))
185
+ # plan gate and outcomes
186
+ plan = (load(out_dir / PLAN, {}) or {}).get("variants", {})
187
+ outcomes = outcomes_by_variant(load(out_dir / "findings.json", {}) or {})
188
+ for sub in sorted(out_dir.glob("*/findings.json")): # a multi-engine scan: each engine's findings
189
+ outcomes.update({k: v for k, v in outcomes_by_variant(load(sub, {}) or {}).items() if k not in outcomes})
190
+ small = SmallTables(load(out_dir / "db_catalog.json", {}) or {}, cfg.get("small_table_max_rows"))
191
+ cap = int((cfg.get("model") or {}).get("max_variants", model.DEFAULTS["max_variants"]))
192
+ for f in fams.values():
193
+ f["variants"] = model.order(f["variants"])
194
+ if len(f["variants"]) > cap:
195
+ for v in f["variants"][cap:]:
196
+ model.add_unbuilt(f, v.get("condition") or "", "over_cap", f"more than {cap} variants")
197
+ f["variants"] = f["variants"][:cap]
198
+ for v in f["variants"]:
199
+ if v["id"] in plan:
200
+ v["valid"] = plan[v["id"]]
201
+ if v["id"] in outcomes:
202
+ v["outcome"] = outcomes[v["id"]]
203
+ elif (v.get("valid") or {}).get("planned"):
204
+ o = small.outcome(v["sql"], f["site"].get("engine") or "")
205
+ if o:
206
+ v["outcome"] = o
207
+ model.rollup(f, cfg.get("model"))
208
+ doc = {"schema_version": model.SCHEMA_VERSION, "generated_at": now(), "repo": {k: inv.get("repo", {}).get(k) for k in ("name", "commit", "branch")},
209
+ "bases": [{"key": b, "label": model.BASIS_LABEL[b], "help": model.BASIS_HELP[b], "solid": b in model.SOLID} for b in model.BASES],
210
+ "production": {e: {k: v for k, v in p.items() if k != "queries"} for e, p in production.items()},
211
+ "summary": summary(list(fams.values())), "families": list(fams.values())}
212
+ (out_dir / FILE).write_text(json.dumps(doc, indent=1))
213
+ if production:
214
+ (out_dir / "families_located.json").write_text(json.dumps({e: p["queries"] for e, p in production.items()}))
215
+ return doc
216
+
217
+
218
+ class SmallTables:
219
+ """"Nothing to gain" from the real catalog: a variant that plans and reads only tables the pulled catalog shows small
220
+ (at most `small_table_max_rows`, blockers' confirm_small_table_max_rows by default). ClickHouse tables count only
221
+ when the catalog has storage figures for them (parts or bytes), so an unknown size is never read as small."""
222
+
223
+ def __init__(self, catalog: dict, max_rows: int | None = None):
224
+ from ..blockers import DEFAULTS as B
225
+ self.max_rows = int(max_rows if max_rows is not None else B["confirm_small_table_max_rows"])
226
+ self.rows: dict[str, dict[str, int]] = {}
227
+ for engine, conn in (catalog.get("connections") or {}).items():
228
+ per = self.rows.setdefault(engine, {})
229
+ for t in conn.get("tables") or []:
230
+ if engine == "clickhouse" and not (t.get("parts") or t.get("bytes_on_disk")):
231
+ continue
232
+ if t.get("rows") is None:
233
+ continue
234
+ name = str(t.get("name") or "").lower()
235
+ per[name] = max(per.get(name, 0), int(t["rows"]))
236
+
237
+ def outcome(self, sql: str, engine: str) -> dict | None:
238
+ per = self.rows.get(engine or "postgres")
239
+ if not per:
240
+ return None
241
+ from ..sqlinfo import analyze
242
+ info = analyze(sql, engine or "postgres", False)
243
+ names = {t.split(".")[-1].strip('"`').lower() for t in info.tables}
244
+ if not names or not all(n in per for n in names):
245
+ return None
246
+ rows = {n: per[n] for n in sorted(names)}
247
+ if max(rows.values()) > self.max_rows:
248
+ return None
249
+ return {"state": "nothing_to_gain", "reason": "small_table", "from": "catalog",
250
+ "evidence": {"basis": "catalog", "rows": rows, "max_rows": self.max_rows}}
251
+
252
+
253
+ def outcomes_by_variant(findings: dict) -> dict[str, dict]:
254
+ """A finding benchmarked a statement: its outcome belongs to the variant with the same normalised text."""
255
+ out = {}
256
+ for x in findings.get("findings") or []:
257
+ # the baseline pass writes the statement typed (`{p1:uuid}`); the variant's own text is its original_sql
258
+ for sql in (x.get("baseline_sql"), x.get("original_sql")):
259
+ if sql and x.get("outcome"):
260
+ out.setdefault(model.variant_id(sql), x["outcome"])
261
+ return out
262
+
263
+
264
+ def summary(fams: list[dict]) -> dict:
265
+ sites = [f for f in fams if f["site"]["kind"] == "site"]
266
+ with_stmt = [f for f in sites if f["variants"]]
267
+ planned = [f for f in sites if model.valid_variants(f)]
268
+ by_basis = Counter(v["basis"] for f in sites for v in f["variants"])
269
+ best_basis = Counter(min((v["basis"] for v in f["variants"]), key=lambda b: model.RANK[b]) for f in with_stmt)
270
+ exact = [f for f in with_stmt if any(v.get("exact") for v in f["variants"])]
271
+ return {
272
+ "sites": len(sites), "builders": len(fams) - len(sites),
273
+ "with_statement": len(with_stmt), "with_exact_statement": len(exact), "with_planning_statement": len(planned),
274
+ "variants": sum(len(f["variants"]) for f in sites), "unbuilt": sum(len(f["unbuilt"]) for f in sites),
275
+ "variants_by_basis": dict(by_basis), "sites_by_best_basis": dict(best_basis),
276
+ "rollup": dict(Counter(f["rollup"]["state"] for f in sites)),
277
+ "reasons": dict(Counter(f["rollup"].get("reason") for f in sites if f["rollup"].get("reason"))),
278
+ "by_mechanism": {m: {"sites": n, "with_statement": sum(1 for f in with_stmt if f["site"]["mechanism"] == m)}
279
+ for m, n in Counter(f["site"]["mechanism"] for f in sites).items()},
280
+ }
@@ -0,0 +1,177 @@
1
+ """`codecop families`: statement families of run-time-built call sites.
2
+
3
+ codecop families build OUT [--repo PATH] [--org NAME=ROOT[:INVENTORY]] [--plan] [--evaluate] [--driver --budget USD]
4
+ codecop families show OUT SITE one site's family, as the console panel shows it
5
+ codecop families tag-patch PATH --out OUT print the query-tag helper patch for the repository (never applied)
6
+
7
+ Settings under `[families]` in codecop.toml: `evaluate` (pure slice of builders, default false in the CLI, true in the
8
+ hosted runner), `driver` (agent-written drivers, default false in the CLI), `org` ({name = "root[:inventory]"}), and the
9
+ tables `holes`, `locate`, `isolate`, `model`, `driver`.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import os
16
+ from pathlib import Path
17
+ from typing import List, Optional
18
+
19
+ import typer
20
+
21
+ from ..agent import DEFAULT_AGENT
22
+ from rich.console import Console
23
+
24
+ families_app = typer.Typer(add_completion=False, no_args_is_help=True,
25
+ help="Statement families: every statement a run-time-built call site can send.")
26
+ console = Console()
27
+ err = Console(stderr=True)
28
+
29
+
30
+ def _hosted() -> bool:
31
+ return os.environ.get("CODECOP_HOSTED") == "1"
32
+
33
+
34
+ def _org(values: list[str], cfg: dict) -> dict:
35
+ out = {}
36
+ pairs = list(values or []) + [f"{k}={v}" for k, v in ((cfg.get("org") or {}).items())]
37
+ for p in pairs:
38
+ name, _, rest = p.partition("=")
39
+ root, _, inv = rest.partition(":")
40
+ doc = {"root": Path(root) if root else None}
41
+ inv_path = Path(inv) if inv else (Path(root) / ".codecop" / "inventory.json" if root else None)
42
+ if inv_path and inv_path.exists():
43
+ doc["inventory"] = json.loads(inv_path.read_text())
44
+ elif root:
45
+ from ..discover import discover
46
+ doc["inventory"] = discover(Path(root))
47
+ out[name] = doc
48
+ return out
49
+
50
+
51
+ @families_app.command("build")
52
+ def build_cmd(
53
+ out: Path = typer.Argument(..., help="The scan's out directory (inventory.json, db_workload.json)."),
54
+ repo: Optional[Path] = typer.Option(None, "--repo", help="Repository root (default: the inventory's)."),
55
+ org: List[str] = typer.Option([], "--org", help="Another repository of the organisation: NAME=ROOT[:INVENTORY]. Repeat."),
56
+ plan: bool = typer.Option(False, "--plan", help="Plan every variant against sandbox schemas from the pulled catalogs."),
57
+ evaluate: Optional[bool] = typer.Option(None, "--evaluate/--no-evaluate",
58
+ help="Run a verified pure slice of Go builders in isolation. Default off in the CLI, on in the hosted runner."),
59
+ driver: Optional[bool] = typer.Option(None, "--driver/--no-driver",
60
+ help="Ask the agent for a driver program (run in isolation) by heat, inside the budget. Default off in the CLI."),
61
+ budget: Optional[float] = typer.Option(None, "--budget", help="Agent budget for drivers, USD (estimate). Default: [agent] budget_usd."),
62
+ agent: str = typer.Option(DEFAULT_AGENT, "--agent", help="The coding agent that writes drivers (default: claude)."),
63
+ fragments: bool = typer.Option(True, "--fragments/--no-fragments", help="Place unlocated production statements by the code's fragments."),
64
+ ):
65
+ """Merge every source of a statement into the family of each run-time-built call site (families.json)."""
66
+ from .. import cli as qcli
67
+ from . import build
68
+ inv = json.loads((out / "inventory.json").read_text())
69
+ root = (repo or Path(inv.get("repo", {}).get("root") or ".")).resolve()
70
+ cfg = qcli.load_config(root).get("families") or {}
71
+ evaluate = cfg.get("evaluate", _hosted()) if evaluate is None else evaluate
72
+ driver = cfg.get("driver", _hosted()) if driver is None else driver
73
+ org_docs = _org(org, cfg)
74
+ log = lambda m: err.print(f"[dim]{m}[/dim]") # noqa: E731
75
+ if evaluate:
76
+ from . import goslice
77
+ goslice.evaluate(out, root, inv, settings=cfg.get("evaluate_settings"), log=log)
78
+ doc = build.build(out, root=root, org=org_docs, settings=cfg, fragments=fragments, log=log)
79
+ if plan:
80
+ _plan(out, doc, inv, log)
81
+ doc = build.build(out, root=root, org=org_docs, settings=cfg, fragments=fragments, log=log)
82
+ if driver:
83
+ from .. import agent as agent_mod, budget as budget_mod
84
+ from . import driver as driver_mod
85
+ runner = agent_mod.get_runner(agent)
86
+ acfg = budget_mod.agent_settings(qcli.load_config(root).get("agent"))
87
+ run = budget_mod.Run(out, budget if budget is not None else acfg["budget_usd"], settings=acfg,
88
+ billing=budget_mod.billing_mode(runner))
89
+ by_id = {s["id"]: s for s in inv.get("call_sites") or []}
90
+ ask = [by_id[i] for i in driver_mod.needs_agent(doc["families"]) if i in by_id]
91
+ match_doc = build.load(out / "db_match.json")
92
+ driver_mod.ask(out, root, driver_mod.heat_order(ask, match_doc), runner=runner, run=run, settings=cfg.get("driver"), log=log)
93
+ doc = build.build(out, root=root, org=org_docs, settings=cfg, fragments=fragments, log=log)
94
+ if plan:
95
+ _plan(out, doc, inv, log)
96
+ doc = build.build(out, root=root, org=org_docs, settings=cfg, fragments=fragments, log=log)
97
+ console.print(f"agent spend (estimate): ${run.spent:.2f}")
98
+ s = doc["summary"]
99
+ console.print(f"{s['sites']} run-time-built sites · {s['with_statement']} with a statement · {s['with_exact_statement']} exact · "
100
+ f"{s['with_planning_statement']} that plan · bases {s['sites_by_best_basis']}")
101
+ for engine, p in (doc.get("production") or {}).items():
102
+ loc = p["located"]
103
+ console.print(f"{engine}: located {loc['with_fragments']['executions']:.1%} of executions, {loc['with_fragments']['read_bytes']:.1%} of bytes read "
104
+ f"(this repository alone {loc['own_repository_sure']['executions']:.1%} / {loc['own_repository_sure']['read_bytes']:.1%}); "
105
+ f"{p['snapshots']} pull snapshot(s)")
106
+
107
+
108
+ def _plan(out: Path, doc: dict, inv: dict, log) -> None:
109
+ from . import plangate
110
+ from ..realdb import facts as facts_mod # noqa: F401 (the catalog file layout)
111
+ cat = {}
112
+ try:
113
+ cat = (json.loads((out / "db_catalog.json").read_text()).get("connections") or {})
114
+ except (OSError, ValueError):
115
+ pass
116
+ versions = {e: str(c.get("version") or "").split(".")[0] if e == "postgres" else ".".join(str(c.get("version") or "").split(".")[:2])
117
+ for e, c in cat.items()}
118
+ plangate.run(out, doc, catalogs=cat, inventory=inv, versions={k: v for k, v in versions.items() if v}, log=log)
119
+
120
+
121
+ @families_app.command("show")
122
+ def show_cmd(out: Path = typer.Argument(...), site: str = typer.Argument(..., help="Site id, or file:line.")):
123
+ """One site's family: template, variants with condition, basis, runs, plans, outcome; unbuilt rows."""
124
+ from . import model
125
+ doc = json.loads((out / "families.json").read_text())
126
+ fam = next((f for f in doc["families"] if f["site"]["id"] == site or f"{f['site']['file']}:{f['site']['line']}" == site), None)
127
+ if fam is None:
128
+ err.print(f"[red]no family for {site}[/red]")
129
+ raise typer.Exit(1)
130
+ s, r, c = fam["site"], fam["rollup"], fam["coverage"]
131
+ console.print(f"[bold]{s['file']}:{s['line']}[/bold] {s['symbol']} · {s['engine']} · family of {len(fam['variants'])} · "
132
+ f"{model.STATE_LABEL[r['state']]} · {c['judged']} of {c['variants']} judged" + (f" · {r['spread']}" if r.get("spread") else ""))
133
+ if fam["template"].get("text"):
134
+ console.print(fam["template"]["text"][:2000], markup=False)
135
+ for i, v in enumerate(fam["variants"], 1):
136
+ p = v.get("production") or {}
137
+ runs = f"{p.get('share_of_site', 0):.0%} · {p.get('executions', 0):,}" if p else "not seen"
138
+ plans = {True: "plans", False: "does not plan", None: "not planned"}[(v.get("valid") or {}).get("planned")]
139
+ oc = (v.get("outcome") or {}).get("state") or "not benchmarked"
140
+ console.print(f"{i:>2} {v['condition'][:60]:<60} {model.BASIS_LABEL[v['basis']]:<22} {runs:<16} {plans:<14} {oc}"
141
+ + (" (unverified)" if v.get("unverified") else ""), markup=False)
142
+ for u in fam["unbuilt"]:
143
+ console.print(f" – {u['condition'][:60]:<60} {u['reason']}: {u.get('detail', '')[:80]}", markup=False)
144
+
145
+
146
+ @families_app.command("tag-patch")
147
+ def tag_patch_cmd(path: Path = typer.Argument(Path("."), help="Repository root."),
148
+ out: Optional[Path] = typer.Option(None, "--out", help="Out dir with inventory.json (default PATH/.codecop).")):
149
+ """Print the small query-tag helper patch for this repository. CodeCop never applies it."""
150
+ from . import tagpatch
151
+ root = path.resolve()
152
+ inv = json.loads(((out or root / ".codecop") / "inventory.json").read_text())
153
+ text, changed = tagpatch.patch(root, inv)
154
+ print(text)
155
+ err.print(f"{len(changed)} client calls wrapped; review and apply with git apply")
156
+
157
+
158
+ def scan_step(path: Path, out_dir: Path, inventory: dict, console_) -> None:
159
+ """Inside `codecop scan` (every engine): the free sources of the families, after discover and before the engines run.
160
+ Builder evaluation (pure slice, isolated) when `[families] evaluate` says so, default on in the hosted runner.
161
+ Never fails the scan: a failure is printed and the scan goes on."""
162
+ from .. import cli as qcli
163
+ from . import build
164
+ try:
165
+ root = Path(path).resolve()
166
+ cfg = qcli.load_config(root).get("families") or {}
167
+ if cfg.get("enabled", True) is False:
168
+ return
169
+ if cfg.get("evaluate", _hosted()):
170
+ from . import goslice
171
+ goslice.evaluate(out_dir, root, inventory, settings=cfg.get("evaluate_settings"))
172
+ doc = build.build(out_dir, root=root, org=_org([], cfg), settings=cfg)
173
+ s = doc["summary"]
174
+ console_.print(f"Statement families: {s['sites']} run-time-built sites, {s['with_statement']} with a statement "
175
+ f"({s['sites_by_best_basis']}) → {out_dir / build.FILE}", highlight=False)
176
+ except Exception as e: # noqa: BLE001 — a family step must never lose the scan
177
+ console_.print(f"[yellow]Statement families not built: {e}[/yellow]")
@@ -0,0 +1,62 @@
1
+ """How a statement family moves its call site down the coverage funnel (coverage.repository calls this).
2
+
3
+ A run-time-built site counts as `obtained` once its family holds a statement, and passes `plans` when a variant plans
4
+ (a family whose every variant was planned and failed stops there, `does_not_plan`). The site then stands for its best
5
+ variant (the most-run exact one that plans, else any that plans, else the first): its text and sql_hash are that
6
+ variant's, so an outcome the baseline pass recorded for the variant is the site's. A family roll-up that is judged
7
+ (improved, needs another fix, nothing to gain) judges the site.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ from pathlib import Path
14
+
15
+ from .. import coverage_reasons as R
16
+ from . import model
17
+
18
+ R.register("family_not_benchmarked", "runs", "Family variants not benchmarked yet", "run the baseline pass on the family's variants",
19
+ "baseline_pass")
20
+ STATE_OF = {"improved": "fixed", "needs_another_fix": "blocked", "nothing_to_gain": "nothing_to_gain"}
21
+
22
+
23
+ def load(out_dir: Path) -> dict | None:
24
+ """site id -> family, from families.json in the out dir (None when there is none)."""
25
+ try:
26
+ doc = json.loads((Path(out_dir) / "families.json").read_text())
27
+ except (OSError, ValueError):
28
+ return None
29
+ return {f["site"]["id"]: f for f in doc.get("families") or [] if f.get("site", {}).get("kind") == "site"}
30
+
31
+
32
+ def best(fam: dict) -> dict | None:
33
+ vs = fam.get("variants") or []
34
+ planned = [v for v in vs if (v.get("valid") or {}).get("planned")]
35
+ for group in ([v for v in planned if v.get("exact")], planned, vs):
36
+ if group:
37
+ return group[0] # build.py ordered them: most-run, strongest basis, exact first
38
+ return None
39
+
40
+
41
+ def apply(site: dict, got: str, fam: dict) -> tuple[dict, str, str, bool, str]:
42
+ """(the site as coverage sees it, obtained, judged state or '', whether a variant's baseline ran, where the judging
43
+ outcomes came from: `sandbox` when any judged variant was measured, else `catalog` or the outcome's own `from`)."""
44
+ v = best(fam)
45
+ state = STATE_OF.get((fam.get("rollup") or {}).get("state"), "")
46
+ froms = {(x.get("outcome") or {}).get("from") for x in fam.get("variants") or [] if (x.get("outcome") or {}).get("state")}
47
+ frm = "sandbox" if froms & {"sandbox", "measured"} else next(iter(sorted(f for f in froms if f)), "")
48
+ if v is None:
49
+ return site, got, state, False, frm
50
+ from ..sqlinfo import analyze
51
+ info = analyze(v["sql"], site.get("engine") or "", bool(site.get("in_loop")))
52
+ s = {**site, "sql": v["sql"], "sql_hash": info.sql_hash or site.get("sql_hash"), "parse_ok": True,
53
+ "statement": site.get("statement") if site.get("statement") not in (None, "unknown") else info.kind,
54
+ "family_variant": v["id"], "family_basis": v["basis"]}
55
+ valid = [x.get("valid") for x in fam.get("variants") or [] if x.get("valid")]
56
+ if valid and not any(x.get("planned") for x in valid):
57
+ s["plan"] = {"ok": False, "reason": "does_not_plan"}
58
+ ran = bool(froms & {"sandbox", "measured"})
59
+ return s, "obtained", state, ran, frm
60
+
61
+
62
+ _ = model