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,540 @@
|
|
|
1
|
+
"""Rules (free: no agent, no sandbox): transaction shapes and the query call sites discovery found, classified into the
|
|
2
|
+
canonical scenarios, each with its mechanical fix where one exists.
|
|
3
|
+
|
|
4
|
+
- queue_claim: a claim `SELECT .. ORDER BY .. LIMIT .. FOR UPDATE` without SKIP LOCKED on a queue-like filter;
|
|
5
|
+
- poll_then_mark: a poll for unmarked rows (an anti-join on a marker table, `marker IS NULL`, `status = 'pending'`)
|
|
6
|
+
without a lock, and a mark of the same rows (INSERT into the marker table, UPDATE of the marker) in the same file;
|
|
7
|
+
- read_modify_write: a keyed read of a column and an UPDATE writing that column from a value in the same function, no
|
|
8
|
+
lock; or an ORM object read, changed from its own value and saved;
|
|
9
|
+
- call_in_transaction: an HTTP/RPC/LLM call, sleep, publish or subprocess inside a transaction after a row was locked
|
|
10
|
+
(UPDATE, DELETE, SELECT .. FOR UPDATE; on SQLite any write);
|
|
11
|
+
- lock_order: two transactions that write the same two tables in opposite orders, or one that updates two rows of a table
|
|
12
|
+
by two different keys in the order the caller gives;
|
|
13
|
+
- fk_without_index: a foreign key whose child has no index starting with its columns, and code that deletes (or
|
|
14
|
+
updates the key of) the parent; from the pulled catalog when there is one, else the repository's DDL;
|
|
15
|
+
- sqlite_deferred_begin: a SQLite transaction (deferred BEGIN) that reads before it writes;
|
|
16
|
+
- sqlite_no_wal_timeout: a SQLite database opened without WAL or without a busy timeout, in a repository that writes it.
|
|
17
|
+
|
|
18
|
+
Each candidate keeps the facts the planner binds (statements in order, tables) and the reason it was chosen; what the
|
|
19
|
+
rules cannot classify is marked `ask`.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import json
|
|
25
|
+
import re
|
|
26
|
+
from collections import defaultdict
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
|
|
29
|
+
from .. import site_id
|
|
30
|
+
from . import shapes
|
|
31
|
+
|
|
32
|
+
QUEUEISH = re.compile(r"(?:status|state|queued?|pending|scheduled|next_run|run_at|available|attempts|claimed|locked|lease|visible|due|job|task|outbox)", re.I)
|
|
33
|
+
UNMARKED = re.compile(r"LEFT\s+(?:OUTER\s+)?JOIN\s+([\w.\"]+)\s+(?:AS\s+)?(\w+)\s+ON\b.*?\bWHERE\b.*?\b\2\.(\w+)\s+IS\s+NULL|"
|
|
34
|
+
r"NOT\s+EXISTS\s*\(\s*SELECT\b.*?\bFROM\s+([\w.\"]+)|"
|
|
35
|
+
r"\b(\w*(?:processed|delivered|sent|handled|notified|published|claimed|picked|acked|consumed|dispatched|posted|synced|"
|
|
36
|
+
r"enqueued|emitted|exported|reported)\w*)\s+IS\s+NULL|"
|
|
37
|
+
r"\b(status|state)\s*(?:=|IN)\s*\(?\s*'(pending|queued|new|ready|waiting|scheduled|unsent|created|open|todo)'", re.I | re.S)
|
|
38
|
+
ONE_OFF = re.compile(r"/(?:migrations?|modelmigration|alembic|versions|scripts?|examples?|internal_docs|docs?|fixtures|seeds?|benchmarks?|perf)/", re.I)
|
|
39
|
+
# a column the code most likely changes by arithmetic on its own value: the rules measure it without asking
|
|
40
|
+
COUNTER = re.compile(r"(?:count|total|balance|qty|quantity|hits|views|amount|seq|version|^n_|num_|attempts|used|remaining|credits|tokens|spent|"
|
|
41
|
+
r"score|stock|points|sum|size|bytes|retries)", re.I)
|
|
42
|
+
LOCK_FOR = re.compile(r"\bFOR\s+(?:NO\s+KEY\s+)?UPDATE\b", re.I)
|
|
43
|
+
KEY_LOOKUP = re.compile(r"\b\w*id\s*=\s*(?:\$\d+|\?|%s|:\w+|@\w+)", re.I)
|
|
44
|
+
QUEUE_FILTER = re.compile(r"\b\w*(?:status|state|queued|pending|scheduled|run_at|next_run\w*|available_at|visible_at|locked_at|claimed_at|"
|
|
45
|
+
r"lease\w*|locked_until|claimed_until|attempts)\b\s*(?:=\s*'|IN\s*\(\s*'|IS\s+(?:NOT\s+)?NULL|<=?\s*(?:now|current_timestamp))", re.I)
|
|
46
|
+
SKIPPED = re.compile(r"\bSKIP\s+LOCKED\b|\bNOWAIT\b", re.I)
|
|
47
|
+
ORDER_LIMIT = re.compile(r"\bORDER\s+BY\b.*\bLIMIT\b|\bLIMIT\b", re.I | re.S)
|
|
48
|
+
KEYED = re.compile(r"\bWHERE\b[^;]*?\b(\w+)\s*=\s*(\$\d+|\?|%s|:\w+|@\w+|%\(\w+\)s)", re.I | re.S)
|
|
49
|
+
SET_PARAM = re.compile(r"\bSET\b(.*?)\bWHERE\b", re.I | re.S)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def bare(t: str) -> str:
|
|
53
|
+
return str(t or "").replace('"', "").split(".")[-1].lower()
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def lock_of(sql: str) -> str:
|
|
57
|
+
s = sql or ""
|
|
58
|
+
if SKIPPED.search(s):
|
|
59
|
+
return "skip_locked" if re.search(r"SKIP\s+LOCKED", s, re.I) else "nowait"
|
|
60
|
+
if LOCK_FOR.search(s):
|
|
61
|
+
return "for_update"
|
|
62
|
+
if re.search(r"\bFOR\s+(?:KEY\s+)?SHARE\b", s, re.I):
|
|
63
|
+
return "for_share"
|
|
64
|
+
return ""
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def step_of(q: dict) -> dict:
|
|
68
|
+
op = (q.get("statement") or "other").lower()
|
|
69
|
+
table = (q.get("writes") or q.get("tables") or [""])[0]
|
|
70
|
+
return {"line": q.get("line"), "op": op if op in ("select", "insert", "update", "delete") else "other", "table": bare(table),
|
|
71
|
+
"lock": lock_of(q.get("sql") or ""), "site": q.get("id"), "sql": " ".join(str(q.get("sql") or "").split())[:4000],
|
|
72
|
+
"engine": q.get("engine") or ""}
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def is_write(st: dict) -> bool:
|
|
76
|
+
return st["op"] in ("insert", "update", "delete")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class Index:
|
|
80
|
+
"""The query call sites by file and by function name."""
|
|
81
|
+
|
|
82
|
+
def __init__(self, inventory: dict):
|
|
83
|
+
self.sites = [s for s in (inventory or {}).get("call_sites") or [] if isinstance(s, dict) and s.get("sql") and not s.get("is_test")]
|
|
84
|
+
self.by_file: dict[str, list[dict]] = defaultdict(list)
|
|
85
|
+
self.by_symbol: dict[str, list[dict]] = defaultdict(list)
|
|
86
|
+
for s in self.sites:
|
|
87
|
+
self.by_file[s["file"]].append(s)
|
|
88
|
+
if s.get("symbol"):
|
|
89
|
+
self.by_symbol[s["symbol"]].append(s)
|
|
90
|
+
for v in self.by_file.values():
|
|
91
|
+
v.sort(key=lambda s: s.get("line") or 0)
|
|
92
|
+
|
|
93
|
+
def within(self, file: str, a: int, b: int) -> list[dict]:
|
|
94
|
+
return [s for s in self.by_file.get(file, []) if a <= (s.get("line") or 0) <= b]
|
|
95
|
+
|
|
96
|
+
def of_function(self, file: str, name: str) -> list[dict]:
|
|
97
|
+
return [s for s in self.by_file.get(file, []) if s.get("symbol") == name]
|
|
98
|
+
|
|
99
|
+
def callee(self, file: str, name: str) -> list[dict]:
|
|
100
|
+
same = [s for s in self.by_file.get(file, []) if s.get("symbol") == name]
|
|
101
|
+
if same:
|
|
102
|
+
return same
|
|
103
|
+
got = self.by_symbol.get(name) or []
|
|
104
|
+
files = {s["file"] for s in got}
|
|
105
|
+
return got if len(files) == 1 else []
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def block_steps(block: dict, idx: Index) -> list[dict]:
|
|
109
|
+
"""The statements of a transaction block in order: its own lines, then the functions it hands the transaction to."""
|
|
110
|
+
steps = [step_of(q) for q in idx.within(block["file"], block["line"], block.get("end_line") or block["line"])]
|
|
111
|
+
for c in block.get("callees") or []:
|
|
112
|
+
for q in idx.callee(block["file"], c["name"]):
|
|
113
|
+
st = step_of(q)
|
|
114
|
+
st["line_in_block"] = c["line"]
|
|
115
|
+
st["via"] = c["name"]
|
|
116
|
+
steps.append(st)
|
|
117
|
+
steps.sort(key=lambda st: st.get("line_in_block") or st["line"] or 0)
|
|
118
|
+
return steps
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def engine_of(steps: list[dict], default: str = "") -> str:
|
|
122
|
+
engines = [s["engine"] for s in steps if s.get("engine")]
|
|
123
|
+
return max(set(engines), key=engines.count) if engines else default
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def candidate(scenario: str, *, file: str, line: int, symbol: str, text: str, engine: str, why: str, site: dict | None = None,
|
|
127
|
+
**facts) -> dict:
|
|
128
|
+
c = {"id": (site or {}).get("id") or site_id("transaction", file, symbol, f"{scenario}:{text}"), "scenario": scenario, "file": file,
|
|
129
|
+
"line": line, "symbol": symbol, "engine": engine, "why": why, "ask": False}
|
|
130
|
+
if site is None:
|
|
131
|
+
c["_query_site"] = True
|
|
132
|
+
c.update(facts)
|
|
133
|
+
return c
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
# --- the rules -------------------------------------------------------------------------------------------------------------
|
|
137
|
+
|
|
138
|
+
def classify(sites: list[dict], inventory: dict, root: Path, catalog: dict | None = None, settings: dict | None = None) -> tuple[list[dict], dict]:
|
|
139
|
+
"""(candidates, counts): every rule over the kind's discovered sites and the query call sites."""
|
|
140
|
+
idx = Index(inventory)
|
|
141
|
+
blocks = [s for s in sites if s.get("shape") == "tx" and not s.get("is_test")]
|
|
142
|
+
opens = [s for s in sites if s.get("shape") == "sqlite_open" and not s.get("is_test")]
|
|
143
|
+
rmws = [s for s in sites if s.get("shape") == "orm_rmw" and not s.get("is_test")]
|
|
144
|
+
counts: dict = defaultdict(int)
|
|
145
|
+
out: list[dict] = []
|
|
146
|
+
seen: set = set()
|
|
147
|
+
|
|
148
|
+
def add(c: dict) -> None:
|
|
149
|
+
key = (c["scenario"], c["file"], c["line"])
|
|
150
|
+
if key in seen:
|
|
151
|
+
return
|
|
152
|
+
seen.add(key)
|
|
153
|
+
if ONE_OFF.search("/" + c["file"]) and not (c["scenario"] == "fk_without_index" and not c.get("delete_sql")):
|
|
154
|
+
counts["skipped.migrations_scripts_examples"] += 1 # run once, alone, by hand: nobody runs them concurrently
|
|
155
|
+
return
|
|
156
|
+
out.append(c)
|
|
157
|
+
counts[f"candidates.{c['scenario']}"] += 1
|
|
158
|
+
|
|
159
|
+
block_of_line: dict[tuple[str, int], dict] = {}
|
|
160
|
+
for b in blocks:
|
|
161
|
+
b["steps"] = block_steps(b, idx)
|
|
162
|
+
b["engine"] = engine_of(b["steps"])
|
|
163
|
+
counts["transactions"] += 1
|
|
164
|
+
counts["transactions_with_statements"] += 1 if b["steps"] else 0
|
|
165
|
+
for st in b["steps"]:
|
|
166
|
+
if not st.get("via"):
|
|
167
|
+
block_of_line[(b["file"], st["line"])] = b
|
|
168
|
+
|
|
169
|
+
# queue claims and polls, from the statements themselves (in a block or not)
|
|
170
|
+
for q in idx.sites:
|
|
171
|
+
sql = q.get("sql") or ""
|
|
172
|
+
if (q.get("statement") or "") != "select":
|
|
173
|
+
continue
|
|
174
|
+
lock = lock_of(sql)
|
|
175
|
+
if lock in ("skip_locked", "nowait"):
|
|
176
|
+
counts["already_safe.claims_skip_locked"] += 1
|
|
177
|
+
continue
|
|
178
|
+
if lock == "for_update" and re.search(r"\bORDER\s+BY\b", sql, re.I) and re.search(r"\bLIMIT\b", sql, re.I) and QUEUE_FILTER.search(_where(sql)) \
|
|
179
|
+
and not KEY_LOOKUP.search(_where(sql)):
|
|
180
|
+
b = block_of_line.get((q["file"], q["line"]))
|
|
181
|
+
done = None
|
|
182
|
+
for st in (b["steps"] if b else [step_of(x) for x in idx.of_function(q["file"], q.get("symbol") or "")]):
|
|
183
|
+
if st["op"] == "update" and st["table"] == bare((q.get("tables") or [""])[0]) and (st["line"] or 0) > q["line"]:
|
|
184
|
+
done = st
|
|
185
|
+
break
|
|
186
|
+
add(candidate("queue_claim", file=q["file"], line=q["line"], symbol=q.get("symbol") or "", text=sql, engine=q.get("engine") or "",
|
|
187
|
+
why="claims the next row with FOR UPDATE and no SKIP LOCKED: other workers wait for it", site=None,
|
|
188
|
+
select_sql=sql, done_sql=(done or {}).get("sql"), tables=[bare(t) for t in q.get("tables") or []],
|
|
189
|
+
origin_site=q.get("id"), steps=[step_of(q)] + ([done] if done else [])))
|
|
190
|
+
continue
|
|
191
|
+
if lock:
|
|
192
|
+
continue
|
|
193
|
+
m = UNMARKED.search(sql)
|
|
194
|
+
if not m or not re.search(r"\bLIMIT\b|\bORDER\s+BY\b", sql, re.I):
|
|
195
|
+
continue
|
|
196
|
+
marker = bare(m.group(1) or m.group(4) or "") or ""
|
|
197
|
+
main = bare((q.get("tables") or [""])[0])
|
|
198
|
+
col = m.group(5) or m.group(6) or ""
|
|
199
|
+
marks = []
|
|
200
|
+
for w in idx.by_file.get(q["file"], []):
|
|
201
|
+
if w is q or (w.get("statement") or "") not in ("insert", "update"):
|
|
202
|
+
continue
|
|
203
|
+
target = bare((w.get("writes") or w.get("tables") or [""])[0])
|
|
204
|
+
if marker and target == marker and (w.get("statement") == "insert"):
|
|
205
|
+
marks.append(w)
|
|
206
|
+
elif not marker and target == main and w.get("statement") == "update" and col and re.search(rf"\bSET\b.*\b{re.escape(col)}\b", w.get("sql") or "", re.I | re.S):
|
|
207
|
+
marks.append(w)
|
|
208
|
+
if not marks:
|
|
209
|
+
counts["polls_without_a_mark_in_file"] += 1
|
|
210
|
+
continue
|
|
211
|
+
mark = marks[0]
|
|
212
|
+
same_fn = mark.get("symbol") == q.get("symbol")
|
|
213
|
+
msql = mark.get("sql") or ""
|
|
214
|
+
# a mark that can only succeed once (ON CONFLICT DO NOTHING, or an UPDATE guarded by the unmarked condition) is
|
|
215
|
+
# safe when the code acts only after it succeeded: whether it does is a question for the agent
|
|
216
|
+
guarded = bool(re.search(r"ON\s+CONFLICT\b[^;]*DO\s+NOTHING", msql, re.I)) or bool(
|
|
217
|
+
col and re.search(rf"\bWHERE\b.*\b{re.escape(col)}\b", msql, re.I | re.S))
|
|
218
|
+
add(candidate("poll_then_mark", file=q["file"], line=q["line"], symbol=q.get("symbol") or "", text=sql, engine=q.get("engine") or "",
|
|
219
|
+
why=("polls unmarked rows with no lock and marks them later" + ("" if same_fn else f" in {mark.get('symbol') or 'another function'}")),
|
|
220
|
+
select_sql=sql, mark_sql=mark.get("sql"), mark_line=mark.get("line"), mark_symbol=mark.get("symbol") or "",
|
|
221
|
+
tables=list(dict.fromkeys([main] + ([marker] if marker else []))), origin_site=q.get("id"), act_seen=False,
|
|
222
|
+
guarded=guarded, ask=guarded, steps=[step_of(q), {"line": None, "op": "call", "what": "act"}, step_of(mark)]))
|
|
223
|
+
|
|
224
|
+
# read, compute, write back (SQL)
|
|
225
|
+
for file, qs in idx.by_file.items():
|
|
226
|
+
by_fn: dict[str, list[dict]] = defaultdict(list)
|
|
227
|
+
for q in qs:
|
|
228
|
+
by_fn[q.get("symbol") or ""].append(q)
|
|
229
|
+
for fn, group in by_fn.items():
|
|
230
|
+
if not fn:
|
|
231
|
+
continue
|
|
232
|
+
for r in group:
|
|
233
|
+
if (r.get("statement") or "") != "select" or lock_of(r.get("sql") or "") or not KEYED.search(r.get("sql") or ""):
|
|
234
|
+
continue
|
|
235
|
+
t = bare((r.get("tables") or [""])[0])
|
|
236
|
+
for w in group:
|
|
237
|
+
if (w.get("line") or 0) <= (r.get("line") or 0) or (w.get("statement") or "") != "update" or bare((w.get("writes") or [""])[0]) != t:
|
|
238
|
+
continue
|
|
239
|
+
sm = SET_PARAM.search(w.get("sql") or "")
|
|
240
|
+
if not sm:
|
|
241
|
+
continue
|
|
242
|
+
cols = re.findall(r"\b(\w+)\s*=\s*(?:\$\d+|\?|%s|:\w+|@\w+|%\(\w+\)s)", sm.group(1))
|
|
243
|
+
read_cols = re.split(r"\bFROM\b", r.get("sql") or "", flags=re.I)[0]
|
|
244
|
+
hit = [c for c in cols if re.search(rf"\b{re.escape(c)}\b", read_cols)]
|
|
245
|
+
if not hit or not KEYED.search(w.get("sql") or ""):
|
|
246
|
+
continue
|
|
247
|
+
b = block_of_line.get((file, r["line"]))
|
|
248
|
+
if b and (b.get("isolation") or "").startswith(("SERIALIZABLE", "REPEATABLE")):
|
|
249
|
+
counts["already_safe.rmw_serializable"] += 1
|
|
250
|
+
continue
|
|
251
|
+
add(candidate("read_modify_write", file=file, line=r["line"], symbol=fn, text=(r.get("sql") or "") + (w.get("sql") or ""),
|
|
252
|
+
engine=r.get("engine") or "", why=f"reads {t}.{hit[0]} and writes it back from the application",
|
|
253
|
+
read_sql=r.get("sql"), write_sql=w.get("sql"), column=hit[0], tables=[t], origin_site=r.get("id"),
|
|
254
|
+
ask=not COUNTER.search(hit[0]),
|
|
255
|
+
steps=[step_of(r), {"line": None, "op": "other", "what": "compute"}, step_of(w)]))
|
|
256
|
+
break
|
|
257
|
+
for s in rmws:
|
|
258
|
+
add(candidate("read_modify_write", file=s["file"], line=s["line"], symbol=s.get("symbol") or "", text=f"{s.get('model')}.{s.get('field')}",
|
|
259
|
+
engine="", why=f"reads a {s.get('model')}, changes {s.get('field')} from its own value and saves it, unlocked",
|
|
260
|
+
site=s, tables=[bare(s.get("model") or "")], column=s.get("field"), orm=True,
|
|
261
|
+
steps=[{"line": s["line"], "op": "select", "table": bare(s.get("model") or "")},
|
|
262
|
+
{"line": s.get("inc_line"), "op": "other", "what": "compute"},
|
|
263
|
+
{"line": s.get("end_line"), "op": "update", "table": bare(s.get("model") or "")}]))
|
|
264
|
+
|
|
265
|
+
# transactions: a call inside after a lock; opposite lock orders; SQLite deferred read-then-write
|
|
266
|
+
write_orders: list[tuple[dict, list[str]]] = []
|
|
267
|
+
for b in blocks:
|
|
268
|
+
steps, calls = b["steps"], b.get("calls") or []
|
|
269
|
+
eng = b.get("engine") or ""
|
|
270
|
+
locked = [st for st in steps if st["op"] in ("update", "delete") or st["lock"] in ("for_update", "for_share")
|
|
271
|
+
or (eng == "sqlite" and is_write(st))]
|
|
272
|
+
call = next((c for c in calls if any((st.get("line_in_block") or st["line"] or 0) < c["line"] for st in locked)), None)
|
|
273
|
+
if calls:
|
|
274
|
+
counts["transactions_with_a_call_inside"] += 1
|
|
275
|
+
if call and locked:
|
|
276
|
+
first = next(st for st in locked if (st.get("line_in_block") or st["line"] or 0) < call["line"])
|
|
277
|
+
add(candidate("call_in_transaction", file=b["file"], line=b["line"], symbol=b.get("symbol") or "", text=f"{b['line']}:{call['text']}",
|
|
278
|
+
engine=eng, why=f"holds a row lock ({first['op']} {first['table']}) across {call['what']} at line {call['line']}",
|
|
279
|
+
site=b, write_sql=first["sql"] if first["op"] == "update" else None, call=call, begin_mode=b.get("begin_mode") or "",
|
|
280
|
+
tables=[first["table"]], steps=_with_calls(steps, calls)))
|
|
281
|
+
# rows that already exist are what two transactions can wait on each other for: updates and deletes (an insert
|
|
282
|
+
# of a new row waits on nobody); migrations run once, alone
|
|
283
|
+
writes = [st["table"] for st in steps if st["op"] in ("update", "delete") and st["table"] and st.get("engine") in ("postgres", "")
|
|
284
|
+
and "/migrations/" not in "/" + b["file"]]
|
|
285
|
+
order = list(dict.fromkeys(writes))
|
|
286
|
+
if len(order) >= 2:
|
|
287
|
+
write_orders.append((b, order))
|
|
288
|
+
ups = [st for st in steps if st["op"] == "update"]
|
|
289
|
+
for i in range(len(ups)):
|
|
290
|
+
for j in range(i + 1, len(ups)):
|
|
291
|
+
ki, kj = KEYED.search(ups[i]["sql"]), KEYED.search(ups[j]["sql"])
|
|
292
|
+
# two direct updates of one table, on its key, one after the other (not two arms of a switch through a callee)
|
|
293
|
+
if ups[i]["table"] == ups[j]["table"] and not ups[i].get("via") and not ups[j].get("via") and ki and kj \
|
|
294
|
+
and ki.group(1) == kj.group(1) and ups[i]["line"] != ups[j]["line"] and eng in ("postgres", ""):
|
|
295
|
+
add(candidate("lock_order", file=b["file"], line=b["line"], symbol=b.get("symbol") or "", text=f"self:{ups[i]['sql']}",
|
|
296
|
+
engine=eng, why=f"updates two rows of {ups[i]['table']} in the order the caller gives them",
|
|
297
|
+
site=b, update_sql=ups[i]["sql"], tables=[ups[i]["table"]], ask=True, steps=_with_calls(steps, calls)))
|
|
298
|
+
if eng == "sqlite" and b.get("begin_mode") not in ("IMMEDIATE", "EXCLUSIVE"):
|
|
299
|
+
first_w = next((k for k, st in enumerate(steps) if is_write(st)), None)
|
|
300
|
+
if first_w is not None and any(st["op"] == "select" for st in steps[:first_w]):
|
|
301
|
+
op = _nearest_open(opens, b["file"])
|
|
302
|
+
if op and op.get("txlock") in ("immediate", "exclusive"):
|
|
303
|
+
counts["already_safe.sqlite_txlock"] += 1
|
|
304
|
+
else:
|
|
305
|
+
add(candidate("sqlite_deferred_begin", file=b["file"], line=b["line"], symbol=b.get("symbol") or "", text=f"{b['line']}",
|
|
306
|
+
engine="sqlite", why="a deferred transaction reads, then writes: a second writer gets SQLITE_BUSY at once",
|
|
307
|
+
site=b, wal=(op or {}).get("wal"), busy_timeout_ms=(op or {}).get("busy_timeout_ms"),
|
|
308
|
+
tables=[st["table"] for st in steps if st["table"]][:3], steps=_with_calls(steps, calls)))
|
|
309
|
+
pairs: dict[tuple[str, str], list[dict]] = defaultdict(list)
|
|
310
|
+
for b, order in write_orders:
|
|
311
|
+
for i in range(len(order)):
|
|
312
|
+
for j in range(i + 1, len(order)):
|
|
313
|
+
pairs[(order[i], order[j])].append(b)
|
|
314
|
+
for (x, y), bs in pairs.items():
|
|
315
|
+
if x < y and (y, x) in pairs:
|
|
316
|
+
a, b = bs[0], pairs[(y, x)][0]
|
|
317
|
+
if a.get("engine") not in ("postgres", "") or b.get("engine") not in ("postgres", ""):
|
|
318
|
+
continue
|
|
319
|
+
ux = next((st for st in a["steps"] if st["op"] == "update" and st["table"] == x), None)
|
|
320
|
+
add(candidate("lock_order", file=a["file"], line=a["line"], symbol=a.get("symbol") or "", text=f"{x}>{y}|{b['file']}:{b['line']}",
|
|
321
|
+
engine=a.get("engine") or "", why=f"writes {x} then {y}; {b['file']}:{b['line']} writes {y} then {x}",
|
|
322
|
+
site=a, update_sql=(ux or {}).get("sql"), other={"file": b["file"], "line": b["line"], "symbol": b.get("symbol") or ""},
|
|
323
|
+
tables=[x, y], ask=True, steps=_with_calls(a["steps"], a.get("calls") or [])))
|
|
324
|
+
|
|
325
|
+
# foreign keys without an index, when the parent is deleted
|
|
326
|
+
for c in fk_candidates(inventory, root, idx, catalog):
|
|
327
|
+
add(c)
|
|
328
|
+
# SQLite opened without WAL or a busy timeout, when the repository writes SQLite
|
|
329
|
+
sqlite_writes = [q for q in idx.sites if (q.get("engine") or "") == "sqlite" and (q.get("statement") or "") in ("insert", "update", "delete")]
|
|
330
|
+
for o in opens:
|
|
331
|
+
counts["sqlite_opens"] += 1
|
|
332
|
+
if re.search(r"mode=ro\b|read_?only|SQLITE_OPEN_READONLY|immutable=1", o.get("text") or "", re.I):
|
|
333
|
+
counts["sqlite_opens_read_only"] += 1
|
|
334
|
+
continue
|
|
335
|
+
if o.get("wal") and (o.get("busy_timeout_ms") or 0) > 0:
|
|
336
|
+
counts["already_safe.sqlite_wal_and_timeout"] += 1
|
|
337
|
+
continue
|
|
338
|
+
if not sqlite_writes:
|
|
339
|
+
continue
|
|
340
|
+
add(candidate("sqlite_no_wal_timeout", file=o["file"], line=o["line"], symbol=o.get("symbol") or "", text=o.get("text") or "",
|
|
341
|
+
engine="sqlite", why=("opened without WAL" if not o.get("wal") else "WAL")
|
|
342
|
+
+ (" and without a busy timeout" if not o.get("busy_timeout_ms") else f", busy timeout {o['busy_timeout_ms']} ms"),
|
|
343
|
+
site=o, wal=o.get("wal"), busy_timeout_ms=o.get("busy_timeout_ms"), tables=[], steps=[],
|
|
344
|
+
# the settings are facts; whether two connections or processes write this file at once is not
|
|
345
|
+
ask=True))
|
|
346
|
+
return out, dict(counts)
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def _with_calls(steps: list[dict], calls: list[dict]) -> list[dict]:
|
|
350
|
+
out = [dict(st) for st in steps] + [{"line": c["line"], "op": "call", "what": c["what"], "via": c.get("via")} for c in calls]
|
|
351
|
+
out.sort(key=lambda st: st.get("line_in_block") or st.get("line") or 0)
|
|
352
|
+
return out[:24]
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def _nearest_open(opens: list[dict], file: str) -> dict | None:
|
|
356
|
+
same = [o for o in opens if o["file"] == file]
|
|
357
|
+
if same:
|
|
358
|
+
return same[0]
|
|
359
|
+
d = file.rsplit("/", 1)[0]
|
|
360
|
+
near = [o for o in opens if o["file"].startswith(d)]
|
|
361
|
+
return near[0] if near else (opens[0] if len(opens) == 1 else None)
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
# --- foreign keys -------------------------------------------------------------------------------------------------------------
|
|
365
|
+
|
|
366
|
+
FK_INLINE = re.compile(r"^\s*\"?(\w+)\"?\s+[\w ()\[\]]+?\bREFERENCES\s+([\w.\"]+)\s*(?:\(\s*\"?(\w+)\"?\s*\))?([^,\n]*)", re.I | re.M)
|
|
367
|
+
FK_TABLE = re.compile(r"FOREIGN\s+KEY\s*\(([^)]*)\)\s*REFERENCES\s+([\w.\"]+)\s*(?:\(([^)]*)\))?([^,\n]*)", re.I)
|
|
368
|
+
CREATE = re.compile(r"CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?([\w.\"]+)\s*\(", re.I)
|
|
369
|
+
ALTER_FK = re.compile(r"ALTER\s+TABLE\s+(?:ONLY\s+)?(?:IF\s+EXISTS\s+)?([\w.\"]+)\s+ADD\s+(?:CONSTRAINT\s+\"?\w+\"?\s+)?FOREIGN\s+KEY\s*\(([^)]*)\)\s*"
|
|
370
|
+
r"REFERENCES\s+([\w.\"]+)\s*(?:\(([^)]*)\))?([^;]*)", re.I)
|
|
371
|
+
INDEX = re.compile(r"CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:CONCURRENTLY\s+)?(?:IF\s+NOT\s+EXISTS\s+)?(?:\"?\w+\"?\s+)?ON\s+(?:ONLY\s+)?([\w.\"]+)\s*"
|
|
372
|
+
r"(?:USING\s+\w+\s*)?\(([^)]*)\)", re.I)
|
|
373
|
+
PK = re.compile(r"PRIMARY\s+KEY\s*\(([^)]*)\)|UNIQUE\s*\(([^)]*)\)", re.I)
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def _cols(text: str) -> list[str]:
|
|
377
|
+
return [c.strip().strip('"').split()[0].lower() for c in (text or "").split(",") if c.strip()]
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def schema_fks(root: Path, inventory: dict) -> tuple[list[dict], dict[str, list[list[str]]]]:
|
|
381
|
+
"""Foreign keys and index column lists from the repository's .sql files (migrations, schema dumps)."""
|
|
382
|
+
fks: list[dict] = []
|
|
383
|
+
idx: dict[str, list[list[str]]] = defaultdict(list)
|
|
384
|
+
files = set()
|
|
385
|
+
for t in (inventory or {}).get("tables") or []:
|
|
386
|
+
for where in t.get("defined_at") or []:
|
|
387
|
+
files.add(where.rsplit(":", 1)[0])
|
|
388
|
+
for f in sorted(files):
|
|
389
|
+
if not f.endswith(".sql"):
|
|
390
|
+
continue
|
|
391
|
+
try:
|
|
392
|
+
text = (root / f).read_text(errors="replace")
|
|
393
|
+
except OSError:
|
|
394
|
+
continue
|
|
395
|
+
text = re.sub(r"--[^\n]*", "", text)
|
|
396
|
+
for m in CREATE.finditer(text):
|
|
397
|
+
child = bare(m.group(1))
|
|
398
|
+
depth, j = 1, m.end()
|
|
399
|
+
while j < len(text) and depth:
|
|
400
|
+
depth += {"(": 1, ")": -1}.get(text[j], 0)
|
|
401
|
+
j += 1
|
|
402
|
+
body = text[m.end():j - 1]
|
|
403
|
+
for fm in FK_TABLE.finditer(body):
|
|
404
|
+
fks.append({"child": child, "columns": _cols(fm.group(1)), "parent": bare(fm.group(2)), "parent_key": _cols(fm.group(3) or "id"),
|
|
405
|
+
"on_delete": _on_delete(fm.group(4)), "where": f"{f}:{text[:m.start()].count(chr(10)) + 1}"})
|
|
406
|
+
for line in _top_level(body):
|
|
407
|
+
fm = FK_INLINE.match(line)
|
|
408
|
+
if fm and not re.match(r"\s*(?:CONSTRAINT|FOREIGN|PRIMARY|UNIQUE|CHECK)\b", line, re.I):
|
|
409
|
+
fks.append({"child": child, "columns": [fm.group(1).lower()], "parent": bare(fm.group(2)),
|
|
410
|
+
"parent_key": [(fm.group(3) or "id").lower()], "on_delete": _on_delete(fm.group(4)),
|
|
411
|
+
"where": f"{f}:{text[:m.start()].count(chr(10)) + 1}"})
|
|
412
|
+
if re.search(r"\bPRIMARY\s+KEY\b|\bUNIQUE\b", line, re.I) and not re.match(r"\s*(?:CONSTRAINT|PRIMARY|UNIQUE)\b", line, re.I):
|
|
413
|
+
cm = re.match(r"\s*\"?(\w+)\"?", line)
|
|
414
|
+
if cm:
|
|
415
|
+
idx[child].append([cm.group(1).lower()])
|
|
416
|
+
for pm in PK.finditer(body):
|
|
417
|
+
idx[child].append(_cols(pm.group(1) or pm.group(2)))
|
|
418
|
+
for m in ALTER_FK.finditer(text):
|
|
419
|
+
fks.append({"child": bare(m.group(1)), "columns": _cols(m.group(2)), "parent": bare(m.group(3)), "parent_key": _cols(m.group(4) or "id"),
|
|
420
|
+
"on_delete": _on_delete(m.group(5)), "where": f"{f}:{text[:m.start()].count(chr(10)) + 1}"})
|
|
421
|
+
for m in INDEX.finditer(text):
|
|
422
|
+
idx[bare(m.group(1))].append(_cols(m.group(2)))
|
|
423
|
+
for m in re.finditer(r"ALTER\s+TABLE\s+(?:ONLY\s+)?([\w.\"]+)\s+ADD\s+(?:CONSTRAINT\s+\"?\w+\"?\s+)?(?:PRIMARY\s+KEY|UNIQUE)\s*\(([^)]*)\)", text, re.I):
|
|
424
|
+
idx[bare(m.group(1))].append(_cols(m.group(2)))
|
|
425
|
+
return fks, idx
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def _top_level(body: str) -> list[str]:
|
|
429
|
+
"""The items of a CREATE TABLE column list: split on commas outside parentheses."""
|
|
430
|
+
out, depth, cur = [], 0, []
|
|
431
|
+
for ch in body:
|
|
432
|
+
if ch == "(":
|
|
433
|
+
depth += 1
|
|
434
|
+
elif ch == ")":
|
|
435
|
+
depth -= 1
|
|
436
|
+
if ch == "," and depth == 0:
|
|
437
|
+
out.append("".join(cur).strip())
|
|
438
|
+
cur = []
|
|
439
|
+
else:
|
|
440
|
+
cur.append(ch)
|
|
441
|
+
out.append("".join(cur).strip())
|
|
442
|
+
return [x for x in out if x]
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
def _on_delete(tail: str) -> str:
|
|
446
|
+
m = re.search(r"ON\s+DELETE\s+(CASCADE|RESTRICT|NO\s+ACTION|SET\s+NULL|SET\s+DEFAULT)", tail or "", re.I)
|
|
447
|
+
return re.sub(r"\s+", " ", m.group(1).upper()) if m else "NO ACTION"
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
def catalog_fks(catalog: dict | None) -> tuple[list[dict], dict[str, list[list[str]]], dict[str, dict]] | None:
|
|
451
|
+
conns = [c for c in ((catalog or {}).get("connections") or {}).values() if c.get("engine") == "postgres"]
|
|
452
|
+
if not conns:
|
|
453
|
+
return None
|
|
454
|
+
fks, idx, stats = [], defaultdict(list), {}
|
|
455
|
+
for conn in conns:
|
|
456
|
+
for t in conn.get("tables") or []:
|
|
457
|
+
name = bare(t.get("name"))
|
|
458
|
+
stats[name] = {"deleted": t.get("deleted"), "updated": t.get("updated"), "rows": t.get("rows")}
|
|
459
|
+
for c in t.get("constraints") or []:
|
|
460
|
+
if c.get("type") == "f":
|
|
461
|
+
m = re.match(r"FOREIGN KEY \(([^)]*)\) REFERENCES ([\w.\"]+)\(([^)]*)\)(.*)", c.get("definition") or "", re.I)
|
|
462
|
+
if m:
|
|
463
|
+
fks.append({"child": name, "columns": _cols(m.group(1)), "parent": bare(m.group(2)), "parent_key": _cols(m.group(3)),
|
|
464
|
+
"on_delete": _on_delete(m.group(4)), "where": "catalog", "constraint": c.get("name")})
|
|
465
|
+
for i in t.get("indexes") or []:
|
|
466
|
+
m = re.search(r"\(([^)]*)\)", i.get("definition") or "")
|
|
467
|
+
if m and i.get("is_valid", True) and " WHERE " not in (i.get("definition") or "").upper():
|
|
468
|
+
idx[name].append(_cols(m.group(1)))
|
|
469
|
+
return fks, idx, stats
|
|
470
|
+
|
|
471
|
+
|
|
472
|
+
def fk_candidates(inventory: dict, root: Path, idx: Index, catalog: dict | None) -> list[dict]:
|
|
473
|
+
got = catalog_fks(catalog)
|
|
474
|
+
if got:
|
|
475
|
+
fks, indexes, stats = got
|
|
476
|
+
source = "catalog"
|
|
477
|
+
else:
|
|
478
|
+
fks, indexes = schema_fks(root, inventory)
|
|
479
|
+
stats, source = {}, "repository"
|
|
480
|
+
deletes: dict[str, list[dict]] = defaultdict(list)
|
|
481
|
+
for q in idx.sites:
|
|
482
|
+
if (q.get("engine") or "") not in ("postgres", "") or (q.get("statement") or "") not in ("delete", "update"):
|
|
483
|
+
continue
|
|
484
|
+
t = bare((q.get("writes") or q.get("tables") or [""])[0])
|
|
485
|
+
if q.get("statement") == "delete":
|
|
486
|
+
deletes[t].append(q)
|
|
487
|
+
out = []
|
|
488
|
+
seen = set()
|
|
489
|
+
for fk in fks:
|
|
490
|
+
cols = fk["columns"]
|
|
491
|
+
if not cols or any(ix[:len(cols)] == cols for ix in indexes.get(fk["child"], [])):
|
|
492
|
+
continue
|
|
493
|
+
key = (fk["child"], tuple(cols))
|
|
494
|
+
if key in seen:
|
|
495
|
+
continue
|
|
496
|
+
seen.add(key)
|
|
497
|
+
dels = deletes.get(fk["parent"]) or []
|
|
498
|
+
st = stats.get(fk["parent"]) or {}
|
|
499
|
+
if not dels and not (st.get("deleted") or 0):
|
|
500
|
+
continue
|
|
501
|
+
q = dels[0] if dels else None
|
|
502
|
+
where = q or _defined_at(inventory, fk)
|
|
503
|
+
if where is None:
|
|
504
|
+
continue
|
|
505
|
+
out.append(candidate("fk_without_index", file=where["file"], line=where["line"], symbol=where.get("symbol") or "",
|
|
506
|
+
text=f"{fk['child']}.{','.join(cols)}->{fk['parent']}", engine="postgres",
|
|
507
|
+
why=f"deleting a {fk['parent']} row scans {fk['child']} ({', '.join(cols)} has no index)",
|
|
508
|
+
fk={"child": fk["child"], "column": cols[0], "columns": cols, "parent": fk["parent"], "parent_key": (fk["parent_key"] or ["id"])[0],
|
|
509
|
+
"on_delete": fk["on_delete"], "source": source, "constraint": fk.get("constraint") or "",
|
|
510
|
+
"parent_deletes": st.get("deleted"), "child_rows": (stats.get(fk["child"]) or {}).get("rows")},
|
|
511
|
+
delete_sql=(q or {}).get("sql"), tables=[fk["parent"], fk["child"]], origin_site=(q or {}).get("id"),
|
|
512
|
+
steps=[step_of(q)] if q else []))
|
|
513
|
+
return out
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
def _where(sql: str) -> str:
|
|
517
|
+
parts = re.split(r"\bWHERE\b", sql, flags=re.I)
|
|
518
|
+
return parts[-1] if len(parts) > 1 else ""
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
def _defined_at(inventory: dict, fk: dict) -> dict | None:
|
|
522
|
+
"""Where the child table is defined in the repository (a foreign key the catalog lists, no delete site in the code)."""
|
|
523
|
+
if fk.get("where") and fk["where"] != "catalog" and ":" in fk["where"]:
|
|
524
|
+
f, line = fk["where"].rsplit(":", 1)
|
|
525
|
+
return {"file": f, "line": int(line), "symbol": ""}
|
|
526
|
+
for t in (inventory or {}).get("tables") or []:
|
|
527
|
+
if bare(t.get("name")) == fk["child"] and t.get("defined_at") and not re.search(r"(?:^|/)tests?/|_tests?\.|test_", t["defined_at"][0]):
|
|
528
|
+
f, _, line = t["defined_at"][0].rpartition(":")
|
|
529
|
+
return {"file": f, "line": int(line or 1), "symbol": ""}
|
|
530
|
+
return None
|
|
531
|
+
|
|
532
|
+
|
|
533
|
+
def load_catalog(out_dir: Path, settings: dict | None = None) -> dict | None:
|
|
534
|
+
"""db_catalog.json of the out dir (a pulled catalog), or the file `[kinds.transaction] catalog` names."""
|
|
535
|
+
for p in ([Path(settings["catalog"])] if (settings or {}).get("catalog") else []) + [Path(out_dir) / "db_catalog.json"]:
|
|
536
|
+
try:
|
|
537
|
+
return json.loads(p.read_text())
|
|
538
|
+
except (OSError, ValueError):
|
|
539
|
+
continue
|
|
540
|
+
return None
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""The PostgreSQL sandbox of the transaction kind: one throwaway container per scan, labelled like every CodeCop sandbox
|
|
2
|
+
(engines/base: removed with its volume when the run ends, reaped if the run is killed), its port published on
|
|
3
|
+
127.0.0.1 only so CodeCop's own sessions can reach it, one database per scenario. Small by default (memory and buffers
|
|
4
|
+
are settings). The settings that flatter the numbers (fsync off, synchronous_commit off) are printed on every finding."""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import subprocess
|
|
9
|
+
import time
|
|
10
|
+
import uuid
|
|
11
|
+
|
|
12
|
+
from ...engines.base import SandboxError, find_runtime, reap_orphans, remove_sandbox, sandbox_run_args
|
|
13
|
+
from .schedule import PgDb
|
|
14
|
+
|
|
15
|
+
IMAGE = "docker.io/library/postgres"
|
|
16
|
+
DEFAULTS = {"pg_version": "17", "memory": "512m", "shared_buffers": "64MB", "max_connections": 80, "deadlock_timeout": "1s"}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class PgSandbox:
|
|
20
|
+
def __init__(self, settings: dict | None = None, log=None):
|
|
21
|
+
self.cfg = {**DEFAULTS, **{k: v for k, v in (settings or {}).items() if k in DEFAULTS}}
|
|
22
|
+
self.runtime = None
|
|
23
|
+
self.name = f"codecop-tx-{uuid.uuid4().hex[:8]}"
|
|
24
|
+
self.port = 0
|
|
25
|
+
self.version = ""
|
|
26
|
+
self.dbs = 0
|
|
27
|
+
self.log = log
|
|
28
|
+
|
|
29
|
+
@property
|
|
30
|
+
def server_settings(self) -> dict:
|
|
31
|
+
return {"fsync": "off", "synchronous_commit": "off", "deadlock_timeout": self.cfg["deadlock_timeout"],
|
|
32
|
+
"shared_buffers": self.cfg["shared_buffers"]}
|
|
33
|
+
|
|
34
|
+
def start(self, timeout_s: int = 120) -> None:
|
|
35
|
+
self.runtime = find_runtime()
|
|
36
|
+
reap_orphans(self.runtime)
|
|
37
|
+
image = f"{IMAGE}:{self.cfg['pg_version']}"
|
|
38
|
+
cmd = [self.runtime, "run", "-d", "--name", self.name, *sandbox_run_args(self.runtime, self.name, "/var/lib/postgresql/data", image),
|
|
39
|
+
"--memory", str(self.cfg["memory"]), "-p", "127.0.0.1::5432", "-e", "POSTGRES_HOST_AUTH_METHOD=trust", image,
|
|
40
|
+
"-c", "fsync=off", "-c", "synchronous_commit=off", "-c", "full_page_writes=off", "-c", f"shared_buffers={self.cfg['shared_buffers']}",
|
|
41
|
+
"-c", f"max_connections={int(self.cfg['max_connections'])}", "-c", f"deadlock_timeout={self.cfg['deadlock_timeout']}",
|
|
42
|
+
"-c", "listen_addresses=*", "-c", "autovacuum=off", "-c", "log_min_messages=fatal"]
|
|
43
|
+
proc = subprocess.run(cmd, capture_output=True, text=True)
|
|
44
|
+
if proc.returncode != 0:
|
|
45
|
+
self.stop()
|
|
46
|
+
raise SandboxError(f"Could not start {image}: {proc.stderr.strip()[:300]}")
|
|
47
|
+
deadline = time.monotonic() + timeout_s
|
|
48
|
+
while time.monotonic() < deadline:
|
|
49
|
+
ready = subprocess.run([self.runtime, "exec", self.name, "pg_isready", "-h", "127.0.0.1", "-U", "postgres"], capture_output=True)
|
|
50
|
+
if ready.returncode == 0:
|
|
51
|
+
out = subprocess.run([self.runtime, "port", self.name, "5432/tcp"], capture_output=True, text=True).stdout.strip()
|
|
52
|
+
if out:
|
|
53
|
+
self.port = int(out.splitlines()[0].rsplit(":", 1)[1])
|
|
54
|
+
try:
|
|
55
|
+
c = PgDb(self.port, "postgres").admin()
|
|
56
|
+
self.version = c.run("SHOW server_version")[0][0].split()[0]
|
|
57
|
+
c.close()
|
|
58
|
+
return
|
|
59
|
+
except Exception: # noqa: BLE001 -- the published port can answer a moment after the server
|
|
60
|
+
pass
|
|
61
|
+
time.sleep(0.5)
|
|
62
|
+
self.stop()
|
|
63
|
+
raise SandboxError(f"PostgreSQL {self.cfg['pg_version']} did not become reachable in {timeout_s}s")
|
|
64
|
+
|
|
65
|
+
def database(self) -> PgDb:
|
|
66
|
+
"""A fresh database for one scenario."""
|
|
67
|
+
self.dbs += 1
|
|
68
|
+
name = f"tx{self.dbs}"
|
|
69
|
+
c = PgDb(self.port, "postgres").admin()
|
|
70
|
+
try:
|
|
71
|
+
c.run(f"DROP DATABASE IF EXISTS {name}")
|
|
72
|
+
c.run(f"CREATE DATABASE {name}")
|
|
73
|
+
finally:
|
|
74
|
+
c.close()
|
|
75
|
+
return PgDb(self.port, name, self.version, self.server_settings)
|
|
76
|
+
|
|
77
|
+
def drop(self, db: PgDb) -> None:
|
|
78
|
+
try:
|
|
79
|
+
c = PgDb(self.port, "postgres").admin()
|
|
80
|
+
c.run(f"DROP DATABASE IF EXISTS {db.database} WITH (FORCE)")
|
|
81
|
+
c.close()
|
|
82
|
+
except Exception: # noqa: BLE001
|
|
83
|
+
pass
|
|
84
|
+
|
|
85
|
+
def stop(self) -> None:
|
|
86
|
+
if self.runtime:
|
|
87
|
+
remove_sandbox(self.runtime, self.name)
|
|
88
|
+
|
|
89
|
+
def __enter__(self) -> "PgSandbox":
|
|
90
|
+
self.start()
|
|
91
|
+
return self
|
|
92
|
+
|
|
93
|
+
def __exit__(self, *exc) -> None:
|
|
94
|
+
self.stop()
|