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/coverage.py
ADDED
|
@@ -0,0 +1,1067 @@
|
|
|
1
|
+
"""Coverage: of everything in the repo, how much was found, understood and examined.
|
|
2
|
+
|
|
3
|
+
Every number here is counted from the stage files (inventory.json, rank.json,
|
|
4
|
+
bench.json) and from the status report gives each candidate, so `codecop report`
|
|
5
|
+
and `codecop coverage` can recompute it for a run of any age. No agent, no network.
|
|
6
|
+
|
|
7
|
+
The shape is documented in schemas/run_bundle.schema.json under `$defs.coverage`.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
from collections import Counter
|
|
14
|
+
from datetime import datetime, timezone
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from . import engines
|
|
18
|
+
from .rank import SYSTEM_TABLE, eligible as rank_eligible, in_paths, site_role
|
|
19
|
+
|
|
20
|
+
SCHEMA_VERSION = 1
|
|
21
|
+
ENTRY_KINDS = ("http", "workflow", "activity", "job", "consumer", "cli", "main")
|
|
22
|
+
UNRESOLVED = ("unresolved", "parameter")
|
|
23
|
+
WRITES = ("insert", "update", "delete")
|
|
24
|
+
ONE_OFF_ROLES = ("script", "migration", "tooling")
|
|
25
|
+
STATUSES = ("verified", "unverified", "rejected", "failed")
|
|
26
|
+
FUNNEL = ("found", "non_test", "resolved", "parsed", "engine_known", "understood", "with_entry_point")
|
|
27
|
+
# Why a call site was not looked at, first match wins. `sites` over all reasons plus the examined sites is every site.
|
|
28
|
+
REASONS = ("test", "script_or_migration", "no_sql_text", "unresolved_sql", "engine_unknown", "other_engine", "write", "not_a_read",
|
|
29
|
+
"no_table", "outside_paths", "unchanged", "budget_reached", "agent_failed", "not_request_path", "below_cutoff")
|
|
30
|
+
WRAPPER = "parameter" # resolution of a call site whose SQL arrives as a parameter of a wrapper
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def no_text(sites: list[dict]) -> dict:
|
|
34
|
+
"""Non-test call sites that hold no SQL text at all: a sink whose argument discover could not resolve, and wrappers
|
|
35
|
+
that receive their SQL as a parameter. They can not be ranked or matched to a query log (both read the text), so
|
|
36
|
+
they are counted here instead of being absent. {sites, unresolved, wrapper, by_engine}."""
|
|
37
|
+
rows = [s for s in sites if not is_test(s) and not (s.get("sql") or "").strip()]
|
|
38
|
+
return {"sites": len(rows), "wrapper": sum(1 for s in rows if s.get("resolution") == WRAPPER),
|
|
39
|
+
"unresolved": sum(1 for s in rows if s.get("resolution") != WRAPPER),
|
|
40
|
+
"by_engine": dict(Counter(engine_of(s) for s in rows).most_common())}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def is_test(site: dict) -> bool:
|
|
44
|
+
return bool(site.get("is_test")) or site.get("role") == "test"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def engine_of(site: dict) -> str:
|
|
48
|
+
return site.get("engine") or "unknown"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def entry_kind(site: dict) -> str:
|
|
52
|
+
"""The kind of the nearest entry point; `test` for test code, `none` when nothing was traced."""
|
|
53
|
+
if is_test(site):
|
|
54
|
+
return "test"
|
|
55
|
+
origins = site.get("origins") or []
|
|
56
|
+
return (origins[0].get("kind") or "none") if origins else "none"
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def unresolved_name(name: str) -> bool:
|
|
60
|
+
return name.startswith("?") or any(mark in name for mark in "«»…")
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _funnel(sites: list[dict]) -> dict:
|
|
64
|
+
"""Counts at each step. Every step after `non_test` counts non-test sites only; `understood` is all three of
|
|
65
|
+
resolved, parsed and engine_known."""
|
|
66
|
+
row = dict.fromkeys(FUNNEL, 0)
|
|
67
|
+
for s in sites:
|
|
68
|
+
row["found"] += 1
|
|
69
|
+
if is_test(s):
|
|
70
|
+
continue
|
|
71
|
+
row["non_test"] += 1
|
|
72
|
+
resolved = s.get("resolution") not in UNRESOLVED and bool(s.get("sql"))
|
|
73
|
+
parsed = bool(s.get("parse_ok"))
|
|
74
|
+
known = bool(s.get("engine"))
|
|
75
|
+
row["resolved"] += resolved
|
|
76
|
+
row["parsed"] += parsed
|
|
77
|
+
row["engine_known"] += known
|
|
78
|
+
row["understood"] += resolved and parsed and known
|
|
79
|
+
row["with_entry_point"] += bool(s.get("origins"))
|
|
80
|
+
return row
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _grouped(sites: list[dict], key) -> dict:
|
|
84
|
+
groups: dict[str, list[dict]] = {}
|
|
85
|
+
for s in sites:
|
|
86
|
+
groups.setdefault(key(s), []).append(s)
|
|
87
|
+
return {name: _funnel(rows) for name, rows in sorted(groups.items(), key=lambda kv: (-len(kv[1]), kv[0]))}
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _tables(inventory: dict, sites: list[dict]) -> dict:
|
|
91
|
+
definitions = inventory.get("tables") or []
|
|
92
|
+
defined = {t["name"].split(".")[-1] for t in definitions if not unresolved_name(t["name"])}
|
|
93
|
+
referenced: set[str] = set()
|
|
94
|
+
unresolved: set[str] = set()
|
|
95
|
+
by_engine: dict[str, set[str]] = {}
|
|
96
|
+
sites_unresolved = 0
|
|
97
|
+
for s in sites:
|
|
98
|
+
if is_test(s):
|
|
99
|
+
continue
|
|
100
|
+
hit = False
|
|
101
|
+
for name in s.get("tables") or []:
|
|
102
|
+
if unresolved_name(name):
|
|
103
|
+
unresolved.add(name)
|
|
104
|
+
hit = True
|
|
105
|
+
elif not SYSTEM_TABLE.match(name):
|
|
106
|
+
short = name.split(".")[-1]
|
|
107
|
+
referenced.add(short)
|
|
108
|
+
by_engine.setdefault(engine_of(s), set()).add(short)
|
|
109
|
+
sites_unresolved += hit
|
|
110
|
+
return {
|
|
111
|
+
"defined": len(defined),
|
|
112
|
+
"defined_with_unresolved_name": len(definitions) - sum(1 for t in definitions if not unresolved_name(t["name"])),
|
|
113
|
+
"referenced": len(referenced),
|
|
114
|
+
"referenced_defined": len(referenced & defined),
|
|
115
|
+
"referenced_undefined": len(referenced - defined),
|
|
116
|
+
"defined_unreferenced": len(defined - referenced),
|
|
117
|
+
"unresolved_names": len(unresolved),
|
|
118
|
+
"sites_with_unresolved_name": sites_unresolved,
|
|
119
|
+
"by_engine": {e: {"referenced": len(names), "referenced_undefined": len(names - defined)}
|
|
120
|
+
for e, names in sorted(by_engine.items(), key=lambda kv: (-len(kv[1]), kv[0]))},
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _is_eligible(site: dict, engine: str, paths: list[str]) -> bool:
|
|
125
|
+
try:
|
|
126
|
+
return rank_eligible(site, engine, paths)
|
|
127
|
+
except KeyError: # an inventory from before a field existed
|
|
128
|
+
return False
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _reason(site: dict, engine: str, paths: list[str]) -> str:
|
|
132
|
+
if is_test(site):
|
|
133
|
+
return "test"
|
|
134
|
+
if site_role(site) in ONE_OFF_ROLES:
|
|
135
|
+
return "script_or_migration"
|
|
136
|
+
if not (site.get("sql") or "").strip():
|
|
137
|
+
return "no_sql_text"
|
|
138
|
+
if site.get("resolution") in UNRESOLVED:
|
|
139
|
+
return "unresolved_sql"
|
|
140
|
+
if not site.get("engine"):
|
|
141
|
+
return "engine_unknown"
|
|
142
|
+
if site["engine"] != engine:
|
|
143
|
+
return "other_engine"
|
|
144
|
+
# labelled with the ranked engine, but the engine itself says it is not its SQL, or not a read it benchmarks
|
|
145
|
+
skipped = engines.get(engine).skip_reason(site.get("sql") or "") or engines.get(engine).site_skip_reason(site)
|
|
146
|
+
if skipped == "other_engine":
|
|
147
|
+
return skipped
|
|
148
|
+
if site.get("statement") in WRITES:
|
|
149
|
+
return "write"
|
|
150
|
+
if site.get("statement") != "select":
|
|
151
|
+
return "not_a_read"
|
|
152
|
+
tables = site.get("tables") or []
|
|
153
|
+
if not tables or all(SYSTEM_TABLE.match(t) for t in tables):
|
|
154
|
+
return "no_table"
|
|
155
|
+
if skipped:
|
|
156
|
+
return skipped
|
|
157
|
+
if not in_paths(site, paths):
|
|
158
|
+
return "outside_paths"
|
|
159
|
+
return "below_cutoff"
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _benchmarked(bench: dict | None) -> tuple[set[str], Counter]:
|
|
163
|
+
"""Finding labels whose baseline ran at the largest scale, and the variant verdicts there."""
|
|
164
|
+
scales = (bench or {}).get("scales") or []
|
|
165
|
+
if not scales:
|
|
166
|
+
return set(), Counter()
|
|
167
|
+
largest = scales[-1].get("findings") or []
|
|
168
|
+
ran = {f["finding"] for f in largest if (f.get("baseline") or {}).get("ok")}
|
|
169
|
+
verdicts = Counter(v.get("verdict") or "untested" for f in largest if f["finding"] in ran for v in f.get("variants") or [])
|
|
170
|
+
return ran, verdicts
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _not_benchmarked(bench: dict | None) -> set[str]:
|
|
174
|
+
"""Finding labels that were not measured at the largest scale because one of their tables was not built."""
|
|
175
|
+
scales = (bench or {}).get("scales") or []
|
|
176
|
+
return {f["finding"] for f in (scales[-1].get("findings") or []) if f.get("not_benchmarked")} if scales else set()
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _measured_load(matchdata: dict, stage_sets: dict[str, set[str]]) -> dict:
|
|
180
|
+
"""What share of the database's measured read load each step of the funnel stands for.
|
|
181
|
+
|
|
182
|
+
The load is bytes read by SELECTs in the workload window, from the real query log. A real statement counts
|
|
183
|
+
for a step when a call site it was matched to (exactly or through a template) reached that step. `likely`
|
|
184
|
+
matches are reported on their own and never counted as examined."""
|
|
185
|
+
queries = matchdata.get("queries") or []
|
|
186
|
+
w = matchdata.get("workload") or {}
|
|
187
|
+
total_bytes, total_exec = int(w.get("read_bytes") or 0), int(w.get("executions") or 0)
|
|
188
|
+
|
|
189
|
+
def part(rows: list[dict]) -> dict:
|
|
190
|
+
b, n = sum(q["read_bytes"] for q in rows), sum(q["executions"] for q in rows)
|
|
191
|
+
return {"shapes": len(rows), "read_bytes": b, "executions": n,
|
|
192
|
+
"share_of_read_bytes": round(b / total_bytes, 4) if total_bytes else 0.0,
|
|
193
|
+
"share_of_executions": round(n / total_exec, 4) if total_exec else 0.0}
|
|
194
|
+
|
|
195
|
+
sure = [q for q in queries if q["match"] in ("exact", "template", "tag")]
|
|
196
|
+
out = {
|
|
197
|
+
"engine": matchdata.get("engine", ""), "window_hours": matchdata.get("window_hours"), "since": matchdata.get("since", ""),
|
|
198
|
+
"read_bytes": total_bytes, "executions": total_exec, "shapes": int(w.get("shapes_total") or 0),
|
|
199
|
+
"kept": part(queries), # the heaviest shapes the pull kept; the rest was not looked at
|
|
200
|
+
"matched": part(sure),
|
|
201
|
+
"likely": part([q for q in queries if q["match"] in ("likely", "part")]), # located or guessed, not proven
|
|
202
|
+
"unmatched": part([q for q in queries if q["match"] == "none"]),
|
|
203
|
+
}
|
|
204
|
+
for step in ("examined", "candidate", "benchmarked", "verified"):
|
|
205
|
+
ids = stage_sets.get(step) or set()
|
|
206
|
+
out[step] = part([q for q in sure if ids.intersection(q["site_ids"])])
|
|
207
|
+
return out
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def compute(inventory: dict, rank: dict | None = None, bench: dict | None = None,
|
|
211
|
+
statuses: dict[str, str] | None = None, matchdata: dict | None = None) -> dict:
|
|
212
|
+
"""The coverage object. `statuses` maps a candidate's call-site id to its finding status (report's verdict).
|
|
213
|
+
`matchdata`: the real workload matched to call sites (db_match.json for the ranked engine), when there is one."""
|
|
214
|
+
sites = inventory.get("call_sites") or []
|
|
215
|
+
summary = inventory.get("summary") or {}
|
|
216
|
+
out = {
|
|
217
|
+
"schema_version": SCHEMA_VERSION,
|
|
218
|
+
"engine": (rank or {}).get("engine", ""),
|
|
219
|
+
"stages": {"discover": True, "rank": rank is not None, "bench": bench is not None},
|
|
220
|
+
"files": {"scanned": int(summary.get("files_scanned") or 0), "with_sql": len({s["file"] for s in sites})},
|
|
221
|
+
"sites": {**_funnel(sites), "by_engine": _grouped(sites, engine_of), "by_entry_kind": _grouped(sites, entry_kind)},
|
|
222
|
+
"tables": _tables(inventory, sites),
|
|
223
|
+
"no_text": no_text(sites),
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
by_id = {s["id"]: s for s in sites if s.get("id")}
|
|
227
|
+
engine = out["engine"]
|
|
228
|
+
paths = list((rank or {}).get("paths") or [])
|
|
229
|
+
eligible = [s for s in sites if _is_eligible(s, engine, paths)] if rank else []
|
|
230
|
+
|
|
231
|
+
def covered(ids) -> set[str]:
|
|
232
|
+
"""The call sites the given ids stand for: the site itself and every eligible site with the same SQL
|
|
233
|
+
(the shortlist keeps one site per distinct SQL)."""
|
|
234
|
+
hashes = {by_id[i].get("sql_hash") for i in ids if i in by_id} - {"", None}
|
|
235
|
+
return {i for i in ids if i in by_id} | {s["id"] for s in eligible if s.get("sql_hash") in hashes}
|
|
236
|
+
|
|
237
|
+
statuses = statuses or {}
|
|
238
|
+
stage_sets: dict[str, set[str]] = {}
|
|
239
|
+
if rank:
|
|
240
|
+
depth = rank.get("depth") or "top"
|
|
241
|
+
batches = rank.get("batches") # None for a rank.json from before batches: one call, all of it examined
|
|
242
|
+
done = {b["index"] for b in batches if b.get("status") == "done"} if batches is not None else None
|
|
243
|
+
why = {b["index"]: ("budget_reached" if b.get("reason") == "budget" else "agent_failed") for b in batches or []
|
|
244
|
+
if b.get("status") != "done"}
|
|
245
|
+
planned = rank.get("shortlist") or []
|
|
246
|
+
planned_ids = [s["id"] for s in planned]
|
|
247
|
+
examined_ids = [s["id"] for s in planned if done is None or s.get("batch") in done]
|
|
248
|
+
missed = {reason: covered([s["id"] for s in planned if why.get(s.get("batch")) == reason]) for reason in set(why.values())}
|
|
249
|
+
candidates = [c for c in rank.get("candidates") or [] if c["id"] in set(examined_ids)]
|
|
250
|
+
candidate_ids = [c["id"] for c in candidates]
|
|
251
|
+
ran, verdicts = _benchmarked(bench)
|
|
252
|
+
benchmarked_ids = [c["id"] for c in candidates if c["finding"] in ran]
|
|
253
|
+
verified_ids = [i for i in candidate_ids if statuses.get(i) == "verified"]
|
|
254
|
+
stage_sets = {"examined": covered(examined_ids), "candidate": covered(candidate_ids),
|
|
255
|
+
"benchmarked": covered(benchmarked_ids), "verified": covered(verified_ids)}
|
|
256
|
+
rejected = {r["id"]: r for r in rank.get("rejected") or [] if r.get("id") in set(examined_ids) - set(candidate_ids)}
|
|
257
|
+
status_counts = Counter(statuses.get(i, "unverified") for i in candidate_ids)
|
|
258
|
+
steps = ("select_sites", "examined_sites", "candidates", "benchmarked", "verified")
|
|
259
|
+
by_kind: dict[str, dict] = {}
|
|
260
|
+
for name, ids in zip(steps, ([s["id"] for s in eligible], stage_sets["examined"], candidate_ids, benchmarked_ids, verified_ids)):
|
|
261
|
+
for i in ids:
|
|
262
|
+
if i in by_id:
|
|
263
|
+
by_kind.setdefault(entry_kind(by_id[i]), dict.fromkeys(steps, 0))[name] += 1
|
|
264
|
+
out["ranked"] = {
|
|
265
|
+
"engine": engine,
|
|
266
|
+
"depth": depth,
|
|
267
|
+
"select_sites": len(eligible),
|
|
268
|
+
"select_sites_at_rank": int(rank.get("select_sites") or 0),
|
|
269
|
+
"distinct_sql": len({s.get("sql_hash") for s in eligible}),
|
|
270
|
+
"planned": len(planned_ids),
|
|
271
|
+
"batches": {"total": len(batches or []) or (1 if planned_ids else 0),
|
|
272
|
+
"done": len(done) if done is not None else (1 if planned_ids else 0),
|
|
273
|
+
"failed": sum(1 for b in batches or [] if b.get("status") == "failed"),
|
|
274
|
+
"skipped": sum(1 for b in batches or [] if b.get("status") == "skipped")},
|
|
275
|
+
"examined": len(examined_ids),
|
|
276
|
+
"examined_sites": len(stage_sets["examined"]),
|
|
277
|
+
"candidates": len(candidate_ids),
|
|
278
|
+
"rejected_by_agent": len(rejected),
|
|
279
|
+
"rejected_reasons": dict(Counter(r.get("code") or "other" for r in rejected.values()).most_common()),
|
|
280
|
+
"no_outcome": len(set(examined_ids) - set(candidate_ids) - set(rejected)),
|
|
281
|
+
"benchmarked": len(benchmarked_ids),
|
|
282
|
+
# candidates nothing was measured for because a table they read could not be built (they are `failed`)
|
|
283
|
+
"not_benchmarked": len([c for c in candidates if c["finding"] in _not_benchmarked(bench)]),
|
|
284
|
+
**{s: status_counts.get(s, 0) for s in STATUSES},
|
|
285
|
+
"variants": {"proposed": sum(len(c.get("variants") or []) for c in candidates),
|
|
286
|
+
"measured": sum(verdicts.values()), "by_verdict": dict(verdicts.most_common())},
|
|
287
|
+
"by_entry_kind": dict(sorted(by_kind.items(), key=lambda kv: (-kv[1]["select_sites"], kv[0]))),
|
|
288
|
+
}
|
|
289
|
+
examined = stage_sets["examined"]
|
|
290
|
+
scope = rank.get("scope") if isinstance(rank.get("scope"), dict) else None
|
|
291
|
+
in_scope = set(scope.get("site_ids") or []) if scope else None
|
|
292
|
+
if scope:
|
|
293
|
+
out["ranked"]["scope"] = {k: scope.get(k) for k in ("mode", "ref", "base", "files_changed", "functions_changed", "sites")}
|
|
294
|
+
reasons: dict[str, Counter] = {}
|
|
295
|
+
for s in sites:
|
|
296
|
+
sid = s.get("id")
|
|
297
|
+
if sid in examined:
|
|
298
|
+
continue
|
|
299
|
+
reason = next((r for r, ids in missed.items() if sid in ids), None) or _reason(s, engine, paths)
|
|
300
|
+
if reason == "below_cutoff" and in_scope is not None and sid not in in_scope:
|
|
301
|
+
reason = "unchanged" # a --changed-since scan: eligible, but the change does not touch it
|
|
302
|
+
if reason == "below_cutoff" and depth == "paths":
|
|
303
|
+
reason = "not_request_path"
|
|
304
|
+
reasons.setdefault(reason, Counter())[engine_of(s)] += 1
|
|
305
|
+
out["examined_sites"] = len(examined)
|
|
306
|
+
out["not_examined"] = [{"reason": r, "sites": sum(reasons[r].values()), "by_engine": dict(reasons[r].most_common())}
|
|
307
|
+
for r in REASONS if r in reasons]
|
|
308
|
+
else:
|
|
309
|
+
out["ranked"] = None
|
|
310
|
+
out["examined_sites"] = 0
|
|
311
|
+
out["not_examined"] = []
|
|
312
|
+
|
|
313
|
+
out["entry_points"] = _entry_points(inventory, sites, stage_sets)
|
|
314
|
+
out["measured_load"] = _measured_load(matchdata, stage_sets) if matchdata else None
|
|
315
|
+
return out
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def _entry_points(inventory: dict, sites: list[dict], stage_sets: dict[str, set[str]]) -> dict:
|
|
319
|
+
"""Entry points by kind, and how far down the funnel the SQL they reach got.
|
|
320
|
+
|
|
321
|
+
Which entry point reaches which site is read from `call_sites[].origins`, and discover keeps only the
|
|
322
|
+
nearest few origins per site. `reaching_sql` is exact (discover counts it per entry point); the later
|
|
323
|
+
steps are lower bounds whenever `sites_with_more_origins` is not zero."""
|
|
324
|
+
steps = ("reaching_examined", "reaching_candidate", "reaching_benchmarked", "reaching_verified")
|
|
325
|
+
listed = [e for e in inventory.get("entry_points") or [] if e.get("kind") != "test"]
|
|
326
|
+
known = {(e["kind"], e["name"], e["file"], e.get("line")) for e in listed}
|
|
327
|
+
reached: dict[str, set[tuple]] = {step: set() for step in steps}
|
|
328
|
+
reaching_sql: set[tuple] = set()
|
|
329
|
+
cut = 0
|
|
330
|
+
for s in sites:
|
|
331
|
+
if is_test(s):
|
|
332
|
+
continue
|
|
333
|
+
keys = [(o.get("kind"), o.get("name"), o.get("file"), o.get("line")) for o in s.get("origins") or []]
|
|
334
|
+
reaching_sql.update(keys)
|
|
335
|
+
if s.get("id") in stage_sets.get("examined", ()):
|
|
336
|
+
cut += (s.get("origin_count") or 0) > len(keys)
|
|
337
|
+
for step in steps:
|
|
338
|
+
if s.get("id") in stage_sets.get(step.removeprefix("reaching_"), ()):
|
|
339
|
+
reached[step].update(keys)
|
|
340
|
+
|
|
341
|
+
def row(entries: list[dict]) -> dict:
|
|
342
|
+
keys = {(e["kind"], e["name"], e["file"], e.get("line")) for e in entries}
|
|
343
|
+
return {
|
|
344
|
+
"total": len(entries),
|
|
345
|
+
"reaching_sql": sum(1 for e in entries if (e.get("sites") or 0) > 0 or
|
|
346
|
+
(e["kind"], e["name"], e["file"], e.get("line")) in reaching_sql),
|
|
347
|
+
**{step: len(keys & reached[step]) for step in steps},
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
kinds = list(ENTRY_KINDS) + sorted({e["kind"] for e in listed} - set(ENTRY_KINDS))
|
|
351
|
+
return {
|
|
352
|
+
**row(listed),
|
|
353
|
+
"by_kind": {k: row([e for e in listed if e["kind"] == k]) for k in kinds},
|
|
354
|
+
"test_entry_points": sum(1 for e in inventory.get("entry_points") or [] if e.get("kind") == "test"),
|
|
355
|
+
"sites_with_more_origins": cut,
|
|
356
|
+
"unlisted_origins": len(reaching_sql - known),
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def from_stages(inventory: dict, rank: dict | None, profile: dict | None, bench: dict | None, facts=None) -> dict:
|
|
361
|
+
"""Coverage from whatever stage files a run left behind. `facts`: the pulled real-database files, if any."""
|
|
362
|
+
if rank is None:
|
|
363
|
+
engines_seen = (facts.matchdata.get("engines") or {}) if facts else {}
|
|
364
|
+
return compute(inventory, matchdata=next(iter(engines_seen.values()), None))
|
|
365
|
+
from .report import build_findings # report imports this module
|
|
366
|
+
|
|
367
|
+
return build_findings(rank, profile, bench, inventory, facts)["coverage"]
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def table_rows(cov: dict) -> dict[str, list[list[str]]]:
|
|
371
|
+
"""The funnel as rows of text, for `codecop coverage`. One list of rows per table, the first row is the header."""
|
|
372
|
+
def n(value) -> str:
|
|
373
|
+
return f"{value:,}" if isinstance(value, int) else str(value)
|
|
374
|
+
|
|
375
|
+
sites = cov["sites"]
|
|
376
|
+
funnel = [["", "found", "not test", "resolved", "parses", "engine known", "all three", "entry point"]]
|
|
377
|
+
for label, row in [("all", sites)] + [(f"engine {k}", v) for k, v in sites["by_engine"].items()] \
|
|
378
|
+
+ [(f"from {k}", v) for k, v in sites["by_entry_kind"].items()]:
|
|
379
|
+
funnel.append([label] + [n(row[k]) for k in FUNNEL])
|
|
380
|
+
ep = cov["entry_points"]
|
|
381
|
+
entries = [["entry points", "total", "reach SQL", "examined", "candidate", "benchmarked", "verified"]]
|
|
382
|
+
for label, row in [("all", ep)] + list(ep["by_kind"].items()):
|
|
383
|
+
entries.append([label] + [n(row[k]) for k in ("total", "reaching_sql", "reaching_examined", "reaching_candidate",
|
|
384
|
+
"reaching_benchmarked", "reaching_verified")])
|
|
385
|
+
t = cov["tables"]
|
|
386
|
+
tables = [["tables", "defined", "referenced", "referenced, no definition", "unresolved names"],
|
|
387
|
+
["all", n(t["defined"]), n(t["referenced"]), n(t["referenced_undefined"]), n(t["unresolved_names"])]]
|
|
388
|
+
tables += [[f"engine {k}", "", n(v["referenced"]), n(v["referenced_undefined"]), ""] for k, v in t["by_engine"].items()]
|
|
389
|
+
out = {"sites": funnel, "entry_points": entries, "tables": tables}
|
|
390
|
+
nt = cov.get("no_text") or {}
|
|
391
|
+
if nt.get("sites"):
|
|
392
|
+
out["no_text"] = [["no SQL text (never ranked or matched)", "sites", "unresolved", "wrapper", "by engine"],
|
|
393
|
+
["all", n(nt["sites"]), n(nt["unresolved"]), n(nt["wrapper"]),
|
|
394
|
+
", ".join(f"{k} {v:,}" for k, v in (nt.get("by_engine") or {}).items())]]
|
|
395
|
+
r = cov.get("ranked")
|
|
396
|
+
if r:
|
|
397
|
+
b = r["batches"]
|
|
398
|
+
out["ranked"] = [
|
|
399
|
+
[f"{r['engine']} ({r['depth']})", "SELECT sites", "examined", "candidates", "rejected by agent", "benchmarked",
|
|
400
|
+
"verified", "unverified", "rejected", "failed"],
|
|
401
|
+
["all", n(r["select_sites"]), f"{n(r['examined'])} queries ({n(r['examined_sites'])} sites, {b['done']}/{b['total']} batches)",
|
|
402
|
+
n(r["candidates"]), n(r["rejected_by_agent"]), n(r["benchmarked"]), n(r["verified"]), n(r["unverified"]),
|
|
403
|
+
n(r["rejected"]), n(r["failed"])],
|
|
404
|
+
] + [[f"from {k}", n(v["select_sites"]), n(v["examined_sites"]), n(v["candidates"]), "", n(v["benchmarked"]),
|
|
405
|
+
n(v["verified"]), "", "", ""] for k, v in r["by_entry_kind"].items()]
|
|
406
|
+
out["not_examined"] = [["not examined", "sites", "by engine"]] + [
|
|
407
|
+
[x["reason"], n(x["sites"]), ", ".join(f"{k} {v:,}" for k, v in x["by_engine"].items())] for x in cov["not_examined"]]
|
|
408
|
+
m = cov.get("measured_load")
|
|
409
|
+
if m:
|
|
410
|
+
def gb(part: dict) -> list[str]:
|
|
411
|
+
return [f"{part['read_bytes'] / 1e9:,.1f} GB", f"{part['share_of_read_bytes']:.1%}", n(part["executions"]), f"{part['share_of_executions']:.1%}"]
|
|
412
|
+
window = f"last {m['window_hours']} h" if m.get("window_hours") else "since statistics reset"
|
|
413
|
+
out["measured_load"] = [[f"measured load ({window})", "bytes read", "share", "executions", "share"],
|
|
414
|
+
["all SELECTs", f"{m['read_bytes'] / 1e9:,.1f} GB", "100%", n(m["executions"]), "100%"]] + [
|
|
415
|
+
[label, *gb(m[key])] for label, key in (("heaviest shapes kept", "kept"), ("matched to a call site", "matched"),
|
|
416
|
+
("likely match (not counted)", "likely"), ("no call site in this repo", "unmatched"),
|
|
417
|
+
("examined", "examined"), ("candidates", "candidate"),
|
|
418
|
+
("benchmarked", "benchmarked"), ("verified", "verified"))]
|
|
419
|
+
return out
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
# =====================================================================================================================
|
|
423
|
+
# Repository coverage: the judged share of the query and write sites. This is THE coverage number: `codecop coverage`,
|
|
424
|
+
# the report, the upload, the console and `codecop ci comment` all read it from here.
|
|
425
|
+
#
|
|
426
|
+
# D = every non-test call site that sends a query or a write (SELECT, INSERT, UPDATE, DELETE) in any engine, plus sites
|
|
427
|
+
# with no SQL text, plus the sites the per-library probes find and discovery does not (discover/probes.py). Migration
|
|
428
|
+
# DDL, session statements (SET, BEGIN, ...) and other statements are counted apart, on their own line (`left_out`).
|
|
429
|
+
#
|
|
430
|
+
# A site is judged when its statement has an outcome in the run of its engine: fixed (improved), blocked (needs another
|
|
431
|
+
# fix) or nothing_to_gain; or when it is a member of a loop pattern that was fixed or needs another fix. Every site that
|
|
432
|
+
# shares a site's SQL (sql_hash) shares its outcome. Judged by measurement = fixed, blocked, or nothing to gain decided
|
|
433
|
+
# by the sandbox or the measured load (`from` sandbox|measured); the rest (the agent's word, catalog row counts) is
|
|
434
|
+
# judged "on the agent's word or catalog" and counted apart.
|
|
435
|
+
#
|
|
436
|
+
# Funnel (a site counts at a stage when it passed every stage before; a judged site passed them all):
|
|
437
|
+
# sites -> statement obtained -> plans (parses, and plans when a plan gate ran) -> runs with rows -> outcome
|
|
438
|
+
# Every site that is not judged carries exactly one reason and one next step (coverage_reasons.py).
|
|
439
|
+
#
|
|
440
|
+
# A multi-engine out directory (`--engine auto`: engines.json + one directory per engine, one shared inventory) gives
|
|
441
|
+
# one number for the whole repository: a site is judged when the run of its own engine judged it.
|
|
442
|
+
# =====================================================================================================================
|
|
443
|
+
|
|
444
|
+
REPO_SCHEMA_VERSION = 1
|
|
445
|
+
D_STATEMENTS = ("select", "insert", "update", "delete")
|
|
446
|
+
JUDGED_STATES = ("fixed", "blocked", "nothing_to_gain")
|
|
447
|
+
MEASURED_FROM = ("sandbox", "measured")
|
|
448
|
+
STAGES = ("sites", "obtained", "plans", "runs", "outcome")
|
|
449
|
+
STAGE_LABELS = {"sites": "call sites", "obtained": "statement obtained", "plans": "plans", "runs": "runs, returns rows", "outcome": "outcome"}
|
|
450
|
+
LEGACY_REASONS = {"sql_assembled_at_run_time": "assembled_needs_pull"}
|
|
451
|
+
SETTINGS = {
|
|
452
|
+
# `codecop coverage --check` fails under this judged share (percent of the sites; 0 = no floor)
|
|
453
|
+
"min_judged_share": 0.0,
|
|
454
|
+
# ... or when the judged share dropped by more than this many points against the previous scan of the branch
|
|
455
|
+
"max_drop": 5.0,
|
|
456
|
+
# how many scans `coverage_history.json` keeps
|
|
457
|
+
"history": 200,
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
def coverage_settings(config: dict | None) -> dict:
|
|
462
|
+
"""The `[coverage]` table of codecop.toml over the defaults. A share given as a fraction (0.65) is read as 65%."""
|
|
463
|
+
out = dict(SETTINGS)
|
|
464
|
+
for k, v in (config or {}).items():
|
|
465
|
+
if k in SETTINGS and isinstance(v, (int, float)) and not isinstance(v, bool):
|
|
466
|
+
out[k] = float(v) if k != "history" else int(v)
|
|
467
|
+
if 0 < out["min_judged_share"] <= 1:
|
|
468
|
+
out["min_judged_share"] *= 100
|
|
469
|
+
return out
|
|
470
|
+
|
|
471
|
+
|
|
472
|
+
def _load(path: Path):
|
|
473
|
+
try:
|
|
474
|
+
return json.loads(path.read_text())
|
|
475
|
+
except (OSError, ValueError):
|
|
476
|
+
return None
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
class EngineRun:
|
|
480
|
+
"""The stage files of one engine's run that coverage reads. Any of them may be missing (a run that stopped)."""
|
|
481
|
+
|
|
482
|
+
def __init__(self, engine: str, findings: dict | None = None, rank: dict | None = None, bench: dict | None = None,
|
|
483
|
+
loops: dict | None = None, match: dict | None = None, directory: str = ""):
|
|
484
|
+
self.engine = engine
|
|
485
|
+
self.findings = findings or {}
|
|
486
|
+
self.rank = rank or {}
|
|
487
|
+
self.bench = bench or {}
|
|
488
|
+
self.loops = loops or {}
|
|
489
|
+
self.match = match or {}
|
|
490
|
+
self.directory = directory
|
|
491
|
+
|
|
492
|
+
@classmethod
|
|
493
|
+
def from_dir(cls, d: Path, engine: str = "") -> "EngineRun | None":
|
|
494
|
+
findings = _load(d / "findings.json") or {}
|
|
495
|
+
rank = _load(d / "rank.json") or {}
|
|
496
|
+
engine = engine or findings.get("engine") or rank.get("engine") or ""
|
|
497
|
+
if not engine:
|
|
498
|
+
return None
|
|
499
|
+
match_doc = _load(d / "db_match.json") or (_load(d.parent / "db_match.json") if d.parent != d else None) or {}
|
|
500
|
+
run = cls(engine, findings, rank, _load(d / "bench.json"), _load(d / "loops.json"),
|
|
501
|
+
(match_doc.get("engines") or {}).get(engine), d.name)
|
|
502
|
+
run.baseline = _load(d / "baseline.json") or {}
|
|
503
|
+
return run
|
|
504
|
+
|
|
505
|
+
def outcomes(self, hash_of: dict[str, str]) -> tuple[dict[str, dict], set[str], set[str]]:
|
|
506
|
+
"""(outcome by sql_hash, hashes asked about, hashes whose baseline ran and read rows)."""
|
|
507
|
+
f = self.findings
|
|
508
|
+
oc: dict[str, dict] = {}
|
|
509
|
+
for x in f.get("findings") or []:
|
|
510
|
+
o = dict(x.get("outcome") or {})
|
|
511
|
+
o["_finding"] = x.get("finding") or x.get("label") or ""
|
|
512
|
+
oc[x["id"]] = o
|
|
513
|
+
# what the free baseline pass measured (bench.json outcomes by finding label, baseline.json: label -> call sites),
|
|
514
|
+
# also for statements the report then filed under the agent's verdict
|
|
515
|
+
bench_oc = (self.bench or {}).get("outcomes") or {}
|
|
516
|
+
measured_of: dict[str, dict] = {}
|
|
517
|
+
for st in (getattr(self, "baseline", None) or {}).get("statements") or []:
|
|
518
|
+
o = bench_oc.get(st.get("finding") or "") if isinstance(bench_oc, dict) else None
|
|
519
|
+
if isinstance(o, dict) and o.get("state") in JUDGED_STATES and o.get("from") in MEASURED_FROM:
|
|
520
|
+
for sid in st.get("site_ids") or []:
|
|
521
|
+
measured_of.setdefault(sid, {**o, "_finding": st.get("finding")})
|
|
522
|
+
for r in f.get("rejected_by_agent") or []:
|
|
523
|
+
if r.get("id") and r["id"] not in oc:
|
|
524
|
+
oc[r["id"]] = dict(measured_of.get(r["id"]) or r.get("outcome") or {})
|
|
525
|
+
for sid, o in measured_of.items():
|
|
526
|
+
cur = oc.get(sid)
|
|
527
|
+
if cur is None or (cur.get("state") not in ("fixed", "blocked") and cur.get("from") not in MEASURED_FROM):
|
|
528
|
+
oc[sid] = dict(o) # a measurement beats an opinion about the same statement
|
|
529
|
+
for u in (f.get("outcomes") or {}).get("unanswered") or []:
|
|
530
|
+
if u.get("id"):
|
|
531
|
+
oc.setdefault(u["id"], {"state": u.get("state"), "reason": u.get("reason")})
|
|
532
|
+
base_ok: dict[str, bool] = {}
|
|
533
|
+
for sc in self.bench.get("scales") or []:
|
|
534
|
+
for bf in sc.get("findings") or []:
|
|
535
|
+
b = bf.get("baseline") or {}
|
|
536
|
+
base_ok[bf.get("finding")] = base_ok.get(bf.get("finding"), False) or (bool(b.get("ok")) and (b.get("read_rows") or 0) > 0)
|
|
537
|
+
label_of = {x["id"]: x.get("finding") for x in f.get("findings") or [] if x.get("id")}
|
|
538
|
+
by_hash: dict[str, dict] = {}
|
|
539
|
+
ran: set[str] = set()
|
|
540
|
+
for qid, o in oc.items():
|
|
541
|
+
h = hash_of.get(qid)
|
|
542
|
+
if not h:
|
|
543
|
+
continue
|
|
544
|
+
cur = by_hash.get(h)
|
|
545
|
+
measured = lambda x: x.get("state") in ("fixed", "blocked") or x.get("from") in MEASURED_FROM # noqa: E731
|
|
546
|
+
if cur is None or (o.get("state") in JUDGED_STATES and cur.get("state") not in JUDGED_STATES) or \
|
|
547
|
+
(o.get("state") in JUDGED_STATES and measured(o) and not measured(cur)):
|
|
548
|
+
by_hash[h] = o # a measurement beats an opinion about the same statement
|
|
549
|
+
if base_ok.get(label_of.get(qid)):
|
|
550
|
+
ran.add(h)
|
|
551
|
+
asked = {hash_of[x["id"]] for k in ("shortlist", "rejected", "candidates") for x in self.rank.get(k) or []
|
|
552
|
+
if isinstance(x, dict) and hash_of.get(x.get("id"))}
|
|
553
|
+
asked |= set(by_hash)
|
|
554
|
+
return by_hash, asked, ran
|
|
555
|
+
|
|
556
|
+
def loop_states(self) -> dict[str, str]:
|
|
557
|
+
"""site id -> the best state of a loop pattern it is a member of."""
|
|
558
|
+
out: dict[str, str] = {}
|
|
559
|
+
for pat in self.loops.get("patterns") or []:
|
|
560
|
+
st = (pat.get("outcome") or {}).get("state") or ""
|
|
561
|
+
for mem in pat.get("members") or []:
|
|
562
|
+
sid = mem.get("site_id")
|
|
563
|
+
if sid and (st in JUDGED_STATES or sid not in out):
|
|
564
|
+
out[sid] = st
|
|
565
|
+
return out
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
def out_layout(out_dir: Path) -> tuple[Path, dict | None, list[EngineRun]]:
|
|
569
|
+
"""(directory holding the shared inventory, engines.json or None, one EngineRun per engine). Works on a single-engine
|
|
570
|
+
out directory, on the top of a multi-engine one, and on one engine's directory inside it (it then reads the whole)."""
|
|
571
|
+
out_dir = Path(out_dir)
|
|
572
|
+
top = out_dir
|
|
573
|
+
if not (top / "engines.json").exists() and (top.parent / "engines.json").exists():
|
|
574
|
+
top = top.parent
|
|
575
|
+
index = _load(top / "engines.json")
|
|
576
|
+
runs: list[EngineRun] = []
|
|
577
|
+
if isinstance(index, dict) and isinstance(index.get("engines"), list):
|
|
578
|
+
dirs = [(top / (e.get("dir") or e.get("engine") or ""), e.get("engine") or "") for e in index["engines"]]
|
|
579
|
+
# engines.json is written after each engine finishes: the engine whose report runs now is not in it yet
|
|
580
|
+
listed = {d.resolve() for d, _ in dirs if d.is_dir()}
|
|
581
|
+
dirs += [(d, "") for d in sorted(top.iterdir()) if d.is_dir() and d.resolve() not in listed and (d / "inventory.json").exists()
|
|
582
|
+
and ((d / "findings.json").exists() or (d / "rank.json").exists())]
|
|
583
|
+
for d, eng in dirs:
|
|
584
|
+
run = EngineRun.from_dir(d, eng) if d.is_dir() else None
|
|
585
|
+
if run and run.engine not in {r.engine for r in runs}:
|
|
586
|
+
runs.append(run)
|
|
587
|
+
return top, index, runs
|
|
588
|
+
run = EngineRun.from_dir(out_dir)
|
|
589
|
+
return out_dir, None, [run] if run else []
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
def _is_d(site: dict, got: str) -> bool:
|
|
593
|
+
if (site.get("pass_through") or site.get("other_store")) and got == "none":
|
|
594
|
+
return False # a wrapper's own sink call: its callers are the sites; or a search-engine request, not SQL
|
|
595
|
+
return (site.get("statement") or "unknown") in D_STATEMENTS or got == "none"
|
|
596
|
+
|
|
597
|
+
|
|
598
|
+
def _left_out_kind(site: dict, mech: str) -> str:
|
|
599
|
+
st = site.get("statement") or "unknown"
|
|
600
|
+
if st == "ddl":
|
|
601
|
+
return "migration_ddl" if mech == "sqlfile_migration_ddl" or site_role(site) == "migration" else "ddl"
|
|
602
|
+
if st == "other":
|
|
603
|
+
return "session_and_other"
|
|
604
|
+
if site.get("pass_through"):
|
|
605
|
+
return "wrapper_pass_through"
|
|
606
|
+
if site.get("other_store"):
|
|
607
|
+
return "other_store"
|
|
608
|
+
return "unknown_kind"
|
|
609
|
+
|
|
610
|
+
|
|
611
|
+
def _reason_of(site: dict, got: str, run_engines: set[str], run: dict) -> str:
|
|
612
|
+
"""The first reason that applies, in funnel order."""
|
|
613
|
+
if got == "none":
|
|
614
|
+
return "no_statement_text"
|
|
615
|
+
if got == "partial":
|
|
616
|
+
return "run_time_parts"
|
|
617
|
+
if not site.get("parse_ok"):
|
|
618
|
+
return "does_not_parse"
|
|
619
|
+
plan = site.get("plan")
|
|
620
|
+
if isinstance(plan, dict) and plan.get("ok") is False:
|
|
621
|
+
return plan.get("reason") or "does_not_plan"
|
|
622
|
+
engine = site.get("engine") or ""
|
|
623
|
+
if not engine:
|
|
624
|
+
return "engine_unknown"
|
|
625
|
+
if engine not in run_engines:
|
|
626
|
+
return "other_engine"
|
|
627
|
+
if run.get("state") == "not_judged" and run.get("reason"):
|
|
628
|
+
return LEGACY_REASONS.get(run["reason"], run["reason"])
|
|
629
|
+
if (site.get("statement") or "") in WRITES:
|
|
630
|
+
return "write_never_benchmarked"
|
|
631
|
+
if not run.get("asked"):
|
|
632
|
+
return "select_never_asked"
|
|
633
|
+
return "variants_not_asked" if run.get("ran") else "asked_no_outcome"
|
|
634
|
+
|
|
635
|
+
|
|
636
|
+
KINDS = ("read", "write", "kind_unknown")
|
|
637
|
+
# "unknown": the site's SQL or engine is not known (no statement, run-time parts, missed by discovery, engine unknown)
|
|
638
|
+
UNKNOWN_ALSO = ("engine_unknown",)
|
|
639
|
+
|
|
640
|
+
|
|
641
|
+
def kind_of(row: dict) -> str:
|
|
642
|
+
"""read (SELECT), write (INSERT/UPDATE/DELETE) or kind_unknown (no statement text, or found only by a probe): a site
|
|
643
|
+
of unknown kind may be a read, so the read view counts it."""
|
|
644
|
+
st = row.get("statement") or "unknown"
|
|
645
|
+
return "read" if st == "select" else "write" if st in WRITES else "kind_unknown"
|
|
646
|
+
|
|
647
|
+
|
|
648
|
+
def _is_unknown(reason: str) -> bool:
|
|
649
|
+
from . import coverage_reasons as R
|
|
650
|
+
return reason in UNKNOWN_ALSO or R.get(reason).stage == "obtained"
|
|
651
|
+
|
|
652
|
+
|
|
653
|
+
def kind_view(rows: list[dict], kinds: tuple[str, ...]) -> dict:
|
|
654
|
+
"""The judged, measured and unknown shares of the sites of the given kinds. The read view takes `read` and
|
|
655
|
+
`kind_unknown` (a site whose statement is not known may be a read; it is counted, never dropped)."""
|
|
656
|
+
sel = [r for r in rows if r.get("kind", kind_of(r)) in kinds]
|
|
657
|
+
n = len(sel)
|
|
658
|
+
|
|
659
|
+
def pct(k: int) -> float:
|
|
660
|
+
return round(100 * k / n, 1) if n else 0.0
|
|
661
|
+
|
|
662
|
+
judged = [r for r in sel if r["state"] != "not_judged"]
|
|
663
|
+
measured = sum(1 for r in judged if r["measured"])
|
|
664
|
+
unknown = Counter(r["reason"] for r in sel if r["state"] == "not_judged" and _is_unknown(r["reason"]))
|
|
665
|
+
other = Counter(r["reason"] for r in sel if r["state"] == "not_judged" and not _is_unknown(r["reason"]))
|
|
666
|
+
by_engine: dict[str, dict] = {}
|
|
667
|
+
for r in sel:
|
|
668
|
+
e = by_engine.setdefault(r["engine"], {"sites": 0, "judged": 0, "judged_measured": 0, "unknown": 0})
|
|
669
|
+
e["sites"] += 1
|
|
670
|
+
e["judged"] += r["state"] != "not_judged"
|
|
671
|
+
e["judged_measured"] += r["measured"]
|
|
672
|
+
e["unknown"] += r["state"] == "not_judged" and _is_unknown(r["reason"])
|
|
673
|
+
return {"kinds": list(kinds), "sites": n, "kind_unknown": sum(1 for r in sel if r.get("kind", kind_of(r)) == "kind_unknown"),
|
|
674
|
+
"judged": len(judged), "judged_share": pct(len(judged)),
|
|
675
|
+
"judged_measured": measured, "judged_measured_share": pct(measured),
|
|
676
|
+
"unknown": sum(unknown.values()), "unknown_share": pct(sum(unknown.values())),
|
|
677
|
+
"known_not_judged": sum(other.values()), "known_not_judged_share": pct(sum(other.values())),
|
|
678
|
+
"outcomes": {"improved": sum(r["state"] == "fixed" for r in judged), "needs_another_fix": sum(r["state"] == "blocked" for r in judged),
|
|
679
|
+
"nothing_to_gain_measured": sum(r["state"] == "nothing_to_gain" and r["measured"] for r in judged),
|
|
680
|
+
"nothing_to_gain_word": sum(r["state"] == "nothing_to_gain" and not r["measured"] for r in judged)},
|
|
681
|
+
"unknown_by_reason": dict(unknown.most_common()), "not_judged_by_reason": dict(other.most_common()),
|
|
682
|
+
"by_engine": dict(sorted(by_engine.items(), key=lambda kv: -kv[1]["sites"]))}
|
|
683
|
+
|
|
684
|
+
|
|
685
|
+
def repository(inventory: dict, runs: list[EngineRun], probes: dict | None = None, *, with_sites: bool = False,
|
|
686
|
+
families: dict | None = None) -> dict:
|
|
687
|
+
"""The repository coverage object (schemas/run_bundle.schema.json `$defs.repository_coverage`).
|
|
688
|
+
|
|
689
|
+
`runs`: one EngineRun per engine that was scanned (a single-engine scan: one). `probes`: discover/probes.missed()
|
|
690
|
+
for this inventory (inventory["probes"] when discover stored it); None counts no missed sites and says so."""
|
|
691
|
+
from . import coverage_reasons as R, mechanism
|
|
692
|
+
|
|
693
|
+
all_sites = inventory.get("call_sites") or []
|
|
694
|
+
sites = [s for s in all_sites if not is_test(s)]
|
|
695
|
+
hash_of = {s["id"]: s.get("sql_hash") for s in all_sites if s.get("id")}
|
|
696
|
+
run_engines = {r.engine for r in runs}
|
|
697
|
+
per_engine = {}
|
|
698
|
+
for r in runs:
|
|
699
|
+
by_hash, asked, ran = r.outcomes(hash_of)
|
|
700
|
+
per_engine[r.engine] = (by_hash, asked, ran, r.loop_states())
|
|
701
|
+
if probes is None:
|
|
702
|
+
probes = inventory.get("probes") if isinstance(inventory.get("probes"), dict) else None
|
|
703
|
+
missed = (probes or {}).get("missed") or []
|
|
704
|
+
|
|
705
|
+
rows: list[dict] = []
|
|
706
|
+
left_out: Counter = Counter()
|
|
707
|
+
for s in sites:
|
|
708
|
+
mech, got = mechanism.of(s)
|
|
709
|
+
fam_state = ""
|
|
710
|
+
own_hash = s.get("sql_hash")
|
|
711
|
+
if families and s.get("id") in families: # statement families (families/coverage_hook.py): run-time-built sites
|
|
712
|
+
from .families.coverage_hook import apply as _family
|
|
713
|
+
s, got, fam_state, ran_family, fam_from = _family(s, got, families[s["id"]])
|
|
714
|
+
if not _is_d(s, got):
|
|
715
|
+
left_out[_left_out_kind(s, mech)] += 1
|
|
716
|
+
continue
|
|
717
|
+
eng = s.get("engine") or ""
|
|
718
|
+
h = s.get("sql_hash")
|
|
719
|
+
state, frm, basis, reason_o, asked, ran_ = "", "", "", "", False, False
|
|
720
|
+
if eng in per_engine:
|
|
721
|
+
by_hash, asked_h, ran_h, loops = per_engine[eng]
|
|
722
|
+
# a run-time-built site is measured through its family's variant, whose finding carries the site's own id
|
|
723
|
+
# (so its outcome is filed under the site's own hash): either hash finds it
|
|
724
|
+
hs = [x for x in (h, own_hash) if x]
|
|
725
|
+
o = next((by_hash[x] for x in hs if (by_hash.get(x) or {}).get("state") in JUDGED_STATES), None) \
|
|
726
|
+
or next((by_hash[x] for x in hs if x in by_hash), {})
|
|
727
|
+
state, frm, reason_o = o.get("state") or "", o.get("from") or "", o.get("reason") or ""
|
|
728
|
+
basis = (o.get("evidence") or {}).get("basis") or ""
|
|
729
|
+
asked, ran_ = any(x in asked_h for x in hs), any(x in ran_h for x in hs)
|
|
730
|
+
if loops.get(s.get("id")) in JUDGED_STATES and (state not in JUDGED_STATES or
|
|
731
|
+
(loops[s["id"]] == "fixed" and state != "fixed")):
|
|
732
|
+
# a loop fixed by batching is the site's fix even when one run of its statement is at the floor
|
|
733
|
+
state, frm, reason_o = loops[s["id"]], "sandbox", "loop"
|
|
734
|
+
if fam_state and state not in JUDGED_STATES:
|
|
735
|
+
state, frm, ran_ = fam_state, fam_from, ran_ or ran_family
|
|
736
|
+
basis = "catalog" if fam_from == "catalog" else basis
|
|
737
|
+
if state not in JUDGED_STATES and site_role(s) == "migration" and not is_test(s):
|
|
738
|
+
# a migration, seed or backfill runs once per deployment: nothing to gain, by rule (never asked, never indexed)
|
|
739
|
+
state, frm, basis, reason_o = "nothing_to_gain", "rule", "runs_once", "runs_once"
|
|
740
|
+
judged = state in JUDGED_STATES
|
|
741
|
+
measured = judged and (state in ("fixed", "blocked") or frm in MEASURED_FROM)
|
|
742
|
+
row = {"id": s.get("id"), "file": s.get("file"), "line": s.get("line"), "engine": eng or "unknown",
|
|
743
|
+
"statement": s.get("statement") or "unknown", "mechanism": mech, "obtained": got,
|
|
744
|
+
"state": state if judged else "not_judged", "measured": measured}
|
|
745
|
+
if judged:
|
|
746
|
+
row["basis"] = "measured" if measured else ("catalog" if basis == "catalog" else "runs_once" if basis == "runs_once" else "agent")
|
|
747
|
+
if reason_o == "loop":
|
|
748
|
+
row["via_loop"] = True
|
|
749
|
+
flags_obtained = judged or got == "obtained"
|
|
750
|
+
plan = s.get("plan")
|
|
751
|
+
flags_plans = judged or (flags_obtained and bool(s.get("parse_ok")) and not (isinstance(plan, dict) and plan.get("ok") is False))
|
|
752
|
+
flags_runs = judged or (flags_plans and ran_)
|
|
753
|
+
row["stage"] = "outcome" if judged else "runs" if flags_runs else "plans" if flags_plans else "obtained" if flags_obtained else "sites"
|
|
754
|
+
if not judged:
|
|
755
|
+
row["reason"] = _reason_of(s, got, run_engines, {"state": state, "reason": reason_o, "asked": asked, "ran": ran_})
|
|
756
|
+
rows.append(row)
|
|
757
|
+
for m in missed:
|
|
758
|
+
rows.append({"id": None, "file": m.get("file"), "line": m.get("line"), "engine": "unknown", "statement": "unknown",
|
|
759
|
+
"mechanism": "missed", "obtained": "none", "state": "not_judged", "measured": False, "stage": "sites",
|
|
760
|
+
"reason": "missed_by_discovery", "library": m.get("library")})
|
|
761
|
+
|
|
762
|
+
n = len(rows)
|
|
763
|
+
order = {k: i for i, k in enumerate(STAGES)}
|
|
764
|
+
|
|
765
|
+
def share(k: int, d: int = 0) -> float:
|
|
766
|
+
d = d or n
|
|
767
|
+
return round(100 * k / d, 1) if d else 0.0
|
|
768
|
+
|
|
769
|
+
reached = {st: sum(1 for r in rows if order[r["stage"]] >= order[st]) for st in STAGES}
|
|
770
|
+
judged_rows = [r for r in rows if r["state"] != "not_judged"]
|
|
771
|
+
measured_n = sum(1 for r in judged_rows if r["measured"])
|
|
772
|
+
outcomes = {"improved": sum(r["state"] == "fixed" for r in judged_rows), "needs_another_fix": sum(r["state"] == "blocked" for r in judged_rows),
|
|
773
|
+
"nothing_to_gain_measured": sum(r["state"] == "nothing_to_gain" and r["measured"] for r in judged_rows),
|
|
774
|
+
"nothing_to_gain_catalog": sum(r.get("basis") == "catalog" for r in judged_rows),
|
|
775
|
+
"nothing_to_gain_agent": sum(r.get("basis") == "agent" for r in judged_rows),
|
|
776
|
+
"nothing_to_gain_runs_once": sum(r.get("basis") == "runs_once" for r in judged_rows),
|
|
777
|
+
"via_loop": sum(bool(r.get("via_loop")) for r in judged_rows)}
|
|
778
|
+
# lost at each stage, grouped by reason: the stage a site did not reach
|
|
779
|
+
lost: dict[str, Counter] = {}
|
|
780
|
+
reasons: Counter = Counter()
|
|
781
|
+
for r in rows:
|
|
782
|
+
if r["state"] == "not_judged":
|
|
783
|
+
nxt = STAGES[order[r["stage"]] + 1]
|
|
784
|
+
lost.setdefault(nxt, Counter())[r["reason"]] += 1
|
|
785
|
+
reasons[r["reason"]] += 1
|
|
786
|
+
funnel = []
|
|
787
|
+
for i, st in enumerate(STAGES):
|
|
788
|
+
step = {"stage": st, "label": STAGE_LABELS[st], "sites": reached[st], "share": share(reached[st])}
|
|
789
|
+
if i:
|
|
790
|
+
step["lost"] = [{"reason": k, "sites": v, "label": R.get(k).label, "next_step": R.get(k).next_step, "action": R.get(k).action}
|
|
791
|
+
for k, v in (lost.get(st) or Counter()).most_common()]
|
|
792
|
+
funnel.append(step)
|
|
793
|
+
by_mech: dict[str, dict] = {}
|
|
794
|
+
for r in rows:
|
|
795
|
+
m = by_mech.setdefault(r["mechanism"], {"mechanism": r["mechanism"], "label": mechanism.LABELS.get(r["mechanism"], r["mechanism"]),
|
|
796
|
+
"sites": 0, "obtained": 0, "judged": 0, "judged_measured": 0})
|
|
797
|
+
m["sites"] += 1
|
|
798
|
+
m["obtained"] += order[r["stage"]] >= order["obtained"]
|
|
799
|
+
m["judged"] += r["state"] != "not_judged"
|
|
800
|
+
m["judged_measured"] += r["measured"]
|
|
801
|
+
for m in by_mech.values():
|
|
802
|
+
m["judged_share"] = share(m["judged"], m["sites"])
|
|
803
|
+
m["obtained_share"] = share(m["obtained"], m["sites"])
|
|
804
|
+
by_engine: dict[str, dict] = {}
|
|
805
|
+
for r in rows:
|
|
806
|
+
e = by_engine.setdefault(r["engine"], {"sites": 0, "judged": 0, "judged_measured": 0})
|
|
807
|
+
e["sites"] += 1
|
|
808
|
+
e["judged"] += r["state"] != "not_judged"
|
|
809
|
+
e["judged_measured"] += r["measured"]
|
|
810
|
+
repo = inventory.get("repo") or {}
|
|
811
|
+
for r in rows:
|
|
812
|
+
r["kind"] = kind_of(r)
|
|
813
|
+
out = {
|
|
814
|
+
"schema_version": REPO_SCHEMA_VERSION,
|
|
815
|
+
"scope": "repository",
|
|
816
|
+
"repo": {k: repo.get(k, "") for k in ("name", "commit", "branch")},
|
|
817
|
+
"engines_scanned": sorted(run_engines),
|
|
818
|
+
"sites": n,
|
|
819
|
+
"judged": len(judged_rows), "judged_share": share(len(judged_rows)),
|
|
820
|
+
"judged_measured": measured_n, "judged_measured_share": share(measured_n),
|
|
821
|
+
"judged_on_word": len(judged_rows) - measured_n, "judged_on_word_share": share(len(judged_rows) - measured_n),
|
|
822
|
+
"outcomes": outcomes,
|
|
823
|
+
"funnel": funnel,
|
|
824
|
+
"not_judged": [{"reason": k, "sites": v, **{f: getattr(R.get(k), f) for f in ("stage", "label", "next_step", "action")}}
|
|
825
|
+
for k, v in reasons.most_common()],
|
|
826
|
+
"by_mechanism": sorted(by_mech.values(), key=lambda m: -m["sites"]),
|
|
827
|
+
"by_engine": dict(sorted(by_engine.items(), key=lambda kv: -kv[1]["sites"])),
|
|
828
|
+
"left_out": {"sites": sum(left_out.values()), **dict(left_out.most_common())},
|
|
829
|
+
"missed_by_discovery": {"counted": probes is not None, "sites": len(missed),
|
|
830
|
+
"by_library": {k: v.get("missed_new", v.get("missed", 0)) for k, v in ((probes or {}).get("by_library") or {}).items()
|
|
831
|
+
if v.get("missed_new", v.get("missed", 0))}},
|
|
832
|
+
"production": _production(runs, rows, hash_of, inventory),
|
|
833
|
+
"reasons": R.vocabulary(),
|
|
834
|
+
"reads": kind_view(rows, ("read", "kind_unknown")),
|
|
835
|
+
"writes": kind_view(rows, ("write",)),
|
|
836
|
+
}
|
|
837
|
+
if with_sites:
|
|
838
|
+
out["site_rows"] = rows
|
|
839
|
+
return out
|
|
840
|
+
|
|
841
|
+
|
|
842
|
+
def _production(runs: list[EngineRun], rows: list[dict], hash_of: dict, inventory: dict) -> dict | None:
|
|
843
|
+
"""Weighted by the pulled workload of every engine that has one: the share of executions and of bytes read whose
|
|
844
|
+
statement reached each stage. A shape counts at the furthest stage any call site it was located to reached; a
|
|
845
|
+
shape no call site of this repository sends is `not_located`."""
|
|
846
|
+
order = {k: i for i, k in enumerate(STAGES)}
|
|
847
|
+
best_of_site = {r["id"]: r for r in rows if r.get("id")}
|
|
848
|
+
keys = ("not_located",) + STAGES + ("judged_measured",)
|
|
849
|
+
ex: Counter = Counter()
|
|
850
|
+
rb: Counter = Counter()
|
|
851
|
+
shapes = 0
|
|
852
|
+
engines_with = []
|
|
853
|
+
for run in runs:
|
|
854
|
+
m = run.match or {}
|
|
855
|
+
queries = m.get("queries") or []
|
|
856
|
+
if not queries:
|
|
857
|
+
continue
|
|
858
|
+
engines_with.append({"engine": run.engine, "window_hours": m.get("window_hours"), "since": m.get("since", ""), "shapes": len(queries)})
|
|
859
|
+
for q in queries:
|
|
860
|
+
shapes += 1
|
|
861
|
+
located = [best_of_site[i] for i in q.get("site_ids") or [] if i in best_of_site]
|
|
862
|
+
e, b = int(q.get("executions") or 0), int(q.get("read_bytes") or 0)
|
|
863
|
+
if not q.get("site_ids"):
|
|
864
|
+
ex["not_located"] += e
|
|
865
|
+
rb["not_located"] += b
|
|
866
|
+
continue
|
|
867
|
+
stage = max((order[r["stage"]] for r in located), default=0)
|
|
868
|
+
for st in STAGES[:stage + 1]:
|
|
869
|
+
ex[st] += e
|
|
870
|
+
rb[st] += b
|
|
871
|
+
if any(r["measured"] for r in located):
|
|
872
|
+
ex["judged_measured"] += e
|
|
873
|
+
rb["judged_measured"] += b
|
|
874
|
+
if not engines_with:
|
|
875
|
+
return None
|
|
876
|
+
te = sum(v for k, v in ex.items() if k in ("not_located", "sites")) or 1
|
|
877
|
+
tb = sum(v for k, v in rb.items() if k in ("not_located", "sites")) or 1
|
|
878
|
+
return {"engines": engines_with, "shapes": shapes,
|
|
879
|
+
"executions": {k: ex.get(k, 0) for k in keys}, "read_bytes": {k: rb.get(k, 0) for k in keys},
|
|
880
|
+
"share_executions": {k: round(100 * ex.get(k, 0) / te, 1) for k in keys},
|
|
881
|
+
"share_read_bytes": {k: round(100 * rb.get(k, 0) / tb, 1) for k in keys},
|
|
882
|
+
"note": "the heaviest shapes the pull kept; `sites` = located to a call site of this repository"}
|
|
883
|
+
|
|
884
|
+
|
|
885
|
+
def probes_for(inventory: dict, repo_root: Path | None = None) -> dict | None:
|
|
886
|
+
"""The probe result discover stored, else the probes run now when the repository is on this machine."""
|
|
887
|
+
if isinstance(inventory.get("probes"), dict):
|
|
888
|
+
return inventory["probes"]
|
|
889
|
+
root = repo_root or Path((inventory.get("repo") or {}).get("root") or "")
|
|
890
|
+
if not str(root) or not root.is_dir():
|
|
891
|
+
return None
|
|
892
|
+
from .discover import probes
|
|
893
|
+
return probes.missed(root, inventory.get("call_sites") or [])
|
|
894
|
+
|
|
895
|
+
|
|
896
|
+
def from_out_dir(out_dir: Path, repo_root: Path | None = None, *, with_sites: bool = False) -> dict | None:
|
|
897
|
+
"""Repository coverage from an out directory (single engine, `--engine auto`, or one engine's directory of it)."""
|
|
898
|
+
top, index, runs = out_layout(Path(out_dir))
|
|
899
|
+
inventory = _load(top / "inventory.json")
|
|
900
|
+
if not isinstance(inventory, dict):
|
|
901
|
+
return None
|
|
902
|
+
from .families.coverage_hook import load as _families
|
|
903
|
+
out = repository(inventory, runs, probes_for(inventory, repo_root), with_sites=with_sites, families=_families(top))
|
|
904
|
+
if index:
|
|
905
|
+
out["engines_index"] = [{k: e.get(k) for k in ("engine", "dir", "status")} for e in index.get("engines") or []]
|
|
906
|
+
return out
|
|
907
|
+
|
|
908
|
+
|
|
909
|
+
def refresh_engines(top: Path) -> dict | None:
|
|
910
|
+
"""After the last engine of an `--engine auto` scan: the whole repository's coverage into <top>/coverage.json and into
|
|
911
|
+
`coverage.repository` of every engine's findings.json, so each engine's run (and its upload) carries the same number.
|
|
912
|
+
Never raises."""
|
|
913
|
+
try:
|
|
914
|
+
cov = from_out_dir(top)
|
|
915
|
+
if cov is None:
|
|
916
|
+
return None
|
|
917
|
+
(Path(top) / "coverage.json").write_text(json.dumps(cov, indent=1, ensure_ascii=False))
|
|
918
|
+
for run in out_layout(Path(top))[2]:
|
|
919
|
+
path = Path(top) / run.directory / "findings.json"
|
|
920
|
+
doc = _load(path)
|
|
921
|
+
if isinstance(doc, dict) and isinstance(doc.get("coverage"), dict):
|
|
922
|
+
prev = (doc["coverage"].get("repository") or {}).get("previous_judged_share")
|
|
923
|
+
doc["coverage"]["repository"] = {**cov, "previous_judged_share": prev}
|
|
924
|
+
path.write_text(json.dumps(doc, indent=1, ensure_ascii=False))
|
|
925
|
+
return cov
|
|
926
|
+
except Exception: # noqa: BLE001
|
|
927
|
+
return None
|
|
928
|
+
|
|
929
|
+
|
|
930
|
+
def judged_share(out_dir: Path, repo_root: Path | None = None) -> float | None:
|
|
931
|
+
"""The judged share of the query and write sites (percent, one decimal) for an out directory: the one number. None without an inventory."""
|
|
932
|
+
cov = from_out_dir(out_dir, repo_root)
|
|
933
|
+
return cov["judged_share"] if cov else None
|
|
934
|
+
|
|
935
|
+
|
|
936
|
+
# ---- history and the check ------------------------------------------------------------------------------------------
|
|
937
|
+
|
|
938
|
+
HISTORY_FILE = "coverage_history.json"
|
|
939
|
+
|
|
940
|
+
|
|
941
|
+
def history_entry(cov: dict) -> dict:
|
|
942
|
+
return {"commit": cov["repo"].get("commit", ""), "branch": cov["repo"].get("branch", ""),
|
|
943
|
+
"at": datetime.now(timezone.utc).isoformat(timespec="seconds"), "sites": cov["sites"],
|
|
944
|
+
"judged_share": cov["judged_share"], "judged_measured_share": cov["judged_measured_share"],
|
|
945
|
+
"obtained_share": next(f["share"] for f in cov["funnel"] if f["stage"] == "obtained"),
|
|
946
|
+
"plans_share": next(f["share"] for f in cov["funnel"] if f["stage"] == "plans"),
|
|
947
|
+
**({"reads_judged_share": cov["reads"]["judged_share"], "reads_judged_measured_share": cov["reads"]["judged_measured_share"],
|
|
948
|
+
"reads_unknown_share": cov["reads"]["unknown_share"]} if cov.get("reads") else {})}
|
|
949
|
+
|
|
950
|
+
|
|
951
|
+
def previous_of(history: list[dict], cov: dict) -> dict | None:
|
|
952
|
+
"""The newest earlier scan of the same branch at another commit (the same commit scanned again replaces it)."""
|
|
953
|
+
commit, branch = cov["repo"].get("commit", ""), cov["repo"].get("branch", "")
|
|
954
|
+
for h in reversed(history or []):
|
|
955
|
+
if h.get("branch") == branch and h.get("commit") != commit:
|
|
956
|
+
return h
|
|
957
|
+
return None
|
|
958
|
+
|
|
959
|
+
|
|
960
|
+
def remember(out_dir: Path, cov: dict, keep: int = SETTINGS["history"]) -> dict | None:
|
|
961
|
+
"""Adds this scan to <out>/coverage_history.json (replacing an entry of the same commit and branch) and returns the
|
|
962
|
+
previous scan of the branch, if any. Never raises."""
|
|
963
|
+
top, _, _ = out_layout(Path(out_dir))
|
|
964
|
+
path = top / HISTORY_FILE
|
|
965
|
+
doc = _load(path) or {}
|
|
966
|
+
hist = [h for h in doc.get("scans") or [] if isinstance(h, dict)]
|
|
967
|
+
prev = previous_of(hist, cov)
|
|
968
|
+
entry = history_entry(cov)
|
|
969
|
+
hist = [h for h in hist if not (h.get("commit") == entry["commit"] and h.get("branch") == entry["branch"])] + [entry]
|
|
970
|
+
try:
|
|
971
|
+
path.write_text(json.dumps({"schema_version": 1, "scans": hist[-max(1, keep):]}, indent=1))
|
|
972
|
+
except OSError:
|
|
973
|
+
pass
|
|
974
|
+
return prev
|
|
975
|
+
|
|
976
|
+
|
|
977
|
+
def check(cov: dict, settings: dict, previous: dict | None) -> tuple[bool, list[str]]:
|
|
978
|
+
"""`codecop coverage --check`: (passed, one line per rule). Fails under the floor, or on a drop of more than max_drop
|
|
979
|
+
points against the previous scan of the branch."""
|
|
980
|
+
ok, lines = True, []
|
|
981
|
+
share, floor = cov["judged_share"], settings["min_judged_share"]
|
|
982
|
+
if floor > 0:
|
|
983
|
+
if share < floor:
|
|
984
|
+
ok = False
|
|
985
|
+
lines.append(f"coverage check failed: {share:.1f}% < floor {floor:.1f}% (codecop.toml [coverage] min_judged_share)")
|
|
986
|
+
else:
|
|
987
|
+
lines.append(f"coverage check passed: {share:.1f}% >= floor {floor:.1f}% (codecop.toml [coverage] min_judged_share)")
|
|
988
|
+
if previous is not None and previous.get("judged_share") is not None:
|
|
989
|
+
drop = round(float(previous["judged_share"]) - share, 1)
|
|
990
|
+
if drop > settings["max_drop"]:
|
|
991
|
+
ok = False
|
|
992
|
+
lines.append(f"coverage check failed: dropped {drop:.1f} points from {previous['judged_share']:.1f}% "
|
|
993
|
+
f"(previous scan {str(previous.get('commit', ''))[:7]}; [coverage] max_drop {settings['max_drop']:.1f})")
|
|
994
|
+
else:
|
|
995
|
+
lines.append(f"coverage check passed: {share:.1f}% against {previous['judged_share']:.1f}% before "
|
|
996
|
+
f"(drop allowed {settings['max_drop']:.1f} points)")
|
|
997
|
+
if not lines:
|
|
998
|
+
lines.append(f"coverage check passed: {share:.1f}% (no floor set and no previous scan of this branch)")
|
|
999
|
+
return ok, lines
|
|
1000
|
+
|
|
1001
|
+
|
|
1002
|
+
def one_line(cov: dict, previous: dict | None = None) -> str:
|
|
1003
|
+
"""For the PR comment and logs: "coverage 20.0% of 1,000 query and write sites (3.0% measured), -0.4"."""
|
|
1004
|
+
s = f"coverage {cov['judged_share']:.1f}% of {cov['sites']:,} query and write sites ({cov['judged_measured_share']:.1f}% measured)"
|
|
1005
|
+
if previous and previous.get("judged_share") is not None:
|
|
1006
|
+
s += f", {cov['judged_share'] - float(previous['judged_share']):+.1f}"
|
|
1007
|
+
return s
|
|
1008
|
+
|
|
1009
|
+
|
|
1010
|
+
def R_label(code: str) -> str: # noqa: N802
|
|
1011
|
+
from . import coverage_reasons as R
|
|
1012
|
+
return R.get(code).label
|
|
1013
|
+
|
|
1014
|
+
|
|
1015
|
+
def text_lines(cov: dict, previous: dict | None = None, settings: dict | None = None, width: int = 40) -> list[str]:
|
|
1016
|
+
"""`codecop coverage` in the terminal."""
|
|
1017
|
+
n = cov["sites"] or 1
|
|
1018
|
+
head = f"Judged {cov['judged_share']:.1f}% of {cov['sites']:,} query and write sites"
|
|
1019
|
+
tail = []
|
|
1020
|
+
if previous and previous.get("judged_share") is not None:
|
|
1021
|
+
tail.append(f"previous scan {previous['judged_share']:.1f}%")
|
|
1022
|
+
if settings and settings.get("min_judged_share"):
|
|
1023
|
+
tail.append(f"check floor {settings['min_judged_share']:.1f}%")
|
|
1024
|
+
lines = [head + (" " + " · ".join(tail) if tail else ""),
|
|
1025
|
+
f" {cov['judged_measured_share']:.1f}% by measurement · {cov['judged_on_word_share']:.1f}% on the agent's word, catalog or rule (runs once)"]
|
|
1026
|
+
for label, key in (("Reads", "reads"), ("Writes", "writes")):
|
|
1027
|
+
v = cov.get(key)
|
|
1028
|
+
if not v or not v.get("sites"):
|
|
1029
|
+
continue
|
|
1030
|
+
ku = f" (incl. {v['kind_unknown']:,} of unknown kind)" if v.get("kind_unknown") else ""
|
|
1031
|
+
lines.append(f"{label:<9}{v['judged_share']:.1f}% judged of {v['sites']:,}{ku} · {v['judged_measured_share']:.1f}% by measurement"
|
|
1032
|
+
f" · unknown {v['unknown_share']:.1f}% · known, not judged {v['known_not_judged_share']:.1f}%")
|
|
1033
|
+
top = list(v.get("unknown_by_reason", {}).items())[:3] + list(v.get("not_judged_by_reason", {}).items())[:3]
|
|
1034
|
+
if top:
|
|
1035
|
+
lines.append(" " + ", ".join(f"{R_label(k).lower()} {c:,}" for k, c in sorted(top, key=lambda kv: -kv[1])))
|
|
1036
|
+
p = cov.get("production")
|
|
1037
|
+
if p:
|
|
1038
|
+
se, sb = p["share_executions"], p["share_read_bytes"]
|
|
1039
|
+
lines.append(f" {se['outcome']:.1f}% of production executions · {sb['outcome']:.1f}% of bytes read "
|
|
1040
|
+
f"({se['judged_measured']:.1f}% · {sb['judged_measured']:.1f}% measured) "
|
|
1041
|
+
+ ", ".join(f"{e['engine']}" + (f" {e['window_hours']} h" if e.get('window_hours') else "") for e in p["engines"]))
|
|
1042
|
+
lines.append("")
|
|
1043
|
+
for step in cov["funnel"]:
|
|
1044
|
+
bar = "█" * max(0, round(width * step["sites"] / n))
|
|
1045
|
+
lost = step.get("lost") or []
|
|
1046
|
+
lost_n = sum(x["sites"] for x in lost)
|
|
1047
|
+
extra = ""
|
|
1048
|
+
if lost:
|
|
1049
|
+
extra = f" -{lost_n:,} " + ", ".join(f"{x['label'].lower()} {x['sites']:,}" for x in lost[:3])
|
|
1050
|
+
if step["stage"] == "outcome":
|
|
1051
|
+
o = cov["outcomes"]
|
|
1052
|
+
extra += (" · " if extra else " ") + (f"improved {o['improved']:,} · another fix {o['needs_another_fix']:,} · nothing to gain "
|
|
1053
|
+
f"{o['nothing_to_gain_measured'] + o['nothing_to_gain_catalog'] + o['nothing_to_gain_agent'] + o.get('nothing_to_gain_runs_once', 0):,}")
|
|
1054
|
+
lines.append(f"{step['label']:<20}{step['sites']:>7,} {bar:<{width}}{extra}")
|
|
1055
|
+
lines += ["", f"{'by how the SQL comes to exist':<36}{'sites':>7}{'judged':>8}{'measured':>10}"]
|
|
1056
|
+
for m in cov["by_mechanism"]:
|
|
1057
|
+
lines.append(f" {m['label'][:34]:<34}{m['sites']:>7,}{m['judged_share']:>7.0f}%{m['judged_measured']:>10,}")
|
|
1058
|
+
lines += ["", f"{'could not be judged':<52}{'sites':>7} next step"]
|
|
1059
|
+
for r in cov["not_judged"]:
|
|
1060
|
+
lines.append(f" {r['label'][:50]:<50}{r['sites']:>7,} {r['next_step']}")
|
|
1061
|
+
lo = cov["left_out"]
|
|
1062
|
+
if lo.get("sites"):
|
|
1063
|
+
lines += ["", "left out of the sites, counted apart: " + ", ".join(f"{k.replace('_', ' ')} {v:,}" for k, v in lo.items() if k != "sites")]
|
|
1064
|
+
md = cov["missed_by_discovery"]
|
|
1065
|
+
if not md["counted"]:
|
|
1066
|
+
lines.append("sites discovery missed were not counted: the repository is not on this machine (pass --repo)")
|
|
1067
|
+
return lines
|