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,293 @@
|
|
|
1
|
+
"""The transaction kind's verifier: each candidate's scenario, run before and with the fix by CodeCop's own sessions in the
|
|
2
|
+
sandbox, judged on counts and throughput ratios, written as a finding with its proof, lanes, worker curve, invariant and
|
|
3
|
+
assumptions. Correctness first (a wrong result is the stronger claim), then speed, up to `max_scenarios`."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
import traceback
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from .. import finding, outcome, proof
|
|
12
|
+
from ..pipeline import origin_of
|
|
13
|
+
from . import PG_ONLY, SQLITE_ONLY, TITLES, plan, scenarios
|
|
14
|
+
from .measure import judge, measure, outcome_of, proof_of
|
|
15
|
+
from .schedule import SqliteDb
|
|
16
|
+
|
|
17
|
+
ORDER = {"poll_then_mark": 0, "read_modify_write": 1, "lock_order": 2, "sqlite_deferred_begin": 3, "sqlite_no_wal_timeout": 4,
|
|
18
|
+
"queue_claim": 5, "call_in_transaction": 6, "fk_without_index": 7}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def engine_for(c: dict) -> str:
|
|
22
|
+
code, eng = c["scenario"], (c.get("engine") or "").lower()
|
|
23
|
+
if code in SQLITE_ONLY:
|
|
24
|
+
return "sqlite"
|
|
25
|
+
if code in PG_ONLY:
|
|
26
|
+
return "postgres" if eng in ("", "postgres") else eng
|
|
27
|
+
return eng or "postgres"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def verify_all(kind, ctx, cands: list[dict]) -> list[dict]:
|
|
31
|
+
cfg = kind.cfg(ctx)
|
|
32
|
+
inventory = ctx.inventory or {}
|
|
33
|
+
from .rules import load_catalog
|
|
34
|
+
catalog = load_catalog(ctx.out_dir, ctx.settings)
|
|
35
|
+
production = _production(ctx.out_dir)
|
|
36
|
+
queries = {q.get("id"): q for q in inventory.get("call_sites") or [] if isinstance(q, dict)}
|
|
37
|
+
order = sorted(cands, key=lambda c: (ORDER.get(c["scenario"], 9), c.get("file") or "", c.get("line") or 0))
|
|
38
|
+
out, ran = [], 0
|
|
39
|
+
sandbox = None
|
|
40
|
+
try:
|
|
41
|
+
for c in order:
|
|
42
|
+
f = None
|
|
43
|
+
answer = ctx.answer(kind._key(ctx, c)) if c.get("ask") else None
|
|
44
|
+
if c.get("ask") and answer is None:
|
|
45
|
+
f = _plain(kind, c, "not_judged", "not_asked", source="claimed")
|
|
46
|
+
elif answer is not None and (answer.get("scenario") == "none" or answer.get("concurrent") is False):
|
|
47
|
+
f = _plain(kind, c, "nothing_to_gain", "transaction.already_safe", source="claimed",
|
|
48
|
+
evidence={"agent": (answer.get("why") or "")[:200]})
|
|
49
|
+
else:
|
|
50
|
+
if answer and answer.get("scenario") in scenarios.CODES:
|
|
51
|
+
c["scenario"] = answer["scenario"]
|
|
52
|
+
eng = engine_for(c)
|
|
53
|
+
if eng not in ("postgres", "sqlite"):
|
|
54
|
+
f = _plain(kind, c, "not_judged", "transaction.engine_not_supported", source="claimed", evidence={"engine": eng})
|
|
55
|
+
elif not cfg["sandbox"]:
|
|
56
|
+
f = _plain(kind, c, "not_judged", "sandbox_could_not_run", source="claimed", evidence={"sandbox": "off"})
|
|
57
|
+
elif ran >= int(cfg["max_scenarios"]):
|
|
58
|
+
f = _plain(kind, c, "not_judged", "transaction.not_run", source="claimed", evidence={"max_scenarios": int(cfg["max_scenarios"])})
|
|
59
|
+
elif eng == "postgres" and sandbox is False:
|
|
60
|
+
f = _plain(kind, c, "not_judged", "sandbox_could_not_run", source="claimed", evidence={"sandbox": "did not start"})
|
|
61
|
+
else:
|
|
62
|
+
c["engine"] = eng
|
|
63
|
+
if eng == "postgres" and sandbox is None:
|
|
64
|
+
from .sandbox import PgSandbox
|
|
65
|
+
sandbox = PgSandbox(cfg, log=ctx.say)
|
|
66
|
+
ctx.say(f"transaction: starting a PostgreSQL {cfg['pg_version']} sandbox")
|
|
67
|
+
try:
|
|
68
|
+
sandbox.start()
|
|
69
|
+
except Exception as e: # noqa: BLE001 -- no container runtime: these candidates stay not judged
|
|
70
|
+
ctx.say(f"transaction: the PostgreSQL sandbox did not start ({str(e)[:160]})")
|
|
71
|
+
sandbox = False
|
|
72
|
+
out.append(_origin_and(_plain(kind, c, "not_judged", "sandbox_could_not_run", source="claimed",
|
|
73
|
+
evidence={"sandbox": "did not start"}), c, queries, production))
|
|
74
|
+
continue
|
|
75
|
+
ran += 1
|
|
76
|
+
f = run_one(kind, ctx, c, cfg, inventory, catalog, sandbox, answer)
|
|
77
|
+
if f is None:
|
|
78
|
+
continue
|
|
79
|
+
_origin(f, c, queries)
|
|
80
|
+
_production_facts(f, c, production)
|
|
81
|
+
out.append(f)
|
|
82
|
+
finally:
|
|
83
|
+
if sandbox:
|
|
84
|
+
sandbox.stop()
|
|
85
|
+
return out
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _origin_and(f: dict, c: dict, queries: dict, production: dict | None) -> dict:
|
|
89
|
+
_origin(f, c, queries)
|
|
90
|
+
_production_facts(f, c, production)
|
|
91
|
+
return f
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def run_one(kind, ctx, c: dict, cfg: dict, inventory: dict, catalog: dict | None, sandbox, answer: dict | None) -> dict:
|
|
95
|
+
code = c["scenario"]
|
|
96
|
+
try:
|
|
97
|
+
facts = plan.facts_for(c, inventory, catalog, cfg)
|
|
98
|
+
scn = scenarios.build(code, facts)
|
|
99
|
+
except Exception as e: # noqa: BLE001
|
|
100
|
+
return _plain(kind, c, "not_judged", "transaction.not_replayable", source="claimed", evidence={"error": type(e).__name__, "why": str(e)[:160]})
|
|
101
|
+
m, why = _measure(ctx, c, scn, cfg, sandbox)
|
|
102
|
+
if m is None and code == "fk_without_index" and c.get("delete_sql"):
|
|
103
|
+
# the repository's delete did not run on the modelled parent: the schema's own key with a plain keyed delete
|
|
104
|
+
facts = plan.facts_for({**c, "delete_sql": None}, inventory, catalog, cfg)
|
|
105
|
+
facts["fallback"] = f"the repository's delete did not replay: {why}"[:160]
|
|
106
|
+
scn = scenarios.build(code, facts)
|
|
107
|
+
m, why = _measure(ctx, c, scn, cfg, sandbox)
|
|
108
|
+
elif m is None and facts.get("statements") == "extracted":
|
|
109
|
+
# the repository's statements did not replay (a constraint the generated rows break, a statement the sandbox
|
|
110
|
+
# refuses): the same shape on modelled statements, said so on the finding
|
|
111
|
+
facts = {**{k: v for k, v in facts.items() if k in ("engine", "sessions", "think_ms", "operations", "hot_rows", "items", "batch")},
|
|
112
|
+
**plan._modelled(c, scn.engine), "statements": "modelled", "fallback": f"the extracted statements did not replay: {why}"[:160]}
|
|
113
|
+
scn = scenarios.build(code, facts)
|
|
114
|
+
m, why = _measure(ctx, c, scn, cfg, sandbox)
|
|
115
|
+
if m is None:
|
|
116
|
+
return _plain(kind, c, "not_judged", "sandbox_could_not_run", source="claimed", evidence={"why": why[:160], "statements": facts.get("statements")})
|
|
117
|
+
v = judge(scn, m)
|
|
118
|
+
if scn.statements == "modelled" and v["state"] in ("fixed", "blocked"):
|
|
119
|
+
# a model of the shape, not the repository's statements: shown, never a verdict about this code
|
|
120
|
+
v = {**v, "state": "not_judged", "reason": "transaction.not_replayable",
|
|
121
|
+
"evidence": {**(v.get("evidence") or {}), "modelled_state": v["state"], "fallback": (facts.get("fallback") or "")[:160]}}
|
|
122
|
+
fk = c.get("fk") or {}
|
|
123
|
+
if code == "fk_without_index" and v["state"] == "fixed" and fk.get("parent_deletes") == 0:
|
|
124
|
+
v = {**v, "state": "nothing_to_gain", "reason": "transaction.rarely_runs",
|
|
125
|
+
"evidence": {**(v.get("evidence") or {}), "parent_deletes": 0, "source": "catalog"}}
|
|
126
|
+
elif code == "fk_without_index" and v["state"] == "fixed" and fk.get("source") != "catalog":
|
|
127
|
+
# the gain grows with the child table and matters as often as parents are deleted: neither is known without a
|
|
128
|
+
# catalog, so the measured ratio is shown and the verdict waits on a production fact
|
|
129
|
+
v = {**v, "state": "not_judged", "reason": "needs_production_fact",
|
|
130
|
+
"evidence": {**(v.get("evidence") or {}), "child_rows_modelled": facts.get("children"), "needs": "child rows and parent deletes"}}
|
|
131
|
+
rt = {"engine": "postgresql" if scn.engine == "postgres" else "sqlite",
|
|
132
|
+
"version": sandbox.version if scn.engine == "postgres" else __import__("sqlite3").sqlite_version,
|
|
133
|
+
"settings": sandbox.server_settings if scn.engine == "postgres" else
|
|
134
|
+
{f"before {k}": val for k, val in (scn.db_settings.get("before") or {"journal_mode": "wal", "busy_timeout_ms": 5000}).items()}
|
|
135
|
+
| ({f"after {k}": val for k, val in scn.db_settings["after"].items()} if scn.db_settings.get("after") != scn.db_settings.get("before") else {})}
|
|
136
|
+
p = proof_of(scn, m, v, rt, inputs={"family": f"generated rows, {scn.statements} statements", "typical": scn.compared[:60],
|
|
137
|
+
"observed": "not measured in production"})
|
|
138
|
+
o = outcome_of(v)
|
|
139
|
+
if answer and answer.get("why"):
|
|
140
|
+
o["evidence"]["agent"] = answer["why"][:200]
|
|
141
|
+
fix = dict(scn.fix)
|
|
142
|
+
if answer and answer.get("fix_after"):
|
|
143
|
+
fix = {"change": fix.get("change", ""), "before": answer.get("fix_before") or fix.get("before", ""), "after": answer["fix_after"]}
|
|
144
|
+
if v["variant"] == "after_lock":
|
|
145
|
+
fix = {"change": "select_for_update", "before": scn.fix.get("before", ""), "after": "BEGIN\n-- read with FOR UPDATE, compute, write\nCOMMIT"}
|
|
146
|
+
harm = scn.harm
|
|
147
|
+
return finding(kind.name, id=c["id"], title=title(c, scn), site=_site(c), outcome=o, proof=p, harm=harm,
|
|
148
|
+
severity="high" if o["state"] == "fixed" and harm != "speed" else "medium" if o["state"] == "fixed" else "low",
|
|
149
|
+
confidence="high" if scn.statements == "extracted" else "medium",
|
|
150
|
+
summary=(c.get("why") or "")[:300], fix=fix,
|
|
151
|
+
extra={"scenario": code, "engine": scn.engine, "tables": [t for t in c.get("tables") or [] if t][:6],
|
|
152
|
+
"shape": shape_of(c), "lanes": m.get("lanes") or {}, "workers": workers_of(scn, m),
|
|
153
|
+
"invariant": (answer or {}).get("invariant") or scn.invariant, "assumptions": assumptions(c, scn, m, facts),
|
|
154
|
+
"tradeoff": scn.tradeoff, "statements": scn.statements})
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _measure(ctx, c: dict, scn, cfg: dict, sandbox) -> tuple[dict | None, str]:
|
|
158
|
+
"""(the measurement, '') or (None, why it could not run): an exception, or a replay that did nothing (the poll found
|
|
159
|
+
no rows, every operation failed on an error no contention explains)."""
|
|
160
|
+
db = None
|
|
161
|
+
try:
|
|
162
|
+
if scn.engine == "postgres":
|
|
163
|
+
db = sandbox.database()
|
|
164
|
+
|
|
165
|
+
def make_db(_settings, db=db):
|
|
166
|
+
return db
|
|
167
|
+
else:
|
|
168
|
+
def make_db(st):
|
|
169
|
+
return SqliteDb(**(st or {"journal_mode": "wal", "busy_timeout_ms": 5000}))
|
|
170
|
+
ctx.say(f"transaction: {scn.code} at {c.get('file')}:{c.get('line')} ({scn.statements} statements)")
|
|
171
|
+
m = measure(scn, make_db, cfg, log=ctx.say)
|
|
172
|
+
except Exception as e: # noqa: BLE001
|
|
173
|
+
ctx.say(f"transaction: {scn.code} at {c.get('file')}:{c.get('line')} could not run: {type(e).__name__}: {str(e)[:200]}")
|
|
174
|
+
if ctx.log is None:
|
|
175
|
+
traceback.print_exc()
|
|
176
|
+
return None, f"{type(e).__name__}: {str(e)[:150]}"
|
|
177
|
+
finally:
|
|
178
|
+
if db is not None and sandbox is not None:
|
|
179
|
+
sandbox.drop(db)
|
|
180
|
+
for v, rs in m["results"].items():
|
|
181
|
+
for r in rs:
|
|
182
|
+
if r.ops == 0 and r.errors.get("first_error"):
|
|
183
|
+
return None, f"{v}: {r.errors['first_error']}"
|
|
184
|
+
if scn.code == "poll_then_mark" and all(not r.counters.get("acts") for r in m["results"]["before"]):
|
|
185
|
+
return None, "the poll found none of the generated rows"
|
|
186
|
+
if scn.code == "fk_without_index" and all(r.p50_wait_ms is None for r in m["results"]["before"]):
|
|
187
|
+
first = next((r.errors.get("first_error") for r in m["results"]["before"] if r.errors.get("first_error")), "")
|
|
188
|
+
return None, f"no parent delete ran{': ' + first if first else ''}"
|
|
189
|
+
return m, ""
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def title(c: dict, scn=None) -> str:
|
|
193
|
+
t = (c.get("tables") or [""])[0] or "a table"
|
|
194
|
+
fk = c.get("fk") or {}
|
|
195
|
+
call = (c.get("call") or {}).get("what") or "a call"
|
|
196
|
+
how = ("without WAL or a busy timeout" if not c.get("wal") and not c.get("busy_timeout_ms") else
|
|
197
|
+
"without WAL" if not c.get("wal") else "without a busy timeout")
|
|
198
|
+
return TITLES.get(c["scenario"], TITLES["unknown"]).format(t=t, parent=fk.get("parent") or t, child=fk.get("child") or "its child",
|
|
199
|
+
what=call, col=c.get("column") or "a value", how=how)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _site(c: dict) -> dict:
|
|
203
|
+
return {"file": c.get("file"), "line": c.get("line"), "symbol": c.get("symbol") or ""}
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _plain(kind, c: dict, state: str, reason: str, *, source: str, evidence: dict | None = None) -> dict:
|
|
207
|
+
return finding(kind.name, id=c["id"], title=title(c), site=_site(c), outcome=outcome(kind.name, state, reason, source=source, evidence=evidence or {}),
|
|
208
|
+
proof=proof(source="claimed", measures=[]), harm=scenarios.HARM.get(c["scenario"], "speed"), severity="low", confidence="low",
|
|
209
|
+
summary=(c.get("why") or "")[:300],
|
|
210
|
+
extra={"scenario": c["scenario"], "engine": c.get("engine") or "", "tables": [t for t in c.get("tables") or [] if t][:6],
|
|
211
|
+
"shape": shape_of(c)})
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def shape_of(c: dict) -> dict:
|
|
215
|
+
steps = []
|
|
216
|
+
for s in (c.get("steps") or [])[:24]:
|
|
217
|
+
st = {"line": s.get("line"), "op": s.get("op") or "other"}
|
|
218
|
+
if s.get("table"):
|
|
219
|
+
st["table"] = str(s["table"])[:60]
|
|
220
|
+
if s.get("lock"):
|
|
221
|
+
st["lock"] = s["lock"]
|
|
222
|
+
if s.get("what"):
|
|
223
|
+
st["what"] = s["what"]
|
|
224
|
+
steps.append(st)
|
|
225
|
+
return {"form": c.get("form") or ("begin_commit" if c["scenario"] in ("call_in_transaction", "lock_order", "sqlite_deferred_begin") else "none"),
|
|
226
|
+
"begin_line": c.get("line") if c["scenario"] in ("call_in_transaction", "lock_order", "sqlite_deferred_begin") else None,
|
|
227
|
+
"end_line": c.get("end_line"), "steps": steps}
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def workers_of(scn, m: dict) -> dict:
|
|
231
|
+
pts = m.get("workers") or []
|
|
232
|
+
return {"measure": scn.verdict, "points": [{"n": p["n"], "before": p.get("before"), "after": p.get("after")} for p in pts],
|
|
233
|
+
"production": "unknown"} if pts else {}
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def assumptions(c: dict, scn, m: dict, facts: dict) -> list[str]:
|
|
237
|
+
out = []
|
|
238
|
+
pts = m.get("workers") or []
|
|
239
|
+
one = next((p for p in pts if p["n"] == 1), None)
|
|
240
|
+
if one is not None and not one.get("before") and any(p.get("before") for p in pts if p["n"] > 1) and scn.verdict != "throughput":
|
|
241
|
+
out.append("Fires only with more than one worker; how many run in production is not known.")
|
|
242
|
+
elif pts:
|
|
243
|
+
out.append(f"Measured with {', '.join(str(p['n']) for p in pts)} sessions; how many run in production is not known.")
|
|
244
|
+
if scn.code == "poll_then_mark":
|
|
245
|
+
out.append(f"The act (a post, a send) happens between the poll and the mark; a {scn.think_ms:g} ms pause stands in for it.")
|
|
246
|
+
if c.get("mark_symbol") and c.get("mark_symbol") != c.get("symbol"):
|
|
247
|
+
out.append(f"The poll ({c.get('symbol')}) and the mark ({c.get('mark_symbol')}) are separate calls; whoever calls them decides the order.")
|
|
248
|
+
if scn.code == "call_in_transaction":
|
|
249
|
+
out.append(f"{scn.hot_rows} rows are touched by concurrent requests; a {scn.think_ms:g} ms pause stands in for the call.")
|
|
250
|
+
if scn.code == "read_modify_write":
|
|
251
|
+
out.append(f"{scn.hot_rows} rows are updated by concurrent requests; the value written is computed from the value read (the rules read it so, not checked).")
|
|
252
|
+
if scn.statements == "modelled":
|
|
253
|
+
out.append("Statements modelled on the table names" + (f": {facts.get('fallback')}" if facts.get("fallback") else "") + ".")
|
|
254
|
+
if scn.engine == "postgres":
|
|
255
|
+
out.append("Sandbox durability off (fsync, synchronous_commit): absolute rates are higher than on a real server.")
|
|
256
|
+
return [a[:160] for a in out][:6]
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _origin(f: dict, c: dict, queries: dict) -> None:
|
|
260
|
+
if (f.get("origin") or {}).get("kind") not in (None, "unknown"):
|
|
261
|
+
return
|
|
262
|
+
q = queries.get(c.get("origin_site"))
|
|
263
|
+
if q:
|
|
264
|
+
f["origin"] = origin_of(q)
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _production(out_dir) -> dict | None:
|
|
268
|
+
try:
|
|
269
|
+
return json.loads((Path(out_dir) / "db_locks.json").read_text())
|
|
270
|
+
except (OSError, ValueError):
|
|
271
|
+
return None
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def _production_facts(f: dict, c: dict, production: dict | None) -> None:
|
|
275
|
+
"""The sampled watch's counts beside the finding (production evidence; never a verdict input here)."""
|
|
276
|
+
if not production:
|
|
277
|
+
return
|
|
278
|
+
for conn in (production.get("connections") or {}).values():
|
|
279
|
+
if conn.get("engine") != "postgres" or not conn.get("samples"):
|
|
280
|
+
continue
|
|
281
|
+
out = {"source": "watch", "samples": int(conn.get("samples") or 0), "lock_wait_samples": int(conn.get("lock_wait_samples") or 0),
|
|
282
|
+
"idle_in_tx_samples": int(conn.get("idle_in_tx_samples") or 0),
|
|
283
|
+
"deadlocks": int((conn.get("counters_delta") or {}).get("deadlocks") or 0)}
|
|
284
|
+
tables = {t.split(".")[-1] for t in c.get("tables") or []}
|
|
285
|
+
out["waits_on_these_tables"] = sum(int(p.get("samples") or 0) for p in conn.get("blocking_pairs") or []
|
|
286
|
+
if str(p.get("relation") or "").split(".")[-1] in tables)
|
|
287
|
+
if c["scenario"] == "fk_without_index":
|
|
288
|
+
fk = c.get("fk") or {}
|
|
289
|
+
hit = next((x for x in conn.get("fk_without_index") or [] if str(x.get("child", "")).split(".")[-1] == fk.get("child")), None)
|
|
290
|
+
if hit:
|
|
291
|
+
out["parent_deletes"] = hit.get("parent_deletes")
|
|
292
|
+
f["production"] = out
|
|
293
|
+
return
|
codecop/live.py
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
"""Live status: post run events to the server while a scan works.
|
|
2
|
+
|
|
3
|
+
A scan must never fail or wait because of this. `emit` only appends to a list;
|
|
4
|
+
a background thread posts the list in batches with a short timeout. The first
|
|
5
|
+
failure is logged, later ones are silent, and after a few in a row posting
|
|
6
|
+
stops for the rest of the run. Events carry short labels and counts: no SQL
|
|
7
|
+
text, no absolute paths.
|
|
8
|
+
|
|
9
|
+
The event shape is schemas/run_event.schema.json; the types are listed in
|
|
10
|
+
the console's API.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import json
|
|
16
|
+
import os
|
|
17
|
+
import secrets
|
|
18
|
+
import threading
|
|
19
|
+
import time
|
|
20
|
+
from datetime import datetime, timezone
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
|
|
23
|
+
STATE_FILE = "run.json"
|
|
24
|
+
SCAN_FILE = "scan.json" # {"scan_id"}: the `codecop scan` invocation an out dir belongs to, reported or not
|
|
25
|
+
POST_TIMEOUT_S = 5 # one events request
|
|
26
|
+
FLUSH_INTERVAL_S = 2.0 # how often the background thread posts what has gathered
|
|
27
|
+
BATCH = 200 # events per request
|
|
28
|
+
MAX_PENDING = 2000 # unsent events kept while the server is unreachable; the oldest go first
|
|
29
|
+
MAX_FAILURES = 3 # failed posts in a row before giving up for this run
|
|
30
|
+
HEARTBEAT_S = 30 # with nothing to post for this long, post an empty batch: "still here"
|
|
31
|
+
EVENTS_FILE_ENV = "CODECOP_EVENTS_FILE" # set (a hosted job): every event is also one JSON line in this file
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def append_event_file(stage: str, status: str, type: str, message: str = "", data: dict | None = None) -> None:
|
|
35
|
+
"""With CODECOP_EVENTS_FILE set, append the event as one JSON line, whether or not a server run exists. The hosted
|
|
36
|
+
runner tails the file: a --no-upload pull-request scan shows stage progress on the job page this way. Never
|
|
37
|
+
raises: a scan does not fail because of it."""
|
|
38
|
+
path = os.environ.get(EVENTS_FILE_ENV)
|
|
39
|
+
if not path:
|
|
40
|
+
return
|
|
41
|
+
event = {"stage": stage, "status": status, "type": type, "at": datetime.now(timezone.utc).isoformat(timespec="milliseconds")}
|
|
42
|
+
if message:
|
|
43
|
+
event["message"] = message[:200]
|
|
44
|
+
if data:
|
|
45
|
+
event["data"] = data
|
|
46
|
+
try:
|
|
47
|
+
line = json.dumps(event, ensure_ascii=False, default=str)
|
|
48
|
+
with open(path, "a", encoding="utf-8") as fh:
|
|
49
|
+
fh.write(line + "\n")
|
|
50
|
+
except (OSError, TypeError, ValueError):
|
|
51
|
+
pass
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def new_scan_id() -> str:
|
|
55
|
+
"""One per `codecop scan` invocation; every engine run of that scan carries it."""
|
|
56
|
+
return "scan_" + secrets.token_hex(12)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def load_scan_id(out_dir: Path) -> str:
|
|
60
|
+
"""The scan id an out dir was written under: scan.json, else the live run's run.json. "" when neither has one."""
|
|
61
|
+
for name in (SCAN_FILE, STATE_FILE):
|
|
62
|
+
try:
|
|
63
|
+
value = json.loads((out_dir / name).read_text()).get("scan_id")
|
|
64
|
+
except (OSError, ValueError, AttributeError):
|
|
65
|
+
continue
|
|
66
|
+
if isinstance(value, str) and value:
|
|
67
|
+
return value
|
|
68
|
+
return ""
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def save_scan_id(out_dir: Path, scan_id: str) -> None:
|
|
72
|
+
try:
|
|
73
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
74
|
+
(out_dir / SCAN_FILE).write_text(json.dumps({"scan_id": scan_id}, indent=1))
|
|
75
|
+
except OSError:
|
|
76
|
+
pass # a read-only out dir loses the grouping of a later `codecop push`, nothing else
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def load_state(out_dir: Path) -> dict | None:
|
|
80
|
+
"""The run an out dir is attached to: {"server", "run_id", "url", "project", "next_seq"}."""
|
|
81
|
+
path = out_dir / STATE_FILE
|
|
82
|
+
try:
|
|
83
|
+
state = json.loads(path.read_text())
|
|
84
|
+
except (OSError, ValueError):
|
|
85
|
+
return None
|
|
86
|
+
return state if isinstance(state, dict) and isinstance(state.get("run_id"), str) else None
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def save_state(out_dir: Path, state: dict) -> None:
|
|
90
|
+
try:
|
|
91
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
92
|
+
(out_dir / STATE_FILE).write_text(json.dumps(state, indent=1))
|
|
93
|
+
except OSError:
|
|
94
|
+
pass # a read-only out dir costs --resume its run id, nothing else
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def forget_state(out_dir: Path) -> None:
|
|
98
|
+
try:
|
|
99
|
+
(out_dir / STATE_FILE).unlink()
|
|
100
|
+
except OSError:
|
|
101
|
+
pass
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
class NullRun:
|
|
105
|
+
"""Stands in when a scan is not being reported: every call is a no-op."""
|
|
106
|
+
run_id = ""
|
|
107
|
+
url = ""
|
|
108
|
+
continued = False
|
|
109
|
+
|
|
110
|
+
def emit(self, stage: str, status: str, type: str, message: str = "", data: dict | None = None) -> None:
|
|
111
|
+
append_event_file(stage, status, type, message, data)
|
|
112
|
+
|
|
113
|
+
def flush(self) -> bool:
|
|
114
|
+
return True
|
|
115
|
+
|
|
116
|
+
def beat(self) -> bool:
|
|
117
|
+
return False
|
|
118
|
+
|
|
119
|
+
def close(self) -> None:
|
|
120
|
+
pass
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
class LiveRun(NullRun):
|
|
124
|
+
def __init__(self, client, run_id: str, *, url: str = "", out_dir: Path | None = None, state: dict | None = None,
|
|
125
|
+
seq: int = 0, continued: bool = False, background: bool = True, interval: float = FLUSH_INTERVAL_S,
|
|
126
|
+
timeout: int = POST_TIMEOUT_S, log=None, heartbeat: float = HEARTBEAT_S, clock=time.monotonic):
|
|
127
|
+
self.client, self.run_id, self.url, self.continued = client, run_id, url, continued
|
|
128
|
+
self.out_dir, self.state = out_dir, dict(state or {})
|
|
129
|
+
self.timeout, self.interval, self.log = timeout, interval, log
|
|
130
|
+
self.heartbeat, self.clock = heartbeat, clock
|
|
131
|
+
self.last_post = self.last_try = clock() # the run was just created or continued: the server heard from us
|
|
132
|
+
self.seq = seq
|
|
133
|
+
self.pending: list[dict] = []
|
|
134
|
+
self.failures = 0
|
|
135
|
+
self.warned = False
|
|
136
|
+
self.disabled = False
|
|
137
|
+
self.lock = threading.Lock() # guards seq and pending
|
|
138
|
+
self.posting = threading.Lock() # one request at a time, so batches arrive in order
|
|
139
|
+
self.wake = threading.Event()
|
|
140
|
+
self.stop = False
|
|
141
|
+
self.thread = None
|
|
142
|
+
self._save()
|
|
143
|
+
if background:
|
|
144
|
+
self.thread = threading.Thread(target=self._loop, name="codecop-live", daemon=True)
|
|
145
|
+
self.thread.start()
|
|
146
|
+
|
|
147
|
+
def emit(self, stage: str, status: str, type: str, message: str = "", data: dict | None = None) -> None:
|
|
148
|
+
"""Queue one event. Never blocks on the network and never raises."""
|
|
149
|
+
append_event_file(stage, status, type, message, data)
|
|
150
|
+
if self.disabled:
|
|
151
|
+
return
|
|
152
|
+
event = {"stage": stage, "status": status, "type": type,
|
|
153
|
+
"at": datetime.now(timezone.utc).isoformat(timespec="milliseconds")}
|
|
154
|
+
if message:
|
|
155
|
+
event["message"] = message[:200]
|
|
156
|
+
if data:
|
|
157
|
+
event["data"] = data
|
|
158
|
+
with self.lock:
|
|
159
|
+
event["seq"] = self.seq
|
|
160
|
+
self.seq += 1
|
|
161
|
+
self.pending.append(event)
|
|
162
|
+
if len(self.pending) > MAX_PENDING:
|
|
163
|
+
del self.pending[:len(self.pending) - MAX_PENDING]
|
|
164
|
+
|
|
165
|
+
def flush(self) -> bool:
|
|
166
|
+
"""Post what is queued, one batch per request. False when a post failed."""
|
|
167
|
+
with self.posting:
|
|
168
|
+
while not self.disabled:
|
|
169
|
+
with self.lock:
|
|
170
|
+
batch = self.pending[:BATCH]
|
|
171
|
+
if not batch:
|
|
172
|
+
return True
|
|
173
|
+
self.last_try = self.clock()
|
|
174
|
+
try:
|
|
175
|
+
self.client.send_events(self.run_id, batch, timeout=self.timeout)
|
|
176
|
+
except Exception as exc: # the server being down, slow or wrong must not reach the scan
|
|
177
|
+
self.failures += 1
|
|
178
|
+
if not self.warned and self.log:
|
|
179
|
+
self.log(f"Could not report progress to the server ({str(exc)[:160]}). The scan continues.")
|
|
180
|
+
self.warned = True
|
|
181
|
+
if self.failures >= MAX_FAILURES:
|
|
182
|
+
self.disabled = True
|
|
183
|
+
with self.lock:
|
|
184
|
+
self.pending.clear()
|
|
185
|
+
return False
|
|
186
|
+
self.failures = 0
|
|
187
|
+
self.last_post = self.clock()
|
|
188
|
+
with self.lock:
|
|
189
|
+
sent = {e["seq"] for e in batch}
|
|
190
|
+
self.pending = [e for e in self.pending if e["seq"] not in sent]
|
|
191
|
+
self._save()
|
|
192
|
+
return False
|
|
193
|
+
|
|
194
|
+
def beat(self) -> bool:
|
|
195
|
+
"""The heartbeat: when nothing was posted (or tried) for `heartbeat` seconds, post an empty batch, so
|
|
196
|
+
the server can tell a long agent call from a CLI that was killed. Events that are flowing are the
|
|
197
|
+
heartbeat already: this adds a request only to a silence. True when one was sent.
|
|
198
|
+
|
|
199
|
+
It goes on after event posting was given up on, without logging, and a heartbeat that gets through
|
|
200
|
+
turns event posting back on: the server is reachable again."""
|
|
201
|
+
if self.clock() - max(self.last_post, self.last_try) < self.heartbeat:
|
|
202
|
+
return False
|
|
203
|
+
send = getattr(self.client, "heartbeat", None)
|
|
204
|
+
if send is None:
|
|
205
|
+
return False
|
|
206
|
+
with self.posting:
|
|
207
|
+
self.last_try = self.clock()
|
|
208
|
+
try:
|
|
209
|
+
send(self.run_id, int(self.heartbeat), timeout=self.timeout)
|
|
210
|
+
except Exception: # same rule as events: nothing here may reach the scan
|
|
211
|
+
return False
|
|
212
|
+
self.last_post = self.clock()
|
|
213
|
+
self.failures = 0
|
|
214
|
+
self.disabled = False
|
|
215
|
+
return True
|
|
216
|
+
|
|
217
|
+
def close(self) -> None:
|
|
218
|
+
"""Post the rest and stop the thread. Waits at most a little over one request timeout."""
|
|
219
|
+
self.stop = True
|
|
220
|
+
self.wake.set()
|
|
221
|
+
if self.thread is not None:
|
|
222
|
+
self.thread.join(self.timeout + 2)
|
|
223
|
+
self.thread = None
|
|
224
|
+
else:
|
|
225
|
+
self.flush()
|
|
226
|
+
|
|
227
|
+
def _loop(self) -> None:
|
|
228
|
+
while not self.stop:
|
|
229
|
+
self.wake.wait(self.interval)
|
|
230
|
+
self.flush()
|
|
231
|
+
if not self.stop:
|
|
232
|
+
self.beat()
|
|
233
|
+
self.flush()
|
|
234
|
+
|
|
235
|
+
def _save(self) -> None:
|
|
236
|
+
if self.out_dir is not None:
|
|
237
|
+
save_state(self.out_dir, {**self.state, "run_id": self.run_id, "url": self.url, "next_seq": self.seq})
|