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/joins_view.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"""How a join is shown in the local report: the two sides, their sizes, which filters reach which side, what CodeCop's
|
|
2
|
+
variant changes, and the outcome with its next step. Built from findings.json `joins` and `findings[].join` alone."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import html
|
|
7
|
+
|
|
8
|
+
SIGNAL_LABEL = {
|
|
9
|
+
"joined_side_unbounded": "A side read without the other side's bound",
|
|
10
|
+
"filter_after_join": "Filter applies after the join",
|
|
11
|
+
"join_for_one_column": "Big table joined for one column",
|
|
12
|
+
"big_table_on_build_side": "Bigger side builds the hash table",
|
|
13
|
+
"aggregate_after_join": "Join before the aggregate",
|
|
14
|
+
"unused_left_join": "LEFT JOIN nothing reads",
|
|
15
|
+
"dimension_join_repeated": "Same small table joined by many statements",
|
|
16
|
+
}
|
|
17
|
+
TIER_LABEL = {"shown": "", "agent": "for the agent", "muted": "muted"}
|
|
18
|
+
REWRITE_LABEL = {"push_bound": "bound copied through the join key", "push_filter": "filter moved into the subquery",
|
|
19
|
+
"drop_unused_left_join": "unused LEFT JOIN dropped", "swap_sides": "sides swapped"}
|
|
20
|
+
DIM_WORD = {"tenant": "tenant", "time": "time", "key": "key"}
|
|
21
|
+
|
|
22
|
+
CSS = """
|
|
23
|
+
.jd{display:grid;grid-template-columns:minmax(0,1fr) auto minmax(0,1fr);gap:8px;align-items:stretch;margin:8px 0}
|
|
24
|
+
@media (max-width:640px){.jd{grid-template-columns:1fr}.jd .jj{text-align:left}}
|
|
25
|
+
.js{border:1px solid var(--line);border-radius:6px;padding:6px 10px;background:var(--bg);min-width:0;overflow-wrap:anywhere}
|
|
26
|
+
.js.miss{border-color:var(--bad)}.js b{font:600 13px/1.3 ui-monospace,Menlo,monospace}.js small{display:block;color:var(--muted);font-size:12px}
|
|
27
|
+
.jj{align-self:center;text-align:center;color:var(--muted);font-size:12px;line-height:1.3}.jj b{display:block;color:var(--ink);font-size:12px}
|
|
28
|
+
.jf{display:flex;flex-wrap:wrap;gap:4px;margin-top:4px}.jf .tag{font-size:11px;padding:1px 6px}
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def e(text) -> str:
|
|
33
|
+
return html.escape(str(text if text is not None else ""))
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def tag(text, cls="") -> str:
|
|
37
|
+
return f"<span class='tag {e(cls)}'>{e(text)}</span>"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _rows(n) -> str:
|
|
41
|
+
if n is None:
|
|
42
|
+
return "rows unknown"
|
|
43
|
+
for unit, size in (("B", 1e9), ("M", 1e6), ("K", 1e3)):
|
|
44
|
+
if n >= size:
|
|
45
|
+
return f"{n / size:.1f}{unit} rows"
|
|
46
|
+
return f"{n:,} rows"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _side(s: dict, missing: list[str], cls: str = "") -> str:
|
|
50
|
+
dims = {}
|
|
51
|
+
for f in s.get("filters") or []:
|
|
52
|
+
for d in f.get("dims") or []:
|
|
53
|
+
if d in ("tenant", "time"):
|
|
54
|
+
dims.setdefault(d, f["column"])
|
|
55
|
+
chips = [tag(f"{d} · {c}", "verified") for d, c in dims.items()]
|
|
56
|
+
chips += [tag(f"no {d} bound", "failed") for d in missing if d not in dims]
|
|
57
|
+
meta = [_rows(s.get("rows")) + (" (real catalog)" if s.get("rows_from") == "real catalog" else "")]
|
|
58
|
+
if s.get("key"):
|
|
59
|
+
meta.append("key " + ", ".join(s["key"][:5]))
|
|
60
|
+
if s.get("final"):
|
|
61
|
+
meta.append("FINAL")
|
|
62
|
+
return (f"<div class='js {cls}'><b>{e(s.get('name'))}</b><small>{e(' · '.join(meta))}</small>"
|
|
63
|
+
f"<div class=jf>{''.join(chips)}</div></div>")
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def drawing_html(drawing: list[dict], signals: list[dict] | None = None) -> str:
|
|
67
|
+
"""One row per flagged join: driving side → join → joined side, with the bounds each side gets."""
|
|
68
|
+
out = []
|
|
69
|
+
for d in drawing or []:
|
|
70
|
+
sig = [s for s in signals or [] if s.get("position") == d["position"]]
|
|
71
|
+
|
|
72
|
+
def missing(side: str) -> list[str]:
|
|
73
|
+
return sorted({s.get("dim") for s in sig if s.get("signal") == "joined_side_unbounded" and s.get("dim") in ("tenant", "time")
|
|
74
|
+
and ((s.get("evidence") or {}).get("side") or "joined") == side})
|
|
75
|
+
keys = " · ".join(f"{a} = {b}" for a, b in d.get("keys") or [])
|
|
76
|
+
jtype = " ".join(x for x in (d.get("strictness"), d.get("type")) if x) + " JOIN"
|
|
77
|
+
change = d.get("change") or {}
|
|
78
|
+
out.append(
|
|
79
|
+
f"<div class=jd>{_side(d['driving'], missing('driving'), 'miss' if missing('driving') else '')}"
|
|
80
|
+
f"<div class=jj><b>{e(jtype)}</b>{e(keys)}</div>"
|
|
81
|
+
f"{_side(d['joined'], missing('joined'), 'miss' if missing('joined') else '')}</div>"
|
|
82
|
+
"<div class=chips>" + "".join(
|
|
83
|
+
tag(SIGNAL_LABEL.get(s["signal"], s["signal"]) + (f" · {s['dim']}" if s.get("dim") else "")
|
|
84
|
+
+ (" · the driving side" if (s.get("evidence") or {}).get("side") == "driving" else "")
|
|
85
|
+
+ (f" · {TIER_LABEL[s['tier']]}" if TIER_LABEL.get(s.get("tier") or "") else "")
|
|
86
|
+
+ (" · a run-time part may hold it" if s.get("uncertain") else ""), "unverified") for s in sig)
|
|
87
|
+
+ (tag("Variant: " + REWRITE_LABEL.get(change.get("rewrite"), change.get("rewrite") or "")
|
|
88
|
+
+ (f" · {change['verdict']}" if change.get("verdict") else ""), "verified" if change.get("verdict") == "win" else "")
|
|
89
|
+
if change else "") + "</div>")
|
|
90
|
+
return "".join(out)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def finding_html(f: dict) -> str:
|
|
94
|
+
j = f.get("join")
|
|
95
|
+
if not j:
|
|
96
|
+
return ""
|
|
97
|
+
return "<h4>The join</h4>" + drawing_html(j.get("drawing") or [], j.get("signals"))
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def section(data: dict, state_tag, next_chips) -> str:
|
|
101
|
+
"""The run's join statements: counts per signal, then each statement drawn, with its state and next step."""
|
|
102
|
+
jb = data.get("joins")
|
|
103
|
+
if not jb or not jb.get("statements"):
|
|
104
|
+
return ""
|
|
105
|
+
s = jb.get("summary") or {}
|
|
106
|
+
counts = {}
|
|
107
|
+
for key, n in (jb.get("counts") or {}).items():
|
|
108
|
+
name, tier = key.rsplit(":", 1)
|
|
109
|
+
if tier in ("shown", "agent"):
|
|
110
|
+
counts[(name, tier)] = n
|
|
111
|
+
chips = tag(f"{s.get('join_statements', 0):,} join statements read") + "".join(
|
|
112
|
+
tag(f"{SIGNAL_LABEL.get(n, n)}{' · ' + TIER_LABEL[t] if TIER_LABEL.get(t) else ''} · {c}", "unverified") for (n, t), c in sorted(counts.items()))
|
|
113
|
+
chips += tag(f"sizes: {s.get('sizes_from', 'none')}")
|
|
114
|
+
rows = []
|
|
115
|
+
for st in jb["statements"]:
|
|
116
|
+
where = f"{st['file'].split('/')[-1]}:{st['line']}" if st.get("file") else st["id"]
|
|
117
|
+
link = f" · <a href='#{e(st['finding'])}'>{e(st['finding'])}</a>" if st.get("finding") else ""
|
|
118
|
+
o = st.get("outcome") or {}
|
|
119
|
+
rows.append(f"<div class=finding><header><h3><code>{e(where)}</code>{link}</h3>{state_tag(st)}</header>"
|
|
120
|
+
+ drawing_html(st.get("drawing") or [], st.get("signals"))
|
|
121
|
+
+ "<div class=chips>" + "".join(next_chips(o.get("evidence") or {})) + "</div></div>")
|
|
122
|
+
dims = "".join(tag(f"{d['table']} · joined by {d['statements']} statements · {_rows(d.get('rows'))}") for d in jb.get("dimension_tables") or [])
|
|
123
|
+
return ("<h2>Joins that may do more work than the page needs</h2>"
|
|
124
|
+
"<p class=muted>Found from the parsed statements, not measured. A variant CodeCop could prove from the keys is benchmarked "
|
|
125
|
+
"like any other; the rest need a judgement and go to the agent.</p>"
|
|
126
|
+
f"<div class=chips>{chips}</div>" + (f"<h4>Joined by many statements</h4><div class=chips>{dims}</div>" if dims else "")
|
|
127
|
+
+ "".join(rows))
|
|
@@ -0,0 +1,507 @@
|
|
|
1
|
+
"""Kinds of finding: the shared contract and the registry that lets CodeCop carry findings that are not SQL queries.
|
|
2
|
+
|
|
3
|
+
A finding has a `kind` (`query`: today's, the default when absent; `regex`; `transaction`; room for more), a `harm`
|
|
4
|
+
(`speed`, `correctness`: a wrong result under concurrency such as a lost update, a duplicate or a deadlock, or `both`) and
|
|
5
|
+
a `proof`: one unit that says how it was verified, the same shape for every kind (`proof()` below; docs/kinds.md is the
|
|
6
|
+
contract). The four outcome states are shared (fixed, blocked shown as "Needs another fix", not_judged, nothing_to_gain);
|
|
7
|
+
a kind's own reason codes carry its name as a prefix (`regex.input_bounded`), and the generic codes in `GENERIC_REASONS`
|
|
8
|
+
need none.
|
|
9
|
+
|
|
10
|
+
A kind is a `Kind` subclass registered with `@register`. Its hooks, each optional:
|
|
11
|
+
|
|
12
|
+
discover(ctx) raw call sites ({file, line, language, symbol?, ...}); discovery adds role, origins, loops
|
|
13
|
+
rules(ctx, sites) candidates ({id, file, line, ..., ask: bool}): cheap, no agent, no sandbox
|
|
14
|
+
questions(ctx, cands) budget items (ctx.item(...)) for what rules cannot judge: one run budget, one queue
|
|
15
|
+
ask(ctx, cands, runner) the paid call for the chosen candidates; answers go to ctx.verdicts (per item)
|
|
16
|
+
verify(ctx, cands) findings (finding(...)) with their proof and outcome: the sandbox verifier
|
|
17
|
+
report_html(ctx, found) an extra section of report.html; handoff(finding) the hand-off text (default: generic)
|
|
18
|
+
|
|
19
|
+
`pipeline.py` runs them; `testkind.py` is the built-in kind used only by tests (hidden: never on unless asked for).
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import hashlib
|
|
25
|
+
import re
|
|
26
|
+
from dataclasses import dataclass, field
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
from typing import Any
|
|
29
|
+
|
|
30
|
+
SCHEMA_VERSION = 1
|
|
31
|
+
QUERY = "query"
|
|
32
|
+
# the documented kinds (docs/kinds.md): reserved names
|
|
33
|
+
PLANNED = ("query", "regex", "transaction", "calls")
|
|
34
|
+
NAME = re.compile(r"^[a-z][a-z0-9_]{1,23}$")
|
|
35
|
+
STATES = ("fixed", "blocked", "not_judged", "nothing_to_gain")
|
|
36
|
+
HARMS = ("speed", "correctness", "both")
|
|
37
|
+
# where a proof's numbers come from: the sandbox measured them, production measured them, or someone claimed them
|
|
38
|
+
SOURCES = ("sandbox", "production", "claimed")
|
|
39
|
+
BETTER = ("lower", "higher")
|
|
40
|
+
# The sameness check, by kind: each kind names its own (a new kind adds its name here and to the server's words).
|
|
41
|
+
SAMENESS = {"query": "same_rows", "regex": "same_matches", "transaction": "same_final_state", "calls": "same_output",
|
|
42
|
+
"testkind": "same_output"}
|
|
43
|
+
# Reason codes every kind may use without a prefix, with the state each belongs to.
|
|
44
|
+
GENERIC_REASONS = {
|
|
45
|
+
"verified": "fixed", # measured: the fix gains beyond the spread, and the sameness check held
|
|
46
|
+
"no_gain_measured": "blocked", # measured: no fix gains beyond the spread of the repeated runs
|
|
47
|
+
"fix_results_differ": "blocked", # a fix gained, the sameness check failed: a trade-off, never fixed
|
|
48
|
+
"no_variant_proposed": "blocked", # nothing was proposed to measure
|
|
49
|
+
"not_asked": "not_judged", # waits on the agent: not asked yet (the run budget, or --no-agent)
|
|
50
|
+
"agent_no_answer": "not_judged",
|
|
51
|
+
"agent_failed": "not_judged",
|
|
52
|
+
"budget_reached": "not_judged",
|
|
53
|
+
"sandbox_could_not_run": "not_judged",
|
|
54
|
+
"needs_production_fact": "not_judged", # the gain depends on a size or rate nobody measured
|
|
55
|
+
"already_cheap_measured": "nothing_to_gain",
|
|
56
|
+
}
|
|
57
|
+
GENERIC_WORDS = {
|
|
58
|
+
"verified": "a fix gains beyond the spread, same result",
|
|
59
|
+
"no_gain_measured": "no fix gains beyond the spread",
|
|
60
|
+
"fix_results_differ": "a fix gains, the result differs (a trade-off)",
|
|
61
|
+
"no_variant_proposed": "no fix was proposed",
|
|
62
|
+
"not_asked": "not asked yet",
|
|
63
|
+
"agent_no_answer": "examined, the agent returned nothing",
|
|
64
|
+
"agent_failed": "its agent call failed",
|
|
65
|
+
"budget_reached": "budget reached before its call",
|
|
66
|
+
"sandbox_could_not_run": "the sandbox could not run it",
|
|
67
|
+
"needs_production_fact": "needs a production fact",
|
|
68
|
+
"already_cheap_measured": "already cheap (measured)",
|
|
69
|
+
}
|
|
70
|
+
STATE_WORDS = {"fixed": "Fixed", "blocked": "Needs another fix", "not_judged": "Could not be judged", "nothing_to_gain": "Nothing to gain"}
|
|
71
|
+
HARM_WORDS = {"speed": "speed", "correctness": "wrong results under concurrency", "both": "speed and wrong results under concurrency"}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def harm_words(kind: str, harm: str) -> str:
|
|
75
|
+
"""The words of a harm for one kind: a kind may say what its correctness harm is (`Kind.harm_words`), such as a call
|
|
76
|
+
that can hang, instead of the shared "wrong results under concurrency"."""
|
|
77
|
+
k = REGISTRY.get(kind) if kind else None
|
|
78
|
+
own = getattr(k, "harm_words", None) or {}
|
|
79
|
+
return own.get(harm) or HARM_WORDS.get(harm, harm)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class ContractError(ValueError):
|
|
83
|
+
"""A kind broke the contract: an unknown state, an unprefixed reason, a proof without a source."""
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
# --- the registry ------------------------------------------------------------------------------------------------------
|
|
87
|
+
|
|
88
|
+
class Kind:
|
|
89
|
+
"""One kind of finding. Subclass it, set the class attributes, override the hooks you need, and `@register` it."""
|
|
90
|
+
|
|
91
|
+
name: str = "" # `regex`: lower case, the finding's `kind`, the inventory key under `kinds`
|
|
92
|
+
label: str = "" # `Regexes`: the list's name
|
|
93
|
+
one: str = "" # `regex`: one item, in sentences
|
|
94
|
+
prefix: str = "" # `R`: finding ids R-001; one letter or two, unique
|
|
95
|
+
sameness: str = "" # `same_matches`; default SAMENESS[name]
|
|
96
|
+
default_on: bool = True # `codecop scan` runs it unless `--skip <name>`
|
|
97
|
+
hidden: bool = False # never on unless named (`--only <name>`): the test kind
|
|
98
|
+
# The kind's own reason codes: `<name>.<code>` -> (state, the words in report.html). The console has its own words
|
|
99
|
+
# table for these codes; the two are kept in step.
|
|
100
|
+
reasons: dict[str, tuple[str, str]] = {}
|
|
101
|
+
# The kind's measure names: code -> (words, unit). A measure not here is shown as its own text.
|
|
102
|
+
measures: dict[str, tuple[str, str]] = {}
|
|
103
|
+
# One agent question kind in the run budget's queue (budget.py): items per call and the first-run prior per item.
|
|
104
|
+
items_per_call: int = 20
|
|
105
|
+
cost_per_item_usd: tuple[float, float] = (0.03, 0.06)
|
|
106
|
+
|
|
107
|
+
# hooks ------------------------------------------------------------------------------------------------------------
|
|
108
|
+
def discover(self, ctx: "Context") -> list[dict]:
|
|
109
|
+
return []
|
|
110
|
+
|
|
111
|
+
def rules(self, ctx: "Context", sites: list[dict]) -> list[dict]:
|
|
112
|
+
return []
|
|
113
|
+
|
|
114
|
+
def questions(self, ctx: "Context", candidates: list[dict]) -> list[dict]:
|
|
115
|
+
return []
|
|
116
|
+
|
|
117
|
+
def ask(self, ctx: "Context", candidates: list[dict], runner) -> None:
|
|
118
|
+
return None
|
|
119
|
+
|
|
120
|
+
def verify(self, ctx: "Context", candidates: list[dict]) -> list[dict]:
|
|
121
|
+
return []
|
|
122
|
+
|
|
123
|
+
def report_html(self, ctx: "Context", findings: list[dict]) -> str:
|
|
124
|
+
return ""
|
|
125
|
+
|
|
126
|
+
def handoff(self, finding: dict) -> str:
|
|
127
|
+
return handoff_text(finding)
|
|
128
|
+
|
|
129
|
+
# derived ----------------------------------------------------------------------------------------------------------
|
|
130
|
+
@property
|
|
131
|
+
def queue_kind(self) -> str:
|
|
132
|
+
"""The budget queue's item kind (and agent step) of this kind's questions."""
|
|
133
|
+
return f"kind_{self.name}"
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
REGISTRY: dict[str, Kind] = {}
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def register(cls):
|
|
140
|
+
"""Class decorator: check the kind's attributes and add one instance to the registry (and its question kind to the
|
|
141
|
+
run budget). Registering the same name twice replaces the first (a test may re-register)."""
|
|
142
|
+
k = cls() if isinstance(cls, type) else cls
|
|
143
|
+
if not NAME.fullmatch(k.name or "") or k.name == QUERY:
|
|
144
|
+
raise ContractError(f"kind name {k.name!r}: lower case letters, digits and _, 2 to 24 characters, not `query`")
|
|
145
|
+
if not k.label or not k.one or not re.fullmatch(r"[A-Z]{1,2}", k.prefix or ""):
|
|
146
|
+
raise ContractError(f"kind {k.name}: label, one and a one- or two-letter capital prefix are required")
|
|
147
|
+
taken = {o.prefix: o.name for o in REGISTRY.values() if o.name != k.name}
|
|
148
|
+
if k.prefix in taken or k.prefix in ("Q", "O", "SB", "SC", "G", "J"):
|
|
149
|
+
raise ContractError(f"kind {k.name}: prefix {k.prefix} is taken")
|
|
150
|
+
k.sameness = k.sameness or SAMENESS.get(k.name, "same_output")
|
|
151
|
+
for code, value in (k.reasons or {}).items():
|
|
152
|
+
if not code.startswith(k.name + ".") or not isinstance(value, tuple) or len(value) != 2 or value[0] not in STATES:
|
|
153
|
+
raise ContractError(f"kind {k.name}: reason {code!r} must be `{k.name}.<code>` -> (state, words)")
|
|
154
|
+
REGISTRY[k.name] = k
|
|
155
|
+
from .. import budget
|
|
156
|
+
budget.register_queue_kind(k.queue_kind, step=k.queue_kind, label=k.label.lower(), next_step=f"ask_agent_about_{k.name}",
|
|
157
|
+
items_per_call=k.items_per_call, cost=k.cost_per_item_usd)
|
|
158
|
+
return cls
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def get(name: str) -> Kind | None:
|
|
162
|
+
_load_builtin()
|
|
163
|
+
return REGISTRY.get(name)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def all_kinds() -> list[Kind]:
|
|
167
|
+
_load_builtin()
|
|
168
|
+
return list(REGISTRY.values())
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
_LOADED = False
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _load_builtin() -> None:
|
|
175
|
+
"""The built-in kinds. The family packages (regex, transaction) add their import here."""
|
|
176
|
+
global _LOADED
|
|
177
|
+
if _LOADED:
|
|
178
|
+
return
|
|
179
|
+
_LOADED = True
|
|
180
|
+
from . import testkind # noqa: F401 (hidden: only on when named)
|
|
181
|
+
from . import regex # noqa: F401
|
|
182
|
+
from . import transaction # noqa: F401 (locks and contention)
|
|
183
|
+
from . import calls # noqa: F401 (outbound calls: client per call, blocking in async, no timeout)
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def parse_list(text: Any) -> list[str]:
|
|
187
|
+
if text is None:
|
|
188
|
+
return []
|
|
189
|
+
items = text if isinstance(text, (list, tuple)) else str(text).split(",")
|
|
190
|
+
return [str(t).strip().lower() for t in items if str(t).strip()]
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def selection(only: Any = None, skip: Any = None, settings: dict | None = None) -> list[str]:
|
|
194
|
+
"""The kinds a scan runs, `query` included when it runs. `--only a,b` runs exactly those; `--skip a` drops one; the
|
|
195
|
+
default is `query` and every kind whose `default_on` is true and is not `enabled = false` under `[kinds.<name>]` in
|
|
196
|
+
codecop.toml. A hidden kind runs only when named in `--only`. Unknown names raise ContractError."""
|
|
197
|
+
known = {QUERY} | {k.name for k in all_kinds()}
|
|
198
|
+
want, drop = parse_list(only), parse_list(skip)
|
|
199
|
+
bad = [n for n in want + drop if n not in known]
|
|
200
|
+
if bad:
|
|
201
|
+
raise ContractError(f"unknown kind {', '.join(bad)}: one of {', '.join(sorted(n for n in known if not (get(n) and get(n).hidden)))}")
|
|
202
|
+
if want:
|
|
203
|
+
chosen = [n for n in [QUERY] + [k.name for k in all_kinds()] if n in want]
|
|
204
|
+
else:
|
|
205
|
+
cfg = settings or {}
|
|
206
|
+
chosen = [QUERY] + [k.name for k in all_kinds() if k.default_on and not k.hidden
|
|
207
|
+
and (cfg.get(k.name) or {}).get("enabled", True) is not False]
|
|
208
|
+
return [n for n in chosen if n not in drop]
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
# --- the contract's builders -------------------------------------------------------------------------------------------
|
|
212
|
+
|
|
213
|
+
def site_id(kind: str, file: str, symbol: str, text: str) -> str:
|
|
214
|
+
"""A call site's stable id for a kind: the same file, function and text give the same id across runs."""
|
|
215
|
+
h = hashlib.sha256("\n".join([kind, file or "", symbol or "", text or ""]).encode("utf-8", "replace")).hexdigest()
|
|
216
|
+
return f"{kind[:3]}{h[:13]}"
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _num(v: Any) -> float | None:
|
|
220
|
+
return float(v) if isinstance(v, (int, float)) and not isinstance(v, bool) else None
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def measure(name: str, unit: str, before: float | None, after: float | None, *, better: str = "lower", of: float | None = None,
|
|
224
|
+
spread_before: tuple | list | None = None, spread_after: tuple | list | None = None, runs: int | None = None,
|
|
225
|
+
verdict: bool = True) -> dict:
|
|
226
|
+
"""One named measure, before and after the fix. `ratio` is after / before (None when before is 0 or a side is missing);
|
|
227
|
+
`of`: the whole a count is out of (lost updates of 1,600); `spread_*`: [low, high] over the repeated runs; `verdict`:
|
|
228
|
+
whether the verdict rests on it (a tail latency is shown, never judged)."""
|
|
229
|
+
if better not in BETTER:
|
|
230
|
+
raise ContractError(f"measure {name}: better must be lower or higher")
|
|
231
|
+
b, a = _num(before), _num(after)
|
|
232
|
+
out: dict = {"name": name, "unit": unit, "better": better, "before": b, "after": a,
|
|
233
|
+
"ratio": round(a / b, 6) if a is not None and b else None, "verdict": bool(verdict)}
|
|
234
|
+
if _num(of) is not None:
|
|
235
|
+
out["of"] = _num(of)
|
|
236
|
+
spread = {}
|
|
237
|
+
for key, rng in (("before", spread_before), ("after", spread_after)):
|
|
238
|
+
if rng and len(rng) == 2 and all(_num(x) is not None for x in rng):
|
|
239
|
+
spread[key] = [float(min(rng)), float(max(rng))]
|
|
240
|
+
if spread or runs:
|
|
241
|
+
out["spread"] = {**spread, **({"runs": int(runs)} if runs else {})}
|
|
242
|
+
return out
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def sameness(check: str, held: bool | None, *, compared: int | None = None, differed: int | None = None, basis: str = "") -> dict:
|
|
246
|
+
"""The sameness check: its kind-specific name (same_rows, same_matches, same_final_state, ...), whether it held (None:
|
|
247
|
+
not compared), how many were compared and how many differed, and the basis in a few words (cut to 120 characters)."""
|
|
248
|
+
out: dict = {"check": check, "held": held}
|
|
249
|
+
if compared is not None:
|
|
250
|
+
out["compared"] = int(compared)
|
|
251
|
+
if differed is not None:
|
|
252
|
+
out["differed"] = int(differed)
|
|
253
|
+
if basis:
|
|
254
|
+
out["basis"] = str(basis)[:120]
|
|
255
|
+
return out
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def proof(*, source: str, measures: list[dict], same: dict | None = None, runtime: dict | None = None, scale: dict | None = None,
|
|
259
|
+
schedule: dict | None = None, series: list[dict] | None = None, inputs: dict | None = None) -> dict:
|
|
260
|
+
"""The proof unit (docs/kinds.md "proof"). `runtime`: {engine, version, settings{name: value}} (settings that flatter
|
|
261
|
+
the numbers, such as fsync off, are printed); `scale`: {name, unit, points[], at} what it was measured at; `schedule`:
|
|
262
|
+
{name: value} facts of a concurrent schedule (sessions, operations, hot_rows, think_ms, ...); `series`: curves
|
|
263
|
+
[{name, x_unit, y_unit, points[[x, y]]}] (time against input size); `inputs`: {family, typical, observed} words."""
|
|
264
|
+
if source not in SOURCES:
|
|
265
|
+
raise ContractError(f"proof source {source!r}: one of {', '.join(SOURCES)}")
|
|
266
|
+
out: dict = {"schema_version": SCHEMA_VERSION, "source": source, "measures": [m for m in measures or [] if isinstance(m, dict)]}
|
|
267
|
+
if same:
|
|
268
|
+
out["sameness"] = same
|
|
269
|
+
for key, value in (("runtime", runtime), ("scale", scale), ("schedule", schedule), ("series", series), ("inputs", inputs)):
|
|
270
|
+
if value:
|
|
271
|
+
out[key] = value
|
|
272
|
+
return out
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def outcome(kind: str, state: str, reason: str, *, source: str = "sandbox", evidence: dict | None = None,
|
|
276
|
+
next_step: str = "") -> dict:
|
|
277
|
+
"""An outcome in the shared shape (bundle `$defs.outcome`). The reason is a generic code (GENERIC_REASONS) or the
|
|
278
|
+
kind's own `<kind>.<code>`; either must belong to the state."""
|
|
279
|
+
if state not in STATES:
|
|
280
|
+
raise ContractError(f"state {state!r}: one of {', '.join(STATES)}")
|
|
281
|
+
if reason in GENERIC_REASONS:
|
|
282
|
+
if GENERIC_REASONS[reason] != state:
|
|
283
|
+
raise ContractError(f"reason {reason} belongs to {GENERIC_REASONS[reason]}, not {state}")
|
|
284
|
+
else:
|
|
285
|
+
k = get(kind)
|
|
286
|
+
own = (k.reasons if k else {}).get(reason)
|
|
287
|
+
if not reason.startswith(kind + ".") or own is None:
|
|
288
|
+
raise ContractError(f"reason {reason!r}: a generic code or one `{kind}.<code>` the kind registered")
|
|
289
|
+
if own[0] != state:
|
|
290
|
+
raise ContractError(f"reason {reason} belongs to {own[0]}, not {state}")
|
|
291
|
+
out = {"state": state, "reason": reason, "from": source, "evidence": dict(evidence or {})}
|
|
292
|
+
if next_step:
|
|
293
|
+
out["next_step"] = next_step
|
|
294
|
+
return out
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def finding(kind: str, *, id: str, title: str, site: dict, outcome: dict, proof: dict | None = None, harm: str = "speed",
|
|
298
|
+
severity: str = "medium", confidence: str = "medium", summary: str = "", origin: dict | None = None,
|
|
299
|
+
fix: dict | None = None, extra: dict | None = None) -> dict:
|
|
300
|
+
"""One finding of a kind, in the findings.json shape. `id`: the call site's stable id (site_id); `site`: {file, line,
|
|
301
|
+
symbol}; `fix`: {change (a code), before, after} short texts of the best fix (shown as a diff; never SQL here);
|
|
302
|
+
`extra`: the kind's own fields (its custom panels read them). The finding id (R-001) is given by the pipeline."""
|
|
303
|
+
if harm not in HARMS:
|
|
304
|
+
raise ContractError(f"harm {harm!r}: one of {', '.join(HARMS)}")
|
|
305
|
+
state = (outcome or {}).get("state")
|
|
306
|
+
status = "verified" if state == "fixed" else "unverified"
|
|
307
|
+
out = {"kind": kind, "id": id, "title": str(title)[:200], "severity": severity, "confidence": confidence, "status": status,
|
|
308
|
+
"summary": str(summary)[:300], "harm": harm, "site": {k: site.get(k) for k in ("file", "line", "symbol") if site.get(k) is not None},
|
|
309
|
+
"tables": [], "outcome": outcome, "origin": origin or {"role": "unknown", "kind": "unknown", "entry_points": [], "verified": False}}
|
|
310
|
+
if proof:
|
|
311
|
+
out["proof"] = proof
|
|
312
|
+
if fix:
|
|
313
|
+
out["fix"] = {k: str(v)[:4000] for k, v in fix.items() if isinstance(v, str)}
|
|
314
|
+
if extra:
|
|
315
|
+
out.update({k: v for k, v in extra.items() if k not in out})
|
|
316
|
+
return out
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
# --- today's query findings, mapped onto the proof unit --------------------------------------------------------------
|
|
320
|
+
|
|
321
|
+
def query_proof(f: dict, engine: str = "", version: str = "") -> dict | None:
|
|
322
|
+
"""The proof unit of one query finding, from the fields it already has (report.build_findings): the best variant's
|
|
323
|
+
rows and bytes read and time at the largest scale, the same-rows check, the scales. None when nothing was measured.
|
|
324
|
+
The query's own fields stay as they are: this is an added view, never a replacement."""
|
|
325
|
+
variants = [v for v in f.get("variants") or [] if isinstance(v, dict) and v.get("scales")]
|
|
326
|
+
if not variants:
|
|
327
|
+
return None
|
|
328
|
+
v = next((x for x in variants if x.get("verdict") == "win"), variants[0])
|
|
329
|
+
last = v["scales"][-1] or {}
|
|
330
|
+
b, a = last.get("baseline") or {}, last.get("variant") or {}
|
|
331
|
+
if not b.get("ok"):
|
|
332
|
+
return None
|
|
333
|
+
ms = []
|
|
334
|
+
for key, unit in (("read_rows", "rows"), ("read_bytes", "bytes")):
|
|
335
|
+
if _num(b.get(key)) is not None and _num(a.get(key)) is not None:
|
|
336
|
+
ms.append(measure(key, unit, b[key], a[key]))
|
|
337
|
+
if _num(b.get("duration_ms")) is not None and _num(a.get("duration_ms")) is not None:
|
|
338
|
+
rb = [x for x in ((b.get("runs_detail") or {}).get("duration_ms") or []) if _num(x) is not None]
|
|
339
|
+
ra = [x for x in ((a.get("runs_detail") or {}).get("duration_ms") or []) if _num(x) is not None]
|
|
340
|
+
ms.append(measure("duration_ms", "ms", b["duration_ms"], a["duration_ms"], spread_before=(min(rb), max(rb)) if rb else None,
|
|
341
|
+
spread_after=(min(ra), max(ra)) if ra else None, runs=max(len(rb), len(ra)) or None, verdict=False))
|
|
342
|
+
match = v.get("results_match")
|
|
343
|
+
held = True if match is True else False if match is False else None
|
|
344
|
+
rows = [s.get("rows") for s in v["scales"] if _num(s.get("rows")) is not None]
|
|
345
|
+
return proof(source="sandbox", measures=ms,
|
|
346
|
+
same=sameness("same_rows", held, compared=int(b["result_rows"]) if _num(b.get("result_rows")) is not None else None,
|
|
347
|
+
basis=str(v.get("compared") or "")[:120]),
|
|
348
|
+
runtime={"engine": engine, "version": version} if engine else None,
|
|
349
|
+
scale={"name": "table rows", "unit": "rows", "points": rows, "at": rows[-1]} if rows else None)
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def with_query_contract(data: dict) -> dict:
|
|
353
|
+
"""findings.json with `kind: query`, `harm: speed` and `proof` on every query finding (old fields untouched)."""
|
|
354
|
+
for f in data.get("findings") or []:
|
|
355
|
+
if not isinstance(f, dict) or f.get("kind") not in (None, QUERY):
|
|
356
|
+
continue
|
|
357
|
+
f["kind"] = QUERY
|
|
358
|
+
f.setdefault("harm", "speed")
|
|
359
|
+
if "proof" not in f:
|
|
360
|
+
p = query_proof(f, data.get("engine") or "", data.get("engine_version") or "")
|
|
361
|
+
if p:
|
|
362
|
+
f["proof"] = p
|
|
363
|
+
return data
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
# --- words, for report.html and the hand-off ---------------------------------------------------------------------------
|
|
367
|
+
|
|
368
|
+
def reason_words(kind: str, reason: str) -> str:
|
|
369
|
+
if reason in GENERIC_WORDS:
|
|
370
|
+
return GENERIC_WORDS[reason]
|
|
371
|
+
k = get(kind)
|
|
372
|
+
own = (k.reasons if k else {}).get(reason)
|
|
373
|
+
return own[1] if own else reason.split(".", 1)[-1].replace("_", " ")
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def measure_words(kind: str, name: str) -> str:
|
|
377
|
+
k = get(kind)
|
|
378
|
+
own = (k.measures if k else {}).get(name) or COMMON_MEASURES.get(name)
|
|
379
|
+
return own[0] if own else name.replace("_", " ")
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
COMMON_MEASURES = {"read_rows": ("rows read", "rows"), "read_bytes": ("bytes read", "bytes"), "duration_ms": ("time", "ms"),
|
|
383
|
+
"throughput": ("operations per second", "ops/s")}
|
|
384
|
+
SAMENESS_WORDS = {"same_rows": "same rows", "same_matches": "same matches", "same_final_state": "same final state",
|
|
385
|
+
"same_output": "same output"}
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def _fmt(n: Any) -> str:
|
|
389
|
+
x = _num(n)
|
|
390
|
+
if x is None:
|
|
391
|
+
return "?"
|
|
392
|
+
if abs(x) >= 1000 or x == int(x):
|
|
393
|
+
return f"{x:,.0f}"
|
|
394
|
+
return f"{x:.3g}"
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def ratio_words(m: dict) -> str:
|
|
398
|
+
"""`x7.5` (higher is better and grew), `-87%` style is left to the console; here: `to 0`, `x0.13`, `x7.5`."""
|
|
399
|
+
if m.get("after") == 0 and m.get("before"):
|
|
400
|
+
return "to 0"
|
|
401
|
+
r = m.get("ratio")
|
|
402
|
+
return f"x{r:.3g}" if isinstance(r, (int, float)) else ""
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def proof_lines(kind: str, p: dict | None) -> list[str]:
|
|
406
|
+
"""The proof as short lines (hand-off, MCP, terminal): measures, sameness, scale or schedule, runtime, source."""
|
|
407
|
+
if not p:
|
|
408
|
+
return ["Proof: none (nothing was measured)"]
|
|
409
|
+
out = [f"Evidence: {p.get('source')}"]
|
|
410
|
+
for m in p.get("measures") or []:
|
|
411
|
+
of = f" of {_fmt(m['of'])}" if m.get("of") is not None else ""
|
|
412
|
+
sp = m.get("spread") or {}
|
|
413
|
+
spread = ""
|
|
414
|
+
if sp.get("after") or sp.get("before"):
|
|
415
|
+
spread = f" (runs {sp.get('runs') or '?'}: before {_fmt((sp.get('before') or [None])[0])}-{_fmt((sp.get('before') or [None, None])[-1])}, " \
|
|
416
|
+
f"after {_fmt((sp.get('after') or [None])[0])}-{_fmt((sp.get('after') or [None, None])[-1])})"
|
|
417
|
+
out.append(f"- {measure_words(kind, m.get('name', ''))}: {_fmt(m.get('before'))} -> {_fmt(m.get('after'))} {m.get('unit', '')}{of} "
|
|
418
|
+
f"{ratio_words(m)}{spread}{'' if m.get('verdict', True) else ' (shown, not judged)'}".rstrip())
|
|
419
|
+
s = p.get("sameness") or {}
|
|
420
|
+
if s:
|
|
421
|
+
held = {True: "held", False: "did not hold", None: "not compared"}.get(s.get("held"))
|
|
422
|
+
counts = f", {s['differed']} of {s['compared']} differed" if s.get("compared") is not None and s.get("differed") is not None \
|
|
423
|
+
else (f", {s['compared']} compared" if s.get("compared") is not None else "")
|
|
424
|
+
out.append(f"Sameness: {SAMENESS_WORDS.get(s.get('check'), str(s.get('check')).replace('_', ' '))} {held}{counts}"
|
|
425
|
+
+ (f" ({s['basis']})" if s.get("basis") else ""))
|
|
426
|
+
if p.get("scale"):
|
|
427
|
+
sc = p["scale"]
|
|
428
|
+
out.append(f"Measured at: {sc.get('name')} {_fmt(sc.get('at'))} {sc.get('unit') or ''}".rstrip())
|
|
429
|
+
if p.get("schedule"):
|
|
430
|
+
out.append("Schedule: " + ", ".join(f"{k.replace('_', ' ')} {v}" for k, v in p["schedule"].items()))
|
|
431
|
+
rt = p.get("runtime") or {}
|
|
432
|
+
if rt:
|
|
433
|
+
out.append(f"Runtime: {rt.get('engine', '')} {rt.get('version', '')}".rstrip()
|
|
434
|
+
+ (" (" + ", ".join(f"{k} {v}" for k, v in (rt.get("settings") or {}).items()) + ")" if rt.get("settings") else ""))
|
|
435
|
+
return out
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def handoff_text(f: dict) -> str:
|
|
439
|
+
"""The generic hand-off of a finding of any kind: where, what, the state, the proof, the fix. Plain text."""
|
|
440
|
+
kind = f.get("kind") or QUERY
|
|
441
|
+
site = f.get("site") or {}
|
|
442
|
+
o = f.get("outcome") or {}
|
|
443
|
+
lines = [f"{f.get('finding') or f.get('id')} [{kind}] {site.get('file', '')}:{site.get('line', '')} {site.get('symbol') or ''}".rstrip(),
|
|
444
|
+
f"{f.get('title', '')}",
|
|
445
|
+
f"State: {STATE_WORDS.get(o.get('state'), o.get('state') or 'unknown')}"
|
|
446
|
+
+ (f" ({reason_words(kind, o['reason'])})" if o.get("reason") else "")]
|
|
447
|
+
if f.get("harm") in ("correctness", "both"):
|
|
448
|
+
lines.append(f"Harm: {harm_words(kind, f['harm'])}")
|
|
449
|
+
h = f.get("heat") if isinstance(f.get("heat"), dict) else None
|
|
450
|
+
if h and h.get("words"):
|
|
451
|
+
lines.append(f"How often it runs: {h['words']} [{h.get('source') or 'none'}, {h.get('confidence') or 'low'} confidence]")
|
|
452
|
+
lines += proof_lines(kind, f.get("proof"))
|
|
453
|
+
fix = f.get("fix") or {}
|
|
454
|
+
if fix.get("before") or fix.get("after"):
|
|
455
|
+
lines.append("Fix:")
|
|
456
|
+
lines += [f"- {x}" for x in str(fix.get("before") or "").splitlines()] + [f"+ {x}" for x in str(fix.get("after") or "").splitlines()]
|
|
457
|
+
lines.append("Claims hold for the measured inputs or schedule only; production size and rate are not judged.")
|
|
458
|
+
return "\n".join(lines)
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
# --- the pipeline's context --------------------------------------------------------------------------------------------
|
|
462
|
+
|
|
463
|
+
@dataclass
|
|
464
|
+
class Context:
|
|
465
|
+
"""What a kind's hooks get. `settings`: the `[kinds.<name>]` table of codecop.toml; `run`: the scan's budget.Run (None
|
|
466
|
+
without an agent); `verdicts`: the per-item answer store (verdicts.Store, shared with the query pipeline)."""
|
|
467
|
+
root: Path
|
|
468
|
+
out_dir: Path
|
|
469
|
+
kind: str
|
|
470
|
+
settings: dict = field(default_factory=dict)
|
|
471
|
+
inventory: dict | None = None
|
|
472
|
+
run: Any = None
|
|
473
|
+
verdicts: Any = None
|
|
474
|
+
no_agent: bool = False
|
|
475
|
+
fresh: Any = False
|
|
476
|
+
by_lang: dict = field(default_factory=dict)
|
|
477
|
+
log: Any = None
|
|
478
|
+
|
|
479
|
+
def say(self, text: str) -> None:
|
|
480
|
+
if self.log:
|
|
481
|
+
self.log(text)
|
|
482
|
+
|
|
483
|
+
def sites(self) -> list[dict]:
|
|
484
|
+
sec = ((self.inventory or {}).get("kinds") or {}).get(self.kind) or {}
|
|
485
|
+
return [s for s in sec.get("sites") or [] if isinstance(s, dict)]
|
|
486
|
+
|
|
487
|
+
def item(self, ref: str, *, label: str = "", file: str = "", line: int = 0, path: bool = False, score: float = 0.0,
|
|
488
|
+
units: int = 1, why: str = "") -> dict:
|
|
489
|
+
"""One budget item (budget.item) of this kind's question: one call site the agent would judge."""
|
|
490
|
+
from .. import budget
|
|
491
|
+
return budget.item(f"kind_{self.kind}", ref, label=label, file=file, line=line, path=path, score=score, units=units, why=why)
|
|
492
|
+
|
|
493
|
+
def answer_key(self, text: str, *, runtime: str = "", version: str = "", prompt_version: str = "") -> str:
|
|
494
|
+
"""The verdict store's key of one item: its text (pattern, transaction shape), runtime and prompt version."""
|
|
495
|
+
from .. import verdicts
|
|
496
|
+
return verdicts.key(f"kind_{self.kind}", hashlib.sha256(text.encode("utf-8", "replace")).hexdigest()[:16], [], {}, runtime,
|
|
497
|
+
version, prompt_version)
|
|
498
|
+
|
|
499
|
+
def answer(self, key: str) -> dict | None:
|
|
500
|
+
from .. import verdicts
|
|
501
|
+
if self.verdicts is None or verdicts.wants_fresh(self.fresh):
|
|
502
|
+
return None
|
|
503
|
+
return self.verdicts.get(key)
|
|
504
|
+
|
|
505
|
+
def remember(self, key: str, record: dict) -> None:
|
|
506
|
+
if self.verdicts is not None:
|
|
507
|
+
self.verdicts.put(key, {"kind": f"kind_{self.kind}", **record})
|