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.
- codecop/__init__.py +7 -0
- codecop/access.py +140 -0
- codecop/access_postgres.py +284 -0
- codecop/advisor.py +1512 -0
- codecop/advisor_bench.py +493 -0
- codecop/advisor_ch.py +2080 -0
- codecop/advisor_view.py +381 -0
- codecop/advisors.py +184 -0
- codecop/agent.py +221 -0
- codecop/agentfacts.py +745 -0
- codecop/apply/__init__.py +327 -0
- codecop/apply/check.py +344 -0
- codecop/apply/cli.py +162 -0
- codecop/apply/clickhouse.py +379 -0
- codecop/apply/common.py +238 -0
- codecop/apply/html.py +264 -0
- codecop/apply/patch.py +213 -0
- codecop/apply/postgres.py +102 -0
- codecop/apply/trial.py +166 -0
- codecop/assemble.py +104 -0
- codecop/baseline.py +1043 -0
- codecop/bench.py +2464 -0
- codecop/blockers.py +935 -0
- codecop/budget.py +980 -0
- codecop/catalog_profile.py +525 -0
- codecop/changed.py +261 -0
- codecop/cicmd.py +1002 -0
- codecop/cli.py +5421 -0
- codecop/client.py +729 -0
- codecop/coverage.py +1067 -0
- codecop/coverage_reasons.py +116 -0
- codecop/crashlog.py +70 -0
- codecop/datagen.py +766 -0
- codecop/datagen_postgres.py +630 -0
- codecop/datagen_sqlite.py +323 -0
- codecop/dbcli.py +885 -0
- codecop/definitions.py +457 -0
- codecop/discover/__init__.py +702 -0
- codecop/discover/arms.py +160 -0
- codecop/discover/base.py +234 -0
- codecop/discover/dialect.py +296 -0
- codecop/discover/elixir.py +64 -0
- codecop/discover/engine_go.py +320 -0
- codecop/discover/go.py +1947 -0
- codecop/discover/java.py +1528 -0
- codecop/discover/loops.py +1671 -0
- codecop/discover/named_go.py +258 -0
- codecop/discover/origins.py +4565 -0
- codecop/discover/origins_ts.py +1584 -0
- codecop/discover/orm_django.py +2772 -0
- codecop/discover/orm_django_models.py +814 -0
- codecop/discover/orm_django_sql.py +662 -0
- codecop/discover/orm_ent.py +565 -0
- codecop/discover/orm_ex_ecto.py +2138 -0
- codecop/discover/orm_go.py +2134 -0
- codecop/discover/orm_go_bun.py +602 -0
- codecop/discover/orm_go_run.py +636 -0
- codecop/discover/orm_go_types.py +1082 -0
- codecop/discover/orm_java.py +1450 -0
- codecop/discover/orm_jdbi.py +743 -0
- codecop/discover/orm_jooq.py +806 -0
- codecop/discover/orm_jpa.py +1307 -0
- codecop/discover/orm_mybatis.py +730 -0
- codecop/discover/orm_py.py +557 -0
- codecop/discover/orm_py_peewee.py +1266 -0
- codecop/discover/orm_py_prisma.py +298 -0
- codecop/discover/orm_rb_activerecord.py +1906 -0
- codecop/discover/orm_rust.py +1248 -0
- codecop/discover/orm_rust_seaorm.py +734 -0
- codecop/discover/orm_sqlalchemy.py +2475 -0
- codecop/discover/orm_stats.py +307 -0
- codecop/discover/orm_tables.py +29 -0
- codecop/discover/orm_ts.py +503 -0
- codecop/discover/orm_ts_drizzle.py +697 -0
- codecop/discover/orm_ts_knex.py +1117 -0
- codecop/discover/orm_ts_kysely.py +861 -0
- codecop/discover/orm_ts_prisma.py +1045 -0
- codecop/discover/orm_ts_schema.py +169 -0
- codecop/discover/orm_ts_sequelize.py +1401 -0
- codecop/discover/orm_ts_typeorm.py +1067 -0
- codecop/discover/probes.py +323 -0
- codecop/discover/python.py +595 -0
- codecop/discover/ruby.py +793 -0
- codecop/discover/rust.py +2378 -0
- codecop/discover/schema.py +520 -0
- codecop/discover/schema_ent.py +145 -0
- codecop/discover/schema_ts.py +420 -0
- codecop/discover/tsresolve.py +257 -0
- codecop/discover/typescript.py +1728 -0
- codecop/discover/xml_mapper.py +526 -0
- codecop/engines/__init__.py +515 -0
- codecop/engines/base.py +498 -0
- codecop/engines/clickhouse.py +1558 -0
- codecop/engines/pg_ddl.py +444 -0
- codecop/engines/pg_hints.py +137 -0
- codecop/engines/postgres.py +1060 -0
- codecop/engines/sqlite.py +742 -0
- codecop/families/__init__.py +3 -0
- codecop/families/build.py +280 -0
- codecop/families/cli.py +177 -0
- codecop/families/coverage_hook.py +62 -0
- codecop/families/driver.py +221 -0
- codecop/families/goslice.py +229 -0
- codecop/families/goslice_tool/go.mod +3 -0
- codecop/families/goslice_tool/main.go +403 -0
- codecop/families/holes.py +451 -0
- codecop/families/images/Dockerfile.go +5 -0
- codecop/families/images/Dockerfile.python +4 -0
- codecop/families/images/Dockerfile.rust +4 -0
- codecop/families/isolate.py +171 -0
- codecop/families/locate.py +270 -0
- codecop/families/model.py +301 -0
- codecop/families/plangate.py +271 -0
- codecop/families/tagpatch.py +174 -0
- codecop/fidelity.py +671 -0
- codecop/fixgroups.py +130 -0
- codecop/formerly.py +91 -0
- codecop/grantscript.py +254 -0
- codecop/groupbench.py +1375 -0
- codecop/groups.py +594 -0
- codecop/groups_view.py +186 -0
- codecop/heat.py +1405 -0
- codecop/heatcli.py +219 -0
- codecop/joins.py +1749 -0
- codecop/joins_view.py +127 -0
- codecop/kinds/__init__.py +507 -0
- codecop/kinds/calls/__init__.py +501 -0
- codecop/kinds/calls/extract.py +1097 -0
- codecop/kinds/calls/harness.py +408 -0
- codecop/kinds/calls/measure.py +342 -0
- codecop/kinds/calls/rules.py +139 -0
- codecop/kinds/calls/runners/RunCalls.java +167 -0
- codecop/kinds/calls/runners/run_go.go +141 -0
- codecop/kinds/calls/runners/run_node.js +186 -0
- codecop/kinds/calls/runners/run_python.py +319 -0
- codecop/kinds/calls/runners/run_rust.rs +200 -0
- codecop/kinds/calls/standin.py +340 -0
- codecop/kinds/pipeline.py +288 -0
- codecop/kinds/regex/__init__.py +1167 -0
- codecop/kinds/regex/engines/RegexHarness.java +129 -0
- codecop/kinds/regex/engines/run_go.go +294 -0
- codecop/kinds/regex/engines/run_node.js +99 -0
- codecop/kinds/regex/engines/run_python.py +295 -0
- codecop/kinds/regex/engines/run_rust.rs +149 -0
- codecop/kinds/regex/extract.py +1438 -0
- codecop/kinds/regex/harness.py +235 -0
- codecop/kinds/regex/measure.py +270 -0
- codecop/kinds/regex/shapes.py +418 -0
- codecop/kinds/regex/syntax.py +1721 -0
- codecop/kinds/testkind.py +107 -0
- codecop/kinds/transaction/__init__.py +228 -0
- codecop/kinds/transaction/bind.py +355 -0
- codecop/kinds/transaction/measure.py +264 -0
- codecop/kinds/transaction/plan.py +462 -0
- codecop/kinds/transaction/rules.py +540 -0
- codecop/kinds/transaction/sandbox.py +94 -0
- codecop/kinds/transaction/scenarios.py +520 -0
- codecop/kinds/transaction/schedule.py +483 -0
- codecop/kinds/transaction/shapes.py +418 -0
- codecop/kinds/transaction/verify.py +293 -0
- codecop/live.py +237 -0
- codecop/loopbench.py +2071 -0
- codecop/loopschema.py +591 -0
- codecop/mcpserver.py +120 -0
- codecop/mechanism.py +214 -0
- codecop/members.py +200 -0
- codecop/multi.py +443 -0
- codecop/observed.py +1868 -0
- codecop/parts.py +102 -0
- codecop/patterns.py +830 -0
- codecop/patterns_view.py +559 -0
- codecop/plangate.py +242 -0
- codecop/profile.py +439 -0
- codecop/prompts/areas.md +19 -0
- codecop/prompts/observed_variants.md +20 -0
- codecop/prompts/profile.md +60 -0
- codecop/prompts/profile_postgres.md +68 -0
- codecop/prompts/profile_sizes.md +26 -0
- codecop/prompts/profile_sqlite.md +69 -0
- codecop/prompts/rank.md +84 -0
- codecop/prompts/rank_postgres.md +96 -0
- codecop/prompts/rank_sqlite.md +94 -0
- codecop/prompts/scenario_variants.md +20 -0
- codecop/rank.py +1473 -0
- codecop/realdb/__init__.py +688 -0
- codecop/realdb/clickhouse.py +1223 -0
- codecop/realdb/facts.py +815 -0
- codecop/realdb/locality.py +964 -0
- codecop/realdb/locks.py +355 -0
- codecop/realdb/match.py +531 -0
- codecop/realdb/postgres.py +643 -0
- codecop/realdb/ratios.py +77 -0
- codecop/realdb/sample.py +126 -0
- codecop/relations.py +227 -0
- codecop/report.py +1854 -0
- codecop/resources.py +332 -0
- codecop/resources_view.py +266 -0
- codecop/rules/entry_points.toml +1013 -0
- codecop/rules/sinks.toml +362 -0
- codecop/runsonce.py +8 -0
- codecop/sandboxschema.py +555 -0
- codecop/scenario_agent.py +172 -0
- codecop/scenario_bind.py +507 -0
- codecop/scenario_sql.py +971 -0
- codecop/scenarios.py +675 -0
- codecop/scenarios_view.py +274 -0
- codecop/schemacli.py +67 -0
- codecop/schemas/areas_output.schema.json +21 -0
- codecop/schemas/profile_output.schema.json +362 -0
- codecop/schemas/rank_output.schema.json +385 -0
- codecop/sizes.py +200 -0
- codecop/sqlinfo.py +558 -0
- codecop/typedparams.py +576 -0
- codecop/verdicts.py +212 -0
- codecop/writebench.py +720 -0
- codecop/writecost.py +440 -0
- codecop/writes.py +1208 -0
- codecop-0.1.0.dist-info/METADATA +42 -0
- codecop-0.1.0.dist-info/RECORD +222 -0
- codecop-0.1.0.dist-info/WHEEL +4 -0
- codecop-0.1.0.dist-info/entry_points.txt +2 -0
- codecop-0.1.0.dist-info/licenses/LICENSE +21 -0
codecop/loopschema.py
ADDED
|
@@ -0,0 +1,591 @@
|
|
|
1
|
+
"""Loop members benchmarked on the repository's own schema, with no agent: `codecop bench` without rank.json.
|
|
2
|
+
|
|
3
|
+
The loop benchmark (loopbench.py) needs the member's statement as it runs and the tables it reads built in the
|
|
4
|
+
sandbox. When the statement is fixed text in the code (literal or constant) with placeholders on columns of known type,
|
|
5
|
+
loopbench.synthesize makes it runnable by rule. What is missing without the paid steps is the rest of the bench input:
|
|
6
|
+
|
|
7
|
+
table definitions from the repository: the CREATE TABLE the code or a migration runs (SQLite schemas are often
|
|
8
|
+
created in code strings; discover records each statement as a `ddl` call site), else one written
|
|
9
|
+
from the inventory's columns; the CREATE INDEX statements of the code and the inventory's indexes
|
|
10
|
+
a data profile from the columns alone ("schema only, no agent"), as joins.schema_profile does: the generator kind
|
|
11
|
+
follows the type and the name, literals the code compares a column with become its values, and
|
|
12
|
+
`rows` is a setting (`schema_rows`, default 100,000), said as a guess
|
|
13
|
+
candidates each qualifying member and its driver, synthesized from their own SQL; the values of their
|
|
14
|
+
parameters are put on a few rows of the table they filter (a fixture), so the statement selects
|
|
15
|
+
rows. They carry no variants of their own: what is judged is the loop (loops.json).
|
|
16
|
+
|
|
17
|
+
Everything made here is labelled (`source: repository`, `basis: schema only`), and nothing is a finding unless the
|
|
18
|
+
sandbox measured it: the loop's verdict rule is loopbench's.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import copy
|
|
24
|
+
import re
|
|
25
|
+
|
|
26
|
+
from . import loopbench
|
|
27
|
+
from .engines.pg_ddl import split_statements, statement_kind
|
|
28
|
+
|
|
29
|
+
DEFAULTS = {"schema_rows": 100_000, "fixture_share": 0.002, "fixture_min_rows": 20, "key_rows_per_value": 10,
|
|
30
|
+
"max_literal_values": 12, "max_members": 400}
|
|
31
|
+
|
|
32
|
+
CREATE_TABLE = re.compile(r"^\s*CREATE\s+(?:(?:TEMP|TEMPORARY)\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?((?:[`\"\[]?\w+[`\"\]]?\.)?[`\"\[]?[\w$]+[`\"\]]?)", re.I)
|
|
33
|
+
CREATE_INDEX = re.compile(r"^\s*CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:IF\s+NOT\s+EXISTS\s+)?([`\"\[]?[\w.$]+[`\"\]]?)\s+ON\s+([`\"\[]?[\w.$]+[`\"\]]?)", re.I)
|
|
34
|
+
ALTER_ADD = re.compile(r"^\s*ALTER\s+TABLE\s+([`\"\[]?[\w.$]+[`\"\]]?)\s+ADD\s+(?:COLUMN\s+)?", re.I)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def settings_of(config: dict | None) -> dict:
|
|
38
|
+
out = dict(DEFAULTS)
|
|
39
|
+
for k, v in (config or {}).items():
|
|
40
|
+
if k in DEFAULTS and isinstance(v, (int, float)) and not isinstance(v, bool) and v > 0:
|
|
41
|
+
out[k] = type(DEFAULTS[k])(v)
|
|
42
|
+
return out
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _bare(name: str) -> str:
|
|
46
|
+
return re.sub(r"[`\"\[\]]", "", name or "").split(".")[-1].lower()
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _statements(site: dict) -> list[str]:
|
|
50
|
+
return [s for s in split_statements(site.get("sql") or "") if s.strip()]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _fits_engine(site: dict, engine: str) -> bool:
|
|
54
|
+
return (site.get("engine") or "") in (engine, "")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
# ---------------------------------------------------------------------------- definitions
|
|
58
|
+
|
|
59
|
+
def _nearness(path: str, near: list[str]) -> int:
|
|
60
|
+
"""How many path parts a definition's file shares with the files of the statements that read the table, summed."""
|
|
61
|
+
parts = (path or "").split("/")[:-1]
|
|
62
|
+
total = 0
|
|
63
|
+
for f in near:
|
|
64
|
+
other = f.split("/")[:-1]
|
|
65
|
+
n = 0
|
|
66
|
+
while n < min(len(parts), len(other)) and parts[n] == other[n]:
|
|
67
|
+
n += 1
|
|
68
|
+
total += n
|
|
69
|
+
return total
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def sqlite_definition(inventory: dict, name: str, near: list[str] | None = None) -> dict | None:
|
|
73
|
+
"""The CREATE TABLE (and its indexes) the repository runs for an SQLite table, comments dropped. A statement the code
|
|
74
|
+
labels SQLite wins over an unlabelled one, then the one nearest the statements that read the table (`near`: their
|
|
75
|
+
files; two stores of one repository can each have a table of that name), code outside tests over tests, the longest
|
|
76
|
+
over shorter copies; a statement SQLite itself does not accept is passed over. Without one, a definition written
|
|
77
|
+
from the inventory's columns (`inferred`)."""
|
|
78
|
+
import sqlite3
|
|
79
|
+
want = _bare(name)
|
|
80
|
+
found: list[tuple[tuple, str, dict]] = []
|
|
81
|
+
indexes: dict[str, str] = {}
|
|
82
|
+
alters: list[str] = []
|
|
83
|
+
for s in (inventory or {}).get("call_sites") or []:
|
|
84
|
+
if s.get("statement") not in ("ddl", "other", "unknown") or not _fits_engine(s, "sqlite"):
|
|
85
|
+
continue
|
|
86
|
+
for stmt in _statements(s):
|
|
87
|
+
m = CREATE_TABLE.match(stmt)
|
|
88
|
+
if m and _bare(m.group(1)) == want:
|
|
89
|
+
try:
|
|
90
|
+
sqlite3.connect(":memory:").execute(stmt)
|
|
91
|
+
except Exception: # noqa: BLE001 - a statement SQLite rejects is not this table's SQLite definition
|
|
92
|
+
continue
|
|
93
|
+
found.append(((s.get("engine") == "sqlite", _nearness(s.get("file") or "", near or []), not s.get("is_test"), len(stmt)), stmt, s))
|
|
94
|
+
continue
|
|
95
|
+
m = CREATE_INDEX.match(stmt)
|
|
96
|
+
if m and _bare(m.group(2)) == want and s.get("engine") == "sqlite":
|
|
97
|
+
indexes.setdefault(_bare(m.group(1)), stmt)
|
|
98
|
+
continue
|
|
99
|
+
m = ALTER_ADD.match(stmt)
|
|
100
|
+
if m and _bare(m.group(1)) == want and s.get("engine") == "sqlite":
|
|
101
|
+
alters.append(stmt)
|
|
102
|
+
table = next((t for t in (inventory or {}).get("tables") or [] if _bare(t["name"]) == want and not t.get("engine")), None)
|
|
103
|
+
for ix in (table or {}).get("indexes") or []:
|
|
104
|
+
if ix.get("name") and ix.get("columns") and not ix.get("primary") and _bare(ix["name"]) not in indexes:
|
|
105
|
+
indexes[_bare(ix["name"])] = (f"CREATE {'UNIQUE ' if ix.get('unique') else ''}INDEX \"{ix['name']}\" ON \"{want}\" "
|
|
106
|
+
f"({', '.join(ix['columns'])})" + (f" WHERE {ix['where']}" if ix.get("where") else ""))
|
|
107
|
+
if found:
|
|
108
|
+
found.sort(key=lambda f: f[0], reverse=True)
|
|
109
|
+
_, stmt, site = found[0]
|
|
110
|
+
where = f"{site.get('file')}:{site.get('line')}"
|
|
111
|
+
inferred = False
|
|
112
|
+
elif table and table.get("columns"):
|
|
113
|
+
cols = [f'"{c["name"]}" {c.get("type") or ""}'.rstrip() for c in table["columns"]]
|
|
114
|
+
pk = table.get("primary_key") or ""
|
|
115
|
+
stmt = f'CREATE TABLE "{want}" (\n ' + ",\n ".join(cols) + (f",\n PRIMARY KEY ({pk})" if pk else "") + "\n)"
|
|
116
|
+
where = (table.get("defined_at") or [""])[0]
|
|
117
|
+
inferred = True
|
|
118
|
+
else:
|
|
119
|
+
return None
|
|
120
|
+
# an ALTER TABLE that adds a column the CREATE TABLE lacks: run after it, so a statement naming the column builds
|
|
121
|
+
script = ";\n".join([stmt] + alters + list(indexes.values()))
|
|
122
|
+
return {"name": want, "create_sql": script, "inferred": inferred, "source": "repository",
|
|
123
|
+
"basis": f"Written by CodeCop from the repository's definition at {where}" + (" (columns only)" if inferred else "") + "."}
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
PG_TYPE_OF = [
|
|
127
|
+
# Prisma, SQLAlchemy / SQLModel, Django, Python annotations and SQL spellings -> a PostgreSQL type the sandbox builds
|
|
128
|
+
(r"^(?:uuid|uuidfield|uuid4|uuidstr|guid)$", "uuid"),
|
|
129
|
+
(r"^(?:bigint|biginteger|bigautofield|bigserial|int8|int64|bigintegerfield|positivebigintegerfield)$", "bigint"),
|
|
130
|
+
(r"^(?:smallint|smallinteger|int2|smallintegerfield|positivesmallintegerfield|tinyint)$", "smallint"),
|
|
131
|
+
(r"^(?:int|integer|int4|serial|autofield|integerfield|positiveintegerfield|foreignkey|onetoonefield|int32|mediumint)$", "integer"),
|
|
132
|
+
(r"^(?:bool|boolean|booleanfield|nullbooleanfield)$", "boolean"),
|
|
133
|
+
(r"^(?:datetime|datetimefield|timestamp|timestamptz|utctimestamp|timestamp with time zone|timestamp without time zone|"
|
|
134
|
+
r"awaredatetime|datetime64|datetime\w*)$", "timestamptz"),
|
|
135
|
+
(r"^(?:date|datefield)$", "date"),
|
|
136
|
+
(r"^(?:time|timefield)$", "time"),
|
|
137
|
+
(r"^(?:interval|timedelta|durationfield)$", "interval"),
|
|
138
|
+
(r"^(?:float|double|double precision|real|float8|float4|floatfield|float64|float32|numberfield)$", "double precision"),
|
|
139
|
+
(r"^(?:decimal|numeric|decimalfield|money)$", "numeric"),
|
|
140
|
+
(r"^(?:json|jsonb|jsonfield|jsonvariant|json_|jsondict|jsonlist|jsontype|dict|list|hstore|mutabledict|mutablelist)$", "jsonb"),
|
|
141
|
+
(r"^(?:bytes|bytea|blob|largebinary|binaryfield|binary|varbinary|longblob)$", "bytea"),
|
|
142
|
+
(r"^(?:inet|cidr|genericipaddressfield|ipaddressfield)$", "text"),
|
|
143
|
+
]
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def pg_type_of(raw: str) -> str:
|
|
147
|
+
"""A PostgreSQL type for a column type as the repository's schema spells it (Prisma `String[]`, SQLAlchemy
|
|
148
|
+
`BigInteger`, Django `ForeignKey`, a Python annotation `UUID`): an unknown or empty one is `text`."""
|
|
149
|
+
t = re.sub(r"\s+(?:NOT\s+NULL|NULL|PRIMARY\s+KEY|UNIQUE|DEFAULT\b.*|REFERENCES\b.*|@.*|\?)$", "", (raw or "").strip(), flags=re.I).strip()
|
|
150
|
+
array = t.endswith("[]")
|
|
151
|
+
t = t[:-2] if array else t
|
|
152
|
+
t = re.sub(r"^(?:Nullable|LowCardinality|Optional|Mapped)\((.*)\)$", r"\1", t)
|
|
153
|
+
base = re.sub(r"\(.*\)$", "", t).strip().split(".")[-1].lower()
|
|
154
|
+
out = "text"
|
|
155
|
+
for pat, pg in PG_TYPE_OF:
|
|
156
|
+
if re.match(pat, base):
|
|
157
|
+
out = pg
|
|
158
|
+
break
|
|
159
|
+
else:
|
|
160
|
+
if re.fullmatch(r"(?:varchar|character varying|char|character|nvarchar)(?:\s*\(\d+\))?", t, re.I):
|
|
161
|
+
out = "text"
|
|
162
|
+
return out + ("[]" if array else "")
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _pg_ident(name: str) -> str:
|
|
166
|
+
return ".".join('"' + p.replace('"', '""') + '"' for p in name.split("."))
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def postgres_definition(inventory: dict, name: str, cfg: dict | None = None) -> dict | None:
|
|
170
|
+
"""A CREATE TABLE PostgreSQL builds for a table the repository defines (its models, Prisma schema or migrations,
|
|
171
|
+
as discover recorded them in `tables`), written by CodeCop for a loop's statements when no ranked candidate reads the
|
|
172
|
+
table: every name quoted as the code spells it, each type made a PostgreSQL one (pg_type_of), a one-column primary
|
|
173
|
+
key kept (its column generated unique), the schema's indexes kept, unique ones built plain (the generated rows are
|
|
174
|
+
not made unique on their columns). None when the repository has no columns for it."""
|
|
175
|
+
from .definitions import _schema_tables
|
|
176
|
+
want = _bare(name)
|
|
177
|
+
t = _schema_tables(inventory).get(want)
|
|
178
|
+
if t is None or not t.get("columns") or t.get("engine"):
|
|
179
|
+
return None
|
|
180
|
+
# as the statement names it: `auth.users` is built in its schema, `"LiteLLM_TeamTable"` keeps its case
|
|
181
|
+
exact = ".".join(re.sub(r'[`"\[\]]', "", name).split(".")[-2:])
|
|
182
|
+
pk = [c.strip().strip('"`') for c in re.split(r"\s*,\s*", t.get("primary_key") or "") if c.strip()]
|
|
183
|
+
cols, typed = [], 0
|
|
184
|
+
for c in t["columns"]:
|
|
185
|
+
if not c.get("name"):
|
|
186
|
+
continue
|
|
187
|
+
pg = pg_type_of(c.get("type") or "")
|
|
188
|
+
typed += bool((c.get("type") or "").strip())
|
|
189
|
+
cols.append(f"{_pg_ident(c['name'])} {pg}" + (" PRIMARY KEY" if len(pk) == 1 and c["name"].lower() == pk[0].lower() else ""))
|
|
190
|
+
if not cols:
|
|
191
|
+
return None
|
|
192
|
+
stmts = ([f"CREATE SCHEMA IF NOT EXISTS {_pg_ident(exact.split('.')[0])}"] if "." in exact else []) + \
|
|
193
|
+
[f"CREATE TABLE {_pg_ident(exact)} (\n " + ",\n ".join(cols) + "\n)"]
|
|
194
|
+
names = {c["name"].lower() for c in t["columns"] if c.get("name")}
|
|
195
|
+
seen = set()
|
|
196
|
+
for ix in t.get("indexes") or []:
|
|
197
|
+
ic = [x for x in ix.get("columns") or [] if x]
|
|
198
|
+
if not ic or ix.get("primary") or any(x.lower() not in names for x in ic) or tuple(ic) in seen:
|
|
199
|
+
continue
|
|
200
|
+
seen.add(tuple(ic))
|
|
201
|
+
stmts.append(f"CREATE INDEX ON {_pg_ident(exact)} ({', '.join(_pg_ident(x) for x in ic)})")
|
|
202
|
+
if len(pk) > 1 and tuple(pk) not in seen and all(x.lower() in names for x in pk):
|
|
203
|
+
stmts.append(f"CREATE INDEX ON {_pg_ident(exact)} ({', '.join(_pg_ident(x) for x in pk)})")
|
|
204
|
+
where = (t.get("defined_at") or [""])[0]
|
|
205
|
+
unique = sorted({ix["columns"][0] for ix in t.get("indexes") or [] if ix.get("unique") and len(ix.get("columns") or []) == 1
|
|
206
|
+
and ix["columns"][0].lower() in names} | ({pk[0]} if len(pk) == 1 else set()))
|
|
207
|
+
return {"name": exact, "create_sql": ";\n".join(stmts), "inferred": True, "source": "repository", "schema_only": True,
|
|
208
|
+
"unique_columns": unique,
|
|
209
|
+
"basis": f"Written by CodeCop from the repository's definition at {where} (columns, keys and indexes; "
|
|
210
|
+
f"{typed} of {len(cols)} column types given there, the rest text). Schema only: no agent, no sample."}
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def definition(inventory: dict, name: str, engine: str, near: list[str] | None = None) -> dict | None:
|
|
214
|
+
if engine == "sqlite":
|
|
215
|
+
return sqlite_definition(inventory, name, near)
|
|
216
|
+
if engine == "postgres":
|
|
217
|
+
return postgres_definition(inventory, name)
|
|
218
|
+
from .joins import repository_definition
|
|
219
|
+
return repository_definition(inventory, name, engine)
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
# ---------------------------------------------------------------------------- a profile from the columns
|
|
223
|
+
|
|
224
|
+
KIND_NAME = re.compile(r"(?:^|_)(?:kind|type|status|state|language|lang|category|level|severity|mode|role|phase|scope_kind)$", re.I)
|
|
225
|
+
TIME_NAME = re.compile(r"(?:_at|_on|_time|_ts|^ts|timestamp|^created|^updated|^date)$", re.I)
|
|
226
|
+
KEY_NAME = re.compile(r"(?:^id$|_id$|Id$|_key$|^key$|_hash$|^hash$|_uuid$|^uuid$)", re.I)
|
|
227
|
+
NAMEISH = re.compile(r"(?:name|path|file|url|qualified|signature|label|title|email|package|module|symbol)$", re.I)
|
|
228
|
+
LITERAL = re.compile(r"""[`"\[]?(\w+)[`"\]]?\s*(?:=|==|!=|<>)\s*'([^'\n]{1,60})'|[`"\[]?(\w+)[`"\]]?\s+IN\s*\(((?:\s*'[^'\n]{1,60}'\s*,?)+)\)""", re.I)
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def literals_by_column(inventory: dict, table: str, engine: str) -> dict[str, list[str]]:
|
|
232
|
+
"""Values the code compares a column of this table with (`status = 'open'`, `kind IN ('a', 'b')`)."""
|
|
233
|
+
out: dict[str, list[str]] = {}
|
|
234
|
+
want = _bare(table)
|
|
235
|
+
for s in (inventory or {}).get("call_sites") or []:
|
|
236
|
+
if (s.get("engine") or "") != engine or want not in {_bare(t) for t in s.get("tables") or []}:
|
|
237
|
+
continue
|
|
238
|
+
for m in LITERAL.finditer(s.get("sql") or ""):
|
|
239
|
+
col = (m.group(1) or m.group(3) or "").lower()
|
|
240
|
+
values = [m.group(2)] if m.group(2) is not None else re.findall(r"'([^'\n]{1,60})'", m.group(4) or "")
|
|
241
|
+
for v in values:
|
|
242
|
+
if v not in out.setdefault(col, []):
|
|
243
|
+
out[col].append(v)
|
|
244
|
+
return out
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def column_spec_sqlite(col: str, declared: str, rows: int, *, rowid: bool, literals: list[str] | None, cfg: dict) -> dict:
|
|
248
|
+
from .datagen_sqlite import affinity, is_boolean, is_time
|
|
249
|
+
aff = affinity(declared)
|
|
250
|
+
spec: dict = {"name": col, "source": "schema only, no agent", "confidence": "low", "evidence": "inferred"}
|
|
251
|
+
if rowid:
|
|
252
|
+
spec.update(kind="unique")
|
|
253
|
+
elif literals and not (KEY_NAME.search(col) and not KIND_NAME.search(col)):
|
|
254
|
+
values = [{"value": v, "weight": 1} for v in literals[: cfg["max_literal_values"]]]
|
|
255
|
+
spec.update(kind="categorical", values=values + [{"value": f"{col}-other", "weight": 1}] if aff == "TEXT" or aff == "NUMERIC" else values,
|
|
256
|
+
source="schema only: the values the code compares it with")
|
|
257
|
+
elif is_boolean(declared):
|
|
258
|
+
spec.update(kind="int", min=0, max=1)
|
|
259
|
+
elif is_time(declared) or (TIME_NAME.search(col) and aff in ("INTEGER", "TEXT", "NUMERIC")):
|
|
260
|
+
spec.update(kind="timestamp", days_back=30, distribution="uniform")
|
|
261
|
+
elif KIND_NAME.search(col):
|
|
262
|
+
spec.update(kind="key", distinct=20, distribution="skewed", source="schema only: a type-like name, 20 values, skewed (a guess)")
|
|
263
|
+
elif KEY_NAME.search(col) or (NAMEISH.search(col) and aff == "TEXT"):
|
|
264
|
+
per = max(int(cfg["key_rows_per_value"]), 1) if not NAMEISH.search(col) else 2
|
|
265
|
+
spec.update(kind="key", distinct=max(rows // per, 20), distribution="uniform",
|
|
266
|
+
source=f"schema only: a key-like name, about {per} rows per value (a guess)")
|
|
267
|
+
elif aff == "INTEGER":
|
|
268
|
+
spec.update(kind="int", min=0, max=1000)
|
|
269
|
+
elif aff in ("REAL", "NUMERIC"):
|
|
270
|
+
spec.update(kind="float", min=0, max=1000)
|
|
271
|
+
elif aff == "BLOB" and declared.strip():
|
|
272
|
+
spec.update(kind="text", avg_len=32)
|
|
273
|
+
else:
|
|
274
|
+
spec.update(kind="text", avg_len=32)
|
|
275
|
+
return spec
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def schema_profile(d: dict, inventory: dict, engine: str, cfg: dict) -> dict:
|
|
279
|
+
"""A data profile for one table from its definition alone: no agent, no sample."""
|
|
280
|
+
from .rank import _columns
|
|
281
|
+
rows = int(cfg["schema_rows"])
|
|
282
|
+
got = _columns(d.get("create_sql") or "", d.get("name") or "")
|
|
283
|
+
literals = literals_by_column(inventory, d["name"], engine)
|
|
284
|
+
specs = []
|
|
285
|
+
for col, text in (got[1] if got else {}).items():
|
|
286
|
+
words = text.split()
|
|
287
|
+
declared = " ".join(w for w in words[1:3] if not re.match(r"^(?:PRIMARY|NOT|NULL|DEFAULT|UNIQUE|REFERENCES|CHECK|COLLATE|GENERATED|AS|CONSTRAINT)$", w, re.I))
|
|
288
|
+
rowid = bool(re.search(r"\bPRIMARY\s+KEY\b", text, re.I)) or (col.lower() == "id" and "INT" in declared.upper()) or \
|
|
289
|
+
col.lower() in {c.lower() for c in d.get("unique_columns") or []} # a unique index of the schema: one row per value
|
|
290
|
+
if re.search(r"\bGENERATED\b|\bAS\s*\(", text, re.I):
|
|
291
|
+
continue
|
|
292
|
+
specs.append(column_spec_sqlite(col, declared, rows, rowid=rowid, literals=literals.get(col.lower()), cfg=cfg)
|
|
293
|
+
if engine == "sqlite" else _generic_spec(col, declared, rows, rowid))
|
|
294
|
+
return {"name": d["name"], "rows": rows, "rows_basis": f"schema only: {rows:,} rows (setting schema_rows)", "rows_confidence": "low",
|
|
295
|
+
"basis": "schema only, no agent", "columns": specs, "fixtures": [], "relations": []}
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _generic_spec(col: str, declared: str, rows: int, rowid: bool) -> dict:
|
|
299
|
+
spec = {"name": col, "source": "schema only, no agent", "confidence": "low", "evidence": "inferred"}
|
|
300
|
+
t = declared.lower()
|
|
301
|
+
if rowid:
|
|
302
|
+
spec.update(kind="unique")
|
|
303
|
+
elif re.search(r"time|date", t):
|
|
304
|
+
spec.update(kind="timestamp", days_back=30)
|
|
305
|
+
elif re.search(r"int|serial", t):
|
|
306
|
+
spec.update(kind="key", distinct=max(rows // 10, 20)) if KEY_NAME.search(col) else spec.update(kind="int", min=0, max=1000)
|
|
307
|
+
elif re.search(r"bool", t):
|
|
308
|
+
spec.update(kind="categorical", values=[{"value": "true"}, {"value": "false"}])
|
|
309
|
+
elif re.search(r"real|double|float|numeric|decimal", t):
|
|
310
|
+
spec.update(kind="float", min=0, max=1000)
|
|
311
|
+
elif KEY_NAME.search(col) or KIND_NAME.search(col):
|
|
312
|
+
spec.update(kind="key", distinct=20 if KIND_NAME.search(col) else max(rows // 10, 20))
|
|
313
|
+
else:
|
|
314
|
+
spec.update(kind="text", avg_len=32)
|
|
315
|
+
return spec
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
# ---------------------------------------------------------------------------- the bench input
|
|
319
|
+
|
|
320
|
+
def _value_for(spec: dict | None, typ: str) -> object:
|
|
321
|
+
"""A value the generated data holds for this column, without a fixture: the most common one where that is known."""
|
|
322
|
+
from .datagen_sqlite import affinity
|
|
323
|
+
if spec is None:
|
|
324
|
+
return None
|
|
325
|
+
kind = spec.get("kind")
|
|
326
|
+
numeric = affinity(typ) in ("INTEGER", "REAL", "NUMERIC")
|
|
327
|
+
if kind in ("key", "unique"):
|
|
328
|
+
return 0 if numeric else f"{spec.get('prefix') or spec['name'] + '_'}0"
|
|
329
|
+
if kind == "categorical":
|
|
330
|
+
return (spec.get("values") or [{}])[0].get("value")
|
|
331
|
+
return None
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def extend(rank: dict, profile: dict | None, patterns_doc: dict, inventory: dict, settings: dict | None = None,
|
|
335
|
+
loop_settings: dict | None = None, agent_statements: dict | None = None) -> tuple[dict, dict | None, dict]:
|
|
336
|
+
"""rank and profile with the loop members (and their drivers) that no candidate stands for, made runnable by rule
|
|
337
|
+
from their own SQL or their ORM call's translation (loopbench.member_text), each table they read that the rank does
|
|
338
|
+
not load written from the repository's schema (postgres_definition: `source: repository`, `schema_only`) and given a
|
|
339
|
+
profile from its columns alone (`basis: schema only, no agent`). The rank's own definitions and profiles are kept as
|
|
340
|
+
they are. Returns (rank, profile, report: {wanted, covered, built, tables_added, not_built: {why: n}, why_by_site}).
|
|
341
|
+
PostgreSQL and SQLite; nothing changes for other engines."""
|
|
342
|
+
engine = rank.get("engine") or ""
|
|
343
|
+
cfg = settings_of(settings)
|
|
344
|
+
lcfg = loopbench.settings_of(loop_settings)
|
|
345
|
+
report = {"wanted": 0, "covered": 0, "built": 0, "tables_added": [], "not_built": {}, "why_by_site": {}, "over_max": 0}
|
|
346
|
+
if engine not in ("postgres", "sqlite") or not patterns_doc:
|
|
347
|
+
return rank, profile, report
|
|
348
|
+
sites = {s.get("id"): s for s in (inventory or {}).get("call_sites") or []}
|
|
349
|
+
covered = {str(c.get("id")) for c in rank.get("candidates") or [] if c.get("baseline_sql") and c.get("sql_from") != "query_log"}
|
|
350
|
+
covered |= {str(sid) for c in rank.get("candidates") or [] for sid in (c.get("observed") or {}).get("places") or []}
|
|
351
|
+
rank = copy.deepcopy(rank)
|
|
352
|
+
loaded = {_bare(d["name"]): d for d in rank.get("table_definitions") or []}
|
|
353
|
+
added: dict[str, dict] = {}
|
|
354
|
+
wanted: list[tuple[dict, str]] = []
|
|
355
|
+
seen: set = set()
|
|
356
|
+
for p in patterns_doc.get("patterns") or []:
|
|
357
|
+
ok, _ = loopbench.qualify(p, lcfg)
|
|
358
|
+
if not ok:
|
|
359
|
+
continue
|
|
360
|
+
ids = [(m["site_id"], "member") for m in loopbench.qualifying_members(p)] + \
|
|
361
|
+
[(sid, "driver") for sid in (p.get("driver") or {}).get("site_ids") or []]
|
|
362
|
+
for sid, role in ids:
|
|
363
|
+
s = sites.get(sid)
|
|
364
|
+
if s is None or sid in seen or (s.get("engine") or engine) != engine:
|
|
365
|
+
continue
|
|
366
|
+
seen.add(sid)
|
|
367
|
+
wanted.append((s, role))
|
|
368
|
+
report["wanted"] = sum(1 for _, r in wanted if r == "member")
|
|
369
|
+
from collections import Counter
|
|
370
|
+
why: Counter = Counter()
|
|
371
|
+
out = []
|
|
372
|
+
max_n = int(cfg["max_members"])
|
|
373
|
+
for s, role in wanted:
|
|
374
|
+
if str(s["id"]) in covered:
|
|
375
|
+
report["covered"] += role == "member"
|
|
376
|
+
continue
|
|
377
|
+
if len(out) >= max_n:
|
|
378
|
+
report["over_max"] += 1
|
|
379
|
+
continue
|
|
380
|
+
def defs_for(names: list[str]) -> tuple[dict[str, dict], list[str]]:
|
|
381
|
+
got, lacking = {}, []
|
|
382
|
+
for raw in names:
|
|
383
|
+
t = _bare(raw)
|
|
384
|
+
d = loaded.get(t) or added.get(t) or definition(inventory, re.sub(r'[`"]', "", raw), engine)
|
|
385
|
+
if d is None:
|
|
386
|
+
lacking.append(t)
|
|
387
|
+
else:
|
|
388
|
+
got[t] = d
|
|
389
|
+
return got, lacking
|
|
390
|
+
tables = [_bare(t) for t in s.get("tables") or []]
|
|
391
|
+
defs, lacking = defs_for(s.get("tables") or [])
|
|
392
|
+
cand = None
|
|
393
|
+
if lacking:
|
|
394
|
+
reason = "a table it reads has no definition in the repository's schema"
|
|
395
|
+
else:
|
|
396
|
+
cand, reason = loopbench.synthesize(s, defs, engine, inventory)
|
|
397
|
+
st = (agent_statements or {}).get(str(s["id"]))
|
|
398
|
+
if cand is None and st:
|
|
399
|
+
# no runnable form by rule: the paid step's per-item statement, run as the agent wrote it (sql_from agent)
|
|
400
|
+
defs, lacking = defs_for(st.get("tables") or [])
|
|
401
|
+
tables = [_bare(t) for t in st.get("tables") or []]
|
|
402
|
+
cand, why_agent = loopbench.agent_candidate(str(s["id"]), st, s, defs, engine) if not lacking else \
|
|
403
|
+
(None, "a table the agent's statement reads has no definition in the repository's schema")
|
|
404
|
+
reason = f"{reason}; {why_agent}" if cand is None else reason
|
|
405
|
+
if cand is not None:
|
|
406
|
+
for t, d in defs.items():
|
|
407
|
+
if t not in loaded and t not in added:
|
|
408
|
+
added[t] = d
|
|
409
|
+
by_agent = cand.get("sql_from") == "agent"
|
|
410
|
+
cand.update(sql_from="agent" if by_agent else "code", loop_role=role, built_for="loop_member",
|
|
411
|
+
schema_only=any(t in added for t in tables), finding=f"{'LA' if by_agent else 'LM'}-{len(out) + 1:03d}",
|
|
412
|
+
title=f"Loop {role} at {str(s.get('file', '')).split('/')[-1]}:{s.get('line', 0)}",
|
|
413
|
+
severity="medium", confidence="high", causes=[],
|
|
414
|
+
assumptions=list(cand.get("assumptions") or []) + [
|
|
415
|
+
("the agent's per-item statement" if by_agent else "a loop statement made runnable by rule; every parameter "
|
|
416
|
+
"typed from the column it is compared with") + "; it carries no variants of its own: what is judged is the "
|
|
417
|
+
"loop (loops.json)"])
|
|
418
|
+
out.append(cand)
|
|
419
|
+
report["built"] += role == "member"
|
|
420
|
+
report.setdefault("by_agent", 0)
|
|
421
|
+
report["by_agent"] += by_agent and role == "member"
|
|
422
|
+
continue
|
|
423
|
+
if role == "member":
|
|
424
|
+
why[reason] += 1
|
|
425
|
+
report["why_by_site"][str(s["id"])] = reason
|
|
426
|
+
report["not_built"] = dict(why.most_common())
|
|
427
|
+
if not out:
|
|
428
|
+
return rank, profile, report
|
|
429
|
+
rank["candidates"] = list(rank.get("candidates") or []) + out
|
|
430
|
+
rank["table_definitions"] = list(rank.get("table_definitions") or []) + [added[t] for t in sorted(added)]
|
|
431
|
+
report["tables_added"] = sorted(added)
|
|
432
|
+
prof = copy.deepcopy(profile) if profile else {"engine": engine, "tables": []}
|
|
433
|
+
have = {_bare(t["name"]) for t in prof.get("tables") or []}
|
|
434
|
+
for t in sorted(added):
|
|
435
|
+
if t not in have:
|
|
436
|
+
prof.setdefault("tables", []).append(schema_profile(added[t], inventory, engine, cfg))
|
|
437
|
+
by_table = {_bare(t["name"]): t for t in prof.get("tables") or []}
|
|
438
|
+
sql_of = {_bare(d["name"]): d.get("create_sql") or "" for d in rank["table_definitions"]}
|
|
439
|
+
for cand in out:
|
|
440
|
+
_values_on_rows(cand, by_table, cfg, sql_of)
|
|
441
|
+
return rank, prof, report
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
ENUM_TYPE = re.compile(r"CREATE\s+TYPE\s+(?:IF\s+NOT\s+EXISTS\s+)?([\w.\"]+)\s+AS\s+ENUM\s*\(([^)]*)\)", re.I)
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def enum_labels(create_sql: str, table: str, column: str) -> list[str]:
|
|
448
|
+
"""The labels of the enum type a column is declared with, when the definition creates that type (`CREATE TYPE
|
|
449
|
+
job_status_enum AS ENUM ('queued', ...)` before the CREATE TABLE, as the repository's migrations write it); else []."""
|
|
450
|
+
types = {m.group(1).replace('"', "").split(".")[-1].lower(): re.findall(r"'((?:[^']|'')*)'", m.group(2))
|
|
451
|
+
for m in ENUM_TYPE.finditer(create_sql or "")}
|
|
452
|
+
if not types:
|
|
453
|
+
return []
|
|
454
|
+
from .rank import _columns
|
|
455
|
+
got = _columns(create_sql, table)
|
|
456
|
+
line = next((v for k, v in (got[1] if got else {}).items() if k.replace('"', "").lower() == column.replace('"', "").lower()), "")
|
|
457
|
+
words = line.split()
|
|
458
|
+
typ = words[1].replace('"', "").split(".")[-1].lower() if len(words) > 1 else ""
|
|
459
|
+
return [x.replace("''", "'") for x in types.get(typ, [])]
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
def typed_value(typ: str, column: str, n: int = 1):
|
|
463
|
+
"""A value of the parameter's type that generated data can hold: a uuid the generator writes, a number, a date."""
|
|
464
|
+
t = (typ or "").lower().strip()
|
|
465
|
+
if t.endswith("[]"):
|
|
466
|
+
return "{}" # a list parameter (`<> ALL({ids:text[]})`) is run with the empty list
|
|
467
|
+
if t == "uuid":
|
|
468
|
+
return f"00000000-0000-4000-8000-{n:012d}"
|
|
469
|
+
if re.match(r"^(?:small|big)?int|^integer|^numeric|^decimal|^real|^double|^float", t):
|
|
470
|
+
return n
|
|
471
|
+
if t.startswith("bool"):
|
|
472
|
+
return True
|
|
473
|
+
if re.match(r"^(?:timestamp|date)", t):
|
|
474
|
+
return "2026-01-01 00:00:00"
|
|
475
|
+
return f"{column}_{n}" # as the generator writes a key or unique text column: its name, _, an index
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
def _values_on_rows(cand: dict, by_table: dict, cfg: dict, sql_of: dict | None = None) -> None:
|
|
479
|
+
"""The candidate's parameter values, each also put on a few rows of the table it filters (a fixture), so its own
|
|
480
|
+
statement selects rows; the loop benchmark takes its items from the sandbox's rows. A column of an enum type takes
|
|
481
|
+
one of its labels (`sql_of`: table -> its definition, which creates the type), never `status_1`: PostgreSQL refuses
|
|
482
|
+
a value outside the type and the whole table is not built."""
|
|
483
|
+
types = dict(PARAM_TYPES.findall(cand.get("baseline_sql") or ""))
|
|
484
|
+
fixtures: dict[str, list[dict]] = {}
|
|
485
|
+
for pname, where in (cand.get("synthesized") or {}).items():
|
|
486
|
+
spec = next((c for c in (by_table.get(_bare(where["table"])) or {}).get("columns") or [] if c.get("name", "").lower() == where["column"].lower()), {})
|
|
487
|
+
labels = enum_labels((sql_of or {}).get(_bare(where["table"]), ""), _bare(where["table"]), where["column"])
|
|
488
|
+
if labels:
|
|
489
|
+
# the profile's most common value when it is a label, else the type's first label
|
|
490
|
+
said = sorted((v for v in spec.get("values") or [] if str(v.get("value")) in labels) if spec.get("kind") == "categorical" else [],
|
|
491
|
+
key=lambda v: -float(v.get("weight", 1)))
|
|
492
|
+
value = str(said[0]["value"]) if said else labels[0]
|
|
493
|
+
else:
|
|
494
|
+
value = typed_value(types.get(pname, ""), where["column"])
|
|
495
|
+
cand.setdefault("params", {})[pname] = value
|
|
496
|
+
if spec.get("kind") == "unique" or value == "{}":
|
|
497
|
+
continue # one row per value: a fixture would repeat it (a LIMIT 1 then picks any of them)
|
|
498
|
+
fixtures.setdefault(_bare(where["table"]), []).append({"column": where["column"], "value": value})
|
|
499
|
+
for t, vals in fixtures.items():
|
|
500
|
+
if t in by_table:
|
|
501
|
+
by_table[t].setdefault("fixtures", []).append({"id": cand["finding"], "values": vals, "share": float(cfg["fixture_share"]),
|
|
502
|
+
"min_rows": int(cfg["fixture_min_rows"]),
|
|
503
|
+
"basis": "schema only: the statement's parameter values on a few rows"})
|
|
504
|
+
|
|
505
|
+
|
|
506
|
+
PARAM_TYPES = re.compile(r"\{(\w+)\s*:\s*([^{}]+?)\}")
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
def augment(patterns_doc: dict, inventory: dict, engine: str, settings: dict | None = None,
|
|
510
|
+
loop_settings: dict | None = None) -> tuple[dict | None, dict | None, list[str]]:
|
|
511
|
+
"""(rank, profile, notes) for the loop members of `engine` that can run by rule on the repository's own schema, or
|
|
512
|
+
(None, None, notes) when none can."""
|
|
513
|
+
cfg = settings_of(settings)
|
|
514
|
+
lcfg = loopbench.settings_of(loop_settings)
|
|
515
|
+
notes: list[str] = []
|
|
516
|
+
sites = {s.get("id"): s for s in (inventory or {}).get("call_sites") or []}
|
|
517
|
+
definitions: dict[str, dict] = {}
|
|
518
|
+
missing: set[str] = set()
|
|
519
|
+
|
|
520
|
+
def table_def(t: str) -> dict | None:
|
|
521
|
+
key = _bare(t)
|
|
522
|
+
if key not in definitions and key not in missing:
|
|
523
|
+
d = definition(inventory, key, engine, readers.get(key))
|
|
524
|
+
if d is None:
|
|
525
|
+
missing.add(key)
|
|
526
|
+
else:
|
|
527
|
+
definitions[key] = d
|
|
528
|
+
return definitions.get(key)
|
|
529
|
+
|
|
530
|
+
wanted: list[tuple[dict, str]] = [] # (site, role)
|
|
531
|
+
for p in (patterns_doc or {}).get("patterns") or []:
|
|
532
|
+
ok, _ = loopbench.qualify(p, lcfg)
|
|
533
|
+
if not ok or p.get("engine") not in (engine,):
|
|
534
|
+
continue
|
|
535
|
+
for m in loopbench.qualifying_members(p):
|
|
536
|
+
if (sites.get(m["site_id"]) or {}).get("engine") == engine:
|
|
537
|
+
wanted.append((sites[m["site_id"]], "member"))
|
|
538
|
+
for sid in (p.get("driver") or {}).get("site_ids") or []:
|
|
539
|
+
if (sites.get(sid) or {}).get("engine") == engine:
|
|
540
|
+
wanted.append((sites[sid], "driver"))
|
|
541
|
+
readers: dict[str, list[str]] = {}
|
|
542
|
+
for site, _role in wanted:
|
|
543
|
+
for t in site.get("tables") or []:
|
|
544
|
+
readers.setdefault(_bare(t), []).append(site.get("file") or "")
|
|
545
|
+
candidates, seen = [], set()
|
|
546
|
+
for site, role in wanted:
|
|
547
|
+
if site["id"] in seen:
|
|
548
|
+
continue
|
|
549
|
+
seen.add(site["id"])
|
|
550
|
+
tables = [_bare(t) for t in site.get("tables") or []]
|
|
551
|
+
if not tables or any(table_def(t) is None for t in tables):
|
|
552
|
+
continue
|
|
553
|
+
cand, why = loopbench.synthesize(site, definitions, engine, inventory)
|
|
554
|
+
if cand is None:
|
|
555
|
+
continue
|
|
556
|
+
cand.update(sql_from="code", loop_role=role, schema_only=True)
|
|
557
|
+
candidates.append(cand)
|
|
558
|
+
if not candidates:
|
|
559
|
+
if missing:
|
|
560
|
+
notes.append(f"no loop member could run on the repository's schema: {len(missing)} table(s) it reads have no definition")
|
|
561
|
+
return None, None, notes
|
|
562
|
+
used = {_bare(t) for c in candidates for t in c["tables"]}
|
|
563
|
+
defs = [definitions[t] for t in sorted(used)]
|
|
564
|
+
profile = {"engine": engine, "basis": "schema only, no agent", "tables": [schema_profile(d, inventory, engine, cfg) for d in defs]}
|
|
565
|
+
by_table = {t["name"]: t for t in profile["tables"]}
|
|
566
|
+
# every parameter's value on a few rows of the table it filters, so each statement selects rows
|
|
567
|
+
from .rank import _columns
|
|
568
|
+
for cand in candidates:
|
|
569
|
+
values: dict[str, list[dict]] = {}
|
|
570
|
+
for pname, where in (cand.get("synthesized") or {}).items():
|
|
571
|
+
table = _bare(where["table"])
|
|
572
|
+
col = where["column"]
|
|
573
|
+
spec = next((c for c in by_table[table]["columns"] if c["name"].lower() == col.lower()), None)
|
|
574
|
+
got = _columns(definitions[table]["create_sql"], table)
|
|
575
|
+
line = next((v for k, v in (got[1] if got else {}).items() if k.lower() == col.lower()), "")
|
|
576
|
+
typ = (line.split() + ["", ""])[1]
|
|
577
|
+
value = _value_for(spec, typ)
|
|
578
|
+
if value is None:
|
|
579
|
+
# "qopt-": kept from before the rename (formerly qopt) so the generated rows stay the same
|
|
580
|
+
value = f"qopt-{col}-1" if not re.search(r"INT|REAL|NUM|FLOA|DOUB", typ, re.I) else 1
|
|
581
|
+
values.setdefault(table, []).append({"column": spec["name"] if spec else col, "value": value})
|
|
582
|
+
cand["params"][pname] = value
|
|
583
|
+
for table, vals in values.items():
|
|
584
|
+
by_table[table]["fixtures"].append({"id": cand["finding"], "values": vals, "share": float(cfg["fixture_share"]),
|
|
585
|
+
"min_rows": int(cfg["fixture_min_rows"]),
|
|
586
|
+
"basis": "schema only: the statement's parameter values on a few rows"})
|
|
587
|
+
rank = {"engine": engine, "engine_version": "", "candidates": candidates, "table_definitions": defs, "schema_only": True,
|
|
588
|
+
"agent": {"runner": "", "model": "", "cost_usd": 0.0}, "shortlist": [], "rejected": []}
|
|
589
|
+
notes.append(f"{len(candidates)} loop statement(s) on {len(defs)} table(s) of the repository's own schema, with data from the "
|
|
590
|
+
"columns alone (no agent): their loops are benchmarked, nothing else")
|
|
591
|
+
return rank, copy.deepcopy(profile), notes
|