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,26 @@
1
+ ## Sizes: how many bytes a value takes
2
+ Row width decides what a query costs as much as row count does. A query that selects a 30 kB payload reads thousands of times more bytes per row than one that selects an id, and the engine fits fewer wide rows into each unit it reads (a granule, a page), so even the number of rows read changes. A sandbox whose payload columns are 40 bytes wide measures a different query.
3
+
4
+ For every column you list whose value is a string, JSON, an array or a blob, give:
5
+ - `content`: what the value is. One of `id`, `uuid` (36 characters), `hash` (hex digest), `email`, `url`, `name`, `enum`, `json` (a serialized object or event), `tool_call` (arguments or result of a tool or function call), `llm_messages` (a list of chat messages: a prompt with its history), `llm_response` (one model reply), `text` (prose), `html`, `code`, `base64`, `ciphertext` (encrypted or random bytes: does not compress), `user_agent`, `ip`, `path`, `other`.
6
+ - `typical_bytes`: the size of an ordinary value in bytes (the median), as stored, uncompressed.
7
+ - `large_bytes`: the size of a large value (about the 99th percentile). For payloads this is usually 10 to 100 times the typical size.
8
+ - `size_basis`: one sentence: the evidence, with file and line, or "general knowledge of <what>".
9
+ - `size_confidence`: high, medium or low.
10
+ Give them for kinds `key`, `unique` and `categorical` too when the value is a string (a tenant id that is a uuid: content `uuid`, 36). For kind `text` they replace `avg_len`.
11
+
12
+ How to estimate, in this order:
13
+ 1. The write path. Find where the row is written: the INSERT site, the struct or model that maps to the column, the producer of the message that becomes the row. See what is serialized into the column (a whole request body? a list of messages? one field?) and whether the writer truncates or caps it. A limit in the writer bounds the stored size. A truncation in a reader (`[:1500]` before display) says nothing about what is stored.
14
+ 2. If nothing in this repository writes the table (another service does), say so in `size_basis` and estimate from what the value is.
15
+ 3. What such values weigh in practice. Reference points, uncompressed:
16
+ - uuid 36; sha256 hex 64; email 20 to 30; URL 60 to 150; user agent 90 to 150; enum label 5 to 20; IPv4 text 7 to 15.
17
+ - tool-call arguments: typical 100 to 500 bytes, large 5 kB.
18
+ - tool or function results (file contents, search results, API responses, query results): typical 2 to 10 kB, large 200 kB to several MB. Their mean is often 20 to 50 kB because of the tail.
19
+ - a chat request with its message history, system prompt and tool definitions: typical 5 to 30 kB, large 200 kB to 1 MB.
20
+ - one model reply: typical 0.5 to 2 kB, large 20 kB.
21
+ - a raw event or webhook body as JSON: typical 1 to 5 kB, large 50 kB. An audit or compliance event with embedded content: 2 to 10 kB.
22
+ - a preview or title cut by the writer: the cut length is the large size; the typical size is well below it.
23
+ - HTML of a page 30 to 100 kB; a stack trace 1 to 5 kB; an encrypted header set or token 100 bytes to 1 kB.
24
+ `typical_bytes` is the median, not the mean: the generator adds the long tail up to `large_bytes` itself, which makes the mean two to four times the median. So do not put the tail into the typical size. The two usual mistakes are (a) a typical size taken from the top of a range, which the tail then multiplied, and (b) optional columns: a JSON or text column with a DEFAULT of `''`, `'{}'` or `'[]'`, or one filled only for some kinds of rows (errors, attachments, annotations, findings), is empty in most rows. Give such a column the size of its empty value as typical (0 to 2 bytes) and the filled size as large. Columns that every row fills (the request, the response, the raw event) are the ones that carry the row's weight: spend your effort on those. Sizes of ids and enums are known exactly; state them with high confidence.
25
+
26
+ Also list, as kind `text` with its sizes, every other column of the table that you expect to average more than about 200 bytes, even when no candidate reads it: it is part of the row, and the row's width decides how many rows the engine reads together.
@@ -0,0 +1,69 @@
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} database filled with generated data. The benchmark is only as good as that data: how many pages a SCAN or a SEARCH reads depends on how many rows match each value and how wide the rows are, so a filter on a value that matches 0.01% of rows and one that matches 40% read very different amounts. 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 take their DEFAULT), or get a neutral value (0, '', the current time) 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 (an INTEGER PRIMARY KEY is the rowid) or unique column.
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; a boolean is 0 or 1.
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). A column with INTEGER affinity gets epoch seconds; any other gets 'YYYY-MM-DD HH:MM:SS' text, as CURRENT_TIMESTAMP writes it. When the application stores another form (epoch milliseconds, RFC 3339 with a zone), use `expr`.
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`. For a JSON column write the JSON text.
23
+ - `expr`: a raw SQLite expression, only when no other kind can express the shape (a value derived from another column's generator, JSON with specific keys that a query extracts, a time in another format). Give `sql`. It is evaluated in `SELECT <sql> FROM <a row per number>`, so it may use `number` (the row index, an integer starting at 0) and nothing else from the row: it cannot refer to other columns. It is not cast (the column's affinity applies), and it must not be NULL for a NOT NULL column. For randomness use `codecop_hash(number, <seed of your own>)` (a non-negative integer) or `codecop_u(number, <seed>)` (a number in [0, 1)): do not use `random()`, so that the data is the same on every run. Examples: `json_object('severity', CASE codecop_hash(number, 7) % 2 WHEN 0 THEN 'low' ELSE 'high' END, 'score', number % 100)`, `'file-' || (number % 5000) || '.go'`, `number / 3` (three child rows per parent), `(unixepoch() - codecop_hash(number, 9) % 2592000) * 1000` (epoch milliseconds over 30 days).
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 a list in `IN (...)`, 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
+ ## The rowid
31
+ An `INTEGER PRIMARY KEY` (AUTOINCREMENT or not) that you do not list is numbered by SQLite: 1, 2, 3 … in load order, which is not `number` (that starts at 0). 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 `INSERT OR IGNORE`: 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 JSON value is its JSON text, a boolean is 1 or 0, 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 `'k' || number`, 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
+ - What the generator does with `relations` in SQLite: it does not apply them yet (the benchmark says so per table); give both sides of a join the same `kind`, `prefix` and `distinct` so the values match.
64
+
65
+ ## Tables
66
+ {tables}
67
+
68
+ ## Candidate queries
69
+ {candidates}
@@ -0,0 +1,84 @@
1
+ You are reviewing the database queries of the repository in the current directory to find the ones most worth optimizing. Your output feeds an automated benchmark: every candidate you return will be run on a sandbox {engine} {engine_version} server filled with generated data, and each variant you propose will be measured against the original. A candidate that cannot be run is wasted, so precision matters more than volume.
2
+
3
+ You have read-only tools (Read, Grep, Glob). Use them: the shortlist below came from a static scan that sees one call site at a time. It does not know what calls the function, how often, or what the run-time parts of a query contain.
4
+
5
+ ## Scope
6
+ - Engine: {engine} {engine_version}. Use only syntax, functions and settings that exist in that version.
7
+ - Read queries only. Every candidate is a SELECT. Do not propose changes to INSERT, UPDATE or DELETE statements.
8
+ - Return every query worth benchmarking as a candidate, best first: there is no limit on their number. Return none when none is worth it. Do not pad.
9
+
10
+ ## What makes a good candidate
11
+ Prefer queries where a real cost is likely and a concrete fix can be tested:
12
+ - On a hot path: a request handler, a dashboard endpoint, a loop, a periodic job. Read the callers to find out; say what you found.
13
+ - Reading far more than needed: a filter that does not use the table's ordering key, FINAL on a large table, SELECT * or unused columns on a wide table, no partition pruning, an unbounded result, OFFSET paging deep into a table, a leading-wildcard LIKE, one query per item in a loop, a join with the large table on the wrong side.
14
+ - On a table that is plausibly large (logs, events, per-request rows) rather than a small config table. A full scan of a 200-row config table is not a finding.
15
+ Skip one-off scripts, migrations, admin tools and tests unless nothing better exists.
16
+
17
+ ## Value first
18
+ Rank by what a fix is worth, which depends on where the query runs:
19
+ 1. A request path: an API endpoint or anything a user waits on. Highest value, because it runs per request.
20
+ 2. Recurring background work: workflows, activities, queue consumers, scheduled jobs, sync loops. High value: steady load even though nobody waits.
21
+ 3. Startup code, admin pages and internal tools. Low.
22
+ 4. One-off scripts, backfills and migrations. Lowest: a slow one costs minutes once. Return one only when it clearly runs on a schedule (then it is a job, and say what runs it).
23
+ 5. Tests are never candidates.
24
+ Each shortlist entry shows the static scan's guess at its role and the entry points that reach it. That guess follows function names through the code and can be wrong or empty: verify it by reading the callers, and correct it in `origin`.
25
+
26
+ ## What to return for each candidate
27
+ - `id`: the shortlist id, copied exactly.
28
+ - `title`: under 80 characters, naming the problem (for example "FINAL scan of events per dashboard request").
29
+ - `causes`: one to four reasons this query reads more than it needs, most important first. The product shows these as labelled chips, never as prose, so each is a code plus a few words:
30
+ - `code`: key_not_used (a filter cannot use the sorting key), no_partition_pruning, final_merge (FINAL on a large table), wide_read (SELECT * or unused columns), heavy_columns (large text/JSON columns read or decompressed for every row), per_row_function (JSON extraction, regex or casts evaluated per row), full_sort (sorts everything to return a few rows), offset_paging, leading_wildcard, in_loop (one query per item), unbounded_result, repeated_read (the same data read twice), join_order, skip_index_ineffective (an existing skip index that cannot prune), cross_tenant_scan, other.
31
+ - `column`: the column or expression concerned, or "".
32
+ - `detail`: at most 60 characters, a fact not a sentence (for example "range filter, not in ORDER BY" or "12 JSONExtractString calls").
33
+ - `origin`: where this query runs from, after you have read the callers.
34
+ - `role`: app, job, script, migration, tooling, test or unknown: the kind of code it lives in.
35
+ - `kind`: http, workflow, activity, job, consumer, cli, main or unknown: the kind of entry point that reaches it most often.
36
+ - `entry_points`: the entry points you confirmed reach it, most important first, at most five: `kind`, `name` (for HTTP "METHOD /path", otherwise the workflow, job or command name), and the `file` and `line` where it is registered or defined.
37
+ - `path`: the call chain from the entry point's handler down to the function holding the query, in call order, at most six steps: `symbol`, `file`, `line`. Only functions you read. Empty when the handler itself holds the query or you could not trace it.
38
+ - `frequency`: how often it runs, as fields. `trigger`: per_request, per_item (once per item of a batch or loop over data), scheduled, on_event (queue message, webhook), startup, manual or unknown. `every_seconds`: the interval for scheduled work, else 0. `in_loop`: true when the call sits in a loop that can run it several times per trigger. `cache_seconds`: lifetime of a cache in front of it, 0 when there is none. `note`: at most 40 characters for a limit that matters (for example "up to 10 pages"), else "".
39
+ - `severity`: high, medium or low. Your estimate of impact before measurement, weighing the cost of one execution by how often it runs.
40
+ - `confidence`: high, medium or low. How sure you are the problem is real.
41
+ - `baseline_sql`: the query exactly as the application would send it, runnable as written on the sandbox. Resolve every run-time part marked «…» by reading the code: table names, column lists, optional WHERE clauses (choose the most common real combination and say which in `assumptions`). Keep driver parameters as ClickHouse parameters `{name:Type}`; rewrite `%(name)s` and `?` binds to that form. Do not include a trailing semicolon or a FORMAT clause.
42
+ - `assumptions`: zero to four short labels (at most 80 characters each) for the choices you made to build the baseline: the branch or optional filters chosen, and anything you could not determine. Labels, not sentences.
43
+ - `params`: a value for every `{name:Type}` parameter in the baseline and the variants, as strings. Choose realistic values (a tenant id, a time window like the application's default). The data generator will make sure these values exist in the sandbox data, so prefer values the code or tests show.
44
+ - `tables`: every table the baseline or a variant reads.
45
+ - `variants`: one to three fixes to benchmark. For each:
46
+ - `kind`: one of rewrite, skip_index, projection, ordering_key, materialized_view, column_type.
47
+ - `change`: at most 80 characters naming the change (for example "Re-key as (tenant_id, started_at, request_id)" or "minmax skip index on timestamp").
48
+ - `tradeoffs`: what the change costs, any of: extra_storage, slower_inserts, backfill (existing data must be rewritten or materialized), code_change, schema_migration, changes_results, needs_setting.
49
+ - `sql`: the query to run for this variant. For a rewrite this is the rewritten query. For a schema change it is usually the unchanged baseline (the schema does the work); give it anyway.
50
+ - `setup_sql`: statements to run on the sandbox before measuring: for example `ALTER TABLE t ADD INDEX …` followed by `ALTER TABLE t MATERIALIZE INDEX …`, or `ALTER TABLE t ADD PROJECTION …` and `MATERIALIZE PROJECTION`. Empty for a pure rewrite. For ordering_key and column_type, never alter the original table: create a second table named `<table>__codecop_variant` with the new key or types, fill it with `INSERT INTO … SELECT * FROM <table>`, and point `sql` at it. Each variant is measured on its own and its setup is undone afterwards, so do not rely on another variant's setup.
51
+ - `same_results`: true when the variant must return exactly the same rows as the baseline; false when it is intentionally approximate or changes semantics (then include changes_results in `tradeoffs`).
52
+ A rewrite must be a real change to the query text. Rank a schema change above a rewrite when both would help, because a schema change cannot alter results.
53
+
54
+ ## Table definitions
55
+ The sandbox builds its tables from what you return in `table_definitions`, so return one entry for every table that any candidate or variant reads (except the ones under "Table definitions already established"):
56
+ - `name`: the table name as the queries use it.
57
+ - `create_sql`: a complete CREATE TABLE statement for {engine} that the sandbox can run as written: real name, every column with its type, engine, PARTITION BY, ORDER BY, and any skip indexes and projections the real table has. Replace Replicated*, Shared* and Distributed engines with their plain MergeTree-family equivalent. Leave out TTL clauses.
58
+ - `inferred`: false when you copied the definition from a CREATE TABLE in the code; true when you had to assemble it from other evidence.
59
+ - `basis`: where each part came from (file and line), and which parts are guesses.
60
+ The static scan found the definitions listed under "Table definitions found by the static scan". Start from those, but verify them against the code: some have a name that is built at run time, and some are test scaffolding that differs from the real table. When a table is not listed, find it in the code (a CREATE TABLE built with a run-time name, an INSERT column list, a row struct, a migration). Do not return a candidate whose tables you can neither find nor assemble.
61
+
62
+ ## No prose
63
+ Every text field you return is rendered as a short label in a diagram. Keep to the length limits; do not write sentences or explanations anywhere.
64
+
65
+ ## Honesty
66
+ - If you could not read a caller, leave `entry_points` and `path` empty and set `trigger` to unknown rather than asserting a hot path.
67
+ - If a run-time part could not be resolved, do not invent it: drop the candidate, or state the assumption in `assumptions`.
68
+ - `rejected` is for shortlist entries you judged not worth benchmarking; give the id, a `code` (small_table, already_cheap, duplicate, one_off, unresolved_sql, other_engine, cached or other) and a `detail` of at most 80 characters. Every shortlist entry you do not return as a candidate must appear in `rejected`, each exactly once, so the developer can see what happened to every query that was examined.
69
+ - `already_cheap` is a claim about every table the query reads, and it is checked afterwards against the definitions: use it only when each table is reached through a prefix of its sorting key (and its partition key, when it has one) with values that are parameters or literals. A partitioned table that gets its partition key only through a join, or not at all, is not cheap by inspection.
70
+
71
+ ## Table definitions found by the static scan
72
+ {tables}
73
+
74
+ ## Table definitions already established
75
+ The definitions below are settled: either read from the real database's catalog (marked `real`, with the table's real size: these are exact) or returned by earlier passes over this repository. Build every candidate that reads these tables on them: same table name, same columns, same types. Do not return a listed table again in `table_definitions`, with one exception: when a query you return needs a column the listed definition lacks, return that table once more with the listed definition unchanged plus the missing columns (never change the type or the key of what is listed). Otherwise return only definitions for tables that are not listed here.
76
+
77
+ {known_definitions}
78
+
79
+ ## Shortlist ({shortlist_note})
80
+ An entry with a `measured (...)` line was matched to the real database's query log: those executions, bytes read and timings are facts about production, and they outrank any guess about how hot a path is. An entry without that line was not seen in the log window or could not be matched; that is not evidence that it is cold.
81
+
82
+ Each entry: id, location, enclosing function, the static scan's role and entry points, how the SQL was resolved, heuristic flags, how many other call sites send the same SQL (and where from: one fix covers all of them), tables, and the SQL template. «…» marks a part only known at run time.
83
+
84
+ {shortlist}
@@ -0,0 +1,96 @@
1
+ You are reviewing the database queries of the repository in the current directory to find the ones most worth optimizing. Your output feeds an automated benchmark: every candidate you return will be run on a sandbox {engine} {engine_version} server filled with generated data, and each variant you propose will be measured against the original. A candidate that cannot be run is wasted, so precision matters more than volume.
2
+
3
+ You have read-only tools (Read, Grep, Glob). Use them: the shortlist below came from a static scan that sees one call site at a time. It does not know what calls the function, how often, which indexes exist, or what the run-time parts of a query contain.
4
+
5
+ ## Scope
6
+ - Engine: {engine} {engine_version}. Use only syntax, functions and settings that exist in that version. The sandbox is a bare server: the contrib extensions that ship with PostgreSQL (pg_trgm, btree_gin, btree_gist, citext, uuid-ossp, pgcrypto, hstore, ltree, unaccent) can be created; pgvector, PostGIS, TimescaleDB, pg_partman and other third-party extensions cannot. Do not return a candidate or a variant that needs one of those.
7
+ - Read queries only. Every candidate is a SELECT (a WITH ... SELECT counts). Do not propose changes to INSERT, UPDATE or DELETE statements, and no SELECT ... FOR UPDATE.
8
+ - A shortlist entry whose SQL is plainly for another database (ClickHouse functions, FINAL, `{name:Type}` binds) is mislabelled: reject it with `other_engine`.
9
+ - Return every query worth benchmarking as a candidate, best first: there is no limit on their number. Return none when none is worth it. Do not pad.
10
+
11
+ ## What makes a good candidate
12
+ Prefer queries where a real cost is likely and a concrete fix can be tested:
13
+ - On a hot path: a request handler, a dashboard endpoint, a loop, a periodic job. Read the callers to find out; say what you found.
14
+ - Reading far more than needed. In PostgreSQL that is: a sequential scan of a large table because no index matches the filter; an index that exists but cannot be used because the column is wrapped in a function or a cast, compared with a different type, or matched with a leading-wildcard LIKE/ILIKE; an index used for one filter while the others throw most fetched rows away; a join whose inner side has no index on the join key; ORDER BY ... LIMIT that sorts the whole match because no index returns rows in that order; OFFSET paging deep into a result; an exact count(*) over a large set for a page counter; a correlated subquery run once per row; SELECT * or large jsonb/text columns fetched and not used; jsonb or array containment without a GIN index; OR across columns that no single index covers; one query per item in a loop.
15
+ - On a table that is plausibly large (events, logs, findings, per-request or per-user rows) rather than a small config table. A sequential scan of a 200-row table is the right plan, not a finding.
16
+ Skip one-off scripts, migrations, admin tools and tests unless nothing better exists.
17
+
18
+ Before you return a candidate, establish which indexes its tables really have. Start from "Index statements found by text search" below, then read the migrations in order: an index can be added, replaced or dropped in a later file, and ORM models can declare indexes too. A proposed index that already exists is the worst possible result: the benchmark would report a win that production already has. When you cannot establish the indexes of a table, do not use it.
19
+
20
+ ## Value first
21
+ Rank by what a fix is worth, which depends on where the query runs:
22
+ 1. A request path: an API endpoint or anything a user waits on. Highest value, because it runs per request.
23
+ 2. Recurring background work: workflows, activities, queue consumers, scheduled jobs, sync loops. High value: steady load even though nobody waits.
24
+ 3. Startup code, admin pages and internal tools. Low.
25
+ 4. One-off scripts, backfills and migrations. Lowest: a slow one costs minutes once. Return one only when it clearly runs on a schedule (then it is a job, and say what runs it).
26
+ 5. Tests are never candidates.
27
+ Each shortlist entry shows the static scan's guess at its role and the entry points that reach it. That guess follows function names through the code and can be wrong or empty: verify it by reading the callers, and correct it in `origin`.
28
+
29
+ ## What to return for each candidate
30
+ - `id`: the shortlist id, copied exactly.
31
+ - `title`: under 80 characters, naming the problem (for example "Seq scan of findings per dashboard request").
32
+ - `causes`: one to four reasons this query reads more than it needs, most important first. The product shows these as labelled chips, never as prose, so each is a code plus a few words:
33
+ - `code`: seq_scan (large table scanned because no index matches the filter), non_sargable (an index exists but a function, cast, type mismatch or expression on the column stops it being used), missing_join_index (the join key of the inner table has no index), partial_index_match (an index serves one filter; the rest are applied to fetched rows), not_covering (an index scan that visits the heap for columns a covering index could hold), or_conditions (OR across columns defeats a single index), count_scan (exact count over a large set), correlated_subquery (a subquery executed per outer row), no_gin_index (jsonb, array or full-text predicate without a GIN/GiST index), wide_read (SELECT * or unused columns), heavy_columns (large text/jsonb columns detoasted for every row), per_row_function (jsonb extraction, regex or casts evaluated per row), full_sort (sorts the whole match to return a few rows: no index in ORDER BY order), offset_paging, leading_wildcard (LIKE/ILIKE '%x'), in_loop (one query per item), unbounded_result, repeated_read (the same data read twice), join_order, no_partition_pruning, cross_tenant_scan, other.
34
+ - `column`: the column or expression concerned, or "".
35
+ - `detail`: at most 60 characters, a fact not a sentence (for example "no index on (tenant_id, created_at)" or "lower(email) vs index on email").
36
+ - `origin`: where this query runs from, after you have read the callers.
37
+ - `role`: app, job, script, migration, tooling, test or unknown: the kind of code it lives in.
38
+ - `kind`: http, workflow, activity, job, consumer, cli, main or unknown: the kind of entry point that reaches it most often.
39
+ - `entry_points`: the entry points you confirmed reach it, most important first, at most five: `kind`, `name` (for HTTP "METHOD /path", otherwise the workflow, job or command name), and the `file` and `line` where it is registered or defined.
40
+ - `path`: the call chain from the entry point's handler down to the function holding the query, in call order, at most six steps: `symbol`, `file`, `line`. Only functions you read. Empty when the handler itself holds the query or you could not trace it.
41
+ - `frequency`: how often it runs, as fields. `trigger`: per_request, per_item (once per item of a batch or loop over data), scheduled, on_event (queue message, webhook), startup, manual or unknown. `every_seconds`: the interval for scheduled work, else 0. `in_loop`: true when the call sits in a loop that can run it several times per trigger. `cache_seconds`: lifetime of a cache in front of it, 0 when there is none. `note`: at most 40 characters for a limit that matters (for example "up to 10 pages"), else "".
42
+ - `severity`: high, medium or low. Your estimate of impact before measurement, weighing the cost of one execution by how often it runs.
43
+ - `confidence`: high, medium or low. How sure you are the problem is real.
44
+ - `baseline_sql`: the query exactly as the application would send it, runnable as written on the sandbox. Resolve every run-time part marked «…» by reading the code: table names, column lists, optional WHERE clauses (choose the most common real combination and say which in `assumptions`). Write every bind parameter as `{name:type}` with a PostgreSQL type: rewrite `$1`, `?`, `:name`, `@name` and `%s` binds to that form, for example `{tenant_id:uuid}`, `{since:timestamptz}`, `{limit:int}`, `{ids:uuid[]}` (used as `= ANY({ids:uuid[]})`), `{q:text}`. Use the type of the column it is compared with, exactly as the application binds it: when the code binds a text value against a uuid column, keep that, because the mismatch is the finding. Do not include a trailing semicolon.
45
+ - `assumptions`: zero to four short labels (at most 80 characters each) for the choices you made to build the baseline: the branch or optional filters chosen, and anything you could not determine. Labels, not sentences.
46
+ - `params`: a value for every `{name:type}` parameter in the baseline and the variants, as strings. An array is a PostgreSQL array literal such as `{a,b,c}`. Choose realistic values (a tenant id, a time window like the application's default, a page size the code uses). The data generator will make sure these values exist in the sandbox data, so prefer values the code or tests show. A timestamp parameter is a fixed value: the data is generated relative to the moment of the run, so write time windows relative to now() in the SQL when the application does, and otherwise say in `assumptions` which window the value stands for.
47
+ - `tables`: every table the baseline or a variant reads, named as in `table_definitions`.
48
+ - `variants`: one to three fixes to benchmark. For each:
49
+ - `kind`: one of
50
+ - `rewrite`: the query text changes (keyset instead of OFFSET, EXISTS instead of IN or count, a sargable predicate, fewer columns, a join or LATERAL instead of a correlated subquery, UNION ALL instead of OR, one batched query instead of one per item).
51
+ - `index`: a new index: btree (single or composite, equality columns first, then the range or sort column), partial (`WHERE`), covering (`INCLUDE`), expression, GIN (jsonb, arrays, trigram search), BRIN (append-only time columns on very large tables).
52
+ - `materialized_view`: a precomputed result the query reads instead.
53
+ - `column_type`: a column stored as a better type (uuid or timestamptz instead of text, an extracted jsonb field as a real column).
54
+ - `partitioning`: the table declared PARTITION BY range, list or hash so that the filter prunes partitions.
55
+ - `change`: at most 80 characters naming the change (for example "Index on (tenant_id, created_at DESC)" or "Keyset paging on (created_at, id)").
56
+ - `tradeoffs`: what the change costs, any of: extra_storage, slower_inserts (every index and materialized view slows writes), backfill (existing data must be rewritten or the view refreshed), code_change, schema_migration, changes_results, needs_setting.
57
+ - `sql`: the query to run for this variant. For a rewrite this is the rewritten query. For an index it is the unchanged baseline (the planner picks the index up); give it anyway.
58
+ - `setup_sql`: statements to run on the sandbox before measuring, one statement per entry, for example `CREATE INDEX codecop_findings_tenant_created ON findings (tenant_id, created_at DESC)`. Empty for a pure rewrite. Name everything you create with a `codecop_` prefix or a `__codecop_variant` suffix. Never alter or drop the original table or its existing indexes. For column_type and partitioning, create a second table named `<table>__codecop_variant` with the new types or `PARTITION BY` clause, create its partitions, fill it with `INSERT INTO … SELECT … FROM <table>`, give it the same indexes as the original, and point `sql` at it. For materialized_view, `CREATE MATERIALIZED VIEW codecop_… AS …` plus any index it needs. The sandbox runs ANALYZE (and VACUUM on new tables) after the setup; do not add those. Do not use CONCURRENTLY. Each variant is measured on its own and everything its setup created is dropped afterwards, so do not rely on another variant's setup.
59
+ - `same_results`: true when the variant must return exactly the same rows as the baseline; false when it is intentionally approximate or changes semantics (then include changes_results in `tradeoffs`). A batched query that replaces a per-item query returns different rows: false.
60
+ A rewrite must be a real change to the query text. Rank a schema change above a rewrite when both would help, because a schema change cannot alter results. The benchmark judges a variant by buffers touched and rows scanned, not by time: a variant that only saves CPU (a cheaper expression, a smaller sort) will measure as no change, so prefer fixes that make the query read less.
61
+
62
+ ## Table definitions
63
+ The sandbox builds its tables from what you return in `table_definitions`, so return one entry for every table that any candidate or variant reads (except the ones under "Table definitions already established"):
64
+ - `name`: the table name as the queries use it, with its schema when the queries qualify it.
65
+ - `create_sql`: a script for {engine} that the sandbox can run as written, statements separated by `;`: first any `CREATE TYPE … AS ENUM` the table needs, then one complete `CREATE TABLE` with the real name, every column with its type, defaults, NOT NULL, the primary key and unique constraints, then one `CREATE INDEX` statement for every index the real table has, with the real index names. For a partitioned table include `PARTITION BY` and a handful of representative partitions that cover the data (the generated timestamps run from `days_back` days ago to now). Apply every later migration: added, renamed and dropped columns and indexes. Keep every foreign key (`REFERENCES`, `FOREIGN KEY`, or `ALTER TABLE … ADD FOREIGN KEY` as a statement of the script) and every CHECK constraint the real table declares: the sandbox does not create them, it reads them, so that a generated row points at an existing parent row and stays inside what a CHECK allows. Leave out triggers, policies, grants, comments, and anything from an extension the sandbox cannot create.
66
+ - `inferred`: false when you copied the definition from migrations or schema files in the code; true when you had to assemble it from other evidence (an ORM model, a struct, INSERT column lists).
67
+ - `basis`: where each part came from (file and line), and which parts are guesses. Name the files the indexes came from.
68
+ The static scan found the definitions listed under "Table definitions found by the static scan" and the index statements under "Index statements found by text search". Start from those, but verify them against the code: some are test scaffolding that differs from the real table, and a later migration may have changed them. When a table is not listed, find it in the code. Do not return a candidate whose tables you can neither find nor assemble.
69
+
70
+ ## No prose
71
+ Every text field you return is rendered as a short label in a diagram. Keep to the length limits; do not write sentences or explanations anywhere.
72
+
73
+ ## Honesty
74
+ - If you could not read a caller, leave `entry_points` and `path` empty and set `trigger` to unknown rather than asserting a hot path.
75
+ - If a run-time part could not be resolved, do not invent it: drop the candidate, or state the assumption in `assumptions`.
76
+ - `rejected` is for shortlist entries you judged not worth benchmarking; give the id, a `code` (small_table, already_cheap (an index already serves it), duplicate, one_off, unresolved_sql, other_engine, cached or other) and a `detail` of at most 80 characters. Every shortlist entry you do not return as a candidate must appear in `rejected`, each exactly once, so the developer can see what happened to every query that was examined.
77
+ - `already_cheap` is a claim about every table the query reads, and it is checked afterwards against the definitions: use it only when each table is reached by a whole unique key or a selective index prefix whose values are parameters or literals. It does not hold by inspection when a partitioned table gets its partition key only through a join (no partition can be ruled out when the query is planned), when a join gives a table two or more columns that different indexes start with (which index runs depends on statistics, not on the query), or when a composite key is entered through a short prefix. Such a query on a large table is a candidate: return it with the index or the rewrite that removes the doubt.
78
+
79
+ ## Table definitions found by the static scan
80
+ {tables}
81
+
82
+ ## Index statements found by text search
83
+ Verify these: the search sees one statement at a time and cannot tell whether a later migration dropped or replaced an index.
84
+ {context}
85
+
86
+ ## Table definitions already established
87
+ The definitions below are settled: either read from the real database's catalog (marked `real`, with the table's real size: these are exact) or returned by earlier passes over this repository. Build every candidate that reads these tables on them: same table name, same columns, same types, same indexes. Do not return a listed table again in `table_definitions`, with one exception: when a query you return needs a column the listed definition lacks, or you found an index of the real table that the listed script lacks, return that table once more with the listed script unchanged plus the missing columns and `CREATE INDEX` statements (never change the type, the key or an index of what is listed). Otherwise return only definitions for tables that are not listed here.
88
+
89
+ {known_definitions}
90
+
91
+ ## Shortlist ({shortlist_note})
92
+ An entry with a `measured (...)` line was matched to the real database's query log: those executions, bytes read and timings are facts about production, and they outrank any guess about how hot a path is. An entry without that line was not seen in the log window or could not be matched; that is not evidence that it is cold.
93
+
94
+ Each entry: id, location, enclosing function, the static scan's role and entry points, how the SQL was resolved, heuristic flags, how many other call sites send the same SQL (and where from: one fix covers all of them), tables (the scan also lists CTE and function names here), and the SQL template. «…» marks a part only known at run time.
95
+
96
+ {shortlist}
@@ -0,0 +1,94 @@
1
+ You are reviewing the database queries of the repository in the current directory to find the ones most worth optimizing. Your output feeds an automated benchmark: every candidate you return will be run on a sandbox {engine} {engine_version} database (a file opened in-process, as the application opens it) filled with generated data, and each variant you propose will be measured against the original. A candidate that cannot be run is wasted, so precision matters more than volume.
2
+
3
+ You have read-only tools (Read, Grep, Glob). Use them: the shortlist below came from a static scan that sees one call site at a time. It does not know what calls the function, how often, which indexes exist, or what the run-time parts of a query contain.
4
+
5
+ ## Scope
6
+ - Engine: {engine} {engine_version}, the library the benchmark runs on. Use only syntax and functions SQLite has (window functions, json_each/json_extract, FTS5 and the math functions are there; loadable extensions such as sqlite-vec or spatialite are not). Do not return a candidate or a variant that needs an extension.
7
+ - Read queries only. Every candidate is a SELECT (a WITH ... SELECT counts). Do not propose changes to INSERT, UPDATE or DELETE statements.
8
+ - A shortlist entry whose SQL is plainly for another database (PostgreSQL casts `::`, ILIKE, `DISTINCT ON`, jsonb operators, ClickHouse functions, FINAL) is mislabelled: reject it with `other_engine`.
9
+ - Return every query worth benchmarking as a candidate, best first: there is no limit on their number. Return none when none is worth it. Do not pad.
10
+
11
+ ## What makes a good candidate
12
+ Prefer queries where a real cost is likely and a concrete fix can be tested:
13
+ - On a hot path: a request handler, a dashboard endpoint, a loop, a periodic job. Read the callers to find out; say what you found.
14
+ - Reading far more than needed. In SQLite that is: a SCAN of a large table because no index matches the filter (EXPLAIN QUERY PLAN says SCAN, not SEARCH); an index that exists but cannot be used because the column is wrapped in a function (lower(), date(), json_extract()), compared with a value of another affinity, or matched with a leading-wildcard LIKE; an index used for one filter while the others throw most rows away; a join whose inner side has no index on the join key (SQLite then builds an AUTOMATIC INDEX on every run); ORDER BY ... LIMIT that sorts the whole match in a TEMP B-TREE because no index returns rows in that order; OFFSET paging; count(*) over a large set; a correlated subquery run once per row; SELECT * or large TEXT/BLOB columns read and not used; OR across columns that no single index covers; one query per item in a loop (in SQLite each statement costs no network round trip, but N statements each prepare, plan and walk the B-tree again).
15
+ - On a table that is plausibly large (events, logs, findings, per-request or per-user rows) rather than a small config table. A sequential scan of a 200-row table is the right plan, not a finding.
16
+ Skip one-off scripts, migrations, admin tools and tests unless nothing better exists.
17
+
18
+ Before you return a candidate, establish which indexes its tables really have. Start from "Index statements found by text search" below, then read the migrations in order: an index can be added, replaced or dropped in a later file, and ORM models can declare indexes too. A proposed index that already exists is the worst possible result: the benchmark would report a win that production already has. When you cannot establish the indexes of a table, do not use it.
19
+
20
+ ## Value first
21
+ Rank by what a fix is worth, which depends on where the query runs:
22
+ 1. A request path: an API endpoint or anything a user waits on. Highest value, because it runs per request.
23
+ 2. Recurring background work: workflows, activities, queue consumers, scheduled jobs, sync loops. High value: steady load even though nobody waits.
24
+ 3. Startup code, admin pages and internal tools. Low.
25
+ 4. One-off scripts, backfills and migrations. Lowest: a slow one costs minutes once. Return one only when it clearly runs on a schedule (then it is a job, and say what runs it).
26
+ 5. Tests are never candidates.
27
+ Each shortlist entry shows the static scan's guess at its role and the entry points that reach it. That guess follows function names through the code and can be wrong or empty: verify it by reading the callers, and correct it in `origin`.
28
+
29
+ ## What to return for each candidate
30
+ - `id`: the shortlist id, copied exactly.
31
+ - `title`: under 80 characters, naming the problem (for example "Seq scan of findings per dashboard request").
32
+ - `causes`: one to four reasons this query reads more than it needs, most important first. The product shows these as labelled chips, never as prose, so each is a code plus a few words:
33
+ - `code`: full_scan (large table scanned because no index matches the filter), no_usable_index (an index exists but serves none of the filters), temp_btree_sort (the match is sorted in a temp B-tree to return a few rows), automatic_index (SQLite builds an index on every run because a join key has none), non_sargable (a function, a value of another affinity or an expression on the column stops an index being used), not_covering (an index search that reads the table row for columns a covering index could hold), or_conditions (OR across columns defeats a single index), count_scan (count over a large set), correlated_subquery (a subquery executed per outer row), wide_read (SELECT * or unused columns), heavy_columns (large TEXT or BLOB columns read for every row, often from overflow pages), per_row_function (json_extract, regexp or casts evaluated per row), full_sort (sorts the whole match to return a few rows: no index in ORDER BY order), offset_paging, leading_wildcard (LIKE/ILIKE '%x'), in_loop (one query per item), unbounded_result, repeated_read (the same data read twice), join_order, no_partition_pruning, cross_tenant_scan, other.
34
+ - `column`: the column or expression concerned, or "".
35
+ - `detail`: at most 60 characters, a fact not a sentence (for example "no index on (repo_id, path)" or "lower(email) vs index on email").
36
+ - `origin`: where this query runs from, after you have read the callers.
37
+ - `role`: app, job, script, migration, tooling, test or unknown: the kind of code it lives in.
38
+ - `kind`: http, workflow, activity, job, consumer, cli, main or unknown: the kind of entry point that reaches it most often.
39
+ - `entry_points`: the entry points you confirmed reach it, most important first, at most five: `kind`, `name` (for HTTP "METHOD /path", otherwise the workflow, job or command name), and the `file` and `line` where it is registered or defined.
40
+ - `path`: the call chain from the entry point's handler down to the function holding the query, in call order, at most six steps: `symbol`, `file`, `line`. Only functions you read. Empty when the handler itself holds the query or you could not trace it.
41
+ - `frequency`: how often it runs, as fields. `trigger`: per_request, per_item (once per item of a batch or loop over data), scheduled, on_event (queue message, webhook), startup, manual or unknown. `every_seconds`: the interval for scheduled work, else 0. `in_loop`: true when the call sits in a loop that can run it several times per trigger. `cache_seconds`: lifetime of a cache in front of it, 0 when there is none. `note`: at most 40 characters for a limit that matters (for example "up to 10 pages"), else "".
42
+ - `severity`: high, medium or low. Your estimate of impact before measurement, weighing the cost of one execution by how often it runs.
43
+ - `confidence`: high, medium or low. How sure you are the problem is real.
44
+ - `baseline_sql`: the query exactly as the application would send it, runnable as written on the sandbox. Resolve every run-time part marked «…» by reading the code: table names, column lists, optional WHERE clauses (choose the most common real combination and say which in `assumptions`). Write every bind parameter as `{name:type}` with the declared type of the column it is compared with (INTEGER, TEXT, REAL, BLOB, or the type the CREATE TABLE writes, such as DATETIME): rewrite `?`, `?1`, `:name`, `@name` and `$name` binds to that form, for example `{repo_id:INTEGER}`, `{path:TEXT}`, `{limit:INTEGER}`. A number is bound bare and anything else as a quoted string, as a driver binds it; when the code binds a text value against an INTEGER column, keep that, because the mismatch is the finding. A list the code expands into `IN (?, ?, ...)` is written with literal values. Do not include a trailing semicolon.
45
+ - `assumptions`: zero to four short labels (at most 80 characters each) for the choices you made to build the baseline: the branch or optional filters chosen, and anything you could not determine. Labels, not sentences.
46
+ - `params`: a value for every `{name:type}` parameter in the baseline and the variants, as strings. Choose realistic values (a tenant id, a time window like the application's default, a page size the code uses). The data generator will make sure these values exist in the sandbox data, so prefer values the code or tests show. A timestamp parameter is a fixed value: the data is generated relative to the moment of the run, so write time windows relative to 'now' (datetime('now', '-1 day')) in the SQL when the application does, and otherwise say in `assumptions` which window the value stands for.
47
+ - `tables`: every table the baseline or a variant reads, named as in `table_definitions`.
48
+ - `variants`: one to three fixes to benchmark. For each:
49
+ - `kind`: one of
50
+ - `rewrite`: the query text changes (keyset instead of OFFSET, EXISTS instead of IN or count, a sargable predicate, fewer columns, a join instead of a correlated subquery, UNION ALL instead of OR, one batched query instead of one per item).
51
+ - `index`: a new index: single or composite (equality columns first, then the range or sort column), partial (`WHERE`), covering (the selected columns added at the end of the key: SQLite has no INCLUDE), expression (`lower(email)`, `json_extract(data, '$.k')`).
52
+ - `column_type`: a column stored differently (an extracted JSON field as a real column, a generated column with an index).
53
+ - `change`: at most 80 characters naming the change (for example "Index on (tenant_id, created_at DESC)" or "Keyset paging on (created_at, id)").
54
+ - `tradeoffs`: what the change costs, any of: extra_storage, slower_inserts (every index and materialized view slows writes), backfill (existing data must be rewritten or the view refreshed), code_change, schema_migration, changes_results, needs_setting.
55
+ - `sql`: the query to run for this variant. For a rewrite this is the rewritten query. For an index it is the unchanged baseline (the planner picks the index up); give it anyway.
56
+ - `setup_sql`: statements to run on the sandbox before measuring, one statement per entry, for example `CREATE INDEX codecop_findings_tenant_created ON findings (tenant_id, created_at DESC)`. Empty for a pure rewrite. Name everything you create with a `codecop_` prefix or a `__codecop_variant` suffix. Never alter or drop the original table or its existing indexes. For column_type, create a second table named `<table>__codecop_variant` with the new columns, fill it with `INSERT INTO … SELECT … FROM <table>`, give it the same indexes as the original, and point `sql` at it. The sandbox does not run ANALYZE (most applications never do); do not add it unless the application runs it, and then say so. Each variant is measured on its own and everything its setup created is dropped afterwards, so do not rely on another variant's setup.
57
+ - `same_results`: true when the variant must return exactly the same rows as the baseline; false when it is intentionally approximate or changes semantics (then include changes_results in `tradeoffs`). A batched query that replaces a per-item query returns different rows: false.
58
+ A rewrite must be a real change to the query text. Rank a schema change above a rewrite when both would help, because a schema change cannot alter results. The benchmark judges a variant by the pages it asks SQLite's pager for (and states the rows full scans step over), not by time: a variant that only saves CPU (a cheaper expression, a smaller sort) will measure as no change, so prefer fixes that make the query read less.
59
+
60
+ ## Table definitions
61
+ The sandbox builds its tables from what you return in `table_definitions`, so return one entry for every table that any candidate or variant reads (except the ones under "Table definitions already established"):
62
+ - `name`: the table name as the queries use it, with its schema when the queries qualify it.
63
+ - `create_sql`: a script for {engine} that the sandbox can run as written, statements separated by `;`: one complete `CREATE TABLE` with the real name, every column with its declared type, defaults, NOT NULL, the primary key (an `INTEGER PRIMARY KEY` is the rowid), unique constraints, WITHOUT ROWID or STRICT when the real table has them, then one `CREATE INDEX` statement for every index the real table has, with the real index names (SQLite schemas are often created in code strings: read them there). Apply every later `ALTER TABLE … ADD COLUMN` and every index the code creates later. Keep foreign keys and CHECK constraints as written: the sandbox leaves them out and reads them. Leave out triggers.
64
+ - `inferred`: false when you copied the definition from migrations or schema files in the code; true when you had to assemble it from other evidence (an ORM model, a struct, INSERT column lists).
65
+ - `basis`: where each part came from (file and line), and which parts are guesses. Name the files the indexes came from.
66
+ The static scan found the definitions listed under "Table definitions found by the static scan" and the index statements under "Index statements found by text search". Start from those, but verify them against the code: some are test scaffolding that differs from the real table, and a later migration may have changed them. When a table is not listed, find it in the code. Do not return a candidate whose tables you can neither find nor assemble.
67
+
68
+ ## No prose
69
+ Every text field you return is rendered as a short label in a diagram. Keep to the length limits; do not write sentences or explanations anywhere.
70
+
71
+ ## Honesty
72
+ - If you could not read a caller, leave `entry_points` and `path` empty and set `trigger` to unknown rather than asserting a hot path.
73
+ - If a run-time part could not be resolved, do not invent it: drop the candidate, or state the assumption in `assumptions`.
74
+ - `rejected` is for shortlist entries you judged not worth benchmarking; give the id, a `code` (small_table, already_cheap (an index already serves it), duplicate, one_off, unresolved_sql, other_engine, cached or other) and a `detail` of at most 80 characters. Every shortlist entry you do not return as a candidate must appear in `rejected`, each exactly once, so the developer can see what happened to every query that was examined.
75
+ - `already_cheap` is a claim about every table the query reads, and it is checked afterwards against the definitions: use it only when each table is reached by a whole unique key or a selective index prefix whose values are parameters or literals. It does not hold by inspection when a partitioned table gets its partition key only through a join (no partition can be ruled out when the query is planned), when a join gives a table two or more columns that different indexes start with (which index runs depends on statistics, not on the query), or when a composite key is entered through a short prefix. Such a query on a large table is a candidate: return it with the index or the rewrite that removes the doubt.
76
+
77
+ ## Table definitions found by the static scan
78
+ {tables}
79
+
80
+ ## Index statements found by text search
81
+ Verify these: the search sees one statement at a time and cannot tell whether a later migration dropped or replaced an index.
82
+ {context}
83
+
84
+ ## Table definitions already established
85
+ The definitions below are settled: either read from the real database's catalog (marked `real`, with the table's real size: these are exact) or returned by earlier passes over this repository. Build every candidate that reads these tables on them: same table name, same columns, same types, same indexes. Do not return a listed table again in `table_definitions`, with one exception: when a query you return needs a column the listed definition lacks, or you found an index of the real table that the listed script lacks, return that table once more with the listed script unchanged plus the missing columns and `CREATE INDEX` statements (never change the type, the key or an index of what is listed). Otherwise return only definitions for tables that are not listed here.
86
+
87
+ {known_definitions}
88
+
89
+ ## Shortlist ({shortlist_note})
90
+ An entry with a `measured (...)` line was matched to the real database's query log: those executions, bytes read and timings are facts about production, and they outrank any guess about how hot a path is. An entry without that line was not seen in the log window or could not be matched; that is not evidence that it is cold.
91
+
92
+ Each entry: id, location, enclosing function, the static scan's role and entry points, how the SQL was resolved, heuristic flags, how many other call sites send the same SQL (and where from: one fix covers all of them), tables (the scan also lists CTE and function names here), and the SQL template. «…» marks a part only known at run time.
93
+
94
+ {shortlist}
@@ -0,0 +1,20 @@
1
+ You are proposing variants of database statements for an automated benchmark. Each statement below was found by a rule that recognises a known kind of waste in dashboard and analytics systems; the rule could not write the variant itself, and what is asked is given with each statement, with the evidence that made it a candidate. The statements run on {engine} {engine_version}. Every variant you propose is run against the statement 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 sends it; read it to see what the statement is for, which columns the code uses and where its values come from.
4
+
5
+ ## Rules
6
+ - The baseline is fixed. Never return a changed baseline. 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 that answers what is asked would return the same rows. 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. A variant that returns fewer columns (what the code uses) is `same_results: false`.
11
+ - `setup_sql`: the statements a variant needs before it runs (an index, a projection), with table names as shown.
12
+ - `change`: under 80 characters, naming the change. `tradeoffs`: codes from the schema.
13
+
14
+ ## Table definitions (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 after ###, copied exactly) and `variants`.