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/profile.py ADDED
@@ -0,0 +1,439 @@
1
+ """Stage 3, size: the data profile.
2
+
3
+ The agent proposes row counts and per-column distributions from the code and
4
+ docs. The developer reviews and edits profile.json before anything is generated:
5
+ the CLI never silently picks a scale.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from datetime import datetime, timezone
12
+ from pathlib import Path
13
+
14
+ from . import __version__, engines, sizes
15
+ from .agent import AgentRunner, billing
16
+ from .rank import _fill, load_prompt, load_schema
17
+
18
+ GENERATOR_FIELDS = ("distinct", "distribution", "prefix", "values", "min", "max", "days_back", "avg_len", "value", "sql",
19
+ "null_fraction", "pinned") + tuple(k for k in sizes.SIZE_FIELDS if k not in ("size_evidence", "size_estimate",
20
+ "mean_bytes", "compress_ratio", "width_by_age"))
21
+ AGENT_ESTIMATE = "agent estimate"
22
+ REAL_CATALOG = "real catalog"
23
+ FILLER_MIN_BYTES = 16 # a real column the agent did not describe is generated at its real size from this mean up
24
+ FILLER_MIN_BYTES_POSTGRES = 64 # PostgreSQL: only the wide ones; a short text column may be an enum-like value with a rule
25
+ STRING_TYPE = re.compile(r"^(?:Nullable\(|LowCardinality\()*(?:String|FixedString)|^Array\((?:Nullable\(|LowCardinality\()*String|"
26
+ r"^(?:text|character varying|varchar|json|jsonb|bytea)\b", re.I)
27
+
28
+
29
+ def build_prompt(rank: dict, facts=None, db_sizes: bool = True) -> str:
30
+ def note(t: dict) -> str:
31
+ real = facts.table_note(rank["engine"], t["name"], sizes=db_sizes) if facts and t.get("source") == "real catalog" else ""
32
+ if not real:
33
+ return ""
34
+ widths = facts.column_sizes(rank["engine"], t["name"]) if db_sizes else {}
35
+ top = sorted(widths.items(), key=lambda kv: -kv[1]["mean_bytes"])[:8]
36
+ wide = ("\nreal mean uncompressed bytes per value: " + ", ".join(f"{n} {v['mean_bytes']:,.0f}" for n, v in top)
37
+ + ". These means are applied for you; still give `content`, `typical_bytes` and `large_bytes`, which decide the spread.") if top else ""
38
+ return f"\n{real} (these are facts: use this row count){wide}"
39
+ tables = "\n\n".join(
40
+ f"### {t['name']}{' (definition assembled from evidence, not copied)' if t.get('inferred') else ''}{note(t)}\n```sql\n{t['create_sql'].strip()}\n```"
41
+ for t in rank["table_definitions"]
42
+ )
43
+ blocks = []
44
+ for c in rank["candidates"]:
45
+ params = ", ".join(f"{k} = {v!r}" for k, v in c["params"].items()) or "(none)"
46
+ variants = "\n".join(
47
+ f"variant ({v['kind']}): {v.get('change', '')}\n```sql\n{v['sql'].strip()}\n```" for v in c["variants"] if v["kind"] == "rewrite"
48
+ )
49
+ blocks.append(
50
+ f"### {c['finding']}: {c['title']}\n{c['site']['file']}:{c['site']['line']}\n"
51
+ f"parameters: {params}\n```sql\n{c['baseline_sql'].strip()}\n```\n{variants}".rstrip()
52
+ )
53
+ eng = engines.get(rank["engine"])
54
+ return _fill(load_prompt(eng.profile_prompt), {
55
+ "sizes": load_prompt("profile_sizes"),
56
+ "engine": eng.label,
57
+ "engine_version": rank["engine_version"],
58
+ "tables": tables or "(none)",
59
+ "candidates": "\n\n".join(blocks) or "(none)",
60
+ })
61
+
62
+
63
+ def clean_column(col: dict) -> dict:
64
+ """Drop the generator fields the agent left null, so the file is easy to read and edit."""
65
+ out = {"name": col["name"], "kind": col["kind"]}
66
+ for key in GENERATOR_FIELDS:
67
+ if col.get(key) not in (None, [], ""):
68
+ out[key] = col[key]
69
+ out["source"] = col.get("source", "")
70
+ out["confidence"] = col.get("confidence", "low")
71
+ return out
72
+
73
+
74
+ def guess_content(name: str, ratio: float | None) -> str:
75
+ """A content kind for a real column nobody described, from how it compresses and what it is called."""
76
+ low = name.lower()
77
+ if ratio is not None and ratio < 1.8:
78
+ return "ciphertext"
79
+ if any(w in low for w in ("messages", "conversation")):
80
+ return "llm_messages"
81
+ if any(w in low for w in ("json", "payload", "metadata", "arguments", "params", "headers", "event", "config", "raw")):
82
+ return "json"
83
+ return "text"
84
+
85
+
86
+ def apply_sizes(table: dict, engine: str, facts) -> dict:
87
+ """Real column sizes override the agent's estimates, which fill what the catalog lacks; each column says which it was.
88
+
89
+ A real mean replaces the estimated one and the estimate is kept beside it (`size_estimate`), so the two can be
90
+ compared. A real string column the agent did not list is added at its real size: it is never read by a candidate,
91
+ but it is part of the row, and row width decides how many rows a granule (ClickHouse) or a page (PostgreSQL) holds."""
92
+ apply_real_sizes(table, engine, facts)
93
+ apply_age_widths(table, engine, facts)
94
+ return table
95
+
96
+
97
+ def apply_real_sizes(table: dict, engine: str, facts, text_only: bool = False) -> list[dict]:
98
+ """The size part of `apply_sizes`; safe to run again on a profile (`codecop profile --refresh-facts`): a column that
99
+ already has the real mean gets the newer one, the agent's first estimate is kept, and a column added for its width
100
+ is not added twice. `text_only`: only text columns, the ones generated from a size, are touched (a refresh leaves
101
+ keys and timestamps as they were). Returns one record per text column whose size changed or that was added:
102
+ {column, mean_bytes, added}."""
103
+ widths = facts.column_sizes(engine, table["name"]) if facts else {}
104
+ described = {c["name"] for c in table["columns"]}
105
+ changed = []
106
+ for c in table["columns"]:
107
+ if text_only and c.get("kind") != "text":
108
+ continue
109
+ if any(c.get(k) for k in ("typical_bytes", "large_bytes")) and c.get("size_evidence") not in (REAL_CATALOG, sizes.REAL_PARTITIONS):
110
+ c["size_evidence"] = AGENT_ESTIMATE
111
+ real = widths.get(c["name"])
112
+ if not real:
113
+ continue
114
+ estimate = sizes.mean_bytes(c) if c.get("size_evidence") not in (REAL_CATALOG, sizes.REAL_PARTITIONS) else None
115
+ if estimate is None and c.get("kind") == "text" and c.get("avg_len") and "size_estimate" not in c:
116
+ estimate = float(c["avg_len"])
117
+ if estimate and "size_estimate" not in c:
118
+ c["size_estimate"] = {"mean_bytes": round(estimate, 1), "typical_bytes": c.get("typical_bytes"), "large_bytes": c.get("large_bytes")}
119
+ if c.get("mean_bytes") != real["mean_bytes"] and c.get("kind") == "text":
120
+ changed.append({"column": c["name"], "mean_bytes": real["mean_bytes"], "added": False})
121
+ c["mean_bytes"] = real["mean_bytes"]
122
+ if real.get("compress_ratio"):
123
+ c["compress_ratio"] = real["compress_ratio"]
124
+ if c.get("size_evidence") != sizes.REAL_PARTITIONS:
125
+ c["size_evidence"] = REAL_CATALOG
126
+ if c.get("kind") == "text" and not c.get("content"):
127
+ c["content"] = guess_content(c["name"], real.get("compress_ratio"))
128
+ for name, real in widths.items():
129
+ least = FILLER_MIN_BYTES if engine == "clickhouse" else FILLER_MIN_BYTES_POSTGRES
130
+ if name in described or real["mean_bytes"] < least or real.get("default_kind") in ("MATERIALIZED", "ALIAS", "EPHEMERAL"):
131
+ continue
132
+ if not STRING_TYPE.match(real.get("type") or ""):
133
+ continue
134
+ table["columns"].append({
135
+ "name": name, "kind": "text", "content": guess_content(name, real.get("compress_ratio")), "mean_bytes": real["mean_bytes"],
136
+ **({"compress_ratio": real["compress_ratio"]} if real.get("compress_ratio") else {}),
137
+ "source": "real catalog: the column's size. The profile did not describe it; it is here because it is part of the row's width.",
138
+ "confidence": "high", "evidence": REAL_CATALOG, "size_evidence": REAL_CATALOG, "filler": True})
139
+ changed.append({"column": name, "mean_bytes": real["mean_bytes"], "added": True})
140
+ return changed
141
+
142
+
143
+ def apply_age_widths(table: dict, engine: str, facts, settings: dict | None = None) -> list[dict]:
144
+ """Where the real catalog has column sizes per partition and the partitions are periods of time, a text column
145
+ whose width changes with age gets `width_by_age`, and says so in `size_evidence`.
146
+
147
+ The table's mean stays what the catalog says; the bands say how it is spread over time, so recent rows are
148
+ generated at their real width. Returns what was applied or left, one record per column the catalog has bands for:
149
+ {column, applied, bands | reason}. Safe to run again on a profile: earlier bands are replaced.
150
+ `settings`: the `[profile]` table of codecop.toml (width_bands, width_band_tolerance)."""
151
+ settings = settings or {}
152
+ for c in table["columns"]:
153
+ if c.pop("width_by_age", None) is not None and c.get("size_evidence") == sizes.REAL_PARTITIONS:
154
+ c["size_evidence"] = REAL_CATALOG
155
+ if not facts or engine != "clickhouse" or not hasattr(facts, "width_by_age"):
156
+ return []
157
+ found = facts.width_by_age(engine, table["name"], int(settings.get("width_bands") or sizes.WIDTH_BANDS),
158
+ float(settings.get("width_band_tolerance") or sizes.BAND_TOLERANCE))
159
+ by_name = {c["name"]: c for c in table["columns"]}
160
+ out = []
161
+ for name, w in found.items():
162
+ c, when = by_name.get(name), by_name.get(w["column"])
163
+ if c is None or c.get("kind") != "text" or not c.get("mean_bytes"):
164
+ continue # not generated from a size: nothing to spread
165
+ if when is None or when.get("kind") not in ("timestamp", "expr"):
166
+ # an `expr` column is taken as the time it is named for: the generator reads its age from the row only when
167
+ # the table's column is a date or time type (datagen.insert_statements)
168
+ out.append({"column": name, "applied": False,
169
+ "reason": f"the profile does not generate {w['column']} as a timestamp, so rows have no age to follow"})
170
+ continue
171
+ c["width_by_age"] = w
172
+ c["size_evidence"] = sizes.REAL_PARTITIONS
173
+ out.append({"column": name, "applied": True, "bands": len(w["bands"])})
174
+ return out
175
+
176
+
177
+ def apply_planner_stats(table: dict, facts, rows: int | None) -> dict:
178
+ """PostgreSQL: the server's own column statistics replace the guessed distinct count and NULL share.
179
+
180
+ pg_stats is already in the read-only catalog tier (no data values are read): n_distinct, null_frac, correlation.
181
+ The correlation is recorded for the reader; the generator does not order rows by it yet."""
182
+ stats = facts.planner_stats(table["name"]) if facts else {}
183
+ total = rows or table.get("rows") or 0
184
+ for c in table["columns"]:
185
+ s = stats.get(c["name"])
186
+ if not s:
187
+ continue
188
+ n = s.get("n_distinct")
189
+ if c.get("kind") == "key" and n:
190
+ real = int(round(n if n > 0 else -n * total))
191
+ if real > 0:
192
+ c.update(distinct_estimate=c.get("distinct"), distinct=real, evidence=REAL_CATALOG, confidence="high")
193
+ if s.get("null_frac") is not None and (s["null_frac"] > 0 or c.get("null_fraction")):
194
+ c.update(null_fraction=round(float(s["null_frac"]), 4), evidence=REAL_CATALOG)
195
+ if s.get("correlation") is not None:
196
+ c["correlation"] = s["correlation"]
197
+ return table
198
+
199
+
200
+ def apply_facts(table: dict, engine: str, facts, db_sizes: bool = True) -> dict:
201
+ """Replace what was guessed with what the real database says, and record which is which.
202
+
203
+ Row counts come from the catalog. With a tier D sample, a key column's distinct count comes from the
204
+ sample when the sample covered the whole table; otherwise the sampled count is kept beside the guess.
205
+ Column sizes come from the catalog where it reports them (`apply_sizes`)."""
206
+ table["rows_evidence"] = "inferred"
207
+ for c in table["columns"]:
208
+ c.setdefault("evidence", "inferred")
209
+ apply_sizes(table, engine, facts if db_sizes else None)
210
+ if not facts:
211
+ return table
212
+ rows = facts.rows(engine, table["name"])
213
+ if rows:
214
+ table.update(rows=rows, rows_basis="real catalog: the table's row count", rows_confidence="high", rows_evidence="real catalog")
215
+ if engine == "postgres":
216
+ apply_planner_stats(table, facts, rows)
217
+ sample = facts.sampled(engine, table["name"])
218
+ if sample:
219
+ whole = sample.get("sampled_rows", 0) >= (rows or table["rows"]) * 0.95
220
+ for c in table["columns"]:
221
+ stat = (sample.get("columns") or {}).get(c["name"])
222
+ if not stat:
223
+ continue
224
+ c["sampled_distinct"] = stat.get("distinct_in_sample")
225
+ if whole and c.get("kind") == "key" and stat.get("distinct_in_sample"):
226
+ c.update(distinct=stat["distinct_in_sample"], evidence="real sample", confidence="high")
227
+ return table
228
+
229
+
230
+ def observed_plan(observed: dict, profile: dict | None, facts, engine: str, version: str) -> dict:
231
+ """What `codecop profile --observed` would ask: {tables, rank, estimate}.
232
+
233
+ `tables`: the tables the statements production ran (observed.json) read that profile.json does not describe (a
234
+ table it describes keeps its description; one bench gave a catalog-only description is asked about). `rank`: the
235
+ input build_prompt and propose take: those tables' real definitions and the statements that read them.
236
+ `estimate`: {cost_low_usd, cost_high_usd, basis}: the last profile run's cost per table when profile.json records
237
+ one, else the rank stage's measured cost per query (rank.COST_PER_QUERY_USD), times what is asked."""
238
+ from .rank import COST_PER_QUERY_USD
239
+ have = {t["name"] for t in (profile or {}).get("tables") or [] if t.get("basis") != "catalog, no agent"}
240
+ wanted = sorted({t for c in observed.get("candidates") or [] for t in c.get("tables") or []} - have)
241
+ definitions = [d for d in (facts.definition(engine, n) for n in wanted) if d] if facts else []
242
+ names = [d["name"] for d in definitions]
243
+ cands = [{**{k: c.get(k) for k in ("finding", "id", "title", "site", "tables", "baseline_sql")}, "params": c.get("params") or {}, "variants": []}
244
+ for c in observed.get("candidates") or [] if set(c.get("tables") or []) & set(names)]
245
+ rank = {"engine": engine, "engine_version": version, "candidates": cands, "table_definitions": definitions}
246
+ agent = (profile or {}).get("agent") or {}
247
+ before = len((profile or {}).get("tables") or [])
248
+ if agent.get("cost_usd") and before:
249
+ per = float(agent["cost_usd"]) / before
250
+ low, high = per * len(names), per * len(names) * 2
251
+ basis = f"the last profile run: ${float(agent['cost_usd']):.2f} for {before} tables, {agent.get('cost_basis') or 'at API rates'}"
252
+ else:
253
+ low, high = COST_PER_QUERY_USD[0] * len(cands), COST_PER_QUERY_USD[1] * len(cands)
254
+ basis = "the rank stage's measured cost per query"
255
+ return {"tables": names, "rank": rank, "estimate": {"cost_low_usd": round(low, 2), "cost_high_usd": round(high, 2), "basis": basis}}
256
+
257
+
258
+ # What one table costs the profile step at API rates, low and high, when no earlier profile run says (a rough prior).
259
+ COST_PER_TABLE_USD = (0.05, 0.25)
260
+
261
+
262
+ def estimate(rank: dict, profile: dict | None = None) -> dict:
263
+ """What `codecop profile` would spend, before it does: {tables, candidates, cost_low_usd, cost_high_usd, basis}.
264
+
265
+ The last profile run's cost per table when profile.json records one, else COST_PER_TABLE_USD."""
266
+ names = [d["name"] for d in rank.get("table_definitions") or []]
267
+ agent = (profile or {}).get("agent") or {}
268
+ before = len((profile or {}).get("tables") or [])
269
+ if agent.get("cost_usd") and before:
270
+ per = float(agent["cost_usd"]) / before
271
+ low, high = per * len(names), per * len(names) * 2
272
+ basis = f"the last profile run: ${float(agent['cost_usd']):.2f} for {before} tables, {agent.get('cost_basis') or 'at API rates'}"
273
+ else:
274
+ low, high = COST_PER_TABLE_USD[0] * len(names), COST_PER_TABLE_USD[1] * len(names)
275
+ basis = "recorded profile runs' cost per table"
276
+ return {"tables": names, "candidates": len(rank.get("candidates") or []), "cost_low_usd": round(low, 2),
277
+ "cost_high_usd": round(high, 2), "basis": basis}
278
+
279
+
280
+ BIND = r"\{\s*(\w+)\s*:[^{}]+\}"
281
+ _QUAL = r'(?:"?(\w+)"?\.)?"?(\w+)"?'
282
+ # `t.col = {p:T}`, `col IN ({p:T})`, `col = ANY({p:T})`, and `{p:T} = t.col`
283
+ PARAM_EQ = re.compile(_QUAL + r"\s*(?:=|\bIN\b)\s*(?:ANY\s*)?\(?\s*" + BIND, re.I)
284
+ PARAM_EQ_REV = re.compile(BIND + r"\s*=\s*" + _QUAL, re.I)
285
+ FROM_ALIAS = re.compile(r'\b(?:FROM|JOIN)\s+((?:"?\w+"?\.)?"?\w+"?)(?:\s+(?:AS\s+)?(?!ON\b|WHERE\b|USING\b|JOIN\b|LEFT\b|INNER\b|CROSS\b|GROUP\b|ORDER\b|LIMIT\b)(\w+))?', re.I)
286
+ UUID_TEXT = re.compile(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")
287
+ RULE_FIXTURE_SHARE = 0.01 # a rule fixture's share of its table when no other fixture of the table says better
288
+ RULE_FIXTURE_MIN_ROWS = 100
289
+
290
+
291
+ def _first_value(value) -> str | None:
292
+ """The first value of a parameter: an array literal `{a,b}` gives `a`; a list its first item."""
293
+ if isinstance(value, list):
294
+ value = value[0] if value else None
295
+ if value is None:
296
+ return None
297
+ text = str(value).strip()
298
+ if text.startswith("{") and text.endswith("}"):
299
+ items = [x.strip().strip('"') for x in text[1:-1].split(",") if x.strip()]
300
+ return items[0] if items else None
301
+ return text
302
+
303
+
304
+ def _short(name: str) -> str:
305
+ return name.replace('"', "").split(".")[-1].lower()
306
+
307
+
308
+ def rule_fixtures(prof: dict, rank_data: dict) -> list[dict]:
309
+ """Fixtures for candidates the agent's profile never saw: a table described before (on the same definition) is not
310
+ asked again, so a candidate added later (a second rank, `rank --focus assembled`) had no rows holding its parameter
311
+ values, and its baseline read nothing ("parameters match no rows"). For each such candidate and table: the columns
312
+ its filters compare with a parameter (`col = {p:T}`, `col IN`, `= ANY`), each given the candidate's own value, on a
313
+ share of the rows like the table's other fixtures. Time columns get no value (their range is the window's), nor a
314
+ column whose kind the value does not fit (a uuid column, a number). Changes `prof` in place; returns what was added
315
+ ({table, finding, columns})."""
316
+ from .rank import _columns
317
+ tables = {t["name"]: t for t in prof.get("tables") or []}
318
+ by_short: dict[str, list[dict]] = {}
319
+ for t in tables.values():
320
+ by_short.setdefault(_short(t["name"]), []).append(t)
321
+ # the columns and types each table really has: its definition (the profile describes only some columns)
322
+ typed: dict[str, dict[str, str]] = {}
323
+ for d in rank_data.get("table_definitions") or []:
324
+ got = _columns(d.get("create_sql") or "", d["name"])
325
+ if got:
326
+ typed[d["name"]] = {k.replace('"', "").lower(): str(v or "").lower() for k, v in got[1].items()}
327
+ added = []
328
+ for c in rank_data.get("candidates") or []:
329
+ fid, sql, params = c.get("finding") or "", c.get("baseline_sql") or "", c.get("params") or {}
330
+ if not fid or not sql or not params:
331
+ continue
332
+ # by its name; a bare name may meet the one table of that name in another schema, a qualified one never does
333
+ mine = [tables.get(n) or ((by_short.get(_short(n)) or [None])[0] if "." not in n and len(by_short.get(_short(n)) or []) == 1 else None)
334
+ for n in c.get("tables") or []]
335
+ mine = [t for t in mine if t]
336
+ if not mine:
337
+ continue
338
+ aliases = {}
339
+ for m in FROM_ALIAS.finditer(sql):
340
+ aliases[(m.group(2) or _short(m.group(1))).lower()] = _short(m.group(1))
341
+ pairs = [(m.group(1), m.group(2), m.group(3)) for m in PARAM_EQ.finditer(sql)]
342
+ pairs += [(m.group(2), m.group(3), m.group(1)) for m in PARAM_EQ_REV.finditer(sql)]
343
+ want: dict[str, dict[str, str]] = {}
344
+ for qual, col, pname in pairs:
345
+ value = _first_value(params.get(pname))
346
+ if value is None:
347
+ continue
348
+ col_l = col.lower()
349
+
350
+ def has(t: dict) -> bool:
351
+ return col_l in typed.get(t["name"], {}) or any(x["name"].lower() == col_l for x in t.get("columns") or [])
352
+ owners = [t for t in mine if has(t)]
353
+ if qual:
354
+ owners = [t for t in owners if _short(t["name"]) == aliases.get(qual.lower(), qual.lower())]
355
+ if not owners or (qual and len(owners) != 1):
356
+ continue # a column no table of the statement has, or a qualifier that names none: no guess
357
+ # an unqualified column several tables have (each CTE filters its own table by the tenant): all of them, since
358
+ # a fixture's rows are the same row numbers in every table (datagen.place_fixtures)
359
+ for t in owners:
360
+ spec = next((x for x in t.get("columns") or [] if x["name"].lower() == col_l), {})
361
+ kind, sqltype = spec.get("kind") or "", typed.get(t["name"], {}).get(col_l, "")
362
+ if kind in ("timestamp", "constant", "expr", "unique") or re.search(r"time|date", sqltype) or \
363
+ ("uuid" in sqltype and not UUID_TEXT.match(value)) or \
364
+ ((kind in ("int", "float") or re.search(r"int|numeric|float|double|real|serial", sqltype))
365
+ and not re.fullmatch(r"-?\d+(\.\d+)?", value)):
366
+ continue # a time gets its range; a constant, an expression or a unique column keeps its own values
367
+ want.setdefault(t["name"], {}).setdefault(spec.get("name") or col, value)
368
+ for name, values in want.items():
369
+ t = tables[name]
370
+ have = t.setdefault("fixtures", [])
371
+ if any(fid in str(f.get("id") or "").split("+") for f in have):
372
+ continue # the agent placed this candidate's rows itself
373
+ held = {(v.get("column", "").lower(), str(v.get("value"))) for f in have for v in f.get("values") or []}
374
+ held |= {(c["name"].lower(), str(p.get("value"))) for c in t.get("columns") or [] for p in c.get("pinned") or []}
375
+ values = {k: v for k, v in values.items() if (k.lower(), str(v)) not in held}
376
+ if not values:
377
+ continue # the generated rows hold these values already (a pinned value, another fixture's)
378
+ shares = sorted(float(f.get("share") or 0) for f in have if f.get("share"))
379
+ share = shares[len(shares) // 2] if shares else RULE_FIXTURE_SHARE
380
+ have.append({"id": fid, "share": share, "min_rows": RULE_FIXTURE_MIN_ROWS,
381
+ "values": [{"column": k, "value": v} for k, v in values.items()],
382
+ "basis": "rule: the candidate's own parameter values (the table was described before it)"})
383
+ added.append({"table": name, "finding": fid, "columns": sorted(values)})
384
+ return added
385
+
386
+
387
+ def merge_observed(profile: dict | None, got: dict, tables: list[str]) -> dict:
388
+ """profile.json with the tables the agent described for the statements production ran added (`profiled_for`:
389
+ observed). A table profile.json already describes is never replaced; the run's cost is kept beside the first one's."""
390
+ import copy
391
+ out = copy.deepcopy(profile) if profile else {k: got.get(k) for k in ("schema_version", "tool_version", "generated_at", "engine",
392
+ "engine_version", "confirmed")} | {"tables": []}
393
+ have = {t["name"] for t in out.get("tables") or [] if t.get("basis") != "catalog, no agent"}
394
+ out["tables"] = [t for t in out.get("tables") or [] if t["name"] in have or t["name"] not in tables]
395
+ for t in got.get("tables") or []:
396
+ if t["name"] in tables and t["name"] not in have:
397
+ out["tables"].append({**t, "profiled_for": "observed"})
398
+ out.setdefault("observed_agent", []).append(got.get("agent") or {})
399
+ if not out.get("agent"):
400
+ out["agent"] = got.get("agent") or {}
401
+ return out
402
+
403
+
404
+ def propose(rank: dict, root: Path, runner: AgentRunner, *, model: str | None = None,
405
+ max_budget_usd: float | None = None, facts=None, db_sizes: bool = True) -> dict:
406
+ """`db_sizes=False`: the agent is not shown the real catalog's sizes and they are not applied (to test its estimates)."""
407
+ result = runner.run(build_prompt(rank, facts, db_sizes), load_schema("profile_output"), root, model=model, max_budget_usd=max_budget_usd)
408
+ known = {t["name"] for t in rank["table_definitions"]}
409
+ tables = []
410
+ for t in result.output.get("tables", []):
411
+ if t["name"] not in known:
412
+ continue
413
+ tables.append(apply_facts({
414
+ "name": t["name"],
415
+ "rows": int(t["rows"]),
416
+ "rows_basis": t.get("rows_basis", ""),
417
+ "rows_confidence": t.get("rows_confidence", "low"),
418
+ "columns": [clean_column(c) for c in t.get("columns", [])],
419
+ "fixtures": t.get("fixtures") or [],
420
+ # relations.py: which columns hold another table's key, and which columns a row shares with that parent
421
+ "relations": [{"column": r["column"], "parent_table": r["parent_table"], "parent_column": r["parent_column"],
422
+ "same_as_parent": [{"column": s["column"], "parent_column": s["parent_column"]}
423
+ for s in r.get("same_as_parent") or [] if s.get("column") and s.get("parent_column")],
424
+ "basis": r.get("basis") or ""}
425
+ for r in t.get("relations") or [] if r.get("column") and r.get("parent_table") in known and r.get("parent_column")],
426
+ **({"duplicate_share": float(t["duplicate_share"]), "duplicate_basis": t.get("duplicate_basis") or ""}
427
+ if t.get("duplicate_share") is not None else {}),
428
+ }, rank["engine"], facts, db_sizes))
429
+ return {
430
+ "schema_version": 1,
431
+ "tool_version": __version__,
432
+ "generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
433
+ "engine": rank["engine"],
434
+ "engine_version": rank["engine_version"],
435
+ "confirmed": False,
436
+ "agent": {"runner": runner.name, "model": result.model, "cost_usd": result.cost_usd, **billing(runner),
437
+ "duration_s": result.duration_s, "turns": result.turns, "usage": result.usage},
438
+ "tables": tables,
439
+ }
@@ -0,0 +1,19 @@
1
+ You are classifying the code areas of the repository in the current directory, so that a query-optimization tool can tell production code from tests and one-off scripts. A query that runs on every API request matters far more than one in a script somebody ran once.
2
+
3
+ Below is a list of directories that contain database queries, each with the role a path-based guess gave it, the number of query call sites, and sample files. For each one, decide what the code there really is. Use your read-only tools (Read, Grep, Glob) where the path does not make it obvious: look at a README, the entry file, how it is deployed (Dockerfile, compose, CI, k8s manifests, cron definitions), and whether anything imports it.
4
+
5
+ Roles:
6
+ - `app`: a deployed service that handles requests (an API, a web backend, a gateway).
7
+ - `job`: deployed code that runs repeatedly without a request: workers, queue consumers, workflows, scheduled jobs, sync loops.
8
+ - `script`: run by hand or once: backfills, audits, data fixes, exports, benchmarks, experiments.
9
+ - `migration`: schema or data migrations.
10
+ - `tooling`: developer and operations tooling that is not part of the product: CI helpers, deploy scripts, local dev utilities, examples.
11
+ - `test`: tests, fixtures and test harnesses.
12
+ - `unknown`: you could not tell.
13
+
14
+ A directory called `scripts` that a cron job or a deployed worker runs every hour is `job`, not `script`: say what runs it. A directory named like a product (`apps_legacy/foo`) may be a real deployed service or an abandoned experiment: check.
15
+
16
+ Return one entry for every directory listed, with `path` copied exactly, the `role`, a `description` of at most 15 words saying what the code is and what runs it, and `confidence` (high, medium, low).
17
+
18
+ ## Directories
19
+ {areas}
@@ -0,0 +1,20 @@
1
+ You are proposing faster variants of database statements that production ran, for an automated benchmark. Each statement below is the exact text a {engine} {engine_version} server logged for one query shape of the repository in the current directory (its literals were replaced by the server; CodeCop put the code's own values back and named the rest as parameters). Every variant you propose is run against it on a sandbox with generated data and kept only if it reads meaningfully less and returns the same rows.
2
+
3
+ You have read-only tools (Read, Grep, Glob). The call site named with each statement is where the code builds it, or one of the places when the statement is assembled from pieces. Read it to understand what the statement is for and which of its parts are fixed in code and which are built at run time.
4
+
5
+ ## Rules
6
+ - The baseline is fixed. Never return a changed baseline: production ran it as it is shown. Your variants change the statement or the table, not what the baseline means.
7
+ - Use only syntax, functions and settings that exist in {engine} {engine_version}.
8
+ - Keep every parameter (`{name:Type}`) of the baseline in a rewrite, with the same name and type.
9
+ - Propose at most three variants per statement, the most promising first, and none when nothing plausible would read less. A statement you return with no variant is fine.
10
+ - `same_results`: true only when the variant returns exactly the rows of the baseline for every value of its parameters.
11
+ - `setup_sql`: the statements a variant needs before it runs (an index, a projection, a copy of the table with another key), with table names as shown.
12
+ - `change`: under 80 characters, naming the change. `tradeoffs`: codes from the schema.
13
+
14
+ ## Table definitions (real, read from the database catalog: never change them)
15
+ {tables}
16
+
17
+ ## Statements
18
+ {statements}
19
+
20
+ Return JSON that matches the schema: `candidates`, one entry per statement you have variants for, each with `id` (the statement's id, copied exactly) and `variants`.
@@ -0,0 +1,60 @@
1
+ You are writing a data profile for a benchmark sandbox. A set of candidate queries from the repository in the current directory will be run on a {engine} {engine_version} server filled with generated data. The benchmark is only as good as that data: a filter on a value that matches 0.01% of rows and one that matches 40% get different plans, so the shape of each column matters more than its exact contents.
2
+
3
+ You have read-only tools (Read, Grep, Glob). Use them to find evidence for sizes and distributions: enums and validators, constants, seed files, test factories and fixtures, docs and runbooks, retention and TTL settings, comments about scale, dashboards, and the business domain.
4
+
5
+ ## What to return
6
+ For every table in "Tables" below, return an entry with:
7
+ - `name`: the table name, copied exactly.
8
+ - `rows`: your estimate of the table's row count in production. Give the real figure even when it is very large; the benchmark scales it down itself. Base it on evidence (retention × traffic, tenant counts, comments) and say so in `rows_basis`.
9
+ - `rows_basis`: one or two sentences: the evidence, with file and line, or "guess" when there is none.
10
+ - `rows_confidence`: high, medium or low.
11
+ - `columns`: one entry for every column that any candidate query reads in any way: selects (a `SELECT *` reads every column), filters, joins, groups, sorts or aggregates on; plus the ordering-key and partition-key columns of the table; plus the wide columns described under "Sizes". Other columns are filled with defaults.
12
+
13
+ For each column:
14
+ - `name`: copied exactly from the table definition.
15
+ - `kind`: one of
16
+ - `unique`: every row has its own value (request ids, row ids). Optional `prefix`.
17
+ - `key`: an identifier with a known number of distinct values (tenant_id, user_id, session_id). Give `distinct` (the real production figure) and `distribution` (`uniform`, or `skewed` when a few values own most rows, which is the usual case for tenants, users and keys). Optional `prefix`.
18
+ - `categorical`: a small fixed set (status, kind, provider, boolean flags). Give `values` as a list of value and weight; weights are relative frequencies. Use the real values from the code.
19
+ - `int` or `float`: a numeric measure. Give `min`, `max`, and `distribution` (`uniform` or `skewed` toward the minimum).
20
+ - `timestamp`: a time column. Give `days_back` (how far back the data goes: the retention or TTL) and `distribution` (`uniform`, or `skewed` when recent data dominates). Works for DateTime, Date, and numeric epoch columns.
21
+ - `text`: free text, a JSON blob or any payload that queries only return or measure by size. Give `content`, `typical_bytes` and `large_bytes` (see "Sizes").
22
+ - `constant`: the same value in every row. Give `value`.
23
+ - `expr`: a raw {engine} expression, only when no other kind can express the shape (for example a value derived from another column, or JSON with specific keys that a query extracts). Give `sql`. It may use `number` (the row index) and random functions; give every random call a distinct integer argument such as `rand(101)`.
24
+ - `null_fraction`: share of rows that are NULL, 0 to 1. Only for Nullable columns.
25
+ - `pinned`: values that must exist in the data with a stated share of rows. Every parameter value in "Candidate queries" that is compared with this column must be pinned here, or the benchmark filters on a value that matches nothing. Choose the share a real value of that kind would have: a large tenant might own 0.05 of rows, a typical one 0.001. For a time-window parameter, do not pin: make sure `days_back` covers the window instead.
26
+ - `source`: where the shape came from: file and line of the enum, fixture, doc or comment, or "guess from column name and type".
27
+ - `confidence`: high, medium or low. Low-confidence entries are shown to the developer first for review.
28
+
29
+
30
+ {sizes}
31
+ ## Fixtures: rows that make each query return something
32
+ Columns are generated independently, so pinning a tenant on 5% of rows and a finding id on one row in a million leaves no row with both, and the query returns nothing. A benchmark of an empty result proves nothing. So for every candidate query, and for every table it reads, return a fixture in that table's `fixtures`:
33
+ - `id`: the candidate's finding id (for example "Q-003"). Use the same id in every table that candidate reads. When two candidates share the same parameter values on a table, one fixture with a combined id ("Q-001+Q-002") is enough.
34
+ - `values`: `column` and `value` for every column of this table that the query compares with a parameter by equality or IN, using the candidate's parameter values. All of them are set together on the fixture's rows. Do not list time-window columns or join keys that are not parameters.
35
+ - `share`: the share of the table's rows that carry this combination, as a real application would have it (all rows of one tenant: perhaps 0.02; one request id: close to 0).
36
+ - `min_rows`: the least number of rows that must carry it even after the table is scaled down: 1 for a point lookup, more when the query needs several rows to be meaningful.
37
+ A fixture with the same `id` covers the same row numbers in every table (`number` in an `expr`). So when a query joins two tables on a key that is not a parameter, generate that key in both tables as an `expr` of `number` (for example `toString(reinterpretAsUUID(sipHash128(number)))`, or `intDiv(number, 3)` for three child rows per parent) and the fixture rows of one table join the fixture rows of the other. Check every join and every filter of every candidate this way: after your profile is loaded, each baseline must return at least one row.
38
+ Keep `pinned` for single-column shares as before; fixtures are for combinations.
39
+
40
+ Unused generator fields must be omitted or null.
41
+
42
+ ## Relations: rows that belong to a row of another table
43
+ Columns are generated one at a time, so nothing makes a row agree with the row it belongs to unless you say so. An application never writes a span whose trace belongs to another workspace, and a rewrite that is correct for every row the application can write (`AND spans.workspace_id = traces.workspace_id`) returns different rows on generated data that has such spans: the benchmark then rejects a correct fix. {engine} declares no foreign keys, so this is the only place they come from. For every table return `relations`, one entry for each column that holds the key of a row of another table in "Tables":
44
+ - `column`: the column of this table. `parent_table` and `parent_column`: the table and the column it holds a value of, names copied exactly.
45
+ - `same_as_parent`: the columns of this table that always hold the same value as a column of that parent row, as `column` and `parent_column`: the workspace, tenant or project that is written together with the key (a span's `workspace_id` and `project_id` are its trace's). List one only when the code that writes the row guarantees it: read the INSERT. Use an empty list when there is none.
46
+ - `basis`: where you read it: the join, the INSERT, the model; file and line.
47
+ Every join between two tables in "Tables" on a key of one of them is a relation.
48
+ What the generator does with a relation: a row keeps its own key when the parent row it names exists and agrees on the shared columns; otherwise it is given a parent row that has the row's own value in the first shared column (so a workspace pinned at 5% of the child keeps its 5%: give the parent table the same pinned or fixture value, or no parent has it); when no parent has that value, the row takes the parent's. So the invariant always holds, and a fixture or pinned value on a key or a shared column has to exist in the parent too.
49
+
50
+ ## Rules
51
+ - Related columns must agree. When two tables join on a column, give both sides the same `kind`, `prefix` and `distinct`, so the generated values match. Say which join in `source`.
52
+ - Parameter values in "Candidate queries" are fixed. Shape the data around them; do not change them.
53
+ - Do not invent precision. A guess is fine when labelled as a guess with low confidence.
54
+ - A ReplacingMergeTree table (or another deduplicating engine) holds some rows in more than one version until a background merge removes them; FINAL, argMax and LIMIT 1 BY exist to hide them. Give the table `duplicate_share`: the share of its rows that have such an extra version at any moment, with `duplicate_basis`. Judge it from how the table is written: an append-only log where only retries repeat a row, 0.01 to 0.05; rows that are re-fetched or updated in place (status changes, a sync that re-inserts what it already has), 0.2 to 0.5. Use null for a table whose engine does not deduplicate. Keep the ordering-key columns as unique as they really are: the sandbox writes the extra versions itself.
55
+
56
+ ## Tables
57
+ {tables}
58
+
59
+ ## Candidate queries
60
+ {candidates}
@@ -0,0 +1,68 @@
1
+ You are writing a data profile for a benchmark sandbox. A set of candidate queries from the repository in the current directory will be run on a {engine} {engine_version} server filled with generated data. The benchmark is only as good as that data: the planner chooses between a sequential scan, an index scan and a bitmap scan from the statistics of each column, so a filter on a value that matches 0.01% of rows and one that matches 40% get different plans. The shape of each column matters more than its exact contents.
2
+
3
+ You have read-only tools (Read, Grep, Glob). Use them to find evidence for sizes and distributions: enums and validators, constants, seed files, test factories and fixtures, docs and runbooks, retention jobs, comments about scale, dashboards, and the business domain.
4
+
5
+ ## What to return
6
+ For every table in "Tables" below, return an entry with:
7
+ - `name`: the table name, copied exactly.
8
+ - `rows`: your estimate of the table's row count in production. Give the real figure even when it is very large; the benchmark scales it down itself. Base it on evidence (retention × traffic, tenant counts, comments) and say so in `rows_basis`.
9
+ - `rows_basis`: one or two sentences: the evidence, with file and line, or "guess" when there is none.
10
+ - `rows_confidence`: high, medium or low.
11
+ - `columns`: one entry for every column that any candidate query filters, joins, groups, sorts or aggregates on, plus every column of the primary key, of a unique constraint, of any index, and of the partition key. Columns you do not list are left NULL, or get a neutral value (0, '', now(), an empty object) when they are NOT NULL. Also list every column a candidate selects (a `SELECT *` selects all), and the wide columns described under "Sizes", so that rows have their real width.
12
+
13
+ For each column:
14
+ - `name`: copied exactly from the table definition.
15
+ - `kind`: one of
16
+ - `unique`: every row has its own value (ids, request ids). Optional `prefix`. Use this for a single-column primary key or unique column: uuid, integer and text columns all work.
17
+ - `key`: an identifier with a known number of distinct values (tenant_id, user_id, session_id). Give `distinct` (the real production figure) and `distribution` (`uniform`, or `skewed` when a few values own most rows, which is the usual case for tenants, users and keys). Optional `prefix`.
18
+ - `categorical`: a small fixed set (status, kind, provider, booleans, enum types). Give `values` as a list of value and weight; weights are relative frequencies. Use the real values from the code; for an enum type only its labels are valid.
19
+ - `int` or `float`: a numeric measure. Give `min`, `max`, and `distribution` (`uniform` or `skewed` toward the minimum).
20
+ - `timestamp`: a time column. Give `days_back` (how far back the data goes: the retention) and `distribution` (`uniform`, or `skewed` when recent data dominates). Works for timestamptz, timestamp, date, and numeric epoch-seconds columns.
21
+ - `text`: free text, a JSON blob or any payload that queries only return or measure by size. Give `content`, `typical_bytes` and `large_bytes` (see "Sizes"). A jsonb column gets an object with one string of that size.
22
+ - `constant`: the same value in every row. Give `value`. For jsonb write the JSON text; for an array write a PostgreSQL array literal such as `{a,b}`.
23
+ - `expr`: a raw PostgreSQL expression, only when no other kind can express the shape (a value derived from another column's generator, jsonb with specific keys that a query extracts, an array, a search-text column). Give `sql`. It is evaluated in `SELECT <sql> FROM generate_series(...) AS number`, so it may use `number` (the row index, a bigint starting at 0) and nothing else from the row: it cannot refer to other columns. It is cast to the column's type, and it must not be NULL for a NOT NULL column. `number` is a bigint: a function that takes an integer needs a cast (`repeat(md5(number::text), (number % 4)::int)`, `lpad(x, 8)`, `chr(65 + (number % 26)::int)`). For randomness use a hash of the row number with a seed of your own, for example `hashint8extended(number, 101) & 1023` for an integer in 0..1023: do not use `random()`, so that the data is the same on every run. Examples: `jsonb_build_object('severity', (ARRAY['low','high'])[1 + (hashint8extended(number, 7) & 1)], 'score', number % 100)`, `md5(number::text)`, `number / 3` (three child rows per parent).
24
+ - `null_fraction`: share of rows that are NULL, 0 to 1. Ignored for NOT NULL columns.
25
+ - `pinned`: values that must exist in the data with a stated share of rows. Every parameter value in "Candidate queries" that is compared with this column must be pinned here, or the benchmark filters on a value that matches nothing. Choose the share a real value of that kind would have: a large tenant might own 0.05 of rows, a typical one 0.001. For a time-window parameter, do not pin: make sure `days_back` covers the window instead. For an array parameter (`= ANY({ids:uuid[]})`), pin each element.
26
+ - `source`: where the shape came from: file and line of the enum, fixture, doc or comment, or "guess from column name and type".
27
+ - `confidence`: high, medium or low. Low-confidence entries are shown to the developer first for review.
28
+
29
+ {sizes}
30
+ ## Identity and serial columns
31
+ A `GENERATED … AS IDENTITY` or serial column that you do not list takes its sequence value: 1, 2, 3 … in load order, which is not `number` (that starts at 0) and has gaps where rows were dropped. So whenever such a column is a join key or appears in a query, list it, as `unique` or as an `expr` of `number`: then `number` in a child table's foreign key means the same row as in the parent.
32
+
33
+ ## Uniqueness
34
+ The load uses `ON CONFLICT DO NOTHING`: a row that collides with a primary key or unique index is dropped, silently shrinking the table. So:
35
+ - A single-column primary key or unique column must be `unique` (or an `expr` that is unique per `number`).
36
+ - For a composite unique key, make at least one of its columns `unique`, or derive the columns from `number` so that no two rows agree on all of them (for example `number % 500` and `number / 500`).
37
+ - Never pin a value on, or put a fixture value into, a column that is unique on its own with a share that covers more than one row; give it `min_rows` 1 and a share close to 0.
38
+
39
+ ## Fixtures: rows that make each query return something
40
+ Columns are generated independently, so pinning a tenant on 5% of rows and a finding id on one row in a million leaves no row with both, and the query returns nothing. A benchmark of an empty result proves nothing. So for every candidate query, and for every table it reads, return a fixture in that table's `fixtures`:
41
+ - `id`: the candidate's finding id (for example "Q-003"). Use the same id in every table that candidate reads. When two candidates share the same parameter values on a table, one fixture with a combined id ("Q-001+Q-002") is enough.
42
+ - `values`: `column` and `value` for every column of this table that the query compares with a parameter or a literal by equality, IN or `= ANY`, using the candidate's parameter values (for an array parameter, one of its elements). All of them are set together on the fixture's rows. Do not list time-window columns or join keys that are not parameters. Values are text: a jsonb value is its JSON text, a boolean is true or false, and the value `NULL` makes the column NULL on those rows (for `deleted_at IS NULL`).
43
+ - `share`: the share of the table's rows that carry this whole combination, as a real application would have it (all rows of one tenant, or of one tenant and subscriber pair: perhaps 0.02; one request id: close to 0). The fixture is what gives a multi-column scope its size: two columns pinned at 0.02 each overlap on only 0.0004 of the rows, so a query scoped by tenant and subscriber needs a fixture with those two values and the share the scope really has, in every table the query reads. A share close to 0 is right only when the combination identifies a single row.
44
+ - `min_rows`: the least number of rows that must carry it even after the table is scaled down: 1 for a point lookup, more when the query needs several rows to be meaningful (a page of 50 needs at least 50; an OFFSET 1000 query needs more than 1000).
45
+ A fixture with the same `id` covers the same row numbers in every table (`number` in an `expr`): its first `min_rows` rows are guaranteed in every table, the rest of its share is spread over the table. Tables differ in size, so the guaranteed rows are the ones that join for certain. `min_rows` is per table: the first `min_rows` row numbers of the fixture carry its values in that table. Give a table as many as the query needs there (a page of 20 needs 20 in the table being listed), and only 1 where the query expects a single match per key (a lookup guarded by `HAVING count(DISTINCT …) = 1`, a unique column). So when a query joins two tables on a key that is not a parameter, generate that key in both tables as an `expr` of `number` (for example `md5(number::text)::uuid`, or `number / 3` for three child rows per parent) and the fixture rows of one table join the fixture rows of the other. Check every join and every filter of every candidate this way, including literal conditions such as `status = 'open'` or `deleted_at IS NULL` (keep `null_fraction` and categorical weights compatible with them on the fixture rows: put the literal in the fixture's `values`). After your profile is loaded, each baseline must return at least one row.
46
+ Keep `pinned` for single-column shares as before; fixtures are for combinations.
47
+
48
+ Unused generator fields must be omitted or null.
49
+
50
+ ## Relations: rows that belong to a row of another table
51
+ Columns are generated one at a time, so nothing makes a row agree with the row it belongs to unless you say so. An application never writes a feed whose category belongs to another user, and a rewrite that is correct for every row the application can write (`AND feeds.user_id = categories.user_id`) returns different rows on generated data that has such feeds: the benchmark then rejects a correct fix. So for every table return `relations`, one entry for each column that holds the key of a row of another table in "Tables":
52
+ - `column`: the column of this table. `parent_table` and `parent_column`: the table and the column it holds a value of, names copied exactly.
53
+ - `same_as_parent`: the columns of this table that always hold the same value as a column of that parent row, as `column` and `parent_column`: the denormalised owner or tenant that is written together with the key (a feed's `user_id` is its category's `user_id`; a task's `tenant_id` is its run's). List one only when the code that writes the row guarantees it: read the INSERT or the ORM model. The author of a comment is not the author of its post. Use an empty list when there is none.
54
+ - `basis`: where you read it: the foreign key, the join, the INSERT; file and line.
55
+ A declared `FOREIGN KEY` or `REFERENCES` is applied without being listed; list it when it has `same_as_parent` columns. Also list the keys no constraint declares: every join between two tables in "Tables" on a key of one of them is a relation.
56
+ What the generator does with a relation: a row keeps its own key when the parent row it names exists and agrees on the shared columns; otherwise it is given a parent row that has the row's own value in the first shared column (so a tenant pinned at 5% of the child keeps its 5%: give the parent table the same pinned or fixture value, or no parent has it); when no parent has that value, the row takes the parent's. So the invariant always holds, and a fixture or pinned value on a key or a shared column has to exist in the parent too.
57
+
58
+ ## Rules
59
+ - Related columns must agree. When two tables join on a column, give both sides the same `kind`, `prefix` and `distinct`, so the generated values match. Say which join in `source`.
60
+ - Parameter values in "Candidate queries" are fixed. Shape the data around them; do not change them.
61
+ - Do not invent precision. A guess is fine when labelled as a guess with low confidence.
62
+ - A soft-delete or status column that most queries filter on (`deleted_at IS NULL`, `status = 'active'`) decides whether a partial index pays off: give it the real share.
63
+
64
+ ## Tables
65
+ {tables}
66
+
67
+ ## Candidate queries
68
+ {candidates}