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,107 @@
|
|
|
1
|
+
"""The test kind: proves the kinds plumbing end to end, used only by tests. Hidden: it runs only when named
|
|
2
|
+
(`codecop scan --only testkind`), never by default, and the console has no words for it (a kind it does not know is shown
|
|
3
|
+
by its name, which is what a new kind looks like before it has custom panels).
|
|
4
|
+
|
|
5
|
+
It finds comment lines `codecop-test-kind: <name> before=<n> after=<n> [ask] [differs] [race]` in source files. `before` and
|
|
6
|
+
`after` stand for a measured time; `ask`: rules cannot judge it, the agent is asked (one call, through the run budget, its
|
|
7
|
+
answer kept per item); `differs`: the fix changes the output; `race`: the harm is a wrong result (a count of lost updates).
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import re
|
|
13
|
+
|
|
14
|
+
from . import Kind, finding, measure, outcome, proof, register, sameness
|
|
15
|
+
|
|
16
|
+
MARK = re.compile(r"codecop-test-kind:\s*([A-Za-z0-9_]+)\s+before=(\d+)\s+after=(\d+)((?:\s+[a-z]+)*)")
|
|
17
|
+
PROMPT_VERSION = "testkind-1"
|
|
18
|
+
SCHEMA = {"type": "object", "properties": {"answers": {"type": "array", "items": {"type": "object", "properties": {
|
|
19
|
+
"id": {"type": "string"}, "after": {"type": "number"}}, "required": ["id", "after"]}}}, "required": ["answers"]}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@register
|
|
23
|
+
class TestKind(Kind):
|
|
24
|
+
name = "testkind"
|
|
25
|
+
label = "Test kind"
|
|
26
|
+
one = "test item"
|
|
27
|
+
prefix = "TK"
|
|
28
|
+
hidden = True
|
|
29
|
+
default_on = False
|
|
30
|
+
reasons = {"testkind.too_small": ("nothing_to_gain", "too small to matter (test)")}
|
|
31
|
+
measures = {"time_ms": ("time", "ms"), "lost_updates": ("updates lost", "count")}
|
|
32
|
+
items_per_call = 5
|
|
33
|
+
|
|
34
|
+
def discover(self, ctx):
|
|
35
|
+
out = []
|
|
36
|
+
for lang, files in (ctx.by_lang or {}).items():
|
|
37
|
+
for rel in files:
|
|
38
|
+
try:
|
|
39
|
+
text = (ctx.root / rel).read_text(errors="replace")
|
|
40
|
+
except OSError:
|
|
41
|
+
continue
|
|
42
|
+
if "codecop-test-kind:" not in text:
|
|
43
|
+
continue
|
|
44
|
+
for n, line in enumerate(text.splitlines(), 1):
|
|
45
|
+
m = MARK.search(line)
|
|
46
|
+
if m:
|
|
47
|
+
flags = set(m.group(4).split())
|
|
48
|
+
out.append({"file": rel, "line": n, "language": lang, "symbol": m.group(1), "text": m.group(0),
|
|
49
|
+
"before": int(m.group(2)), "after": int(m.group(3)), "flags": sorted(flags)})
|
|
50
|
+
return out
|
|
51
|
+
|
|
52
|
+
def rules(self, ctx, sites):
|
|
53
|
+
return [{"id": s["id"], "name": s["symbol"], "before": s["before"], "after": s["after"], "flags": s.get("flags") or [],
|
|
54
|
+
"ask": "ask" in (s.get("flags") or []), "text": s.get("text") or ""} for s in sites if not s.get("is_test")]
|
|
55
|
+
|
|
56
|
+
def _key(self, ctx, c):
|
|
57
|
+
return ctx.answer_key(c["text"], runtime="test", prompt_version=PROMPT_VERSION)
|
|
58
|
+
|
|
59
|
+
def questions(self, ctx, cands):
|
|
60
|
+
return [ctx.item(c["id"], label=c["name"], file=c.get("file", ""), line=c.get("line", 0), why="rules cannot judge it")
|
|
61
|
+
for c in cands if c["ask"] and ctx.answer(self._key(ctx, c)) is None]
|
|
62
|
+
|
|
63
|
+
def ask(self, ctx, cands, runner):
|
|
64
|
+
todo = [c for c in cands if c["ask"] and ctx.answer(self._key(ctx, c)) is None]
|
|
65
|
+
if not todo:
|
|
66
|
+
return
|
|
67
|
+
prompt = "For each id, give the time after the fix.\n" + "\n".join(f"{c['id']}: {c['name']} before={c['before']}" for c in todo)
|
|
68
|
+
result = runner.run(prompt, SCHEMA, ctx.root)
|
|
69
|
+
answers = (getattr(result, "output", None) or {}).get("answers") or []
|
|
70
|
+
by = {a.get("id"): a for a in answers if isinstance(a, dict)}
|
|
71
|
+
for c in todo:
|
|
72
|
+
if c["id"] in by:
|
|
73
|
+
ctx.remember(self._key(ctx, c), {"after": float(by[c["id"]]["after"])})
|
|
74
|
+
|
|
75
|
+
def verify(self, ctx, cands):
|
|
76
|
+
out = []
|
|
77
|
+
for c in cands:
|
|
78
|
+
site = {"file": c.get("file"), "line": c.get("line"), "symbol": c["name"]}
|
|
79
|
+
after = c["after"]
|
|
80
|
+
if c["ask"]:
|
|
81
|
+
got = ctx.answer(self._key(ctx, c))
|
|
82
|
+
if got is None:
|
|
83
|
+
out.append(finding(self.name, id=c["id"], title=f"{c['name']}: waits on the agent", site=site,
|
|
84
|
+
outcome=outcome(self.name, "not_judged", "not_asked", source="claimed")))
|
|
85
|
+
continue
|
|
86
|
+
after = got["after"]
|
|
87
|
+
race = "race" in c["flags"]
|
|
88
|
+
ms = [measure("time_ms", "ms", c["before"], after, spread_before=(c["before"] * 0.97, c["before"] * 1.03),
|
|
89
|
+
spread_after=(after * 0.97, after * 1.03), runs=3)]
|
|
90
|
+
if race:
|
|
91
|
+
ms.append(measure("lost_updates", "count", 40, 0, of=1600))
|
|
92
|
+
same = sameness("same_output", "differs" not in c["flags"], compared=100, differed=7 if "differs" in c["flags"] else 0,
|
|
93
|
+
basis="100 generated inputs")
|
|
94
|
+
p = proof(source="sandbox", measures=ms, same=same, runtime={"engine": "python", "version": "3"},
|
|
95
|
+
scale={"name": "input size", "unit": "KB", "points": [1, 2, 4], "at": 4},
|
|
96
|
+
schedule={"sessions": 2, "operations": 800} if race else None)
|
|
97
|
+
if c["before"] < 5:
|
|
98
|
+
o = outcome(self.name, "nothing_to_gain", "testkind.too_small", evidence={"before": c["before"]})
|
|
99
|
+
elif "differs" in c["flags"]:
|
|
100
|
+
o = outcome(self.name, "blocked", "fix_results_differ")
|
|
101
|
+
elif after <= c["before"] * 0.8:
|
|
102
|
+
o = outcome(self.name, "fixed", "verified")
|
|
103
|
+
else:
|
|
104
|
+
o = outcome(self.name, "blocked", "no_gain_measured")
|
|
105
|
+
out.append(finding(self.name, id=c["id"], title=f"{c['name']}: slow marker", site=site, outcome=o, proof=p,
|
|
106
|
+
harm="both" if race else "speed", fix={"before": f"slow {c['name']}()", "after": f"fast {c['name']}()"}))
|
|
107
|
+
return out
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
"""The transaction kind: places where concurrent sessions make code slow (waits, low throughput) or wrong (lost updates,
|
|
2
|
+
duplicates, deadlocks, failed writes). docs/kinds.md is the contract; this package:
|
|
3
|
+
|
|
4
|
+
shapes.py discovery: transaction blocks, what runs inside them, SQLite opens, ORM read-modify-write (text only)
|
|
5
|
+
rules.py the canonical scenarios from the shapes and the query call sites, with their mechanical fixes
|
|
6
|
+
bind.py the repository's statements bound to generated rows (sqlglot); plan.py the scenario's facts
|
|
7
|
+
scenarios.py each scenario's program before and with the fix, its final-state check and invariant
|
|
8
|
+
schedule.py N sessions of CodeCop's own against the sandbox (PostgreSQL container, SQLite in-process); lanes, errors
|
|
9
|
+
measure.py repeated runs, spread, the worker curve, the verdict (counts and throughput ratios only)
|
|
10
|
+
sandbox.py the throwaway PostgreSQL container
|
|
11
|
+
|
|
12
|
+
`harm`: correctness (a wrong result under concurrency: its own class, never counted as a speed-up), speed, or both.
|
|
13
|
+
No repository code is executed: only its SQL statements, on generated rows, in the sandbox.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import json
|
|
19
|
+
import re
|
|
20
|
+
import time
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
|
|
23
|
+
from .. import Kind, finding, handoff_text, outcome, proof, register
|
|
24
|
+
from . import shapes
|
|
25
|
+
|
|
26
|
+
PROMPT_VERSION = "transaction-1"
|
|
27
|
+
SETTINGS = {
|
|
28
|
+
"sandbox": True, # run the schedules (false: every candidate stays "could not be judged")
|
|
29
|
+
"max_scenarios": 40, # schedules per scan; the rest stay not run (correctness first)
|
|
30
|
+
"runs": 3, # repeated runs per variant (spread)
|
|
31
|
+
"sessions": 8, # concurrent sessions of a schedule (a poll uses poll_sessions)
|
|
32
|
+
"poll_sessions": 2, # pollers of a poll-then-mark schedule
|
|
33
|
+
"operations": 20, # operations per session
|
|
34
|
+
"think_ms": 20, # pause standing in for the act between statements (a post, a computation)
|
|
35
|
+
"call_ms": 50, # pause standing in for the external call inside a transaction
|
|
36
|
+
"work_ms": 5, # a queue job's work inside its claim
|
|
37
|
+
"hot_rows": 2, # rows concurrent requests touch (call in a transaction, read-modify-write)
|
|
38
|
+
"items": 100, # queue items of a poll or a claim
|
|
39
|
+
"batch": 20, # rows a poll asks for when its LIMIT is a placeholder
|
|
40
|
+
"workers": [1, 2], # worker counts measured beside `sessions` for scenarios that need two workers
|
|
41
|
+
"min_gain": 1.2, # a speed gain below this ratio is not a gain, even beyond the spread
|
|
42
|
+
"parents": 4000, "children": 60000, # foreign-key schedule: parent and child rows
|
|
43
|
+
"lock_rows": 6, # rows two transactions lock in opposite orders
|
|
44
|
+
"timeout_s": 120, # one run's limit
|
|
45
|
+
"sample_ms": 20, # PostgreSQL wait sampler interval inside the sandbox
|
|
46
|
+
"pg_version": "17", "memory": "512m", "shared_buffers": "64MB", "deadlock_timeout": "1s",
|
|
47
|
+
"max_sites": 5000,
|
|
48
|
+
}
|
|
49
|
+
TITLES = {
|
|
50
|
+
# the shape, never the verdict: the state says whether it collided
|
|
51
|
+
"queue_claim": "Queue claim on {t}: FOR UPDATE without SKIP LOCKED",
|
|
52
|
+
"poll_then_mark": "{t}: polled without a lock, acted on, then marked",
|
|
53
|
+
"fk_without_index": "{child} → {parent}: foreign key without an index, parent rows deleted",
|
|
54
|
+
"call_in_transaction": "Transaction on {t} open across an outside call ({what})",
|
|
55
|
+
"read_modify_write": "{t}.{col}: read, computed, written back without a lock",
|
|
56
|
+
"lock_order": "{t}: rows locked in different orders by two code paths",
|
|
57
|
+
"sqlite_deferred_begin": "SQLite transaction reads, then writes, under a deferred BEGIN",
|
|
58
|
+
"sqlite_no_wal_timeout": "SQLite opened {how}",
|
|
59
|
+
"unknown": "Transaction shape the rules could not classify",
|
|
60
|
+
}
|
|
61
|
+
PG_ONLY = {"queue_claim", "fk_without_index", "lock_order"}
|
|
62
|
+
SQLITE_ONLY = {"sqlite_deferred_begin", "sqlite_no_wal_timeout"}
|
|
63
|
+
ANSWER_SCHEMA = {"type": "object", "properties": {"answers": {"type": "array", "items": {"type": "object", "properties": {
|
|
64
|
+
"id": {"type": "string"},
|
|
65
|
+
"scenario": {"type": "string", "enum": ["queue_claim", "poll_then_mark", "read_modify_write", "call_in_transaction", "lock_order",
|
|
66
|
+
"sqlite_deferred_begin", "sqlite_no_wal_timeout", "none"]},
|
|
67
|
+
"concurrent": {"type": "boolean", "description": "can two workers or requests run this at the same time"},
|
|
68
|
+
"invariant": {"type": "string"}, "fix_before": {"type": "string"}, "fix_after": {"type": "string"}, "why": {"type": "string"},
|
|
69
|
+
"statement_lines": {"type": "array", "items": {"type": "integer"}}},
|
|
70
|
+
"required": ["id", "scenario", "concurrent", "why"]}}}, "required": ["answers"]}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@register
|
|
74
|
+
class Transaction(Kind):
|
|
75
|
+
name = "transaction"
|
|
76
|
+
label = "Transactions"
|
|
77
|
+
one = "transaction"
|
|
78
|
+
prefix = "T"
|
|
79
|
+
reasons = {
|
|
80
|
+
"transaction.not_reproduced": ("nothing_to_gain", "the schedule ran; nothing collided"),
|
|
81
|
+
"transaction.already_safe": ("nothing_to_gain", "already safe: the lock clause, claim or atomic form is there"),
|
|
82
|
+
"transaction.rarely_runs": ("nothing_to_gain", "the catalog shows it rarely runs (parent deletes)"),
|
|
83
|
+
"transaction.fix_costs_throughput": ("blocked", "removes the wrong results, costs throughput (a trade-off)"),
|
|
84
|
+
"transaction.no_schema": ("not_judged", "its tables are not defined in the repository or the catalog"),
|
|
85
|
+
"transaction.engine_not_supported": ("not_judged", "no contention sandbox for this engine"),
|
|
86
|
+
"transaction.not_replayable": ("not_judged", "its statements could not be replayed"),
|
|
87
|
+
"transaction.claimed": ("not_judged", "proposed, not measured"),
|
|
88
|
+
"transaction.not_run": ("not_judged", "not run: over the scan's schedule limit (max_scenarios)"),
|
|
89
|
+
}
|
|
90
|
+
measures = {"throughput": ("operations per second", "ops/s"), "duplicates": ("duplicates", "count"), "lost_updates": ("updates lost", "count"),
|
|
91
|
+
"deadlocks": ("deadlocks", "count"), "busy_errors": ("busy errors", "count"), "failed_writes": ("writes failed", "count"),
|
|
92
|
+
"delete_ms": ("parent delete time", "ms"), "lock_wait_share": ("samples with a lock wait", "%"),
|
|
93
|
+
"p95_wait_ms": ("p95 wait", "ms"), "idle_in_tx_share": ("samples idle in a transaction", "%"),
|
|
94
|
+
"lock_hold_ms": ("lock held per transaction", "ms"), "lock_wait_ms": ("wait for the lock per transaction", "ms")}
|
|
95
|
+
items_per_call = 8
|
|
96
|
+
cost_per_item_usd = (0.04, 0.08)
|
|
97
|
+
|
|
98
|
+
def cfg(self, ctx) -> dict:
|
|
99
|
+
return {**SETTINGS, **(ctx.settings or {})}
|
|
100
|
+
|
|
101
|
+
# --- discover ----------------------------------------------------------------------------------------------------
|
|
102
|
+
def discover(self, ctx):
|
|
103
|
+
out = []
|
|
104
|
+
cap = int(self.cfg(ctx)["max_sites"])
|
|
105
|
+
hint = re.compile(r"(?i)begin|transaction|atomic|commit|sqlite|\.save\(|Transactional")
|
|
106
|
+
for lang, files in (ctx.by_lang or {}).items():
|
|
107
|
+
if lang not in shapes.LANGS:
|
|
108
|
+
continue
|
|
109
|
+
for rel in files:
|
|
110
|
+
try:
|
|
111
|
+
text = (ctx.root / rel).read_text(errors="replace")
|
|
112
|
+
except OSError:
|
|
113
|
+
continue
|
|
114
|
+
if not hint.search(text):
|
|
115
|
+
continue
|
|
116
|
+
for b in shapes.blocks(text, lang):
|
|
117
|
+
b.update(file=rel, language=lang, shape="tx", calls=shapes.block_calls(text, lang, b), callees=shapes.callees(text, b),
|
|
118
|
+
text=f"tx:{b['form']}:{(text.splitlines()[b['line'] - 1] if b['line'] <= len(text.splitlines()) else '').strip()[:120]}")
|
|
119
|
+
out.append(b)
|
|
120
|
+
for o in shapes.sqlite_opens(text, lang):
|
|
121
|
+
o.update(file=rel, language=lang, shape="sqlite_open", symbol="", text=f"sqlite:{o['text']}")
|
|
122
|
+
out.append(o)
|
|
123
|
+
for r in shapes.orm_rmw(text, lang):
|
|
124
|
+
r.update(file=rel, language=lang, shape="orm_rmw", text=f"rmw:{r['model']}.{r['field']}")
|
|
125
|
+
out.append(r)
|
|
126
|
+
if len(out) >= cap:
|
|
127
|
+
ctx.say(f"transaction: stopped at {cap} shapes (setting max_sites)")
|
|
128
|
+
return out
|
|
129
|
+
return out
|
|
130
|
+
|
|
131
|
+
# --- rules -------------------------------------------------------------------------------------------------------
|
|
132
|
+
def rules(self, ctx, sites):
|
|
133
|
+
from .rules import classify, load_catalog
|
|
134
|
+
cands, counts = classify(sites, ctx.inventory or {}, Path(ctx.root), load_catalog(ctx.out_dir, ctx.settings), self.cfg(ctx))
|
|
135
|
+
_save_counts(ctx, counts, len(sites))
|
|
136
|
+
return cands
|
|
137
|
+
|
|
138
|
+
# --- the agent ---------------------------------------------------------------------------------------------------
|
|
139
|
+
def _key(self, ctx, c):
|
|
140
|
+
shape = json.dumps({"scenario": c.get("scenario"), "steps": [{k: s.get(k) for k in ("op", "table", "lock", "what", "sql")} for s in c.get("steps") or []]},
|
|
141
|
+
sort_keys=True)
|
|
142
|
+
return ctx.answer_key(shape, runtime=c.get("engine") or "", prompt_version=PROMPT_VERSION)
|
|
143
|
+
|
|
144
|
+
def questions(self, ctx, cands):
|
|
145
|
+
return [ctx.item(c["id"], label=f"{c['scenario']} {c.get('symbol') or ''}".strip(), file=c.get("file", ""), line=c.get("line") or 0,
|
|
146
|
+
score=2.0 if c["scenario"] in ("poll_then_mark", "lock_order") else 1.0, why=c.get("why") or "rules cannot judge it")
|
|
147
|
+
for c in cands if c.get("ask") and ctx.answer(self._key(ctx, c)) is None]
|
|
148
|
+
|
|
149
|
+
def ask(self, ctx, cands, runner):
|
|
150
|
+
todo = [c for c in cands if c.get("ask") and ctx.answer(self._key(ctx, c)) is None]
|
|
151
|
+
for i in range(0, len(todo), self.items_per_call):
|
|
152
|
+
part = todo[i:i + self.items_per_call]
|
|
153
|
+
result = runner.run(prompt_for(part), ANSWER_SCHEMA, ctx.root)
|
|
154
|
+
answers = (getattr(result, "output", None) or {}).get("answers") or []
|
|
155
|
+
by = {a.get("id"): a for a in answers if isinstance(a, dict)}
|
|
156
|
+
for c in part:
|
|
157
|
+
if c["id"] in by:
|
|
158
|
+
ctx.remember(self._key(ctx, c), {k: by[c["id"]].get(k) for k in ANSWER_SCHEMA["properties"]["answers"]["items"]["properties"]})
|
|
159
|
+
|
|
160
|
+
# --- verify ------------------------------------------------------------------------------------------------------
|
|
161
|
+
def verify(self, ctx, cands):
|
|
162
|
+
from .verify import verify_all
|
|
163
|
+
return verify_all(self, ctx, cands)
|
|
164
|
+
|
|
165
|
+
def report_html(self, ctx, found):
|
|
166
|
+
from ...report import e
|
|
167
|
+
rows = []
|
|
168
|
+
for f in found:
|
|
169
|
+
o = f.get("outcome") or {}
|
|
170
|
+
p = f.get("proof") or {}
|
|
171
|
+
first = (p.get("measures") or [{}])[0]
|
|
172
|
+
rows.append(f"<tr><td>{e(f.get('finding'))}</td><td>{e(f.get('scenario'))}</td><td>{e((f.get('site') or {}).get('file'))}:"
|
|
173
|
+
f"{e((f.get('site') or {}).get('line'))}</td><td>{e(f.get('title'))}</td><td>{e(o.get('state'))} ({e(o.get('reason'))})</td>"
|
|
174
|
+
f"<td>{e(f.get('harm'))}</td><td>{e(first.get('name', ''))} {e(first.get('before', ''))} → {e(first.get('after', ''))}</td></tr>")
|
|
175
|
+
return ("<h2>Transactions</h2><p class=muted>Concurrency schedules replayed by CodeCop's own sessions in the sandbox; counts and "
|
|
176
|
+
"throughput ratios decide, tail latencies never.</p><table><tr><th>finding</th><th>scenario</th><th>where</th><th>what</th>"
|
|
177
|
+
f"<th>state</th><th>harm</th><th>verdict measure</th></tr>{''.join(rows)}</table>")
|
|
178
|
+
|
|
179
|
+
def handoff(self, f):
|
|
180
|
+
text = handoff_text(f)
|
|
181
|
+
extra = []
|
|
182
|
+
if f.get("scenario"):
|
|
183
|
+
extra.append(f"Scenario: {f['scenario'].replace('_', ' ')}" + (f" ({f.get('engine')})" if f.get("engine") else ""))
|
|
184
|
+
if f.get("invariant"):
|
|
185
|
+
extra.append(f"Invariant: {f['invariant']}")
|
|
186
|
+
w = f.get("workers") or {}
|
|
187
|
+
if w.get("points"):
|
|
188
|
+
extra.append("Workers: " + ", ".join(f"{p['n']}: {p.get('before')} -> {p.get('after')}" for p in w["points"])
|
|
189
|
+
+ f" ({w.get('measure')}); in production: {w.get('production', 'unknown')}")
|
|
190
|
+
for a in f.get("assumptions") or []:
|
|
191
|
+
extra.append(f"Assumption: {a}")
|
|
192
|
+
if f.get("tradeoff"):
|
|
193
|
+
extra.append(f"Trade-off of the fix: {f['tradeoff']}")
|
|
194
|
+
lines = text.split("\n")
|
|
195
|
+
return "\n".join(lines[:3] + extra + lines[3:])
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def prompt_for(cands: list[dict]) -> str:
|
|
199
|
+
parts = ["You judge transaction shapes in a repository (read the files; do not run anything). For each id: which scenario it "
|
|
200
|
+
"is (queue_claim: workers claim rows of a queue; poll_then_mark: rows are polled, acted on outside the database, then "
|
|
201
|
+
"marked; read_modify_write: a value is read, computed in the application and written back; call_in_transaction: an "
|
|
202
|
+
"outside call while a row lock is held; lock_order: rows or tables locked in different orders by code paths that can "
|
|
203
|
+
"run at once; sqlite_deferred_begin; sqlite_no_wal_timeout: a SQLite file opened without WAL or a busy timeout that two connections, threads or processes write at once; none), whether two workers or requests can run it at the same time (say why, from "
|
|
204
|
+
"the code: a scheduler, a pool of workers, an HTTP handler), the invariant a serial run keeps, and the fix as short "
|
|
205
|
+
"before/after text. Say none when the code is safe (a lock, a unique constraint that makes the second act fail, a "
|
|
206
|
+
"single worker by construction). For poll_then_mark: find who calls the poll and the mark (it may be an HTTP route "
|
|
207
|
+
"whose client is outside the repository: then judge from the API the client is given) and say whether the act "
|
|
208
|
+
"(a post, a send) happens before the mark (unsafe with two workers) or only after the mark reported it changed a row "
|
|
209
|
+
"(safe: none).", ""]
|
|
210
|
+
for c in cands:
|
|
211
|
+
parts.append(f"{c['id']}: {c['scenario']} at {c.get('file')}:{c.get('line')} ({c.get('symbol') or ''}): {c.get('why')}")
|
|
212
|
+
for s in c.get("steps") or []:
|
|
213
|
+
parts.append(f" {s.get('line') or ''} {s.get('op')} {s.get('table') or s.get('what') or ''} {(s.get('sql') or '')[:300]}")
|
|
214
|
+
if c.get("other"):
|
|
215
|
+
parts.append(f" other path: {c['other'].get('file')}:{c['other'].get('line')}")
|
|
216
|
+
return "\n".join(parts)
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _save_counts(ctx, counts: dict, sites: int) -> None:
|
|
220
|
+
try:
|
|
221
|
+
p = Path(ctx.out_dir) / "kinds" / "transaction_rules.json"
|
|
222
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
223
|
+
p.write_text(json.dumps({"generated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "shapes": sites, **counts}, indent=1))
|
|
224
|
+
except OSError:
|
|
225
|
+
pass
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
__all__ = ["Transaction", "TITLES", "SETTINGS", "PG_ONLY", "SQLITE_ONLY", "finding", "outcome", "proof"]
|