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/definitions.py ADDED
@@ -0,0 +1,457 @@
1
+ """The table definitions a benchmark is built from: one per table, and complete for what its candidates read.
2
+
3
+ The rank agent assembles a definition per batch and trims the columns it does not need for the queries it saw, so
4
+ another batch's candidate can read a column no merged definition has (`column "total_count" does not exist` at
5
+ the baseline). And a definition is a trimmed copy of the real schema: "FKs/indexes omitted" leaves the sandbox
6
+ without the indexes the real database has, and a baseline then reads whole tables the real server reaches through an
7
+ index.
8
+
9
+ So before the sandbox is built:
10
+ - a definition that holds several CREATE TABLE statements is split into one per table (split);
11
+ - every column each candidate and variant reads (sqlglot, through aliases and subqueries) is checked against its
12
+ table's definition; a missing one is taken, with its type, from the repository's own schema that discover parsed
13
+ (inventory `tables`: CREATE TABLE and ALTER TABLE ... ADD COLUMN in migrations, ent's migrate/schema.go, ORM models);
14
+ - a secondary index the repository's schema has and the definition does not is added (PostgreSQL);
15
+ - a candidate whose missing column is in no schema at all is held back (`held_back`: definition_incomplete) with the
16
+ column named, instead of failing on the server.
17
+
18
+ Nothing here needs a database."""
19
+
20
+ from __future__ import annotations
21
+
22
+ import copy
23
+ import re
24
+
25
+ import sqlglot
26
+ from sqlglot import exp
27
+ from sqlglot.optimizer.scope import traverse_scope
28
+
29
+ PARAM = re.compile(r"\{\s*\w+\s*:\s*[^{}]+\}")
30
+ # names a server answers whatever the table: row identity and part columns
31
+ PSEUDO = {"ctid", "xmin", "xmax", "cmin", "cmax", "oid", "tableoid", "_part", "_part_offset", "_partition_id", "_row_exists",
32
+ "_part_index", "_part_uuid", "_partition_value", "_sample_factor", "_block_number", "_block_offset"}
33
+ CREATE_TABLE = re.compile(r"CREATE\s+(?:(?:GLOBAL\s+|LOCAL\s+)?(?:TEMP|TEMPORARY)\s+|UNLOGGED\s+|OR\s+REPLACE\s+)?TABLE\s+"
34
+ r"(?:IF\s+NOT\s+EXISTS\s+)?((?:[`\"]?[\w$]+[`\"]?\.)?[`\"]?[\w$]+[`\"]?)", re.I)
35
+ # Inventory column types from other dialects, as PostgreSQL takes them (the rest are written as they are)
36
+ PG_TYPES = {"datetime": "timestamp", "datetime64": "timestamp", "tinyint": "smallint", "mediumint": "integer", "int": "integer",
37
+ "longtext": "text", "mediumtext": "text", "tinytext": "text", "string": "text", "blob": "bytea", "longblob": "bytea",
38
+ "double": "double precision", "float": "real", "bool": "boolean", "json": "jsonb", "uuid": "uuid"}
39
+ DEFAULT_SETTINGS = {
40
+ # add the secondary indexes the repository's schema has to the agent's definitions (PostgreSQL)
41
+ "add_schema_indexes": True,
42
+ # a unique index added from the schema is built as a plain index: the generated rows are not made unique on its columns
43
+ "schema_unique_as_plain": True,
44
+ }
45
+
46
+
47
+ def settings_of(config: dict | None) -> dict:
48
+ out = dict(DEFAULT_SETTINGS)
49
+ for k, v in (config or {}).items():
50
+ if k in DEFAULT_SETTINGS and isinstance(v, bool):
51
+ out[k] = v
52
+ return out
53
+
54
+
55
+ def _bare(name: str) -> str:
56
+ return (name or "").replace('"', "").replace("`", "").split(".")[-1].lower()
57
+
58
+
59
+ def _statements(script: str, engine: str) -> list[str]:
60
+ from .engines.pg_ddl import split_statements
61
+ return split_statements(script) if engine == "postgres" else [s for s in re.split(r";\s*(?:\n|$)", script) if s.strip()]
62
+
63
+
64
+ # ---- one definition per table --------------------------------------------------------------------------------------
65
+
66
+ def split(definitions: list[dict], engine: str) -> tuple[list[dict], list[str]]:
67
+ """Definitions with one CREATE TABLE each. A script that also creates other tables (the agent's `orders` that
68
+ begins with a two-column `customers`) gives each of them a definition of its own, with the indexes and
69
+ ALTERs that name it; the rest of the script (types, extensions) stays with the table the definition is named for.
70
+ Returns (definitions, notes)."""
71
+ out: list[dict] = []
72
+ notes: list[str] = []
73
+ for d in definitions:
74
+ sql = d.get("create_sql") or ""
75
+ if len(CREATE_TABLE.findall(sql)) < 2:
76
+ out.append(d)
77
+ continue
78
+ own = _bare(d["name"])
79
+ parts: dict[str, list[str]] = {}
80
+ order: list[str] = []
81
+ for stmt in _statements(sql, engine):
82
+ m = CREATE_TABLE.match(stmt.strip())
83
+ target = _bare(m.group(1)) if m else ""
84
+ if not m:
85
+ on = re.search(r"\bON\s+(?:ONLY\s+)?([`\"\w.]+)", stmt, re.I) if re.match(r"\s*CREATE\s+(?:UNIQUE\s+)?INDEX", stmt, re.I) \
86
+ else re.match(r"\s*ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?([`\"\w.]+)", stmt, re.I)
87
+ target = _bare(on.group(1)) if on else own
88
+ if target not in parts:
89
+ parts[target] = []
90
+ order.append(target)
91
+ parts[target].append(stmt.strip())
92
+ if own not in parts:
93
+ out.append(d)
94
+ continue
95
+ for name in order:
96
+ text = ";\n".join(parts[name])
97
+ if name == own:
98
+ out.append({**d, "create_sql": text})
99
+ else:
100
+ out.append({"name": name, "create_sql": text, "inferred": True,
101
+ "basis": f"split from the definition of {d['name']}, which also created it"})
102
+ notes.append(f"{d['name']}: its script also created {', '.join(n for n in order if n != own)}; split into one definition per table")
103
+ return out, notes
104
+
105
+
106
+ # ---- what a statement reads ----------------------------------------------------------------------------------------
107
+
108
+ def _parse(sql: str, engine: str):
109
+ from .scenario_sql import dialect_of
110
+ text = PARAM.sub("NULL", sql or "")
111
+ try:
112
+ return sqlglot.parse_one(text, read=dialect_of(engine))
113
+ except Exception: # a statement the parser does not read is not checked
114
+ return None
115
+
116
+
117
+ CATALOG_PREFIXES = ("system", "information_schema", "pg_catalog")
118
+
119
+
120
+ def tables_without_definition(sql: str, engine: str, defined: set[str]) -> list[str]:
121
+ """The tables a statement reads that no definition in `defined` (bare names) builds: not its own CTEs, not the
122
+ server's catalog (system.*, information_schema.*, pg_*), not a table function. [] when the statement does not parse."""
123
+ tree = _parse(sql, engine)
124
+ if tree is None:
125
+ return []
126
+ ctes = {c.alias_or_name.lower() for c in tree.find_all(exp.CTE)}
127
+ out = []
128
+ for t in tree.find_all(exp.Table):
129
+ name = t.name
130
+ if not name or not isinstance(t.this, exp.Identifier):
131
+ continue # a table function (numbers(10), generate_series(...)), a subquery
132
+ db = (t.db or "").lower()
133
+ if name.lower() in ctes or db in CATALOG_PREFIXES or name.lower().startswith("pg_") or name.lower() in ("one", "numbers", "dual"):
134
+ continue
135
+ if _bare(name) not in defined and name not in out:
136
+ out.append(name)
137
+ return out
138
+
139
+
140
+ def columns_read(sql: str, engine: str) -> tuple[dict[str, set[str]], dict[frozenset, set[str]]] | None:
141
+ """(table -> columns read from it for certain, frozenset(tables) -> unqualified columns read from one of
142
+ them), or None when the statement does not parse. A column named through an alias or a table is that table's; an
143
+ unqualified one belongs to one of the tables of its scope (the parser's scopes are not always right about
144
+ ClickHouse's `LIMIT n BY`, so the caller looks for it in every table of the statement)."""
145
+ tree = _parse(sql, engine)
146
+ if tree is None:
147
+ return None
148
+ sure: dict[str, set[str]] = {}
149
+ either: dict[frozenset, set[str]] = {}
150
+ try:
151
+ scopes = traverse_scope(tree)
152
+ except Exception:
153
+ return None
154
+ # names the statement itself defines (an alias anywhere, a CTE, a lambda's parameter, ClickHouse's `WITH 5 AS n`):
155
+ # an unqualified column by such a name is not read from a table
156
+ named = {a.alias.lower() for a in tree.find_all(exp.Alias) if a.alias}
157
+ named |= {c.alias_or_name.lower() for c in tree.find_all(exp.CTE)}
158
+ # a table's alias (or name) used as a value is the whole row (`to_jsonb(row_data)`, `row_to_json(r)`), not a column
159
+ named |= {t.alias_or_name.lower() for t in tree.find_all(exp.Table) if t.alias_or_name}
160
+ # the columns a set-returning function or a VALUES list names (`unnest(x) AS item(value)`, `(VALUES ...) AS v(id)`),
161
+ # and the alias of a function read as a value (`CROSS JOIN LATERAL jsonb_array_elements_text(f) AS domain`)
162
+ for ta in tree.find_all(exp.TableAlias):
163
+ named |= {c.name.lower() for c in ta.columns if getattr(c, "name", "")}
164
+ if ta.name and not isinstance(ta.parent, exp.Table):
165
+ named.add(ta.name.lower())
166
+ for lam in tree.find_all(exp.Lambda):
167
+ named |= {p.name.lower() for p in lam.expressions if getattr(p, "name", "")}
168
+ for scope in scopes:
169
+ tables = {alias: src for alias, src in scope.sources.items() if isinstance(src, exp.Table)}
170
+ derived = [src for src in scope.sources.values() if not isinstance(src, exp.Table)]
171
+ aliases = set()
172
+ if isinstance(scope.expression, exp.Select):
173
+ aliases = {p.alias_or_name.lower() for p in scope.expression.expressions if isinstance(p, exp.Alias)}
174
+ for col in scope.columns:
175
+ name = col.name
176
+ if not name or name.lower() in PSEUDO or isinstance(col.this, exp.Star) or _in_settings(col):
177
+ continue
178
+ qual = col.table
179
+ if qual:
180
+ src = _find_source(scope, qual)
181
+ if isinstance(src, exp.Table):
182
+ sure.setdefault(_bare(src.name), set()).add(name)
183
+ continue
184
+ if name.lower() in aliases or name.lower() in named:
185
+ continue
186
+ if tables:
187
+ either.setdefault(frozenset(_bare(t.name) for t in tables.values()), set()).add(name)
188
+ return sure, either
189
+
190
+
191
+ def _in_settings(col: exp.Column) -> bool:
192
+ """A name in a SETTINGS clause (ClickHouse `SETTINGS max_threads = 1`) is a setting, not a column."""
193
+ node, parent = col, col.parent
194
+ while parent is not None:
195
+ if isinstance(parent, (exp.Select, exp.Query)):
196
+ return any(node is s or node in (s if isinstance(s, list) else [s]) for s in [parent.args.get("settings") or []])
197
+ if isinstance(parent, exp.SettingsProperty):
198
+ return True
199
+ node, parent = parent, parent.parent
200
+ return False
201
+
202
+
203
+ def _find_source(scope, alias: str):
204
+ s = scope
205
+ while s is not None:
206
+ if alias in s.sources:
207
+ return s.sources[alias]
208
+ s = s.parent
209
+ return None
210
+
211
+
212
+ # ---- definitions completed from the repository's schema ------------------------------------------------------------
213
+
214
+ def _def_columns(d: dict, engine: str) -> tuple[int, dict[str, str]] | None:
215
+ from .rank import _columns
216
+ return _columns(d.get("create_sql") or "", d["name"])
217
+
218
+
219
+ def _schema_tables(inventory: dict | None) -> dict[str, dict]:
220
+ out: dict[str, dict] = {}
221
+ for t in (inventory or {}).get("tables") or []:
222
+ name = _bare(t.get("name") or "")
223
+ if not name or name.startswith("?"):
224
+ continue
225
+ seen = out.get(name)
226
+ if seen is None or (seen.get("test_only") and not t.get("test_only")) or \
227
+ (bool(seen.get("test_only")) == bool(t.get("test_only")) and len(t.get("columns") or []) > len(seen.get("columns") or [])):
228
+ out[name] = t
229
+ return out
230
+
231
+
232
+ def _pg_type(t: str) -> str:
233
+ raw = (t or "").strip()
234
+ base = re.sub(r"\(.*$", "", raw).strip().lower()
235
+ if base in ("nullable", "lowcardinality"):
236
+ inner = re.search(r"\((.*)\)", raw)
237
+ return _pg_type(inner.group(1)) if inner else "text"
238
+ if base in PG_TYPES:
239
+ return PG_TYPES[base]
240
+ if re.fullmatch(r"u?int\d+", base) or base in ("enum8", "enum16"):
241
+ return "bigint" if base.startswith(("u", "int")) else "text"
242
+ if base.startswith(("array", "map", "tuple")):
243
+ return "text"
244
+ return raw or "text"
245
+
246
+
247
+ def _add_columns(create_sql: str, table: str, adds: list[str]) -> str:
248
+ """The script with `adds` (`name type` each) appended to the column list of `table`'s CREATE TABLE."""
249
+ from .rank import _columns
250
+ got = _columns(create_sql, table)
251
+ if got is None:
252
+ return create_sql
253
+ end = got[0]
254
+ return create_sql[:end].rstrip() + "".join(f",\n {a}" for a in adds) + "\n" + create_sql[end:]
255
+
256
+
257
+ def _quote(name: str, engine: str) -> str:
258
+ if re.fullmatch(r"[a-z_][a-z0-9_]*", name):
259
+ return name
260
+ return f"`{name}`" if engine == "clickhouse" else '"' + name.replace('"', '""') + '"'
261
+
262
+
263
+ def _index_statements(d: dict, schema: dict, cfg: dict) -> tuple[list[str], list[str]]:
264
+ """CREATE INDEX statements for the schema's secondary indexes the definition does not have (by name, then by
265
+ columns and predicate), and notes. Indexes on a column the definition lacks are left out."""
266
+ from .engines.pg_ddl import parse_definition
267
+ have = parse_definition(d.get("create_sql") or "", d["name"])
268
+ names = {ix.name.lower() for ix in have.indexes}
269
+ shapes = {(tuple(c.column.lower() for c in ix.columns), (ix.where or "").lower()) for ix in have.indexes}
270
+ cols = {c.lower() for c in have.columns}
271
+ out, notes = [], []
272
+ for ix in schema.get("indexes") or []:
273
+ icols = [c for c in ix.get("columns") or []]
274
+ if not icols or not all(c.lower() in cols for c in icols):
275
+ continue
276
+ if (ix.get("name") or "").lower() in names or (tuple(c.lower() for c in icols), (ix.get("where") or "").lower()) in shapes:
277
+ continue
278
+ unique = bool(ix.get("unique")) and not cfg["schema_unique_as_plain"]
279
+ iname = ix.get("name") or f"{_bare(d['name'])}_{'_'.join(icols)}_idx"
280
+ stmt = (f"CREATE {'UNIQUE ' if unique else ''}INDEX {_quote(iname, 'postgres')} ON {d['name']}"
281
+ + (f" USING {ix['method']}" if ix.get("method") else "")
282
+ + f" ({', '.join(_quote(c, 'postgres') for c in icols)})"
283
+ + (f" INCLUDE ({', '.join(_quote(c, 'postgres') for c in ix['include'])})" if ix.get("include") else "")
284
+ + (f" WHERE {ix['where']}" if ix.get("where") else ""))
285
+ out.append(stmt)
286
+ if ix.get("unique") and not unique:
287
+ notes.append(f"{iname} is unique in the schema; added as a plain index (the generated rows are not made unique on it)")
288
+ return out, notes
289
+
290
+
291
+ def complete(rank: dict, inventory: dict | None, settings: dict | None = None) -> tuple[dict, dict]:
292
+ """(rank with complete definitions, report). The report: {split, columns_added: [{table, column, type, from}],
293
+ indexes_added: [{table, index, from}], held_back: [{finding, reason, detail}], notes}. Candidates are not changed
294
+ except for `held_back` on the ones that still read a column no definition has."""
295
+ cfg = settings_of(settings)
296
+ engine = rank.get("engine") or "clickhouse"
297
+ out = copy.deepcopy(rank)
298
+ report: dict = {"split": [], "columns_added": [], "indexes_added": [], "held_back": [], "notes": []}
299
+ defs, report["split"] = split(out.get("table_definitions") or [], engine)
300
+ # a definition split out of another's script is kept only when no definition of its own exists
301
+ seen: dict[str, dict] = {}
302
+ for d in defs:
303
+ key = _bare(d["name"])
304
+ if key in seen and d.get("basis", "").startswith("split from"):
305
+ continue
306
+ if key in seen and seen[key].get("basis", "").startswith("split from"):
307
+ seen[key] = d
308
+ continue
309
+ seen.setdefault(key, d)
310
+ defs = list(seen.values())
311
+ by_name = {_bare(d["name"]): d for d in defs}
312
+ schema = _schema_tables(inventory)
313
+ added_to: dict[str, list[str]] = {}
314
+
315
+ def have(table: str) -> set[str]:
316
+ d = by_name.get(table)
317
+ got = _def_columns(d, engine) if d else None
318
+ return {c.lower() for c in (got[1] if got else {})} | {a.split(" ", 1)[0].lower().strip('"`') for a in added_to.get(table, [])}
319
+
320
+ def recover(table: str, column: str) -> bool:
321
+ t = schema.get(table)
322
+ col = next((c for c in (t or {}).get("columns") or [] if c.get("name", "").lower() == column.lower()), None)
323
+ if col is None or table not in by_name or by_name[table].get("source") == "real catalog":
324
+ return False # the real catalog's definition is exact: a column it lacks is not added
325
+ typ = _pg_type(col.get("type") or "") if engine == "postgres" else (col.get("type") or "String")
326
+ added_to.setdefault(table, []).append(f"{_quote(col['name'], engine)} {typ}")
327
+ report["columns_added"].append({"table": by_name[table]["name"], "column": col["name"], "type": typ,
328
+ "from": (t.get("defined_at") or [""])[0]})
329
+ return True
330
+
331
+ def unknown(text: str, setup: list[str]) -> list[str]:
332
+ """The columns `text` (and the indexes `setup` builds) read that no definition has, after recovery."""
333
+ missing: list[str] = []
334
+ got = columns_read(text, engine)
335
+ if got is not None:
336
+ sure, either = got
337
+ for table, cols in sure.items():
338
+ if table not in by_name:
339
+ continue # a table with no definition: the build says so, not this check
340
+ for col in sorted(cols):
341
+ if col.lower() not in have(table) and not recover(table, col):
342
+ missing.append(f"{table}.{col}")
343
+ every = {t for t in sure} | {t for ts in either for t in ts}
344
+ for tables, cols in either.items():
345
+ known = [t for t in tables if t in by_name]
346
+ if len(known) != len(tables) or any(t not in by_name for t in every):
347
+ continue # a table with no definition: the column may be its
348
+ for col in sorted(cols):
349
+ if any(col.lower() in have(t) for t in every):
350
+ continue # a column of some table the statement reads: not missing
351
+ if not any(recover(t, col) for t in sorted(known) if col.lower() in
352
+ {x.get("name", "").lower() for x in (schema.get(t) or {}).get("columns") or []}):
353
+ missing.append(f"{'|'.join(sorted(known))}.{col}")
354
+ for stmt in setup if engine == "postgres" else []:
355
+ from .engines.pg_ddl import parse_index
356
+ ix = parse_index(stmt)
357
+ if ix is None or _bare(ix.table) not in by_name:
358
+ continue
359
+ table = _bare(ix.table)
360
+ for col in [c.column for c in ix.columns if c.column] + list(ix.include):
361
+ if col.lower() not in have(table) and not recover(table, col):
362
+ missing.append(f"{table}.{col}")
363
+ return list(dict.fromkeys(missing))
364
+
365
+ def say(missing: list[str], what: str) -> str:
366
+ tables = sorted({m.split(".")[0] for m in missing})
367
+ known = [t for t in tables if t in schema]
368
+ return (f"{what} reads {', '.join(missing)}, which neither the agent's definition nor the repository's schema has "
369
+ f"({'the schema defines ' + ', '.join(known) + ' without it' if known else 'the repository defines no such table'})")
370
+
371
+ for c in out.get("candidates") or []:
372
+ # recomputed every time: a candidate kept from an earlier rank must not keep a hold its definitions no longer give
373
+ c.pop("held_back", None)
374
+ for v in c.get("variants") or []:
375
+ v.pop("held_back", None)
376
+ absent = tables_without_definition(c.get("baseline_sql") or "", engine, set(by_name))
377
+ if absent and inventory:
378
+ # a table no pull has and no agent defined, that the repository defines (migrations, DDL files, models):
379
+ # built from the repository's definition (schema only), instead of holding the candidate back
380
+ from .loopschema import definition as repo_definition
381
+ for t in absent:
382
+ d = repo_definition(inventory, t, engine)
383
+ if d and _bare(d["name"]) not in by_name:
384
+ defs.append(d)
385
+ by_name[_bare(d["name"])] = d
386
+ report.setdefault("tables_from_repository", []).append({"table": d["name"], "basis": d.get("basis", "")})
387
+ absent = tables_without_definition(c.get("baseline_sql") or "", engine, set(by_name))
388
+ if absent:
389
+ # a table the statement reads that no definition builds: the baseline would fail with "relation does not
390
+ # exist" on the server; said here, before anything is built
391
+ detail = (f"the query reads {', '.join(absent)}, which no table definition builds (neither the agent's definitions "
392
+ "nor the pulled catalog has it)")
393
+ c["held_back"] = {"reason": "definition_incomplete", "detail": detail, "tables": absent}
394
+ report["held_back"].append({"finding": c.get("finding"), "reason": "definition_incomplete", "detail": detail})
395
+ continue
396
+ missing = unknown(c.get("baseline_sql") or "", [])
397
+ if missing:
398
+ detail = say(missing, "the query")
399
+ c["held_back"] = {"reason": "definition_incomplete", "detail": detail, "columns": missing}
400
+ report["held_back"].append({"finding": c.get("finding"), "reason": "definition_incomplete", "detail": detail})
401
+ for i, v in enumerate(c.get("variants") or []):
402
+ vmissing = unknown(v.get("sql") or "", v.get("setup_sql") or [])
403
+ if vmissing:
404
+ # the variant is not run: its baseline still is (bench_candidate records it as not run, with this)
405
+ v["held_back"] = {"reason": "definition_incomplete", "detail": say(vmissing, f"variant {i + 1}"), "columns": vmissing}
406
+ report.setdefault("variants_held_back", []).append({"finding": c.get("finding"), "variant": i + 1,
407
+ "detail": v["held_back"]["detail"]})
408
+ for table, adds in added_to.items():
409
+ d = by_name[table]
410
+ d["create_sql"] = _add_columns(d["create_sql"], d["name"], list(dict.fromkeys(adds)))
411
+ d["inferred"] = True
412
+ d["basis"] = (d.get("basis", "") + f" Completed: {len(set(adds))} column(s) a candidate reads, from the repository's schema.").strip()
413
+ if engine == "postgres" and cfg["add_schema_indexes"]:
414
+ used = {_bare(t) for c in out.get("candidates") or [] for t in c.get("tables") or []}
415
+ for table in sorted(used):
416
+ d, t = by_name.get(table), schema.get(table)
417
+ if d is None or t is None or d.get("source") == "real catalog":
418
+ continue
419
+ stmts, notes = _index_statements(d, t, cfg)
420
+ if stmts:
421
+ d["create_sql"] = d["create_sql"].rstrip().rstrip(";") + ";\n" + ";\n".join(stmts)
422
+ d["basis"] = (d.get("basis", "") + f" Completed: {len(stmts)} index(es) from the repository's schema.").strip()
423
+ report["indexes_added"] += [{"table": d["name"], "index": s, "from": (t.get("defined_at") or [""])[0]} for s in stmts]
424
+ report["notes"] += notes
425
+ if engine == "postgres":
426
+ _add_functions(out.get("candidates") or [], by_name, inventory, report)
427
+ out["table_definitions"] = defs
428
+ return out, {k: v for k, v in report.items() if v}
429
+
430
+
431
+ FUNCTION_CALL = re.compile(r'((?:"?\w+"?\.)?"?\w+"?)\s*\(')
432
+
433
+
434
+ def _add_functions(candidates: list[dict], by_name: dict[str, dict], inventory: dict | None, report: dict) -> None:
435
+ """The repository's own LANGUAGE sql functions a candidate calls (inventory `sql_functions`, discover), created on the
436
+ sandbox before the table that comes first in the candidate: without them the baseline failed with "function ... does
437
+ not exist" (an expression index on one was left out too). Only schema-qualified calls or names the repository
438
+ defines once; the definition goes ahead of the table's script, its schema created first."""
439
+ funcs = {f["name"]: f for f in (inventory or {}).get("sql_functions") or [] if f.get("name") and f.get("sql")}
440
+ if not funcs:
441
+ return
442
+ for c in candidates:
443
+ texts = [c.get("baseline_sql") or ""] + [v.get("sql") or "" for v in c.get("variants") or []]
444
+ called = {m.group(1).replace('"', "").lower() for t in texts for m in FUNCTION_CALL.finditer(t)}
445
+ host = next((by_name[_bare(t)] for t in c.get("tables") or [] if _bare(t) in by_name), None)
446
+ wanted = [funcs[n] for n in sorted(called) if n in funcs
447
+ and " ".join(funcs[n]["sql"].split())[:200] not in " ".join(((host or {}).get("create_sql") or "").split())]
448
+ if not wanted or host is None:
449
+ continue
450
+ lead = []
451
+ for f in wanted:
452
+ if "." in f["name"]:
453
+ lead.append(f'CREATE SCHEMA IF NOT EXISTS "{f["name"].split(".")[0]}"')
454
+ lead.append(f["sql"].rstrip().rstrip(";"))
455
+ report.setdefault("functions_added", []).append({"table": host["name"], "function": f["name"], "from": f["defined_at"]})
456
+ host["create_sql"] = ";\n".join(lead) + ";\n" + host["create_sql"]
457
+ host["basis"] = (host.get("basis", "") + f" Completed: {len(wanted)} SQL function(s) from the repository.").strip()