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
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
"""The paid step of the scenarios: variants no rule can write, asked of the agent (`codecop rank --scenario-variants`).
|
|
2
|
+
|
|
3
|
+
A rule writes a variant when the change is mechanical (PREWHERE on the key predicates, an existence probe, an identity
|
|
4
|
+
wrapper removed, the page picked on the key first, a skip index). Some changes need judgement: a predicate whose wrapper
|
|
5
|
+
changes the value (`lower(col) = ?`), a time bound that has to come from somewhere (the outer query's, a bound implied by
|
|
6
|
+
the id), the columns a caller really uses, an aggregate carried through wide columns. Those candidates are listed here,
|
|
7
|
+
with the evidence that made them candidates and what is asked, and the agent proposes variants of the statement each is
|
|
8
|
+
bound to. The baseline stays as it is; every variant is benchmarked like any other and is a win only when the sandbox
|
|
9
|
+
verifies it. `--dry-run` writes the prompt and prints the estimate; nothing is spent.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from datetime import datetime, timezone
|
|
15
|
+
|
|
16
|
+
from .agent import AgentError
|
|
17
|
+
from .scenarios import LABEL
|
|
18
|
+
|
|
19
|
+
BATCH = 20
|
|
20
|
+
ASK = {"rewrite_wrapped_predicate": "rewrite the predicate so the key column is compared bare (or through a function the key analysis "
|
|
21
|
+
"sees through), returning the same rows",
|
|
22
|
+
"add_time_bound": "add a bound on the table's time key that the statement already implies (the outer query's window, a "
|
|
23
|
+
"range derived from an id), returning the same rows; none when no bound is implied",
|
|
24
|
+
"narrow_columns": "read only the columns the code uses (read the call site); same rows for the columns it uses",
|
|
25
|
+
"late_materialization_aggregate": "aggregate on narrow columns and read the wide ones only for the rows of the page",
|
|
26
|
+
"query_rewrite": "a rewrite that lets the key serve the filter"}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def statements_for(doc: dict, rank: dict | None, observed: dict | None) -> list[dict]:
|
|
30
|
+
"""One entry per bound statement with at least one change that needs the agent, not asked yet."""
|
|
31
|
+
by_finding = {c["finding"]: c for c in (rank or {}).get("candidates") or []}
|
|
32
|
+
by_finding.update({c["finding"]: c for c in (observed or {}).get("candidates") or []})
|
|
33
|
+
by_finding.update({c["finding"]: c for c in doc.get("runnable") or []})
|
|
34
|
+
out: dict[str, dict] = {}
|
|
35
|
+
for c in doc.get("candidates") or []:
|
|
36
|
+
f = (c.get("bench") or {}).get("finding")
|
|
37
|
+
asks = [x["change"] for x in c.get("changes") or [] if x["proof"] == "needs_agent" and x["change"] in ASK]
|
|
38
|
+
if not f or not asks or c.get("agent_asked") or f not in by_finding:
|
|
39
|
+
continue
|
|
40
|
+
b = by_finding[f]
|
|
41
|
+
e = out.setdefault(f, {"finding": f, "baseline_sql": b.get("baseline_sql") or "", "tables": list(b.get("tables") or []),
|
|
42
|
+
"site": b.get("site") or {}, "items": []})
|
|
43
|
+
e["items"].append({"candidate": c["id"], "fingerprint": c["fingerprint"], "scenario": c["scenario"], "asks": asks,
|
|
44
|
+
"evidence": c.get("evidence") or []})
|
|
45
|
+
return list(out.values())
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def estimate(statements: list[dict]) -> dict:
|
|
49
|
+
from .rank import COST_PER_QUERY_USD
|
|
50
|
+
n = len(statements)
|
|
51
|
+
return {"statements": n, "batches": -(-n // BATCH) if n else 0, "cost_low_usd": round(n * COST_PER_QUERY_USD[0], 2),
|
|
52
|
+
"cost_high_usd": round(n * COST_PER_QUERY_USD[1], 2), "findings": [s["finding"] for s in statements]}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _evidence_line(e: dict) -> str:
|
|
56
|
+
keep = {k: v for k, v in e.items() if k in ("rule", "table", "column", "functions", "time_columns", "wide_columns", "no_result_share",
|
|
57
|
+
"median_run_bytes", "rows_read_per_run", "rows_returned_per_run", "joined_side")}
|
|
58
|
+
return ", ".join(f"{k}: {v}" for k, v in keep.items())
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def prompt(statements: list[dict], definitions: list[dict], engine: str, version: str) -> str:
|
|
62
|
+
from . import engines
|
|
63
|
+
from .rank import _fill, load_prompt
|
|
64
|
+
blocks = []
|
|
65
|
+
for s in statements:
|
|
66
|
+
asks = []
|
|
67
|
+
for it in s["items"]:
|
|
68
|
+
asks += [f"- {LABEL[it['scenario']]} ({it['candidate']}): {ASK[a]}" for a in it["asks"]]
|
|
69
|
+
asks += [f" evidence: {_evidence_line(e)}" for e in it["evidence"]]
|
|
70
|
+
site = s["site"]
|
|
71
|
+
blocks.append(f"### {s['finding']}\ncall site: {site.get('file') or '(none)'}:{site.get('line') or 0}\ntables: {', '.join(s['tables'])}\n"
|
|
72
|
+
+ "\n".join(asks) + f"\n```sql\n{s['baseline_sql']}\n```")
|
|
73
|
+
tables = "\n\n".join(f"### {d['name']}\n```sql\n{d['create_sql'].strip()}\n```" for d in definitions) or "(none)"
|
|
74
|
+
return _fill(load_prompt("scenario_variants"), {"engine": engines.get(engine).label, "engine_version": version,
|
|
75
|
+
"tables": tables, "statements": "\n\n".join(blocks)})
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
PROMPT_REV = "scenario-1" # bumped when the instructions change answers: stored answers are asked again
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def answer_key(s: dict, answers, engine: str) -> str:
|
|
82
|
+
"""The answer store's key of one bound statement's scenario question (verdicts.Answers)."""
|
|
83
|
+
import json
|
|
84
|
+
from . import engines, verdicts
|
|
85
|
+
from .observed import variants_schema
|
|
86
|
+
schema = variants_schema()
|
|
87
|
+
schema["properties"]["candidates"]["items"]["properties"]["variants"]["items"]["properties"]["kind"]["enum"] = list(engines.get(engine).variant_kinds)
|
|
88
|
+
return _answer_key(s, answers, verdicts.prompt_version(PROMPT_REV, json.dumps(schema, sort_keys=True)))
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _answer_key(s: dict, answers, pv: str) -> str:
|
|
92
|
+
asks = sorted({a for it in s.get("items") or [] for a in it.get("asks") or []})
|
|
93
|
+
return answers.key("scenario", s.get("baseline_sql") or "", s.get("tables") or [], pv, ",".join(asks))
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def ask(doc: dict, statements: list[dict], definitions: list[dict], root, runner, *, engine: str, version: str, model: str | None = None,
|
|
97
|
+
max_budget_usd: float | None = None, batch_size: int | None = None, answers=None, fresh=False) -> dict:
|
|
98
|
+
"""Run the paid step. Changes `doc` in place: each asked candidate gets `agent_asked` and `agent_variants`; the
|
|
99
|
+
ledger is `doc.agent`. Returns {asked, with_variants, cost_usd}. `answers` (verdicts.Answers): a statement answered
|
|
100
|
+
before for the same changes, with the same text on the same table definitions, takes its stored answer."""
|
|
101
|
+
from . import engines, verdicts
|
|
102
|
+
from .agent import UsageLimitError
|
|
103
|
+
from .observed import variants_schema
|
|
104
|
+
import json
|
|
105
|
+
schema = variants_schema()
|
|
106
|
+
schema["properties"]["candidates"]["items"]["properties"]["variants"]["items"]["properties"]["kind"]["enum"] = list(engines.get(engine).variant_kinds)
|
|
107
|
+
by_fp = {c["fingerprint"]: c for c in doc.get("candidates") or []}
|
|
108
|
+
spent, asked, got = 0.0, 0, 0
|
|
109
|
+
ledger = doc.setdefault("agent", {"calls": []})
|
|
110
|
+
size = max(int(batch_size or BATCH), 1) # `[agent] items_per_call.scenario`
|
|
111
|
+
stopped = limited = False
|
|
112
|
+
pv = verdicts.prompt_version(PROMPT_REV, json.dumps(schema, sort_keys=True))
|
|
113
|
+
reused = 0
|
|
114
|
+
if answers is not None:
|
|
115
|
+
left = []
|
|
116
|
+
for s in statements:
|
|
117
|
+
rec = answers.get(_answer_key(s, answers, pv), fresh, ref=s["finding"], file=(s.get("site") or {}).get("file") or "")
|
|
118
|
+
if rec is None:
|
|
119
|
+
left.append(s)
|
|
120
|
+
continue
|
|
121
|
+
variants = list((rec.get("answer") or {}).get("variants") or [])
|
|
122
|
+
for it in s["items"]:
|
|
123
|
+
c = by_fp.get(it["fingerprint"])
|
|
124
|
+
if c is not None:
|
|
125
|
+
c["agent_asked"] = True
|
|
126
|
+
c["agent_variants"] = variants
|
|
127
|
+
c["answered_before"] = True
|
|
128
|
+
reused += 1
|
|
129
|
+
statements = left
|
|
130
|
+
for i in range(0, len(statements), size):
|
|
131
|
+
batch = statements[i:i + size]
|
|
132
|
+
left = None if max_budget_usd is None else max(max_budget_usd - spent, 0.0)
|
|
133
|
+
if left is not None and left <= 0:
|
|
134
|
+
stopped = True
|
|
135
|
+
break
|
|
136
|
+
names = {t for s in batch for t in s["tables"]}
|
|
137
|
+
if hasattr(runner, "tell"):
|
|
138
|
+
runner.tell("scenario", len(batch))
|
|
139
|
+
try:
|
|
140
|
+
result = runner.run(prompt(batch, [d for d in definitions if d["name"] in names], engine, version), schema, root, model=model,
|
|
141
|
+
max_budget_usd=left)
|
|
142
|
+
except UsageLimitError:
|
|
143
|
+
stopped = limited = True # the agent's usage limit: what was asked so far is kept
|
|
144
|
+
break
|
|
145
|
+
except AgentError as e:
|
|
146
|
+
if "budget" not in str(e).lower():
|
|
147
|
+
raise
|
|
148
|
+
stopped = True # the run budget is reached: what was asked so far is kept
|
|
149
|
+
break
|
|
150
|
+
spent += float(result.cost_usd or 0)
|
|
151
|
+
ledger["calls"].append({"findings": [s["finding"] for s in batch], "cost_usd": round(float(result.cost_usd or 0), 6),
|
|
152
|
+
"model": result.model, "at": datetime.now(timezone.utc).isoformat(timespec="seconds")})
|
|
153
|
+
said = {e.get("id"): e for e in (result.output or {}).get("candidates") or []}
|
|
154
|
+
for s in batch:
|
|
155
|
+
variants = [v for v in (said.get(s["finding"]) or {}).get("variants") or [] if v.get("sql")][:3]
|
|
156
|
+
for it in s["items"]:
|
|
157
|
+
c = by_fp.get(it["fingerprint"])
|
|
158
|
+
if c is None:
|
|
159
|
+
continue
|
|
160
|
+
c["agent_asked"] = True
|
|
161
|
+
c["agent_variants"] = [{**v, "change": v.get("change") or "agent_variant"} for v in variants]
|
|
162
|
+
asked += 1
|
|
163
|
+
got += bool(variants)
|
|
164
|
+
if answers is not None:
|
|
165
|
+
answers.put(_answer_key(s, answers, pv), {"kind": "scenario", "id": s["finding"], "model": result.model,
|
|
166
|
+
"answer": {"variants": [{**v, "change": v.get("change") or "agent_variant"} for v in variants]}},
|
|
167
|
+
save=False)
|
|
168
|
+
if answers is not None:
|
|
169
|
+
answers.save()
|
|
170
|
+
ledger["cost_total_usd"] = round(sum(x["cost_usd"] for x in ledger["calls"]), 4)
|
|
171
|
+
return {"asked": asked, "with_variants": got, "cost_usd": round(spent, 4), "stopped_by_budget": stopped and not limited,
|
|
172
|
+
"stopped_by_limit": limited, "answered_before": reused}
|