codecop 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- codecop/__init__.py +7 -0
- codecop/access.py +140 -0
- codecop/access_postgres.py +284 -0
- codecop/advisor.py +1512 -0
- codecop/advisor_bench.py +493 -0
- codecop/advisor_ch.py +2080 -0
- codecop/advisor_view.py +381 -0
- codecop/advisors.py +184 -0
- codecop/agent.py +221 -0
- codecop/agentfacts.py +745 -0
- codecop/apply/__init__.py +327 -0
- codecop/apply/check.py +344 -0
- codecop/apply/cli.py +162 -0
- codecop/apply/clickhouse.py +379 -0
- codecop/apply/common.py +238 -0
- codecop/apply/html.py +264 -0
- codecop/apply/patch.py +213 -0
- codecop/apply/postgres.py +102 -0
- codecop/apply/trial.py +166 -0
- codecop/assemble.py +104 -0
- codecop/baseline.py +1043 -0
- codecop/bench.py +2464 -0
- codecop/blockers.py +935 -0
- codecop/budget.py +980 -0
- codecop/catalog_profile.py +525 -0
- codecop/changed.py +261 -0
- codecop/cicmd.py +1002 -0
- codecop/cli.py +5421 -0
- codecop/client.py +729 -0
- codecop/coverage.py +1067 -0
- codecop/coverage_reasons.py +116 -0
- codecop/crashlog.py +70 -0
- codecop/datagen.py +766 -0
- codecop/datagen_postgres.py +630 -0
- codecop/datagen_sqlite.py +323 -0
- codecop/dbcli.py +885 -0
- codecop/definitions.py +457 -0
- codecop/discover/__init__.py +702 -0
- codecop/discover/arms.py +160 -0
- codecop/discover/base.py +234 -0
- codecop/discover/dialect.py +296 -0
- codecop/discover/elixir.py +64 -0
- codecop/discover/engine_go.py +320 -0
- codecop/discover/go.py +1947 -0
- codecop/discover/java.py +1528 -0
- codecop/discover/loops.py +1671 -0
- codecop/discover/named_go.py +258 -0
- codecop/discover/origins.py +4565 -0
- codecop/discover/origins_ts.py +1584 -0
- codecop/discover/orm_django.py +2772 -0
- codecop/discover/orm_django_models.py +814 -0
- codecop/discover/orm_django_sql.py +662 -0
- codecop/discover/orm_ent.py +565 -0
- codecop/discover/orm_ex_ecto.py +2138 -0
- codecop/discover/orm_go.py +2134 -0
- codecop/discover/orm_go_bun.py +602 -0
- codecop/discover/orm_go_run.py +636 -0
- codecop/discover/orm_go_types.py +1082 -0
- codecop/discover/orm_java.py +1450 -0
- codecop/discover/orm_jdbi.py +743 -0
- codecop/discover/orm_jooq.py +806 -0
- codecop/discover/orm_jpa.py +1307 -0
- codecop/discover/orm_mybatis.py +730 -0
- codecop/discover/orm_py.py +557 -0
- codecop/discover/orm_py_peewee.py +1266 -0
- codecop/discover/orm_py_prisma.py +298 -0
- codecop/discover/orm_rb_activerecord.py +1906 -0
- codecop/discover/orm_rust.py +1248 -0
- codecop/discover/orm_rust_seaorm.py +734 -0
- codecop/discover/orm_sqlalchemy.py +2475 -0
- codecop/discover/orm_stats.py +307 -0
- codecop/discover/orm_tables.py +29 -0
- codecop/discover/orm_ts.py +503 -0
- codecop/discover/orm_ts_drizzle.py +697 -0
- codecop/discover/orm_ts_knex.py +1117 -0
- codecop/discover/orm_ts_kysely.py +861 -0
- codecop/discover/orm_ts_prisma.py +1045 -0
- codecop/discover/orm_ts_schema.py +169 -0
- codecop/discover/orm_ts_sequelize.py +1401 -0
- codecop/discover/orm_ts_typeorm.py +1067 -0
- codecop/discover/probes.py +323 -0
- codecop/discover/python.py +595 -0
- codecop/discover/ruby.py +793 -0
- codecop/discover/rust.py +2378 -0
- codecop/discover/schema.py +520 -0
- codecop/discover/schema_ent.py +145 -0
- codecop/discover/schema_ts.py +420 -0
- codecop/discover/tsresolve.py +257 -0
- codecop/discover/typescript.py +1728 -0
- codecop/discover/xml_mapper.py +526 -0
- codecop/engines/__init__.py +515 -0
- codecop/engines/base.py +498 -0
- codecop/engines/clickhouse.py +1558 -0
- codecop/engines/pg_ddl.py +444 -0
- codecop/engines/pg_hints.py +137 -0
- codecop/engines/postgres.py +1060 -0
- codecop/engines/sqlite.py +742 -0
- codecop/families/__init__.py +3 -0
- codecop/families/build.py +280 -0
- codecop/families/cli.py +177 -0
- codecop/families/coverage_hook.py +62 -0
- codecop/families/driver.py +221 -0
- codecop/families/goslice.py +229 -0
- codecop/families/goslice_tool/go.mod +3 -0
- codecop/families/goslice_tool/main.go +403 -0
- codecop/families/holes.py +451 -0
- codecop/families/images/Dockerfile.go +5 -0
- codecop/families/images/Dockerfile.python +4 -0
- codecop/families/images/Dockerfile.rust +4 -0
- codecop/families/isolate.py +171 -0
- codecop/families/locate.py +270 -0
- codecop/families/model.py +301 -0
- codecop/families/plangate.py +271 -0
- codecop/families/tagpatch.py +174 -0
- codecop/fidelity.py +671 -0
- codecop/fixgroups.py +130 -0
- codecop/formerly.py +91 -0
- codecop/grantscript.py +254 -0
- codecop/groupbench.py +1375 -0
- codecop/groups.py +594 -0
- codecop/groups_view.py +186 -0
- codecop/heat.py +1405 -0
- codecop/heatcli.py +219 -0
- codecop/joins.py +1749 -0
- codecop/joins_view.py +127 -0
- codecop/kinds/__init__.py +507 -0
- codecop/kinds/calls/__init__.py +501 -0
- codecop/kinds/calls/extract.py +1097 -0
- codecop/kinds/calls/harness.py +408 -0
- codecop/kinds/calls/measure.py +342 -0
- codecop/kinds/calls/rules.py +139 -0
- codecop/kinds/calls/runners/RunCalls.java +167 -0
- codecop/kinds/calls/runners/run_go.go +141 -0
- codecop/kinds/calls/runners/run_node.js +186 -0
- codecop/kinds/calls/runners/run_python.py +319 -0
- codecop/kinds/calls/runners/run_rust.rs +200 -0
- codecop/kinds/calls/standin.py +340 -0
- codecop/kinds/pipeline.py +288 -0
- codecop/kinds/regex/__init__.py +1167 -0
- codecop/kinds/regex/engines/RegexHarness.java +129 -0
- codecop/kinds/regex/engines/run_go.go +294 -0
- codecop/kinds/regex/engines/run_node.js +99 -0
- codecop/kinds/regex/engines/run_python.py +295 -0
- codecop/kinds/regex/engines/run_rust.rs +149 -0
- codecop/kinds/regex/extract.py +1438 -0
- codecop/kinds/regex/harness.py +235 -0
- codecop/kinds/regex/measure.py +270 -0
- codecop/kinds/regex/shapes.py +418 -0
- codecop/kinds/regex/syntax.py +1721 -0
- codecop/kinds/testkind.py +107 -0
- codecop/kinds/transaction/__init__.py +228 -0
- codecop/kinds/transaction/bind.py +355 -0
- codecop/kinds/transaction/measure.py +264 -0
- codecop/kinds/transaction/plan.py +462 -0
- codecop/kinds/transaction/rules.py +540 -0
- codecop/kinds/transaction/sandbox.py +94 -0
- codecop/kinds/transaction/scenarios.py +520 -0
- codecop/kinds/transaction/schedule.py +483 -0
- codecop/kinds/transaction/shapes.py +418 -0
- codecop/kinds/transaction/verify.py +293 -0
- codecop/live.py +237 -0
- codecop/loopbench.py +2071 -0
- codecop/loopschema.py +591 -0
- codecop/mcpserver.py +120 -0
- codecop/mechanism.py +214 -0
- codecop/members.py +200 -0
- codecop/multi.py +443 -0
- codecop/observed.py +1868 -0
- codecop/parts.py +102 -0
- codecop/patterns.py +830 -0
- codecop/patterns_view.py +559 -0
- codecop/plangate.py +242 -0
- codecop/profile.py +439 -0
- codecop/prompts/areas.md +19 -0
- codecop/prompts/observed_variants.md +20 -0
- codecop/prompts/profile.md +60 -0
- codecop/prompts/profile_postgres.md +68 -0
- codecop/prompts/profile_sizes.md +26 -0
- codecop/prompts/profile_sqlite.md +69 -0
- codecop/prompts/rank.md +84 -0
- codecop/prompts/rank_postgres.md +96 -0
- codecop/prompts/rank_sqlite.md +94 -0
- codecop/prompts/scenario_variants.md +20 -0
- codecop/rank.py +1473 -0
- codecop/realdb/__init__.py +688 -0
- codecop/realdb/clickhouse.py +1223 -0
- codecop/realdb/facts.py +815 -0
- codecop/realdb/locality.py +964 -0
- codecop/realdb/locks.py +355 -0
- codecop/realdb/match.py +531 -0
- codecop/realdb/postgres.py +643 -0
- codecop/realdb/ratios.py +77 -0
- codecop/realdb/sample.py +126 -0
- codecop/relations.py +227 -0
- codecop/report.py +1854 -0
- codecop/resources.py +332 -0
- codecop/resources_view.py +266 -0
- codecop/rules/entry_points.toml +1013 -0
- codecop/rules/sinks.toml +362 -0
- codecop/runsonce.py +8 -0
- codecop/sandboxschema.py +555 -0
- codecop/scenario_agent.py +172 -0
- codecop/scenario_bind.py +507 -0
- codecop/scenario_sql.py +971 -0
- codecop/scenarios.py +675 -0
- codecop/scenarios_view.py +274 -0
- codecop/schemacli.py +67 -0
- codecop/schemas/areas_output.schema.json +21 -0
- codecop/schemas/profile_output.schema.json +362 -0
- codecop/schemas/rank_output.schema.json +385 -0
- codecop/sizes.py +200 -0
- codecop/sqlinfo.py +558 -0
- codecop/typedparams.py +576 -0
- codecop/verdicts.py +212 -0
- codecop/writebench.py +720 -0
- codecop/writecost.py +440 -0
- codecop/writes.py +1208 -0
- codecop-0.1.0.dist-info/METADATA +42 -0
- codecop-0.1.0.dist-info/RECORD +222 -0
- codecop-0.1.0.dist-info/WHEEL +4 -0
- codecop-0.1.0.dist-info/entry_points.txt +2 -0
- codecop-0.1.0.dist-info/licenses/LICENSE +21 -0
codecop/agentfacts.py
ADDED
|
@@ -0,0 +1,745 @@
|
|
|
1
|
+
"""Evidence for coding agents, read from the stage files of one out dir (`codecop mcp`, docs/mcp.md).
|
|
2
|
+
|
|
3
|
+
Pure reading: no network, no database, no agent call, nothing that runs SQL. Every answer is plain text an agent reads,
|
|
4
|
+
built from what CodeCop measured or found, and every line says where its figure comes from:
|
|
5
|
+
|
|
6
|
+
- `[production]` the pulled query log (pg_stat_statements, system.query_log): shares, runs, bytes, busy time, CPU.
|
|
7
|
+
- `[sandbox]` the sandbox's measurement on generated data: ratios of a change against today, the same-rows check,
|
|
8
|
+
the insert cost. Never sandbox milliseconds or bytes as absolutes: agents repeat the numbers they are
|
|
9
|
+
told, and a sandbox absolute is not a production figure.
|
|
10
|
+
- `[claimed]` what a rule, the code or an agent says and nothing measured: shown as such.
|
|
11
|
+
|
|
12
|
+
A sandbox ratio is "not judged" for production when the sandbox was graded off (or not graded) against production.
|
|
13
|
+
Nothing is a win unless the sandbox verified it (same rows, reads less); a trade-off is not a win; an estimate is not a
|
|
14
|
+
saving. These rules close every answer (RULES).
|
|
15
|
+
|
|
16
|
+
The five questions (measured evidence changes an agent's verdict; a code map does not):
|
|
17
|
+
`priorities` what to fix first by measured load, `statement` the evidence for one statement or call site, `table` the
|
|
18
|
+
facts of one table, `call_patterns` loops and queries that fire together in a file or function, `not_asked` what CodeCop has
|
|
19
|
+
not asked yet and the command that asks it.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import json
|
|
25
|
+
import math
|
|
26
|
+
import re
|
|
27
|
+
import subprocess
|
|
28
|
+
from datetime import datetime, timezone
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
from typing import Any
|
|
31
|
+
|
|
32
|
+
RULES = ("Rules: nothing is a win unless the sandbox verified it (same rows, reads less). A trade-off is not a win. "
|
|
33
|
+
"Sandbox figures are ratios on generated data, never production time or size. \"Not judged\" means the sandbox "
|
|
34
|
+
"is not like production for that measure: use the ratio for direction only. An estimate is not a saving.")
|
|
35
|
+
|
|
36
|
+
STATE = {"fixed": "Fixed (verified in the sandbox)", "blocked": "Needs another fix", "not_judged": "Not judged",
|
|
37
|
+
"nothing_to_gain": "Nothing to gain", "": "Not examined"}
|
|
38
|
+
GRADE = {"close": "close (within x1.5 of production)", "near": "near (within x3 of production)", "off": "off (not like production)",
|
|
39
|
+
"unchecked": "not graded"}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
# --- small formatting ------------------------------------------------------------------------------------------------
|
|
43
|
+
|
|
44
|
+
def size(n: Any) -> str:
|
|
45
|
+
"""Decimal bytes: 3.1 MB."""
|
|
46
|
+
if not isinstance(n, (int, float)):
|
|
47
|
+
return "-"
|
|
48
|
+
for unit in ("B", "kB", "MB", "GB", "TB", "PB"):
|
|
49
|
+
if abs(n) < 1000 or unit == "PB":
|
|
50
|
+
return f"{n:.0f} {unit}" if unit == "B" else f"{n:.3g} {unit}"
|
|
51
|
+
n /= 1000
|
|
52
|
+
return "-"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def count(n: Any) -> str:
|
|
56
|
+
return f"{n:,.0f}" if isinstance(n, (int, float)) else "-"
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def ratio(r: Any) -> str:
|
|
60
|
+
if not isinstance(r, (int, float)) or math.isinf(r) or math.isnan(r):
|
|
61
|
+
return "-"
|
|
62
|
+
return f"x{r:.3g}" if 0.9 <= r < 1.5 else f"x{r:.2g}" if r < 10 else f"x{r:.0f}"
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def pct(x: Any) -> str:
|
|
66
|
+
if not isinstance(x, (int, float)):
|
|
67
|
+
return "-"
|
|
68
|
+
return "<0.01%" if 0 < x < 0.0001 else f"{x:.2%}" if x < 0.01 else f"{x:.1%}"
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def short(t: str) -> str:
|
|
72
|
+
return (t or "").split(".")[-1].strip('`"')
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _read(path: Path) -> Any:
|
|
76
|
+
try:
|
|
77
|
+
return json.loads(path.read_text())
|
|
78
|
+
except (OSError, ValueError):
|
|
79
|
+
return None
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _when(text: Any) -> datetime | None:
|
|
83
|
+
if not isinstance(text, str) or not text:
|
|
84
|
+
return None
|
|
85
|
+
try:
|
|
86
|
+
t = datetime.fromisoformat(text.replace(" ", "T", 1).replace("Z", "+00:00"))
|
|
87
|
+
except ValueError:
|
|
88
|
+
try:
|
|
89
|
+
t = datetime.fromisoformat(text.split(".")[0].replace(" ", "T"))
|
|
90
|
+
except ValueError:
|
|
91
|
+
return None
|
|
92
|
+
return t if t.tzinfo else t.replace(tzinfo=timezone.utc)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
# --- the out dir -------------------------------------------------------------------------------------------------------
|
|
96
|
+
|
|
97
|
+
class Stage:
|
|
98
|
+
"""The stage files of one out dir, read once and kept; `refresh()` re-reads them when a file changed."""
|
|
99
|
+
|
|
100
|
+
FILES = ("inventory.json", "findings.json", "db_match.json", "db_catalog.json", "db_workload.json", "advisor.json",
|
|
101
|
+
"patterns.json", "groups.json", "scenarios.json", "agent_plan.json", "loops.json")
|
|
102
|
+
|
|
103
|
+
def __init__(self, out_dir: Path, repo: Path | None = None):
|
|
104
|
+
self.out = Path(out_dir)
|
|
105
|
+
self.repo = Path(repo) if repo else None
|
|
106
|
+
self._stamp: tuple = ()
|
|
107
|
+
self.refresh()
|
|
108
|
+
|
|
109
|
+
def _stamps(self) -> tuple:
|
|
110
|
+
out = []
|
|
111
|
+
for name in self.FILES:
|
|
112
|
+
p = self.out / name
|
|
113
|
+
try:
|
|
114
|
+
out.append((name, p.stat().st_mtime_ns))
|
|
115
|
+
except OSError:
|
|
116
|
+
out.append((name, 0))
|
|
117
|
+
return tuple(out)
|
|
118
|
+
|
|
119
|
+
def refresh(self) -> None:
|
|
120
|
+
stamp = self._stamps()
|
|
121
|
+
if stamp == self._stamp:
|
|
122
|
+
return
|
|
123
|
+
self._stamp = stamp
|
|
124
|
+
self.docs = {name: _read(self.out / name) for name in self.FILES}
|
|
125
|
+
inv = self.docs["inventory.json"] or {}
|
|
126
|
+
self.sites = {s["id"]: s for s in inv.get("call_sites") or [] if isinstance(s, dict) and s.get("id") and not s.get("is_test")}
|
|
127
|
+
self.inv_tables = {short(t.get("name", "")): t for t in inv.get("tables") or [] if isinstance(t, dict)}
|
|
128
|
+
fd = self.docs["findings.json"] or {}
|
|
129
|
+
every = [f for f in fd.get("findings") or [] if isinstance(f, dict)]
|
|
130
|
+
# the query findings keep this name; the other kinds of finding (kinds/) are kept apart and found by id or place
|
|
131
|
+
self.findings = [f for f in every if (f.get("kind") or "query") == "query"]
|
|
132
|
+
self.other = [f for f in every if (f.get("kind") or "query") != "query"]
|
|
133
|
+
self.kinds = fd.get("kinds") or {}
|
|
134
|
+
self.engine = fd.get("engine") or next(iter(((self.docs["db_match.json"] or {}).get("engines") or {}).keys()), "") or ""
|
|
135
|
+
m = (self.docs["db_match.json"] or {}).get("engines") or {}
|
|
136
|
+
self.match = m.get(self.engine) or (next(iter(m.values())) if m else {}) or {}
|
|
137
|
+
self.site_load = self.match.get("sites") or {}
|
|
138
|
+
cat = ((self.docs["db_catalog.json"] or {}).get("connections") or {})
|
|
139
|
+
cat = cat.get(self.engine) or (next(iter(cat.values())) if cat else {}) or {}
|
|
140
|
+
self.catalog = {short(t.get("name", "")): t for t in cat.get("tables") or [] if isinstance(t, dict) and not t.get("is_partition")}
|
|
141
|
+
adv = ((self.docs["advisor.json"] or {}).get("engines") or {})
|
|
142
|
+
adv = adv.get(self.engine) or (next(iter(adv.values())) if adv else {}) or {}
|
|
143
|
+
self.suggestions = [s for s in adv.get("table_suggestions") or [] if isinstance(s, dict)]
|
|
144
|
+
self.by_site_finding: dict[str, list[dict]] = {}
|
|
145
|
+
for f in self.findings:
|
|
146
|
+
for sid in self._site_ids_of(f):
|
|
147
|
+
self.by_site_finding.setdefault(sid, []).append(f)
|
|
148
|
+
self.scen_by_site: dict[str, list[dict]] = {}
|
|
149
|
+
for c in (self.docs["scenarios.json"] or {}).get("candidates") or []:
|
|
150
|
+
for sid in ((c.get("statement") or {}).get("site_ids") or []):
|
|
151
|
+
self.scen_by_site.setdefault(sid, []).append(c)
|
|
152
|
+
|
|
153
|
+
# --- shared pieces ---------------------------------------------------------------------------------------------------
|
|
154
|
+
|
|
155
|
+
def _site_ids_of(self, f: dict) -> list[str]:
|
|
156
|
+
ids = []
|
|
157
|
+
if f.get("id") in self.sites:
|
|
158
|
+
ids.append(f["id"])
|
|
159
|
+
for p in ((f.get("observed") or {}).get("places") or []):
|
|
160
|
+
if isinstance(p, str) and p in self.sites and p not in ids:
|
|
161
|
+
ids.append(p)
|
|
162
|
+
return ids
|
|
163
|
+
|
|
164
|
+
def window(self) -> dict:
|
|
165
|
+
"""The span production's figures cover: {hours, text, cumulative}."""
|
|
166
|
+
h = self.match.get("window_hours")
|
|
167
|
+
if isinstance(h, (int, float)) and h > 0:
|
|
168
|
+
return {"hours": float(h), "text": f"query log window of {h:g} h", "cumulative": False}
|
|
169
|
+
since = _when(self.match.get("since"))
|
|
170
|
+
pulled = _when((self.docs["db_workload.json"] or {}).get("generated_at")) or _when((self.docs["db_match.json"] or {}).get("generated_at"))
|
|
171
|
+
if since and pulled and pulled > since:
|
|
172
|
+
hours = (pulled - since).total_seconds() / 3600
|
|
173
|
+
return {"hours": hours, "text": f"counts since {since:%d %b} ({hours / 24:.1f} days, cumulative)", "cumulative": True}
|
|
174
|
+
return {"hours": None, "text": "counts since the statistics reset (span unknown)", "cumulative": True}
|
|
175
|
+
|
|
176
|
+
def source_line(self, files: list[str]) -> str:
|
|
177
|
+
inv = self.docs["inventory.json"] or {}
|
|
178
|
+
repo = inv.get("repo") or {}
|
|
179
|
+
commit = str(repo.get("commit") or "")[:10]
|
|
180
|
+
made = _when(inv.get("generated_at"))
|
|
181
|
+
age = ""
|
|
182
|
+
if made:
|
|
183
|
+
days = (datetime.now(timezone.utc) - made).total_seconds() / 86400
|
|
184
|
+
age = f", {days:.0f} days old" if days >= 1 else ", under a day old"
|
|
185
|
+
fresh = self._freshness(repo.get("commit"))
|
|
186
|
+
have = [f for f in files if (self.out / f).exists()]
|
|
187
|
+
return (f"Source: CodeCop out dir {self.out.name}/ ({', '.join(have) or 'no stage files'}); scan at commit {commit or '?'}{age}"
|
|
188
|
+
+ (f"; {fresh}" if fresh else "") + ".")
|
|
189
|
+
|
|
190
|
+
def _freshness(self, commit: Any) -> str:
|
|
191
|
+
"""How far HEAD of the repository is from the scanned commit (read-only git), when the repository is known."""
|
|
192
|
+
if not self.repo or not isinstance(commit, str) or not commit:
|
|
193
|
+
return ""
|
|
194
|
+
try:
|
|
195
|
+
out = subprocess.run(["git", "-C", str(self.repo), "rev-list", "--count", f"{commit}..HEAD"], capture_output=True,
|
|
196
|
+
text=True, timeout=5)
|
|
197
|
+
except (OSError, subprocess.SubprocessError):
|
|
198
|
+
return ""
|
|
199
|
+
if out.returncode != 0 or not out.stdout.strip().isdigit():
|
|
200
|
+
return "the scanned commit is not in this repository's history"
|
|
201
|
+
n = int(out.stdout.strip())
|
|
202
|
+
return "HEAD is the scanned commit" if n == 0 else f"HEAD is {n} commit{'s' if n != 1 else ''} ahead: code may have moved"
|
|
203
|
+
|
|
204
|
+
def place(self, sid: str) -> str:
|
|
205
|
+
s = self.sites.get(sid) or {}
|
|
206
|
+
if not s:
|
|
207
|
+
return "no place in code"
|
|
208
|
+
return f"{s.get('file')}:{s.get('line')}" + (f" {s['symbol']}" if s.get("symbol") else "")
|
|
209
|
+
|
|
210
|
+
def load_line(self, row: dict) -> str:
|
|
211
|
+
"""[production] share, runs and bytes of one matched site or shape."""
|
|
212
|
+
w = self.window()
|
|
213
|
+
bits = [f"{pct(row.get('share_of_read_bytes'))} of all bytes read"]
|
|
214
|
+
execs = row.get("executions")
|
|
215
|
+
if w["hours"] and isinstance(execs, (int, float)):
|
|
216
|
+
bits.append(f"{count(execs * 24 / w['hours'])} runs a day")
|
|
217
|
+
if isinstance(row.get("read_bytes"), (int, float)):
|
|
218
|
+
bits.append(f"{size(row['read_bytes'] * 24 / w['hours'])} read a day")
|
|
219
|
+
elif isinstance(execs, (int, float)):
|
|
220
|
+
bits.append(f"{count(execs)} runs, {size(row.get('read_bytes'))} read in total")
|
|
221
|
+
res = row.get("resources") or {}
|
|
222
|
+
if isinstance(res.get("busy_ms"), (int, float)) and execs:
|
|
223
|
+
bits.append(f"busy time {res['busy_ms'] / execs:.3g} ms a run (upper bound of CPU, includes lock waits; not CPU)")
|
|
224
|
+
if isinstance(row.get("avg_ms"), (int, float)):
|
|
225
|
+
bits.append(f"average run {row['avg_ms']:g} ms")
|
|
226
|
+
return "[production] " + ", ".join(bits) + f" ({w['text']})"
|
|
227
|
+
|
|
228
|
+
def state_of(self, sid: str | None, f: dict | None) -> tuple[str, str]:
|
|
229
|
+
"""(state, reason) of a finding, else of the call site's scenario candidates, else not examined."""
|
|
230
|
+
from .report import REASON_LABEL
|
|
231
|
+
if f is not None:
|
|
232
|
+
o = f.get("outcome") or {}
|
|
233
|
+
return o.get("state") or "", REASON_LABEL.get(o.get("reason"), (o.get("reason") or "").replace("_", " "))
|
|
234
|
+
for c in self.scen_by_site.get(sid or "", []):
|
|
235
|
+
o = c.get("outcome") or {}
|
|
236
|
+
if o.get("state"):
|
|
237
|
+
return o["state"], REASON_LABEL.get(o.get("reason"), (o.get("reason") or "").replace("_", " "))
|
|
238
|
+
return "", ""
|
|
239
|
+
|
|
240
|
+
def finding(self, ref: str) -> dict | None:
|
|
241
|
+
return next((f for f in self.findings + self.other if ref in (f.get("finding"), f.get("id"))), None)
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _tail(st: Stage, files: list[str], basis: str) -> str:
|
|
245
|
+
return "\n".join([st.source_line(files), "Basis: " + basis, RULES])
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
# --- 1. priorities -----------------------------------------------------------------------------------------------------
|
|
249
|
+
|
|
250
|
+
def priorities(st: Stage, limit: int = 10, state: str = "") -> str:
|
|
251
|
+
"""What to fix first: statements by their measured share of all bytes the database read, with their state."""
|
|
252
|
+
st.refresh()
|
|
253
|
+
limit = max(1, min(int(limit or 10), 100))
|
|
254
|
+
rows: list[tuple[float, str]] = []
|
|
255
|
+
seen_findings: set[str] = set()
|
|
256
|
+
for sid, row in st.site_load.items():
|
|
257
|
+
if not isinstance(row, dict) or row.get("match") not in ("exact", "template", "tag", None):
|
|
258
|
+
continue
|
|
259
|
+
fs = st.by_site_finding.get(sid) or []
|
|
260
|
+
f = fs[0] if fs else None
|
|
261
|
+
for x in fs:
|
|
262
|
+
seen_findings.add(x.get("finding"))
|
|
263
|
+
s, why = st.state_of(sid, f)
|
|
264
|
+
if state and s != state:
|
|
265
|
+
continue
|
|
266
|
+
rows.append((float(row.get("share_of_read_bytes") or 0), _prio_line(st, st.place(sid), f, s, why, st.load_line(row), sid)))
|
|
267
|
+
for f in st.findings:
|
|
268
|
+
if f.get("finding") in seen_findings or not f.get("real") or not str(f.get("finding", "")).startswith("O-"):
|
|
269
|
+
continue
|
|
270
|
+
s, why = st.state_of(None, f)
|
|
271
|
+
if state and s != state:
|
|
272
|
+
continue
|
|
273
|
+
real = f["real"]
|
|
274
|
+
row = {"share_of_read_bytes": real.get("share_of_read_bytes"), "executions": real.get("executions"), "read_bytes": real.get("read_bytes"),
|
|
275
|
+
"avg_ms": real.get("avg_ms"), "resources": {"busy_ms": real["busy_ms_per_run"] * real["executions"]}
|
|
276
|
+
if real.get("busy_ms_per_run") is not None and real.get("executions") else {}}
|
|
277
|
+
rows.append((float(real.get("share_of_read_bytes") or 0),
|
|
278
|
+
_prio_line(st, "no place in code (a statement production ran)", f, s, why, st.load_line(row), "")))
|
|
279
|
+
files = ["db_match.json", "findings.json", "inventory.json", "scenarios.json"]
|
|
280
|
+
if not rows:
|
|
281
|
+
# no pull: what CodeCop found, by its own order; nothing is ranked by cost
|
|
282
|
+
out = ["No production load in this out dir (run `codecop db pull`, then `codecop scan`): nothing can be ranked by cost. "
|
|
283
|
+
"Findings in CodeCop's order, NOT measured in production:"]
|
|
284
|
+
for f in st.findings[:limit]:
|
|
285
|
+
if state and (f.get("outcome") or {}).get("state") != state:
|
|
286
|
+
continue
|
|
287
|
+
s, why = st.state_of(None, f)
|
|
288
|
+
site = f.get("site") or {}
|
|
289
|
+
out.append(f"- {f.get('finding')} {site.get('file')}:{site.get('line')} {site.get('symbol') or ''}".rstrip()
|
|
290
|
+
+ f" | {f.get('title', '')} | state: {STATE.get(s, s)}" + (f" ({why})" if why else ""))
|
|
291
|
+
return "\n".join(out + ["", _tail(st, ["findings.json", "inventory.json"], "[claimed] CodeCop's order (static score, severity); no production figures")])
|
|
292
|
+
rows.sort(key=lambda r: -r[0])
|
|
293
|
+
total = sum(1 for _ in rows)
|
|
294
|
+
out = [f"{total} statement{'s' if total != 1 else ''} with measured load; top {min(limit, total)} by share of all bytes read "
|
|
295
|
+
f"({st.window()['text']}):"]
|
|
296
|
+
for i, (_, line) in enumerate(rows[:limit], 1):
|
|
297
|
+
out.append(f"{i}. {line}")
|
|
298
|
+
return "\n".join(out + ["", "Next: `statement` with a file:line or id for the evidence; `not_asked` for what CodeCop has not asked yet.",
|
|
299
|
+
_tail(st, files, "[production] the pulled query log; states from CodeCop's sandbox and rules")])
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def _prio_line(st: Stage, place: str, f: dict | None, s: str, why: str, load: str, sid: str) -> str:
|
|
303
|
+
head = f"{place}" + (f" | {f.get('finding')}" if f else "") + (f" | id {sid}" if sid and not f else "")
|
|
304
|
+
tables = ", ".join(short(t) for t in ((st.sites.get(sid) or {}).get("tables") or (f or {}).get("tables") or [])[:4])
|
|
305
|
+
return (head + (f" | tables {tables}" if tables else "") + f"\n {load}\n state: {STATE.get(s, s)}" + (f" ({why})" if why else ""))
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
# --- 2. statement ------------------------------------------------------------------------------------------------------
|
|
309
|
+
|
|
310
|
+
def _resolve(st: Stage, at: str) -> tuple[list[str], list[dict]]:
|
|
311
|
+
"""(site ids, findings) for a reference: Q-011 / O-002, a call-site id, file:line (the nearest site within 3 lines),
|
|
312
|
+
or a file path (every site in it)."""
|
|
313
|
+
at = (at or "").strip()
|
|
314
|
+
f = st.finding(at)
|
|
315
|
+
if f is not None:
|
|
316
|
+
return st._site_ids_of(f), [f]
|
|
317
|
+
if at in st.sites:
|
|
318
|
+
return [at], st.by_site_finding.get(at) or []
|
|
319
|
+
m = re.match(r"^(.*?):(\d+)$", at)
|
|
320
|
+
path, line = (m.group(1), int(m.group(2))) if m else (at, None)
|
|
321
|
+
path = path.lstrip("./")
|
|
322
|
+
cands = [s for s in st.sites.values() if s.get("file") == path or (path and str(s.get("file", "")).endswith("/" + path))]
|
|
323
|
+
if not cands and line is None and at:
|
|
324
|
+
# a function or method name: Type::method, method, pkg.Func
|
|
325
|
+
cands = [s for s in st.sites.values() if str(s.get("symbol") or "") == at or str(s.get("symbol") or "").endswith(("::" + at, "." + at))]
|
|
326
|
+
if line is not None:
|
|
327
|
+
near = sorted((abs(int(s.get("line") or 0) - line), s["id"]) for s in cands if abs(int(s.get("line") or 0) - line) <= 3
|
|
328
|
+
or (s.get("end_line") and int(s.get("line") or 0) <= line <= int(s["end_line"])))
|
|
329
|
+
cands = [st.sites[i] for _, i in near[:1]]
|
|
330
|
+
ids = [s["id"] for s in cands]
|
|
331
|
+
fs = []
|
|
332
|
+
for i in ids:
|
|
333
|
+
fs += [x for x in st.by_site_finding.get(i) or [] if x not in fs]
|
|
334
|
+
# the other kinds of finding at that place (a regex, a transaction): by their own file and line
|
|
335
|
+
for x in st.other:
|
|
336
|
+
site = x.get("site") or {}
|
|
337
|
+
f_file = str(site.get("file") or "")
|
|
338
|
+
if path and (f_file == path or f_file.endswith("/" + path)) and (line is None or abs(int(site.get("line") or 0) - line) <= 3):
|
|
339
|
+
fs.append(x)
|
|
340
|
+
return ids, fs
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def statement(st: Stage, at: str) -> str:
|
|
344
|
+
"""The evidence for one statement or call site."""
|
|
345
|
+
st.refresh()
|
|
346
|
+
ids, fs = _resolve(st, at)
|
|
347
|
+
files = ["findings.json", "inventory.json", "db_match.json", "scenarios.json"]
|
|
348
|
+
if not ids and not fs:
|
|
349
|
+
return (f"No call site or finding matches {at!r}. Give a file:line from the scan, a finding id (Q-001, O-002) or a "
|
|
350
|
+
f"call-site id. The scan only knows the statements it found at its commit.\n\n" + _tail(st, files, "nothing found"))
|
|
351
|
+
if len(ids) > 8 and not fs:
|
|
352
|
+
return f"{len(ids)} call sites in {at}: give a line. First ones: " + ", ".join(st.place(i) for i in ids[:8]) + "\n\n" + _tail(st, files, "the inventory")
|
|
353
|
+
out: list[str] = []
|
|
354
|
+
for sid in ids[:8] if not fs else []:
|
|
355
|
+
out += _site_block(st, sid)
|
|
356
|
+
for f in fs[:4]:
|
|
357
|
+
out += _finding_block(st, f)
|
|
358
|
+
return "\n".join(out + ["", _tail(st, files, "[production] the pulled query log; [sandbox] ratios measured on generated data; "
|
|
359
|
+
"[claimed] rules and code, not measured")])
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def _site_block(st: Stage, sid: str) -> list[str]:
|
|
363
|
+
s = st.sites.get(sid) or {}
|
|
364
|
+
out = [f"## {st.place(sid)} (call site {sid}, {s.get('statement') or '?'} on {', '.join(short(t) for t in s.get('tables') or []) or 'unknown tables'})"]
|
|
365
|
+
if s.get("sql"):
|
|
366
|
+
out.append("SQL: " + re.sub(r"\s+", " ", s["sql"]).strip()[:600])
|
|
367
|
+
row = st.site_load.get(sid)
|
|
368
|
+
out.append(st.load_line(row) if isinstance(row, dict) else "[production] not seen in the query log" if st.site_load
|
|
369
|
+
else "[production] no pull in this out dir: not measured")
|
|
370
|
+
ls = s.get("loop_summary") or ((s.get("loop_context") or [None])[0] if s.get("loop_context") else None)
|
|
371
|
+
if ls:
|
|
372
|
+
out.append(f"[claimed] runs inside a loop ({ls.get('kind')}) at {ls.get('file')}:{ls.get('line')}: see `call_patterns`")
|
|
373
|
+
for c in st.scen_by_site.get(sid, [])[:3]:
|
|
374
|
+
o = c.get("outcome") or {}
|
|
375
|
+
out.append(f"Kind of waste: {c.get('scenario', '').replace('_', ' ')} ({', '.join(c.get('rules') or [])}), proof {c.get('proof')}; "
|
|
376
|
+
f"state: {STATE.get(o.get('state') or '', o.get('state'))}")
|
|
377
|
+
if not st.by_site_finding.get(sid) and not st.scen_by_site.get(sid):
|
|
378
|
+
out.append("state: Not examined (no finding for this call site)")
|
|
379
|
+
return out
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def _fid(f: dict) -> tuple[str, str]:
|
|
383
|
+
fid = f.get("fidelity") or {}
|
|
384
|
+
g = fid.get("grade") or "unchecked"
|
|
385
|
+
r = fid.get("ratios") or {}
|
|
386
|
+
bits = ", ".join(f"{k.replace('_', ' ')} {ratio(v)}" for k, v in r.items() if isinstance(v, (int, float)) and k in ("rows_read", "bytes_read", "rows_returned"))
|
|
387
|
+
return g, bits
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def _kind_block(f: dict) -> list[str]:
|
|
391
|
+
"""A finding of another kind (kinds/): where, the state, the harm, the proof and the hand-off, generic for every kind."""
|
|
392
|
+
from .kinds import get, handoff_text
|
|
393
|
+
k = get(f.get("kind") or "")
|
|
394
|
+
text = k.handoff(f) if k is not None else handoff_text(f)
|
|
395
|
+
lines = text.splitlines()
|
|
396
|
+
return [f"## {lines[0]}"] + lines[1:]
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def _finding_block(st: Stage, f: dict) -> list[str]:
|
|
400
|
+
if (f.get("kind") or "query") != "query":
|
|
401
|
+
return _kind_block(f)
|
|
402
|
+
site = f.get("site") or {}
|
|
403
|
+
where = f"{site.get('file')}:{site.get('line')}" if site.get("file") else "no place in code (a statement production ran)"
|
|
404
|
+
o = f.get("outcome") or {}
|
|
405
|
+
s, why = st.state_of(None, f)
|
|
406
|
+
out = [f"## {f.get('finding')} {where} {site.get('symbol') or ''}".rstrip(), f"Title [claimed]: {f.get('title', '')}",
|
|
407
|
+
f"State: {STATE.get(s, s)}" + (f" ({why})" if why else "")]
|
|
408
|
+
real = f.get("real") or {}
|
|
409
|
+
if real:
|
|
410
|
+
row = {"share_of_read_bytes": real.get("share_of_read_bytes"), "executions": real.get("executions"), "read_bytes": real.get("read_bytes"),
|
|
411
|
+
"avg_ms": real.get("avg_ms"), "resources": {"busy_ms": real["busy_ms_per_run"] * real["executions"]}
|
|
412
|
+
if real.get("busy_ms_per_run") is not None and real.get("executions") else {}}
|
|
413
|
+
out.append("Today: " + st.load_line(row))
|
|
414
|
+
cpu, mem = real.get("cpu") or {}, real.get("memory") or {}
|
|
415
|
+
if cpu.get("seconds_per_day") is not None:
|
|
416
|
+
out.append(f"[production] CPU {cpu['seconds_per_day'] / 3600:.3g} h a day" + (f" ({pct(cpu['share'])} of query CPU)" if cpu.get("share") is not None else ""))
|
|
417
|
+
if mem.get("typical_bytes") is not None:
|
|
418
|
+
out.append(f"[production] peak memory of one run: typical {size(mem['typical_bytes'])}, max {size(mem.get('max_bytes'))}")
|
|
419
|
+
else:
|
|
420
|
+
out.append("Today: [production] not measured (no pull, or the statement was not seen in the query log)")
|
|
421
|
+
g, gbits = _fid(f)
|
|
422
|
+
judged = g in ("close", "near")
|
|
423
|
+
out.append(f"Sandbox like production: {GRADE.get(g, g)}" + (f" [{gbits}]" if gbits else "")
|
|
424
|
+
+ ("" if judged else " -> the ratios below are NOT judged for production; direction only"))
|
|
425
|
+
variants = f.get("variants") or []
|
|
426
|
+
if variants:
|
|
427
|
+
out.append(f"Changes tried ({len(variants)}) [sandbox, ratios of the change against today]:")
|
|
428
|
+
for v in variants[:6]:
|
|
429
|
+
last = (v.get("scales") or [None])[-1] or {}
|
|
430
|
+
b, a = last.get("baseline") or {}, last.get("variant") or {}
|
|
431
|
+
bits = []
|
|
432
|
+
for k, name in (("read_rows", "rows read"), ("read_bytes", "bytes read")):
|
|
433
|
+
if isinstance(b.get(k), (int, float)) and b[k] and isinstance(a.get(k), (int, float)):
|
|
434
|
+
bits.append(f"{name} {ratio(a[k] / b[k])}")
|
|
435
|
+
res = v.get("resources") or {}
|
|
436
|
+
for k, name in (("cpu", "CPU"), ("memory", "memory")):
|
|
437
|
+
if isinstance((res.get(k) or {}).get("ratio"), (int, float)):
|
|
438
|
+
bits.append(f"{name} {ratio(res[k]['ratio'])}")
|
|
439
|
+
same = v.get("results_match") if v.get("results_match") is not None else v.get("same_results")
|
|
440
|
+
ic = v.get("insert_cost") or {}
|
|
441
|
+
ins = ""
|
|
442
|
+
if ic.get("measured"):
|
|
443
|
+
ins = (f"; insert cost: time {ratio(ic.get('insert_time_ratio'))}, storage {ratio(ic.get('storage_ratio'))}, "
|
|
444
|
+
+ ("within the limits" if ic.get("within") else "over the limits (a trade-off)"))
|
|
445
|
+
elif v.get("kind") in ("index", "projection", "order_by"):
|
|
446
|
+
ins = "; insert cost: not measured"
|
|
447
|
+
verdict = str(v.get("verdict") or "").replace("_", " ")
|
|
448
|
+
out.append(f"- {v.get('change') or v.get('kind')} ({v.get('kind')}): verdict {verdict}; "
|
|
449
|
+
+ (", ".join(bits) or "no read figures") + f"; same rows: {'yes' if same is True else 'no' if same is False else 'unknown'}" + ins
|
|
450
|
+
+ (f"; trade-offs: {', '.join(v.get('tradeoffs'))}" if v.get("tradeoffs") else ""))
|
|
451
|
+
est = f.get("resource_estimate") or {}
|
|
452
|
+
if est.get("judged"):
|
|
453
|
+
parts = [f"{n} {size(x['value']) if 'bytes' in k else str(round(x['value'] / 3600, 2)) + ' h'} a day (range {size(x['low']) if 'bytes' in k else round(x['low'] / 3600, 2)} to {size(x['high']) if 'bytes' in k else round(x['high'] / 3600, 2)})"
|
|
454
|
+
for k, n in (("read_bytes_per_day", "read"), ("cpu_seconds_per_day", "CPU")) for x in [est.get(k)] if x]
|
|
455
|
+
if parts:
|
|
456
|
+
out.append(f"Estimate in production with the fix (production x sandbox ratio, graded {est.get('grade')}; NOT a measurement, NOT a saving): " + "; ".join(parts))
|
|
457
|
+
elif est.get("judged") is False and est.get("why") in ("graded_off", "not_graded"):
|
|
458
|
+
out.append("Estimate in production: not judged (the sandbox is not like production for this query)")
|
|
459
|
+
from .formerly import code as _code
|
|
460
|
+
nxt = _code(o.get("next_step"))
|
|
461
|
+
if nxt:
|
|
462
|
+
out.append(f"Next step: {str(nxt).replace('_', ' ')}")
|
|
463
|
+
out.append("Hand-off: " + _handoff(f, judged))
|
|
464
|
+
return out
|
|
465
|
+
|
|
466
|
+
|
|
467
|
+
def _handoff(f: dict, judged: bool) -> str:
|
|
468
|
+
"""A few lines to paste into a PR or a task: the change, what was verified, what is not known. Ratios only."""
|
|
469
|
+
v = next((x for x in f.get("variants") or [] if x.get("verdict") == "win"), None)
|
|
470
|
+
if v is None:
|
|
471
|
+
return ("No change verified for this statement. Do not ship a change for it on CodeCop's word; "
|
|
472
|
+
+ ("measure a proposal in the sandbox first (`codecop bench`)." if f.get("variants") else "CodeCop has no measured proposal."))
|
|
473
|
+
last = (v.get("scales") or [None])[-1] or {}
|
|
474
|
+
b, a = last.get("baseline") or {}, last.get("variant") or {}
|
|
475
|
+
r = (a.get("read_bytes") / b["read_bytes"]) if isinstance(b.get("read_bytes"), (int, float)) and b["read_bytes"] and isinstance(a.get("read_bytes"), (int, float)) else None
|
|
476
|
+
ic = v.get("insert_cost") or {}
|
|
477
|
+
return (f"{v.get('change') or v.get('kind')}: verified in the sandbox, same rows, bytes read {ratio(r)} of today"
|
|
478
|
+
+ (f", insert time {ratio(ic.get('insert_time_ratio'))} and storage {ratio(ic.get('storage_ratio'))} of today" if ic.get("measured") else "")
|
|
479
|
+
+ ("." if judged else "; the sandbox is not like production for this query, so the size of the gain in production is not judged.")
|
|
480
|
+
+ " After the change, run `codecop db pull` and `codecop scan` to measure production again.")
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
# --- findings of any kind ---------------------------------------------------------------------------------------------
|
|
484
|
+
|
|
485
|
+
def findings_list(st: Stage, kind: str = "", state: str = "", limit: int = 20) -> str:
|
|
486
|
+
"""Findings of one kind (query, regex, transaction, ...) or of every kind, with their state, harm and best measure."""
|
|
487
|
+
from .kinds import STATE_WORDS, harm_words, proof_lines, reason_words
|
|
488
|
+
st.refresh()
|
|
489
|
+
limit = max(1, min(int(limit or 20), 200))
|
|
490
|
+
rows = [f for f in st.findings + st.other if (not kind or (f.get("kind") or "query") == kind)
|
|
491
|
+
and (not state or (f.get("outcome") or {}).get("state") == state)]
|
|
492
|
+
if not kind:
|
|
493
|
+
# every kind together: proven gain first, then how hot the code path is × the gain (heat.py); a finding without
|
|
494
|
+
# heat keeps its place after those that have it
|
|
495
|
+
from .heat import rank_key
|
|
496
|
+
rows = sorted(rows, key=lambda f: rank_key(f) if f.get("heat") else (2, 0.0))
|
|
497
|
+
counts = {"query": len(st.findings), **{k: int(v.get("findings") or 0) for k, v in st.kinds.items()}}
|
|
498
|
+
out = ["Findings by kind: " + ", ".join(f"{k} {n}" for k, n in counts.items()) + f". Shown: {min(limit, len(rows))} of {len(rows)}"
|
|
499
|
+
+ (f" ({kind})" if kind else "") + (f" in state {state}" if state else "") + "."]
|
|
500
|
+
for f in rows[:limit]:
|
|
501
|
+
site, o = f.get("site") or {}, f.get("outcome") or {}
|
|
502
|
+
k = f.get("kind") or "query"
|
|
503
|
+
best = next((line[2:] for line in proof_lines(k, f.get("proof"))[1:2] if line.startswith("- ")), "")
|
|
504
|
+
out.append(f"- {f.get('finding')} [{k}] {site.get('file')}:{site.get('line')} | {f.get('title', '')} | "
|
|
505
|
+
f"{STATE_WORDS.get(o.get('state'), 'no state')}" + (f" ({reason_words(k, o['reason'])})" if o.get("reason") else "")
|
|
506
|
+
+ (f" | {harm_words(k, f['harm'])}" if f.get("harm") in ("correctness", "both") else "")
|
|
507
|
+
+ (f" | {best}" if best else "")
|
|
508
|
+
+ (f" | heat: {f['heat'].get('words')} [{f['heat'].get('source')}]" if isinstance(f.get("heat"), dict) else ""))
|
|
509
|
+
return "\n".join(out + ["", "Next: `statement` with a finding id for its proof and hand-off.",
|
|
510
|
+
_tail(st, ["findings.json"], "[sandbox] proof measured on generated inputs or schedules; [claimed] not measured")])
|
|
511
|
+
|
|
512
|
+
|
|
513
|
+
# --- 3. table ----------------------------------------------------------------------------------------------------------
|
|
514
|
+
|
|
515
|
+
def table(st: Stage, name: str) -> str:
|
|
516
|
+
st.refresh()
|
|
517
|
+
key = short(name)
|
|
518
|
+
files = ["inventory.json", "db_catalog.json", "db_match.json", "advisor.json", "findings.json"]
|
|
519
|
+
t = st.inv_tables.get(key)
|
|
520
|
+
c = st.catalog.get(key)
|
|
521
|
+
readers = [s for s in st.sites.values() if key in {short(x) for x in s.get("tables") or []}]
|
|
522
|
+
if not t and not c and not readers:
|
|
523
|
+
like = sorted(k for k in set(st.inv_tables) | set(st.catalog) if key.lower() in k.lower())[:8]
|
|
524
|
+
return f"No table {name!r} in this scan." + (f" Similar: {', '.join(like)}." if like else "") + "\n\n" + _tail(st, files, "the inventory and the catalog")
|
|
525
|
+
out = [f"## table {key}"]
|
|
526
|
+
if c:
|
|
527
|
+
out.append(f"[production] {count(c.get('rows'))} rows, {size(c.get('bytes_on_disk'))} on disk"
|
|
528
|
+
+ (f" ({size(c.get('table_bytes'))} table, {size(c.get('index_bytes'))} indexes)" if c.get("index_bytes") is not None else "")
|
|
529
|
+
+ (f"; {count(c.get('seq_scans'))} sequential scans, {count(c.get('index_scans'))} index scans since the statistics reset"
|
|
530
|
+
if c.get("seq_scans") is not None else "") + " (the real catalog, read once by `codecop db pull`)")
|
|
531
|
+
for ix in (c.get("indexes") or [])[:12]:
|
|
532
|
+
d = ix.get("definition") or ix.get("name")
|
|
533
|
+
out.append(f" index: {re.sub(r' ON [^ ]+ USING ', ' USING ', str(d))}" + (f" | {count(ix.get('scans'))} scans" if ix.get("scans") is not None else ""))
|
|
534
|
+
if c.get("partition_key"):
|
|
535
|
+
out.append(f" partitioned by {c['partition_key']}")
|
|
536
|
+
if c.get("engine") and c.get("engine") != "postgres":
|
|
537
|
+
out.append(f" engine {c.get('engine')}")
|
|
538
|
+
if t:
|
|
539
|
+
cols = [col.get("name") if isinstance(col, dict) else str(col) for col in t.get("columns") or []]
|
|
540
|
+
out.append(f"[claimed] definition in code ({', '.join(str(d) for d in (t.get('defined_at') or [])[:2]) or 'inventory'}): "
|
|
541
|
+
f"{len(cols)} columns" + (f"; key {t.get('order_by')}" if t.get("order_by") else "") + (f"; primary key {t.get('primary_key')}" if t.get("primary_key") else "")
|
|
542
|
+
+ (f"; partition {t.get('partition_by')}" if t.get("partition_by") else ""))
|
|
543
|
+
if cols:
|
|
544
|
+
out.append(" columns: " + ", ".join(str(x) for x in cols[:40]) + (" ..." if len(cols) > 40 else ""))
|
|
545
|
+
loads = sorted(((st.site_load.get(s["id"]) or {}).get("share_of_read_bytes") or -1, s["id"]) for s in readers)
|
|
546
|
+
loads.reverse()
|
|
547
|
+
writes = [s for s in readers if key in {short(x) for x in s.get("writes") or []}]
|
|
548
|
+
out.append(f"Statements on it in code: {len(readers)} ({len(writes)} write it). By measured load [production]:")
|
|
549
|
+
shown = 0
|
|
550
|
+
for share, sid in loads:
|
|
551
|
+
if shown >= 10:
|
|
552
|
+
break
|
|
553
|
+
row = st.site_load.get(sid)
|
|
554
|
+
if not isinstance(row, dict):
|
|
555
|
+
continue
|
|
556
|
+
s, _ = st.state_of(sid, (st.by_site_finding.get(sid) or [None])[0])
|
|
557
|
+
out.append(f"- {st.place(sid)} | {pct(row.get('share_of_read_bytes'))} of all bytes read | state: {STATE.get(s, s)}")
|
|
558
|
+
shown += 1
|
|
559
|
+
if not shown:
|
|
560
|
+
out.append("- none of them seen in the query log" if st.site_load else "- no pull: not measured")
|
|
561
|
+
sug = [x for x in st.suggestions if short(x.get("table", "")) == key]
|
|
562
|
+
if sug:
|
|
563
|
+
out.append(f"Table changes proposed ({len(sug)}) [sandbox unless said]:")
|
|
564
|
+
for x in sug[:8]:
|
|
565
|
+
rg, wc, vd = x.get("read_gain") or {}, x.get("write_cost") or {}, x.get("verdict") or {}
|
|
566
|
+
out.append(f"- {x.get('id')} {x.get('kind')} {'; '.join(x.get('ddl') or [])[:200]} | source {x.get('source')} | "
|
|
567
|
+
f"reads {ratio(rg.get('ratio'))} of today on {rg.get('statements_measured', 0)} measured statement(s), "
|
|
568
|
+
f"{rg.get('statements_won', 0)} won, {rg.get('statements_claimed', 0)} claimed not measured | "
|
|
569
|
+
+ (f"insert time {ratio(wc.get('insert_time_ratio'))}, storage {ratio(wc.get('storage_ratio'))}, "
|
|
570
|
+
+ ("within the limits" if wc.get("within") else "over the limits (a trade-off)") if wc.get("measured") else "insert cost not measured")
|
|
571
|
+
+ f" | state: {STATE.get(vd.get('state') or '', vd.get('state'))}")
|
|
572
|
+
fs = [f for f in st.findings if key in {short(x) for x in f.get("tables") or []}]
|
|
573
|
+
if fs:
|
|
574
|
+
out.append("Findings on it: " + ", ".join(f"{f.get('finding')} ({STATE.get((f.get('outcome') or {}).get('state') or '', '?')})" for f in fs[:12]))
|
|
575
|
+
return "\n".join(out + ["", _tail(st, files, "[production] the real catalog and query log; [sandbox] measured changes; [claimed] the code's definition")])
|
|
576
|
+
|
|
577
|
+
|
|
578
|
+
# --- 4. call patterns --------------------------------------------------------------------------------------------------
|
|
579
|
+
|
|
580
|
+
def call_patterns(st: Stage, at: str) -> str:
|
|
581
|
+
"""Loops that run a query per item, and queries that fire together, in a file or a function (symbol)."""
|
|
582
|
+
st.refresh()
|
|
583
|
+
files = ["patterns.json", "inventory.json", "db_match.json"]
|
|
584
|
+
want = (at or "").strip().lstrip("./")
|
|
585
|
+
m = re.match(r"^(.*?):(\d+)$", want)
|
|
586
|
+
path = m.group(1) if m else want
|
|
587
|
+
|
|
588
|
+
def hit(member: dict) -> bool:
|
|
589
|
+
f, sym = str(member.get("file") or ""), str(member.get("symbol") or "")
|
|
590
|
+
return bool(want) and (f == path or f.endswith("/" + path) or sym == want or sym.endswith("::" + want) or sym.endswith("." + want))
|
|
591
|
+
pats = [p for p in (st.docs["patterns.json"] or {}).get("patterns") or []
|
|
592
|
+
if any(hit(x) for x in p.get("members") or []) or any(hit(lp) for lp in p.get("loops") or [])]
|
|
593
|
+
out = [f"Call patterns touching {at}: {len(pats)}"]
|
|
594
|
+
for p in pats[:8]:
|
|
595
|
+
meas = p.get("measured") or {}
|
|
596
|
+
lp = (p.get("loops") or [{}])[0] or {}
|
|
597
|
+
out.append(f"## {p.get('id')} {p.get('label') or p.get('kind')} ({p.get('kind')}; confidence {p.get('confidence')})")
|
|
598
|
+
if lp:
|
|
599
|
+
out.append(f"[claimed] loop at {lp.get('file')}:{lp.get('line')} over {str(lp.get('over') or lp.get('collection') or '?')[:80]}")
|
|
600
|
+
for x in (p.get("members") or [])[:6]:
|
|
601
|
+
out.append(f"- member {x.get('file')}:{x.get('line')} {x.get('symbol') or ''} on {', '.join(short(t) for t in x.get('tables') or [])}"
|
|
602
|
+
+ (f" ({x.get('role')})" if x.get("role") else ""))
|
|
603
|
+
if meas:
|
|
604
|
+
w = st.window()
|
|
605
|
+
runs = meas.get("executions")
|
|
606
|
+
out.append(f"[production] {pct(meas.get('share_of_read_bytes'))} of all bytes read, "
|
|
607
|
+
+ (f"{count(runs * 24 / w['hours'])} runs a day" if runs and w["hours"] else f"{count(runs)} runs") + f" ({w['text']})")
|
|
608
|
+
batch = p.get("batch") or {}
|
|
609
|
+
bo = batch.get("outcome") or {}
|
|
610
|
+
if bo:
|
|
611
|
+
out.append(f"Batched form [sandbox]: state {STATE.get(bo.get('state') or '', bo.get('state'))}"
|
|
612
|
+
+ (f" ({str(bo.get('reason')).replace('_', ' ')})" if bo.get("reason") else ""))
|
|
613
|
+
elif "batched_query_not_benchmarked" in (p.get("unknowns") or []):
|
|
614
|
+
out.append("Batched form: not benchmarked (no measurement)")
|
|
615
|
+
for ch in (p.get("changes") or [])[:3]:
|
|
616
|
+
out.append(f"Possible change [claimed]: {str(ch.get('change')).replace('_', ' ')} (touches {ch.get('touches')}; proof {str(ch.get('proof')).replace('_', ' ')})")
|
|
617
|
+
if p.get("unknowns"):
|
|
618
|
+
out.append("Not known: " + ", ".join(str(u).replace("_", " ") for u in p["unknowns"][:5]))
|
|
619
|
+
out.append(f"Hand-off text: `codecop handoff {p.get('id')}`")
|
|
620
|
+
# loops the inventory saw around statements in the file, even without a pattern
|
|
621
|
+
loose = [s for s in st.sites.values() if hit(s) and (s.get("loop_summary") or s.get("loop_context"))]
|
|
622
|
+
if loose:
|
|
623
|
+
out.append(f"Statements inside loops in {at} (inventory) : {len(loose)}")
|
|
624
|
+
for s in loose[:10]:
|
|
625
|
+
ls = s.get("loop_summary") or (s.get("loop_context") or [{}])[0]
|
|
626
|
+
out.append(f"- {st.place(s['id'])} in a {ls.get('kind')} loop at {ls.get('file')}:{ls.get('line')}"
|
|
627
|
+
+ (" (query per item)" if ls.get("query_per_item") else ""))
|
|
628
|
+
if not pats and not loose:
|
|
629
|
+
out.append("None found. CodeCop sees loops it can trace statically; a loop through a helper it could not follow is not listed.")
|
|
630
|
+
return "\n".join(out + ["", _tail(st, files, "[claimed] loops traced in code; [production] the pattern's measured load; [sandbox] the batched form")])
|
|
631
|
+
|
|
632
|
+
|
|
633
|
+
# --- 5. not asked ------------------------------------------------------------------------------------------------------
|
|
634
|
+
|
|
635
|
+
def not_asked(st: Stage, limit: int = 15) -> str:
|
|
636
|
+
"""What CodeCop has not asked its agent about yet (budget), and the statements waiting on an agent, with the command."""
|
|
637
|
+
st.refresh()
|
|
638
|
+
files = ["findings.json", "agent_plan.json", "patterns.json"]
|
|
639
|
+
fd = st.docs["findings.json"] or {}
|
|
640
|
+
plan = st.docs["agent_plan.json"] or {}
|
|
641
|
+
after = (fd.get("agent_budget") or {}) or (plan.get("after") or {})
|
|
642
|
+
items = list(after.get("not_asked_items") or [])
|
|
643
|
+
if not items and plan.get("queue"):
|
|
644
|
+
items = [i for i in plan["queue"] if not i.get("fits")]
|
|
645
|
+
waiting = [f for f in st.findings if str((f.get("outcome") or {}).get("next_step") or "").startswith("ask_agent")
|
|
646
|
+
or (f.get("outcome") or {}).get("reason") in ("variants_not_asked", "join_not_asked", "budget_reached")]
|
|
647
|
+
out = []
|
|
648
|
+
if items:
|
|
649
|
+
hi = sum(float(i.get("est_high_usd") or 0) for i in items)
|
|
650
|
+
by: dict[str, int] = {}
|
|
651
|
+
for i in items:
|
|
652
|
+
by[i.get("kind", "?")] = by.get(i.get("kind", "?"), 0) + 1
|
|
653
|
+
out.append(f"Not asked yet (the run's budget stopped before them): {len(items)} item(s): "
|
|
654
|
+
+ ", ".join(f"{n} {k.replace('_', ' ')}" for k, n in sorted(by.items(), key=lambda kv: -kv[1]))
|
|
655
|
+
+ f"; estimated agent cost up to ${hi:.2f} [claimed: CodeCop's estimate]")
|
|
656
|
+
for i in sorted(items, key=lambda i: -(float(i.get("share") or 0)))[:limit]:
|
|
657
|
+
out.append(f"- {i.get('kind')} {i.get('label') or i.get('ref')}" + (f" at {i.get('file')}:{i.get('line')}" if i.get("file") else "")
|
|
658
|
+
+ (f" | {pct(i.get('share'))} of all bytes read [production]" if i.get("share") else ""))
|
|
659
|
+
out.append(f"Command: `codecop scan --budget {math.ceil(hi + 0.5)}` (asks them, then measures the answers in the sandbox)")
|
|
660
|
+
else:
|
|
661
|
+
out.append("Budget: nothing left unasked in the last run's plan" if plan or fd.get("agent_budget") else
|
|
662
|
+
"Budget: this out dir has no run plan (agent_plan.json): run `codecop scan` to see what would be asked")
|
|
663
|
+
if waiting:
|
|
664
|
+
out.append(f"Statements waiting on an agent's variant: {len(waiting)}")
|
|
665
|
+
for f in waiting[:limit]:
|
|
666
|
+
site = f.get("site") or {}
|
|
667
|
+
out.append(f"- {f.get('finding')} " + (f"{site['file']}:{site.get('line')}" if site.get("file") else "no place in code")
|
|
668
|
+
+ f" | {str((f.get('outcome') or {}).get('reason') or '').replace('_', ' ')}"
|
|
669
|
+
+ (f" | {pct((f.get('real') or {}).get('share_of_read_bytes'))} of all bytes read [production]" if (f.get("real") or {}).get("share_of_read_bytes") else ""))
|
|
670
|
+
out.append("Command: `codecop scan` (with a budget that covers them) asks for variants; `codecop bench` measures what comes back.")
|
|
671
|
+
pats = [p for p in (st.docs["patterns.json"] or {}).get("patterns") or [] if "batched_query_not_benchmarked" in (p.get("unknowns") or [])]
|
|
672
|
+
if pats:
|
|
673
|
+
out.append(f"Loop patterns whose batched form was never measured: {len(pats)} (`codecop patterns --agent-variants`, then `codecop bench`)")
|
|
674
|
+
return "\n".join(out + ["", _tail(st, files, "[claimed] CodeCop's plan and estimates; [production] shares where pulled")])
|
|
675
|
+
|
|
676
|
+
|
|
677
|
+
# --- the tool table (mcpserver.py) ---------------------------------------------------------------------------------------
|
|
678
|
+
|
|
679
|
+
TOOLS = [
|
|
680
|
+
{"name": "priorities",
|
|
681
|
+
"description": "What to fix first: the application's database statements ranked by their MEASURED share of all bytes "
|
|
682
|
+
"the production database read (from the pulled query log), each with its file:line and its state "
|
|
683
|
+
"(Fixed = verified in the sandbox, Needs another fix, Not judged, Nothing to gain, Not examined). Use "
|
|
684
|
+
"it before choosing database work; code alone cannot rank statements by cost.",
|
|
685
|
+
"inputSchema": {"type": "object", "properties": {
|
|
686
|
+
"limit": {"type": "integer", "minimum": 1, "maximum": 100, "description": "How many statements (default 10)."},
|
|
687
|
+
"state": {"type": "string", "enum": ["", "fixed", "blocked", "not_judged", "nothing_to_gain"],
|
|
688
|
+
"description": "Only statements in this state (blocked = needs another fix)."}}, "additionalProperties": False}},
|
|
689
|
+
{"name": "statement",
|
|
690
|
+
"description": "The evidence for one statement or call site: give file:line (as in the code), a finding id (Q-011, "
|
|
691
|
+
"O-002) or a call-site id. Returns today's production load, every change CodeCop measured in the sandbox "
|
|
692
|
+
"(rows/bytes read, CPU and memory as ratios of today, same-rows check, insert cost), how like "
|
|
693
|
+
"production the sandbox was (fidelity; off = not judged), the verdict and a hand-off text. Call it "
|
|
694
|
+
"before proposing or reviewing a query or index change.",
|
|
695
|
+
"inputSchema": {"type": "object", "properties": {"at": {"type": "string", "description": "file:line, a file, a function name (Type::method), a finding id or a call-site id."}},
|
|
696
|
+
"required": ["at"], "additionalProperties": False}},
|
|
697
|
+
{"name": "table",
|
|
698
|
+
"description": "Facts of one table: its definition and keys or indexes, real row count and size (when pulled), the "
|
|
699
|
+
"statements that read it ranked by measured load with their state, and the table changes CodeCop "
|
|
700
|
+
"proposed with their measured read gain, insert cost and state.",
|
|
701
|
+
"inputSchema": {"type": "object", "properties": {"name": {"type": "string", "description": "Table name (schema optional)."}},
|
|
702
|
+
"required": ["name"], "additionalProperties": False}},
|
|
703
|
+
{"name": "call_patterns",
|
|
704
|
+
"description": "Loops that run a query per item and queries that fire together, for a file path or a function name: "
|
|
705
|
+
"the loop, its member statements, the measured load, whether the batched form was measured and its "
|
|
706
|
+
"state, and what is not known.",
|
|
707
|
+
"inputSchema": {"type": "object", "properties": {"at": {"type": "string", "description": "A file path or a function/method name."}},
|
|
708
|
+
"required": ["at"], "additionalProperties": False}},
|
|
709
|
+
{"name": "findings",
|
|
710
|
+
"description": "Findings of every kind CodeCop checks (query: database statements; regex; transaction; others as they are "
|
|
711
|
+
"added), or of one kind: each with its place, state (Fixed = verified, Needs another fix, Not judged, "
|
|
712
|
+
"Nothing to gain), whether the harm is a wrong result under concurrency, and its best measure before -> after.",
|
|
713
|
+
"inputSchema": {"type": "object", "properties": {
|
|
714
|
+
"kind": {"type": "string", "description": "query, regex, transaction, ... (empty: every kind)."},
|
|
715
|
+
"state": {"type": "string", "enum": ["", "fixed", "blocked", "not_judged", "nothing_to_gain"]},
|
|
716
|
+
"limit": {"type": "integer", "minimum": 1, "maximum": 200}}, "additionalProperties": False}},
|
|
717
|
+
{"name": "not_asked",
|
|
718
|
+
"description": "What CodeCop has not asked its agent about yet (the run's budget stopped before it) and the statements "
|
|
719
|
+
"waiting for a variant, with the command that asks them. Use it when a statement is Not judged.",
|
|
720
|
+
"inputSchema": {"type": "object", "properties": {"limit": {"type": "integer", "minimum": 1, "maximum": 100}}, "additionalProperties": False}},
|
|
721
|
+
]
|
|
722
|
+
|
|
723
|
+
|
|
724
|
+
def call(st: Stage, name: str, args: dict) -> str:
|
|
725
|
+
"""Run one tool by name; ValueError for an unknown tool or a missing argument."""
|
|
726
|
+
args = args if isinstance(args, dict) else {}
|
|
727
|
+
if name == "priorities":
|
|
728
|
+
return priorities(st, int(args.get("limit") or 10), str(args.get("state") or ""))
|
|
729
|
+
if name == "statement":
|
|
730
|
+
if not args.get("at"):
|
|
731
|
+
raise ValueError("`at` is required: file:line, a finding id or a call-site id")
|
|
732
|
+
return statement(st, str(args["at"]))
|
|
733
|
+
if name == "table":
|
|
734
|
+
if not args.get("name"):
|
|
735
|
+
raise ValueError("`name` is required")
|
|
736
|
+
return table(st, str(args["name"]))
|
|
737
|
+
if name == "call_patterns":
|
|
738
|
+
if not args.get("at"):
|
|
739
|
+
raise ValueError("`at` is required: a file path or a function name")
|
|
740
|
+
return call_patterns(st, str(args["at"]))
|
|
741
|
+
if name == "not_asked":
|
|
742
|
+
return not_asked(st, int(args.get("limit") or 15))
|
|
743
|
+
if name == "findings":
|
|
744
|
+
return findings_list(st, str(args.get("kind") or ""), str(args.get("state") or ""), int(args.get("limit") or 20))
|
|
745
|
+
raise ValueError(f"unknown tool {name!r}")
|