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/apply/trial.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"""`codecop apply --trial`: how to prove a ClickHouse skip index or projection on ONE production partition.
|
|
2
|
+
Text only: CodeCop never runs a write. You run the statements.
|
|
3
|
+
|
|
4
|
+
1. ADD INDEX / ADD PROJECTION metadata only: no part is rewritten, new parts get it as they are written
|
|
5
|
+
2. MATERIALIZE ... IN PARTITION ID builds it for one recent closed partition (a mutation of that partition's parts;
|
|
6
|
+
index files only for a skip index, the data is hard-linked), with the build cost
|
|
7
|
+
estimated from the sandbox's build and the partition's real size (an estimate)
|
|
8
|
+
3. compare SelectedMarks per run of the statements it serves, runs inside the trial
|
|
9
|
+
partition against runs inside a neighbouring one, from the query log: a follow-up
|
|
10
|
+
`codecop db pull --locality-only --trial-compare <id>` reads it (counts only)
|
|
11
|
+
4. DROP if no gain DROP INDEX / DROP PROJECTION (metadata, and a light mutation)
|
|
12
|
+
|
|
13
|
+
Runs that reach over the trial partition and an older one read both: the comparison counts only runs whose partitions
|
|
14
|
+
are exactly the trial partition (or exactly the neighbour). ADD INDEX is quick; MATERIALIZE of a partition of
|
|
15
|
+
millions of rows takes seconds and writes the index's size."""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import re
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
|
|
22
|
+
from .common import APPLY_DIR, human_bytes, human_duration, real_table
|
|
23
|
+
|
|
24
|
+
TRIAL_DIR = "trial"
|
|
25
|
+
KINDS = ("skip_index", "projection", "aggregating_projection")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _partitions(catalog: dict | None, table: str) -> tuple[str | None, str | None, dict]:
|
|
29
|
+
"""(trial partition id, neighbour partition id, sizes): the newest partition nothing writes to any more (by its parts'
|
|
30
|
+
last change), and the one before it."""
|
|
31
|
+
for conn in (catalog or {}).get("connections") or {}:
|
|
32
|
+
c = catalog["connections"][conn]
|
|
33
|
+
if c.get("engine") != "clickhouse":
|
|
34
|
+
continue
|
|
35
|
+
for t in c.get("tables") or []:
|
|
36
|
+
if t.get("name") != table.split(".")[-1]:
|
|
37
|
+
continue
|
|
38
|
+
d = t.get("partition_parts") or {}
|
|
39
|
+
ids = list(d.get("ids") or [])
|
|
40
|
+
if not ids:
|
|
41
|
+
return None, None, {}
|
|
42
|
+
last = d.get("last_modified") or [None] * len(ids)
|
|
43
|
+
newest = max((x for x in last if x), default=None)
|
|
44
|
+
# closed: nothing changed it for a day before the newest change of the table (the newest when none is)
|
|
45
|
+
i = next((k for k, x in enumerate(last) if newest and x and x < newest - 86400), 0)
|
|
46
|
+
j = i + 1 if i + 1 < len(ids) else None
|
|
47
|
+
return ids[i], (ids[j] if j is not None else None), {"rows": int((d.get("rows") or [0])[i] or 0),
|
|
48
|
+
"parts": int((d.get("parts") or [0])[i] or 0),
|
|
49
|
+
"marks": int((d.get("marks") or [0])[i] or 0),
|
|
50
|
+
"database": t.get("database") or ""}
|
|
51
|
+
return None, None, {}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _build_estimate(s: dict, real: dict | None, part_rows: int) -> dict:
|
|
55
|
+
"""The MATERIALIZE of one partition: the sandbox's build time and size scaled by the partition's rows over the
|
|
56
|
+
sandbox table's (an estimate; the server's own speed and load are not known)."""
|
|
57
|
+
ed = s.get("engine_detail") or {}
|
|
58
|
+
size = s.get("size") or {}
|
|
59
|
+
sandbox_bytes = size.get("table_bytes_sandbox") or 0
|
|
60
|
+
out: dict = {"basis": "estimate: the sandbox's build scaled by the partition's size"}
|
|
61
|
+
if real and real.get("bytes_on_disk") and real.get("rows") and part_rows:
|
|
62
|
+
part_bytes = real["bytes_on_disk"] * part_rows / real["rows"]
|
|
63
|
+
share = part_bytes / sandbox_bytes if sandbox_bytes else None
|
|
64
|
+
if share and ed.get("setup_s_sandbox"):
|
|
65
|
+
out["seconds"] = round(float(ed["setup_s_sandbox"]) * share, 1)
|
|
66
|
+
if share and size.get("bytes_sandbox"):
|
|
67
|
+
out["bytes_written"] = int(size["bytes_sandbox"] * share)
|
|
68
|
+
out["partition_bytes"] = int(part_bytes)
|
|
69
|
+
return out
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def plan(s: dict, doc: dict, catalog: dict | None) -> dict:
|
|
73
|
+
"""The trial of one suggestion: {id, table, partition, neighbour, sql: [..], compare, estimate, words}. The trial file
|
|
74
|
+
stays on this machine (it names the database and partitions)."""
|
|
75
|
+
ed = s.get("engine_detail") or {}
|
|
76
|
+
table = s["table"]
|
|
77
|
+
pid, neighbour, sizes = _partitions(catalog, table)
|
|
78
|
+
database = sizes.get("database") or ""
|
|
79
|
+
target = f"{database}.{table}" if database and "." not in table else table
|
|
80
|
+
real = real_table(catalog, "clickhouse", table)
|
|
81
|
+
out = {"id": s["id"], "fingerprint": s.get("fingerprint"), "kind": s["kind"], "table": table, "database": database,
|
|
82
|
+
"now": (s.get("outcome") or {}).get("words") or str((s.get("outcome") or {}).get("reason") or "not judged").replace("_", " "),
|
|
83
|
+
"partition": pid, "neighbour": neighbour,
|
|
84
|
+
"partition_rows": sizes.get("rows"), "estimate": _build_estimate(s, real, sizes.get("rows") or 0), "sql": [], "notes": []}
|
|
85
|
+
if s["kind"] == "skip_index":
|
|
86
|
+
name = ed.get("index")
|
|
87
|
+
g = ed.get("granularity_chosen") or (ed.get("granularities") or [1])[0]
|
|
88
|
+
add = f"ALTER TABLE {target} ADD INDEX {name} {ed.get('expr')} TYPE {ed.get('type')} GRANULARITY {g}"
|
|
89
|
+
build = f"ALTER TABLE {target} MATERIALIZE INDEX {name} IN PARTITION ID '{pid}'"
|
|
90
|
+
drop = f"ALTER TABLE {target} DROP INDEX {name}"
|
|
91
|
+
else:
|
|
92
|
+
name = ed.get("projection")
|
|
93
|
+
body = re.search(r"ADD PROJECTION\s+\S+\s+(\(.*\))\s*$", (s.get("ddl") or [""])[0], re.S)
|
|
94
|
+
add = f"ALTER TABLE {target} ADD PROJECTION {name} {body.group(1) if body else '(...)'}"
|
|
95
|
+
build = f"ALTER TABLE {target} MATERIALIZE PROJECTION {name} IN PARTITION ID '{pid}'"
|
|
96
|
+
drop = f"ALTER TABLE {target} DROP PROJECTION {name}"
|
|
97
|
+
if ed.get("needs_setting"):
|
|
98
|
+
out["notes"].append(f"the table needs {ed['needs_setting']} before the projection is added")
|
|
99
|
+
if pid is None:
|
|
100
|
+
out["notes"].append("the pulled catalog has no partitions for this table: choose a recent closed partition yourself")
|
|
101
|
+
build = build.replace("'None'", "'<partition id>'")
|
|
102
|
+
out["sql"] = [add, build]
|
|
103
|
+
out["drop"] = drop
|
|
104
|
+
# the normalized hashes of the statements production ran that it serves (`shape:<hash>`)
|
|
105
|
+
out["hashes"] = [h for sv in s.get("serves") or [] if sv.get("sql_from") == "query_log"
|
|
106
|
+
for h in [str(sv.get("statement") or "").split(":", 1)[-1]] if h.isdigit()]
|
|
107
|
+
out["name"] = name
|
|
108
|
+
out["compare"] = (f"codecop db pull --locality-only --trial-compare {s['id']} (after the MATERIALIZE has finished and the statements "
|
|
109
|
+
"have run for a while): SelectedMarks per run, as a share of the marks each run chose from, on runs that read only "
|
|
110
|
+
f"partition {pid} after the build against before it (else against runs that read only {neighbour or 'a neighbour'}), "
|
|
111
|
+
"per statement it serves. A statement with no time bound reads every partition and is not compared. Counts only.")
|
|
112
|
+
return out
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def text(t: dict) -> str:
|
|
116
|
+
"""The trial as a .sql file a person reads and runs."""
|
|
117
|
+
est = t["estimate"]
|
|
118
|
+
cost = []
|
|
119
|
+
if est.get("seconds") is not None:
|
|
120
|
+
cost.append(f"about {human_duration(est['seconds'])}")
|
|
121
|
+
if est.get("bytes_written") is not None:
|
|
122
|
+
cost.append(f"about {human_bytes(est['bytes_written'])} written")
|
|
123
|
+
if est.get("partition_bytes"):
|
|
124
|
+
cost.append(f"the partition holds {human_bytes(est['partition_bytes'])}")
|
|
125
|
+
lines = [f"-- codecop apply --trial {t['id']}: {t['kind'].replace('_', ' ')} on {t['table']}, proved on one partition.",
|
|
126
|
+
"-- CodeCop runs none of this: review it, then run it yourself. Where it stands now: " + (t.get("now") or "not judged") + ".",
|
|
127
|
+
"-- This trial (with its insert side within the limits on the sandbox) is what can make it Fixed.", "",
|
|
128
|
+
"-- 1. Metadata only: no existing part is rewritten.", t["sql"][0] + ";", "",
|
|
129
|
+
f"-- 2. Build it for one recent closed partition ({t['partition_rows'] or 0:,} rows"
|
|
130
|
+
+ (f"; {', '.join(cost)}, {est['basis']}" if cost else "; build cost not known: no sandbox build or no real size") + ").",
|
|
131
|
+
"-- A mutation of that partition's parts; on a replicated table every replica builds it.", t["sql"][1] + ";", "",
|
|
132
|
+
"-- 3. Let the statements it serves run on the trial partition, then compare (reads the query log, counts only):",
|
|
133
|
+
f"-- {t['compare']}", "", "-- 4. No gain: remove it (metadata, and a light mutation).", "-- " + t["drop"] + ";"]
|
|
134
|
+
for n in t["notes"]:
|
|
135
|
+
lines.insert(4, f"-- Note: {n}.")
|
|
136
|
+
return "\n".join(lines) + "\n"
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def write(out_dir: Path, trials: list[dict]) -> list[Path]:
|
|
140
|
+
base = out_dir / APPLY_DIR / TRIAL_DIR
|
|
141
|
+
base.mkdir(parents=True, exist_ok=True)
|
|
142
|
+
files = []
|
|
143
|
+
for t in trials:
|
|
144
|
+
p = base / f"{re.sub(r'[^A-Za-z0-9_-]', '_', t['id'])}.sql"
|
|
145
|
+
p.write_text(text(t))
|
|
146
|
+
files.append(p)
|
|
147
|
+
import json
|
|
148
|
+
(base / "trials.json").write_text(json.dumps(trials, indent=1, ensure_ascii=False))
|
|
149
|
+
return files
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def chosen(doc: dict, wanted: list[str]) -> list[dict]:
|
|
153
|
+
"""The suggestions to write a trial for: those named, else every skip index or projection counted on production
|
|
154
|
+
with a gain (measured_on_production) and every one the sandbox verified."""
|
|
155
|
+
want = {w.upper() for w in wanted or []}
|
|
156
|
+
out = []
|
|
157
|
+
for s in doc.get("table_suggestions") or []:
|
|
158
|
+
if s["kind"] not in KINDS:
|
|
159
|
+
continue
|
|
160
|
+
if want:
|
|
161
|
+
if s["id"].upper() in want or str(s.get("fingerprint") or "").upper() in want:
|
|
162
|
+
out.append(s)
|
|
163
|
+
continue
|
|
164
|
+
if (s.get("outcome") or {}).get("reason") in ("measured_on_production", "verified"):
|
|
165
|
+
out.append(s)
|
|
166
|
+
return out
|
codecop/assemble.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""Statements the code assembles at run time, written out by the agent: `codecop rank --focus assembled`.
|
|
2
|
+
|
|
3
|
+
A query the rank step rejected as `unresolved_sql` is one the code builds from pieces (optional clauses, a table or
|
|
4
|
+
column chosen at run time, a CTE template, a filter tree), a piece of a longer statement, a trigger body, or a statement
|
|
5
|
+
over a table the repository does not define. With no pull (or when production's log did not show it) nothing measured
|
|
6
|
+
says what it sends, so it ended "could not be judged". This step asks the agent, in small batches, to read the builder
|
|
7
|
+
and write the statement the code sends in its usual call, as a concrete, runnable candidate. The sandbox then
|
|
8
|
+
measures it like any other candidate; the finding says `sql_from: agent` ("SQL written by the agent from code") and the
|
|
9
|
+
choices the agent made (`assembled.choices`), and a win on it is counted apart from load saved in production
|
|
10
|
+
(blockers.ASSEMBLED_SQL).
|
|
11
|
+
|
|
12
|
+
Which queries go: the earlier rank's `unresolved_sql` rejections, except SQL that comes from outside the code (a
|
|
13
|
+
parameter of a generic executor: nothing at the site says what runs). Local, free; the agent call is rank's.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
from .blockers import OUTSIDE_CODE, has_fragments
|
|
19
|
+
|
|
20
|
+
FOCUS = "assembled"
|
|
21
|
+
REJECTION_CODE = "unresolved_sql"
|
|
22
|
+
# a baseline this much longer than the site's own text is the whole statement a piece belongs to, written by the agent
|
|
23
|
+
PIECE_GROWTH = 1.5
|
|
24
|
+
PIECE_SLACK_CHARS = 80
|
|
25
|
+
|
|
26
|
+
FOCUS_TEXT = """
|
|
27
|
+
## Focus: statements assembled at run time
|
|
28
|
+
|
|
29
|
+
Every entry below was examined before and set aside as `unresolved_sql`: its SQL is built at run time, it is one piece of
|
|
30
|
+
a longer statement, or it reads a table the repository does not define. This pass exists to resolve them. Read the
|
|
31
|
+
function that builds each one and its callers, and return the statement the code really sends as a candidate, runnable
|
|
32
|
+
on the sandbox as written:
|
|
33
|
+
- Optional clauses, a filter tree or a list of conditions: choose the combination the main caller sends (the request
|
|
34
|
+
path's defaults, the UI's default filters, the organization or tenant scope plus the default time range). Say which
|
|
35
|
+
in `assumptions`.
|
|
36
|
+
- A table, column or CTE chosen at run time from a fixed set in the code (a map, an enum, a switch, a constant per
|
|
37
|
+
family or kind): take the one the hottest caller uses. Say which in `assumptions`.
|
|
38
|
+
- A CTE template or a query built by appending parts (QueryBuilder `push`, `strings.Builder`, `format!`, string
|
|
39
|
+
concatenation): write the whole statement as it is sent.
|
|
40
|
+
- An entry that is only a piece of a longer statement (a fragment pushed into a builder, a CTE body over names the
|
|
41
|
+
statement itself defines, a `.sql` file that is part of another): return the whole statement it belongs to as this
|
|
42
|
+
entry's candidate. When the whole statement is itself another entry of this list, reject this one with `duplicate`
|
|
43
|
+
and a `detail` that starts with `part of <that entry's id>`.
|
|
44
|
+
- A trigger or function body that reads `NEW.` or `OLD.` values: it runs once per written row; write it as a standalone
|
|
45
|
+
SELECT with every `NEW.col` and `OLD.col` as a parameter of the column's type, and say `trigger body` in
|
|
46
|
+
`assumptions`.
|
|
47
|
+
- A table no migration or schema file defines (another service owns it): assemble its definition from the columns
|
|
48
|
+
the statements read and write and from the structs or models that map it, return it with `inferred: true`, and name
|
|
49
|
+
the guesses in `basis` (column types, indexes the code relies on). Only when nothing in the code shows its columns,
|
|
50
|
+
reject it.
|
|
51
|
+
Return every entry you resolve as a candidate, also when you expect it to be cheap: the sandbox measures the statement,
|
|
52
|
+
and that measurement, not a guess, decides whether there is anything to gain. When no change is worth testing, return
|
|
53
|
+
an empty `variants` list. The first label of `assumptions` is `assembled: ` followed by the choices you made, at most 80
|
|
54
|
+
characters. Reject with `unresolved_sql` only what the code truly cannot say: SQL taken from a request, a stored query,
|
|
55
|
+
a user's input, or a generic executor's parameter.
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def todo(rank_data: dict | None, inventory: dict | None, *, asked_again: bool = True) -> list[str]:
|
|
60
|
+
"""The call-site ids of the queries the earlier rank rejected as `unresolved_sql` that the code can tell: every one
|
|
61
|
+
except SQL from outside the code (OUTSIDE_CODE resolutions). In the order the rank listed them. `asked_again`
|
|
62
|
+
False leaves out the ones this pass already answered (their shortlist entry is of this focus): what the run's queue
|
|
63
|
+
still has to ask; the command itself asks about all of them (answers stored before cost nothing)."""
|
|
64
|
+
sites = {s["id"]: s for s in (inventory or {}).get("call_sites") or [] if s.get("id")}
|
|
65
|
+
done = {s.get("id") for s in (rank_data or {}).get("shortlist") or [] if s.get("focus") == FOCUS}
|
|
66
|
+
out = []
|
|
67
|
+
for r in (rank_data or {}).get("rejected") or []:
|
|
68
|
+
if r.get("code") != REJECTION_CODE or r.get("by_rule"):
|
|
69
|
+
continue
|
|
70
|
+
if not asked_again and r.get("id") in done:
|
|
71
|
+
continue
|
|
72
|
+
s = sites.get(r.get("id"))
|
|
73
|
+
if not s or s.get("resolution") in OUTSIDE_CODE or not (s.get("sql") or "").strip():
|
|
74
|
+
continue
|
|
75
|
+
if r["id"] not in out:
|
|
76
|
+
out.append(r["id"])
|
|
77
|
+
return out
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def restrict(inventory: dict, ids: list[str] | set[str]) -> dict:
|
|
81
|
+
"""The inventory with only the call sites that send the SQL of `ids` (every site of one query, so the shortlist
|
|
82
|
+
keeps its other locations). A copy."""
|
|
83
|
+
by_id = {s["id"]: s for s in inventory.get("call_sites") or [] if s.get("id")}
|
|
84
|
+
hashes = {by_id[i].get("sql_hash") for i in ids if i in by_id}
|
|
85
|
+
out = dict(inventory)
|
|
86
|
+
out["call_sites"] = [s for s in inventory.get("call_sites") or [] if s.get("sql_hash") in hashes]
|
|
87
|
+
return out
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def label(cand: dict, site: dict | None) -> dict:
|
|
91
|
+
"""What a candidate this pass returned says about where its SQL comes from: `sql_from` `agent` when the site's SQL
|
|
92
|
+
has run-time parts the agent filled (or the agent wrote the whole statement a piece belongs to); otherwise the code's
|
|
93
|
+
own text stood (the definitions were what was missing) and no `sql_from` is set here. `assembled` {by, written,
|
|
94
|
+
choices}: the choices it made, as its labels."""
|
|
95
|
+
sql = " ".join(((site or {}).get("sql") or "").split())
|
|
96
|
+
base = " ".join((cand.get("baseline_sql") or "").split())
|
|
97
|
+
# binds are always rewritten ({name:type}): only run-time parts filled, or a piece grown into its whole statement,
|
|
98
|
+
# make the text the agent's
|
|
99
|
+
written = has_fragments(sql) or len(base) > PIECE_GROWTH * len(sql) + PIECE_SLACK_CHARS
|
|
100
|
+
choices = [a for a in cand.get("assumptions") or [] if isinstance(a, str)][:4]
|
|
101
|
+
out = {"assembled": {"by": "agent", "written": bool(written), "choices": choices}}
|
|
102
|
+
if written:
|
|
103
|
+
out["sql_from"] = "agent" # otherwise observed.sql_from_of decides from the call site, as for any candidate
|
|
104
|
+
return out
|