codecop 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- codecop/__init__.py +7 -0
- codecop/access.py +140 -0
- codecop/access_postgres.py +284 -0
- codecop/advisor.py +1512 -0
- codecop/advisor_bench.py +493 -0
- codecop/advisor_ch.py +2080 -0
- codecop/advisor_view.py +381 -0
- codecop/advisors.py +184 -0
- codecop/agent.py +221 -0
- codecop/agentfacts.py +745 -0
- codecop/apply/__init__.py +327 -0
- codecop/apply/check.py +344 -0
- codecop/apply/cli.py +162 -0
- codecop/apply/clickhouse.py +379 -0
- codecop/apply/common.py +238 -0
- codecop/apply/html.py +264 -0
- codecop/apply/patch.py +213 -0
- codecop/apply/postgres.py +102 -0
- codecop/apply/trial.py +166 -0
- codecop/assemble.py +104 -0
- codecop/baseline.py +1043 -0
- codecop/bench.py +2464 -0
- codecop/blockers.py +935 -0
- codecop/budget.py +980 -0
- codecop/catalog_profile.py +525 -0
- codecop/changed.py +261 -0
- codecop/cicmd.py +1002 -0
- codecop/cli.py +5421 -0
- codecop/client.py +729 -0
- codecop/coverage.py +1067 -0
- codecop/coverage_reasons.py +116 -0
- codecop/crashlog.py +70 -0
- codecop/datagen.py +766 -0
- codecop/datagen_postgres.py +630 -0
- codecop/datagen_sqlite.py +323 -0
- codecop/dbcli.py +885 -0
- codecop/definitions.py +457 -0
- codecop/discover/__init__.py +702 -0
- codecop/discover/arms.py +160 -0
- codecop/discover/base.py +234 -0
- codecop/discover/dialect.py +296 -0
- codecop/discover/elixir.py +64 -0
- codecop/discover/engine_go.py +320 -0
- codecop/discover/go.py +1947 -0
- codecop/discover/java.py +1528 -0
- codecop/discover/loops.py +1671 -0
- codecop/discover/named_go.py +258 -0
- codecop/discover/origins.py +4565 -0
- codecop/discover/origins_ts.py +1584 -0
- codecop/discover/orm_django.py +2772 -0
- codecop/discover/orm_django_models.py +814 -0
- codecop/discover/orm_django_sql.py +662 -0
- codecop/discover/orm_ent.py +565 -0
- codecop/discover/orm_ex_ecto.py +2138 -0
- codecop/discover/orm_go.py +2134 -0
- codecop/discover/orm_go_bun.py +602 -0
- codecop/discover/orm_go_run.py +636 -0
- codecop/discover/orm_go_types.py +1082 -0
- codecop/discover/orm_java.py +1450 -0
- codecop/discover/orm_jdbi.py +743 -0
- codecop/discover/orm_jooq.py +806 -0
- codecop/discover/orm_jpa.py +1307 -0
- codecop/discover/orm_mybatis.py +730 -0
- codecop/discover/orm_py.py +557 -0
- codecop/discover/orm_py_peewee.py +1266 -0
- codecop/discover/orm_py_prisma.py +298 -0
- codecop/discover/orm_rb_activerecord.py +1906 -0
- codecop/discover/orm_rust.py +1248 -0
- codecop/discover/orm_rust_seaorm.py +734 -0
- codecop/discover/orm_sqlalchemy.py +2475 -0
- codecop/discover/orm_stats.py +307 -0
- codecop/discover/orm_tables.py +29 -0
- codecop/discover/orm_ts.py +503 -0
- codecop/discover/orm_ts_drizzle.py +697 -0
- codecop/discover/orm_ts_knex.py +1117 -0
- codecop/discover/orm_ts_kysely.py +861 -0
- codecop/discover/orm_ts_prisma.py +1045 -0
- codecop/discover/orm_ts_schema.py +169 -0
- codecop/discover/orm_ts_sequelize.py +1401 -0
- codecop/discover/orm_ts_typeorm.py +1067 -0
- codecop/discover/probes.py +323 -0
- codecop/discover/python.py +595 -0
- codecop/discover/ruby.py +793 -0
- codecop/discover/rust.py +2378 -0
- codecop/discover/schema.py +520 -0
- codecop/discover/schema_ent.py +145 -0
- codecop/discover/schema_ts.py +420 -0
- codecop/discover/tsresolve.py +257 -0
- codecop/discover/typescript.py +1728 -0
- codecop/discover/xml_mapper.py +526 -0
- codecop/engines/__init__.py +515 -0
- codecop/engines/base.py +498 -0
- codecop/engines/clickhouse.py +1558 -0
- codecop/engines/pg_ddl.py +444 -0
- codecop/engines/pg_hints.py +137 -0
- codecop/engines/postgres.py +1060 -0
- codecop/engines/sqlite.py +742 -0
- codecop/families/__init__.py +3 -0
- codecop/families/build.py +280 -0
- codecop/families/cli.py +177 -0
- codecop/families/coverage_hook.py +62 -0
- codecop/families/driver.py +221 -0
- codecop/families/goslice.py +229 -0
- codecop/families/goslice_tool/go.mod +3 -0
- codecop/families/goslice_tool/main.go +403 -0
- codecop/families/holes.py +451 -0
- codecop/families/images/Dockerfile.go +5 -0
- codecop/families/images/Dockerfile.python +4 -0
- codecop/families/images/Dockerfile.rust +4 -0
- codecop/families/isolate.py +171 -0
- codecop/families/locate.py +270 -0
- codecop/families/model.py +301 -0
- codecop/families/plangate.py +271 -0
- codecop/families/tagpatch.py +174 -0
- codecop/fidelity.py +671 -0
- codecop/fixgroups.py +130 -0
- codecop/formerly.py +91 -0
- codecop/grantscript.py +254 -0
- codecop/groupbench.py +1375 -0
- codecop/groups.py +594 -0
- codecop/groups_view.py +186 -0
- codecop/heat.py +1405 -0
- codecop/heatcli.py +219 -0
- codecop/joins.py +1749 -0
- codecop/joins_view.py +127 -0
- codecop/kinds/__init__.py +507 -0
- codecop/kinds/calls/__init__.py +501 -0
- codecop/kinds/calls/extract.py +1097 -0
- codecop/kinds/calls/harness.py +408 -0
- codecop/kinds/calls/measure.py +342 -0
- codecop/kinds/calls/rules.py +139 -0
- codecop/kinds/calls/runners/RunCalls.java +167 -0
- codecop/kinds/calls/runners/run_go.go +141 -0
- codecop/kinds/calls/runners/run_node.js +186 -0
- codecop/kinds/calls/runners/run_python.py +319 -0
- codecop/kinds/calls/runners/run_rust.rs +200 -0
- codecop/kinds/calls/standin.py +340 -0
- codecop/kinds/pipeline.py +288 -0
- codecop/kinds/regex/__init__.py +1167 -0
- codecop/kinds/regex/engines/RegexHarness.java +129 -0
- codecop/kinds/regex/engines/run_go.go +294 -0
- codecop/kinds/regex/engines/run_node.js +99 -0
- codecop/kinds/regex/engines/run_python.py +295 -0
- codecop/kinds/regex/engines/run_rust.rs +149 -0
- codecop/kinds/regex/extract.py +1438 -0
- codecop/kinds/regex/harness.py +235 -0
- codecop/kinds/regex/measure.py +270 -0
- codecop/kinds/regex/shapes.py +418 -0
- codecop/kinds/regex/syntax.py +1721 -0
- codecop/kinds/testkind.py +107 -0
- codecop/kinds/transaction/__init__.py +228 -0
- codecop/kinds/transaction/bind.py +355 -0
- codecop/kinds/transaction/measure.py +264 -0
- codecop/kinds/transaction/plan.py +462 -0
- codecop/kinds/transaction/rules.py +540 -0
- codecop/kinds/transaction/sandbox.py +94 -0
- codecop/kinds/transaction/scenarios.py +520 -0
- codecop/kinds/transaction/schedule.py +483 -0
- codecop/kinds/transaction/shapes.py +418 -0
- codecop/kinds/transaction/verify.py +293 -0
- codecop/live.py +237 -0
- codecop/loopbench.py +2071 -0
- codecop/loopschema.py +591 -0
- codecop/mcpserver.py +120 -0
- codecop/mechanism.py +214 -0
- codecop/members.py +200 -0
- codecop/multi.py +443 -0
- codecop/observed.py +1868 -0
- codecop/parts.py +102 -0
- codecop/patterns.py +830 -0
- codecop/patterns_view.py +559 -0
- codecop/plangate.py +242 -0
- codecop/profile.py +439 -0
- codecop/prompts/areas.md +19 -0
- codecop/prompts/observed_variants.md +20 -0
- codecop/prompts/profile.md +60 -0
- codecop/prompts/profile_postgres.md +68 -0
- codecop/prompts/profile_sizes.md +26 -0
- codecop/prompts/profile_sqlite.md +69 -0
- codecop/prompts/rank.md +84 -0
- codecop/prompts/rank_postgres.md +96 -0
- codecop/prompts/rank_sqlite.md +94 -0
- codecop/prompts/scenario_variants.md +20 -0
- codecop/rank.py +1473 -0
- codecop/realdb/__init__.py +688 -0
- codecop/realdb/clickhouse.py +1223 -0
- codecop/realdb/facts.py +815 -0
- codecop/realdb/locality.py +964 -0
- codecop/realdb/locks.py +355 -0
- codecop/realdb/match.py +531 -0
- codecop/realdb/postgres.py +643 -0
- codecop/realdb/ratios.py +77 -0
- codecop/realdb/sample.py +126 -0
- codecop/relations.py +227 -0
- codecop/report.py +1854 -0
- codecop/resources.py +332 -0
- codecop/resources_view.py +266 -0
- codecop/rules/entry_points.toml +1013 -0
- codecop/rules/sinks.toml +362 -0
- codecop/runsonce.py +8 -0
- codecop/sandboxschema.py +555 -0
- codecop/scenario_agent.py +172 -0
- codecop/scenario_bind.py +507 -0
- codecop/scenario_sql.py +971 -0
- codecop/scenarios.py +675 -0
- codecop/scenarios_view.py +274 -0
- codecop/schemacli.py +67 -0
- codecop/schemas/areas_output.schema.json +21 -0
- codecop/schemas/profile_output.schema.json +362 -0
- codecop/schemas/rank_output.schema.json +385 -0
- codecop/sizes.py +200 -0
- codecop/sqlinfo.py +558 -0
- codecop/typedparams.py +576 -0
- codecop/verdicts.py +212 -0
- codecop/writebench.py +720 -0
- codecop/writecost.py +440 -0
- codecop/writes.py +1208 -0
- codecop-0.1.0.dist-info/METADATA +42 -0
- codecop-0.1.0.dist-info/RECORD +222 -0
- codecop-0.1.0.dist-info/WHEEL +4 -0
- codecop-0.1.0.dist-info/entry_points.txt +2 -0
- codecop-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
"""Production shapes placed on call sites across every repository of an organisation.
|
|
2
|
+
|
|
3
|
+
A database is usually shared: one service's PostgreSQL also serves another service's workers. Placing a pulled workload
|
|
4
|
+
only against the scanned repository leaves those unlocated; matching it against every repository of the organisation
|
|
5
|
+
(realdb.match.match_many) places them, and the fragment locator places what no text match can.
|
|
6
|
+
|
|
7
|
+
Grades, strongest first: exact, template, tag (realdb.match), then `fragment` (this module), then nothing.
|
|
8
|
+
|
|
9
|
+
Fragment locator. Every string literal of non-test source in every repository, normalised like a shape, is indexed as
|
|
10
|
+
token 3-grams together with the function that holds it. A shape goes to the file whose literals cover most of its
|
|
11
|
+
rarity-weighted grams: at least `min_cover` (0.7) with a margin of `min_margin` (0.05) over the next file of another
|
|
12
|
+
directory or repository; a probe of system tables (`system.*`, `pg_catalog`, `information_schema`) needs `min_cover_system`
|
|
13
|
+
(0.9). The same SQL held in two repositories cannot be placed in one file.
|
|
14
|
+
|
|
15
|
+
Query tags. ClickHouse statements carry `log_comment` tags (pulled by ch.workload.tags, read by realdb.match). PostgreSQL
|
|
16
|
+
keeps a comment such as `/* codecop:src/x.py:12 */` in the first text of a shape: text_tags() reads it into the same
|
|
17
|
+
`tags` field, so the match places it the same way.
|
|
18
|
+
|
|
19
|
+
Reads repository files as text and the pulled aggregates on disk. No database, no network, no code runs.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import bisect
|
|
25
|
+
import math
|
|
26
|
+
import os
|
|
27
|
+
import re
|
|
28
|
+
from collections import Counter, defaultdict
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
|
|
31
|
+
from ..discover import list_files
|
|
32
|
+
from ..discover.base import is_test_path
|
|
33
|
+
from ..realdb.match import GRADES, SURE, TOKEN, match, shape
|
|
34
|
+
|
|
35
|
+
DEFAULTS = {
|
|
36
|
+
"min_cover": 0.7, # share of a shape's rarity-weighted grams the best file's literals must hold
|
|
37
|
+
"min_cover_loose": 0.6, # ... enough for a non-system shape when the margin holds
|
|
38
|
+
"min_margin": 0.05, # lead over the next file of another directory or repository
|
|
39
|
+
"min_cover_system": 0.9, # a probe of system tables is generic: it needs this much
|
|
40
|
+
"min_grams": 4, # a shape with fewer distinct 3-grams is too short to place by fragments
|
|
41
|
+
"max_file_bytes": 3_000_000,
|
|
42
|
+
"max_sites_per_function": 3, # a shape placed on a function with more sites than this attaches to the function (a builder)
|
|
43
|
+
}
|
|
44
|
+
EXT = {".rs": "rust", ".go": "go", ".py": "python", ".java": "java", ".kt": "java", ".ts": "ts", ".tsx": "ts", ".sql": "sql"}
|
|
45
|
+
LIT = re.compile(r'r#"(.*?)"#|"""(.*?)"""|`([^`]*)`|"((?:[^"\\]|\\.)*)"', re.S)
|
|
46
|
+
PY_SINGLE = re.compile(r"'''(.*?)'''|'((?:[^'\\\n]|\\.)*)'", re.S)
|
|
47
|
+
FN = {"rust": re.compile(r"^\s*(?:pub(?:\([^)]*\))?\s+)?(?:const\s+)?(?:async\s+)?fn\s+(\w+)"),
|
|
48
|
+
"go": re.compile(r"^func\s+(?:\([^)]*\)\s*)?(\w+)"),
|
|
49
|
+
"python": re.compile(r"^\s*(?:async\s+)?def\s+(\w+)"),
|
|
50
|
+
"java": re.compile(r"^\s*(?:public|private|protected|static|final|\s)+[\w<>\[\], ?]+\s+(\w+)\s*\([^;]*$"),
|
|
51
|
+
"ts": re.compile(r"^\s*(?:export\s+)?(?:async\s+)?function\s+(\w+)|^\s*(?:public|private|async|static|\s)*(\w+)\s*\([^)]*\)\s*[:{]")}
|
|
52
|
+
SQL_WORD = re.compile(r"(?i)\b(select|from|where|join|group by|order by|insert|update|delete|and|having|limit|as|on|set|values|with|in)\b")
|
|
53
|
+
SYSTEM = re.compile(r"\bsystem\.|pg_catalog|information_schema|\bpg_\w+\b", re.I)
|
|
54
|
+
BREAK = " ¦ "
|
|
55
|
+
SKIP = re.compile(r"(^|/)(node_modules|target|vendor|dist)/|(^|/)\.env|(^|/)envs/")
|
|
56
|
+
TAG_IN_TEXT = re.compile(r"(?:/\*|--)\s*(?:codecop|qopt):([A-Za-z0-9_.:/-]{1,80})")
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def text_tags(conn: dict) -> dict:
|
|
60
|
+
"""The connection with every statement's call-site tag read from its own text (`/* codecop:<tag> */`, `-- codecop:<tag>`):
|
|
61
|
+
PostgreSQL keeps the comment of the first statement of a shape. A tag already pulled (ClickHouse log_comment) is kept."""
|
|
62
|
+
queries = []
|
|
63
|
+
changed = 0
|
|
64
|
+
for q in conn.get("queries") or []:
|
|
65
|
+
tags = list(q.get("tags") or [])
|
|
66
|
+
found = TAG_IN_TEXT.findall(q.get("text") or "")
|
|
67
|
+
known = {t.get("tag") for t in tags}
|
|
68
|
+
for t in found:
|
|
69
|
+
if t not in known:
|
|
70
|
+
tags.append({"tag": t, "executions": int(q.get("executions") or 0), "from": "text"})
|
|
71
|
+
known.add(t)
|
|
72
|
+
changed += 1
|
|
73
|
+
queries.append({**q, "tags": tags} if tags else q)
|
|
74
|
+
return {**conn, "queries": queries} if changed else conn
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def norm(text: str, lang: str) -> str:
|
|
78
|
+
t = text.replace("\\n", " ").replace("\\t", " ").replace('\\"', '"')
|
|
79
|
+
t = re.sub(r"\\\s*\n\s*", " ", t)
|
|
80
|
+
if lang == "rust":
|
|
81
|
+
t = re.sub(r"\{\{|\}\}", "", t)
|
|
82
|
+
if lang != "sql":
|
|
83
|
+
t = re.sub(r"\{[\w.:#?<>]*\}|%\[?\d*\]?[sdvq]|\$\{[^}]*\}|@\{\w+\}", BREAK + "? ", t)
|
|
84
|
+
return shape(t)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def grams(sh: str) -> set[str]:
|
|
88
|
+
out = set()
|
|
89
|
+
for seg in sh.split("¦"):
|
|
90
|
+
tk = TOKEN.findall(seg.replace("«»", " "))
|
|
91
|
+
for i in range(len(tk) - 2):
|
|
92
|
+
g = tk[i:i + 3]
|
|
93
|
+
if sum(1 for x in g if re.match(r"[a-z_]", x)) >= 2:
|
|
94
|
+
out.add(" ".join(g))
|
|
95
|
+
return out
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class FragmentIndex:
|
|
99
|
+
"""Token 3-grams of every SQL-looking literal of every repository, with the (repo, file, function) holding it."""
|
|
100
|
+
|
|
101
|
+
def __init__(self, roots: dict[str, Path | str], settings: dict | None = None):
|
|
102
|
+
self.cfg = {**DEFAULTS, **(settings or {})}
|
|
103
|
+
self.idx: dict[str, set[tuple[str, str, str]]] = defaultdict(set)
|
|
104
|
+
self.files: set[tuple[str, str]] = set()
|
|
105
|
+
for repo, root in roots.items():
|
|
106
|
+
self._add_repo(repo, Path(root))
|
|
107
|
+
self.nfiles = max(1, len(self.files))
|
|
108
|
+
|
|
109
|
+
def _add_repo(self, repo: str, root: Path) -> None:
|
|
110
|
+
for f in list_files(root):
|
|
111
|
+
lang = EXT.get(os.path.splitext(f)[1])
|
|
112
|
+
if not lang or is_test_path(f) or SKIP.search(f):
|
|
113
|
+
continue
|
|
114
|
+
p = root / f
|
|
115
|
+
try:
|
|
116
|
+
if p.stat().st_size > int(self.cfg["max_file_bytes"]):
|
|
117
|
+
continue
|
|
118
|
+
src = p.read_text(encoding="utf-8", errors="replace")
|
|
119
|
+
except OSError:
|
|
120
|
+
continue
|
|
121
|
+
if lang == "sql":
|
|
122
|
+
g = grams(norm(src, "sql"))
|
|
123
|
+
if g:
|
|
124
|
+
self.files.add((repo, f))
|
|
125
|
+
for x in g:
|
|
126
|
+
self.idx[x].add((repo, f, ""))
|
|
127
|
+
continue
|
|
128
|
+
pat = FN.get(lang)
|
|
129
|
+
lines = src.split("\n")
|
|
130
|
+
starts: list[int] = []
|
|
131
|
+
names: list[str] = []
|
|
132
|
+
for i, line in enumerate(lines):
|
|
133
|
+
m = pat.match(line) if pat else None
|
|
134
|
+
if m:
|
|
135
|
+
starts.append(i)
|
|
136
|
+
names.append(next(x for x in m.groups() if x))
|
|
137
|
+
offs = [0]
|
|
138
|
+
for line in lines:
|
|
139
|
+
offs.append(offs[-1] + len(line) + 1)
|
|
140
|
+
lits = [(m.start(), next((x for x in m.groups() if x is not None), "")) for m in LIT.finditer(src)]
|
|
141
|
+
if lang == "python":
|
|
142
|
+
lits += [(m.start(), next((x for x in m.groups() if x is not None), "")) for m in PY_SINGLE.finditer(src)]
|
|
143
|
+
for pos, t in lits:
|
|
144
|
+
if len(t) < 10 or not SQL_WORD.search(t):
|
|
145
|
+
continue
|
|
146
|
+
g = grams(norm(t, lang))
|
|
147
|
+
if not g:
|
|
148
|
+
continue
|
|
149
|
+
ln = bisect.bisect_right(offs, pos) - 1
|
|
150
|
+
j = bisect.bisect_right(starts, ln) - 1
|
|
151
|
+
key = (repo, f, names[j] if j >= 0 else "")
|
|
152
|
+
self.files.add((repo, f))
|
|
153
|
+
for x in g:
|
|
154
|
+
self.idx[x].add(key)
|
|
155
|
+
|
|
156
|
+
def locate(self, text: str) -> dict | None:
|
|
157
|
+
"""The best file for a production statement, or None when it is too short. {repo, file, cover, second, fns, ok}"""
|
|
158
|
+
sh = shape(text)
|
|
159
|
+
g = grams(sh)
|
|
160
|
+
if len(g) < int(self.cfg["min_grams"]):
|
|
161
|
+
return None
|
|
162
|
+
w = {x: math.log(1 + self.nfiles / (1 + len({k[:2] for k in self.idx.get(x, ())}))) for x in g}
|
|
163
|
+
tot = sum(w.values()) or 1.0
|
|
164
|
+
sc: Counter = Counter()
|
|
165
|
+
fsc: Counter = Counter()
|
|
166
|
+
for x in g:
|
|
167
|
+
seen = set()
|
|
168
|
+
for k in self.idx.get(x, ()):
|
|
169
|
+
sc[k] += w[x]
|
|
170
|
+
if k[:2] not in seen:
|
|
171
|
+
fsc[k[:2]] += w[x]
|
|
172
|
+
seen.add(k[:2])
|
|
173
|
+
if not fsc:
|
|
174
|
+
return {"cover": 0.0, "ok": False}
|
|
175
|
+
top = fsc.most_common(4)
|
|
176
|
+
bf, bs = top[0]
|
|
177
|
+
second = next((s for f, s in top[1:] if os.path.dirname(f[1]) != os.path.dirname(bf[1]) or f[0] != bf[0]), 0)
|
|
178
|
+
fns = sorted(((k[2], v / tot) for k, v in sc.items() if k[:2] == bf), key=lambda x: -x[1])[:3]
|
|
179
|
+
cover, second = bs / tot, second / tot
|
|
180
|
+
system = bool(SYSTEM.search(text or ""))
|
|
181
|
+
c = self.cfg
|
|
182
|
+
ok = cover - second >= float(c["min_margin"]) and (cover >= float(c["min_cover"]) or (cover >= float(c["min_cover_loose"]) and not system)) \
|
|
183
|
+
and not (system and cover < float(c["min_cover_system"]))
|
|
184
|
+
return {"repo": bf[0], "file": bf[1], "cover": round(cover, 3), "second": round(second, 3),
|
|
185
|
+
"fns": [[a, round(b, 3)] for a, b in fns], "ok": ok, "system": system}
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def place(engine: str, conn: dict, inventories: dict[str, dict], index: FragmentIndex | None, *, own: str,
|
|
189
|
+
settings: dict | None = None) -> dict:
|
|
190
|
+
"""Every pulled statement of one engine placed on a call site (or a builder function) of any repository.
|
|
191
|
+
|
|
192
|
+
Returns {queries: [{hash, executions, read_bytes, grade, repo, site_ids, file, fn, cover}], located: {...shares},
|
|
193
|
+
by_site: {site_id: [{hash, grade, executions, read_bytes, text}]} for the own repository, builders: {...}}."""
|
|
194
|
+
cfg = {**DEFAULTS, **(settings or {})}
|
|
195
|
+
conn = text_tags(conn)
|
|
196
|
+
qs = {q["hash"]: q for q in conn.get("queries") or [] if q.get("text")}
|
|
197
|
+
rank = {g: i for i, g in enumerate(GRADES)}
|
|
198
|
+
best: dict[str, dict] = {}
|
|
199
|
+
for repo, inv in inventories.items():
|
|
200
|
+
m = match(inv, conn, engine=engine)
|
|
201
|
+
for q in m["queries"]:
|
|
202
|
+
if q["match"] not in SURE:
|
|
203
|
+
continue
|
|
204
|
+
b = best.get(q["hash"])
|
|
205
|
+
if b is None or rank[q["match"]] < rank[b["grade"]] or (q["match"] == b["grade"] and repo == own and b["repo"] != own):
|
|
206
|
+
best[q["hash"]] = {"grade": q["match"], "repo": repo, "site_ids": list(q.get("site_ids") or [])}
|
|
207
|
+
if index is not None:
|
|
208
|
+
for h, q in qs.items():
|
|
209
|
+
if h in best:
|
|
210
|
+
continue
|
|
211
|
+
loc = index.locate(q["text"])
|
|
212
|
+
if loc and loc.get("ok"):
|
|
213
|
+
best[h] = {"grade": "fragment", "repo": loc["repo"], "file": loc["file"], "fn": (loc["fns"][0][0] if loc["fns"] else ""),
|
|
214
|
+
"cover": loc["cover"], "site_ids": []}
|
|
215
|
+
# fragment placements onto the sites of that file and function
|
|
216
|
+
by_fn: dict[tuple, list[dict]] = defaultdict(list)
|
|
217
|
+
for repo, inv in inventories.items():
|
|
218
|
+
for s in inv.get("call_sites") or []:
|
|
219
|
+
if s.get("is_test") or (s.get("engine") and s.get("engine") != engine):
|
|
220
|
+
continue
|
|
221
|
+
last = re.split(r"[.:]+", s.get("symbol") or "")[-1]
|
|
222
|
+
by_fn[(repo, s["file"], last)].append(s)
|
|
223
|
+
by_fn[(repo, s["file"], None)].append(s)
|
|
224
|
+
builders: dict[str, dict] = {}
|
|
225
|
+
for h, b in best.items():
|
|
226
|
+
if b["grade"] != "fragment":
|
|
227
|
+
continue
|
|
228
|
+
cands = by_fn.get((b["repo"], b["file"], b["fn"])) or []
|
|
229
|
+
if not cands:
|
|
230
|
+
built = [s for s in by_fn.get((b["repo"], b["file"], None), []) if run_time_built(s)]
|
|
231
|
+
cands = built if len(built) == 1 else []
|
|
232
|
+
if len(cands) > int(cfg["max_sites_per_function"]):
|
|
233
|
+
cands = [s for s in cands if run_time_built(s)] or cands
|
|
234
|
+
if cands and len(cands) <= int(cfg["max_sites_per_function"]):
|
|
235
|
+
b["site_ids"] = [s["id"] for s in cands]
|
|
236
|
+
else:
|
|
237
|
+
key = f"{b['repo']}:{b['file']}:{b['fn']}"
|
|
238
|
+
b["builder"] = key
|
|
239
|
+
builders.setdefault(key, {"repo": b["repo"], "file": b["file"], "fn": b["fn"], "hashes": []})["hashes"].append(h)
|
|
240
|
+
tot_e = sum(int(q.get("executions") or 0) for q in qs.values()) or 1
|
|
241
|
+
tot_b = sum(int(q.get("read_bytes") or 0) for q in qs.values()) or 1
|
|
242
|
+
|
|
243
|
+
def share(hs) -> dict:
|
|
244
|
+
hs = list(hs)
|
|
245
|
+
return {"shapes": len(hs), "executions": round(sum(int(qs[h].get("executions") or 0) for h in hs) / tot_e, 4),
|
|
246
|
+
"read_bytes": round(sum(int(qs[h].get("read_bytes") or 0) for h in hs) / tot_b, 4)}
|
|
247
|
+
|
|
248
|
+
own_sure = [h for h, b in best.items() if b["repo"] == own and b["grade"] in SURE]
|
|
249
|
+
sure = [h for h, b in best.items() if b["grade"] in SURE]
|
|
250
|
+
unloc = [h for h in qs if h not in best]
|
|
251
|
+
located = {"own_repository_sure": share(own_sure), "all_repositories_sure": share(sure), "with_fragments": share(best),
|
|
252
|
+
"unlocated": share(unloc), "unlocated_system": share(h for h in unloc if SYSTEM.search(qs[h]["text"])),
|
|
253
|
+
"by_repository": dict(Counter(b["repo"] for b in best.values())), "by_grade": dict(Counter(b["grade"] for b in best.values()))}
|
|
254
|
+
by_site: dict[str, list[dict]] = defaultdict(list)
|
|
255
|
+
for h, b in best.items():
|
|
256
|
+
if b["repo"] != own:
|
|
257
|
+
continue
|
|
258
|
+
for sid in b["site_ids"]:
|
|
259
|
+
q = qs[h]
|
|
260
|
+
by_site[sid].append({"hash": h, "grade": b["grade"], "executions": int(q.get("executions") or 0),
|
|
261
|
+
"read_bytes": int(q.get("read_bytes") or 0), "text": q["text"]})
|
|
262
|
+
rows = [{"hash": h, "executions": int(q.get("executions") or 0), "read_bytes": int(q.get("read_bytes") or 0),
|
|
263
|
+
**({k: v for k, v in best[h].items()} if h in best else {"grade": "none"})} for h, q in qs.items()]
|
|
264
|
+
return {"engine": engine, "since": conn.get("since", ""), "located": located, "queries": rows, "by_site": dict(by_site),
|
|
265
|
+
"builders": {k: v for k, v in builders.items() if v["repo"] == own}}
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def run_time_built(site: dict) -> bool:
|
|
269
|
+
sql = site.get("sql") or ""
|
|
270
|
+
return "«" in sql or site.get("resolution") in ("unresolved", "parameter") or not sql.strip()
|
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
"""The statement family of a call site: what a statement is when one site sends many.
|
|
2
|
+
|
|
3
|
+
A literal query is one statement. A site whose SQL is built at run time (conditional fragments, a table or column from
|
|
4
|
+
a variable, a list built in a loop, text assembled across functions, a builder) has a *family*: the template with its
|
|
5
|
+
run-time parts, and the variants it sends, each with the condition that selects it, the basis its text came from, how
|
|
6
|
+
often production ran it, whether it plans, and its outcome.
|
|
7
|
+
|
|
8
|
+
site {id, file, line, symbol, mechanism, kind: site|builder}
|
|
9
|
+
template text with «parts», each part {expr, role: value|table|predicate|list|cte|column|order|tail|unknown}
|
|
10
|
+
variants [{id, sql, condition, basis, bases, exact, production, valid, params, outcome, unverified}]
|
|
11
|
+
unbuilt [{condition, reason}] # shown and counted, never hidden
|
|
12
|
+
coverage {variants, judged, share_of_runs_judged, rule}
|
|
13
|
+
rollup {state, reason, next_step, verified, spread}
|
|
14
|
+
|
|
15
|
+
Sources are merged on the normalised text (realdb.match.shape: binds and literals as `?`, case and spacing removed):
|
|
16
|
+
two sources that give the same statement are one variant that keeps the strongest basis and lists every basis that
|
|
17
|
+
agreed. Two rules about weak bases hold everywhere:
|
|
18
|
+
|
|
19
|
+
- a variant with a part left out can only ever say "nothing to gain": a win measured on it is not a fix;
|
|
20
|
+
- a win on a statement written by the agent stays "unverified" until a stronger basis gives the same text.
|
|
21
|
+
|
|
22
|
+
Pure data: no I/O, no sandbox, no agent. Outcomes are the verdicts' own (`blockers.outcome`), unchanged.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import hashlib
|
|
28
|
+
import re
|
|
29
|
+
|
|
30
|
+
from ..realdb.match import shape
|
|
31
|
+
|
|
32
|
+
SCHEMA_VERSION = 1
|
|
33
|
+
|
|
34
|
+
# Basis vocabulary, strongest first. The key is what files store; the label is what people read.
|
|
35
|
+
BASES = ("production", "code", "evaluated", "library", "tests", "translated", "filled", "part_left_out", "agent")
|
|
36
|
+
BASIS_LABEL = {
|
|
37
|
+
"production": "seen in production",
|
|
38
|
+
"code": "in the code",
|
|
39
|
+
"evaluated": "builder evaluated",
|
|
40
|
+
"library": "rendered by the library",
|
|
41
|
+
"tests": "captured from tests",
|
|
42
|
+
"translated": "translated ORM call",
|
|
43
|
+
"filled": "filled from code",
|
|
44
|
+
"part_left_out": "part left out",
|
|
45
|
+
"agent": "written by the agent",
|
|
46
|
+
}
|
|
47
|
+
BASIS_HELP = {
|
|
48
|
+
"production": "text from the query log, placed by text, tag or fragments",
|
|
49
|
+
"code": "literal, constant, file",
|
|
50
|
+
"evaluated": "a pure slice or driver ran in isolation",
|
|
51
|
+
"library": "opt-in",
|
|
52
|
+
"tests": "opt-in",
|
|
53
|
+
"translated": "translated by rule",
|
|
54
|
+
"filled": "every run-time part resolved statically",
|
|
55
|
+
"part_left_out": "a predicate or tail could not be resolved; baseline only, never a fix",
|
|
56
|
+
"agent": "plans, not confirmed by execution or production",
|
|
57
|
+
}
|
|
58
|
+
# Solid: a statement something executed or stored. Dashed: text somebody (a rule, the filler, the agent) wrote.
|
|
59
|
+
SOLID = ("production", "code", "evaluated", "library", "tests")
|
|
60
|
+
RANK = {b: i for i, b in enumerate(BASES)}
|
|
61
|
+
|
|
62
|
+
# Roles of a run-time part (holes.role): what the SQL around it says it stands for.
|
|
63
|
+
ROLES = ("value", "table", "predicate", "list", "cte", "column", "order", "tail", "unknown")
|
|
64
|
+
|
|
65
|
+
# Outcome states (blockers.STATES) and what the family roll-up shows.
|
|
66
|
+
JUDGED = ("fixed", "blocked", "nothing_to_gain")
|
|
67
|
+
ROLLUP_STATES = ("improved", "needs_another_fix", "nothing_to_gain", "could_not_be_judged")
|
|
68
|
+
STATE_LABEL = {"improved": "improved", "needs_another_fix": "needs another fix", "nothing_to_gain": "nothing to gain",
|
|
69
|
+
"could_not_be_judged": "could not be judged"}
|
|
70
|
+
# Reasons a family leaves its site unjudged, in the report's wording, each with one next step (blockers.NEXT_STEP style).
|
|
71
|
+
REASONS = {
|
|
72
|
+
"run_time_parts": "ask_agent_for_driver_or_allow_builder_evaluation",
|
|
73
|
+
"variants_not_covered": "longer_window_or_allow_builder_evaluation",
|
|
74
|
+
"does_not_plan": "pull_the_tables_or_check_the_statement",
|
|
75
|
+
"no_statement_text": "add_query_tag_helper",
|
|
76
|
+
"family_not_benchmarked": "run_baseline_pass",
|
|
77
|
+
}
|
|
78
|
+
REASON_LABEL = {
|
|
79
|
+
"run_time_parts": "Run-time parts not resolved",
|
|
80
|
+
"variants_not_covered": "Baseline ran, variants not covered",
|
|
81
|
+
"does_not_plan": "No variant plans against the schema",
|
|
82
|
+
"no_statement_text": "No statement text",
|
|
83
|
+
"family_not_benchmarked": "Variants not benchmarked yet",
|
|
84
|
+
}
|
|
85
|
+
NEXT_STEP_LABEL = {
|
|
86
|
+
"ask_agent_for_driver_or_allow_builder_evaluation": "ask the agent for a driver by heat, or allow builder evaluation",
|
|
87
|
+
"longer_window_or_allow_builder_evaluation": "longer production window, or allow builder evaluation",
|
|
88
|
+
"pull_the_tables_or_check_the_statement": "pull the database that holds the tables",
|
|
89
|
+
"add_query_tag_helper": "tag the query at its client helper (codecop families tag-patch)",
|
|
90
|
+
"run_baseline_pass": "run the baseline pass",
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
DEFAULTS = {
|
|
94
|
+
"share_of_runs_judged": 0.8, # a site production saw is judged when the variants with an outcome cover this share of its runs
|
|
95
|
+
"max_variants": 64, # variants kept per site; the rest are counted in `unbuilt` with reason `over_cap`
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def normalised(sql: str) -> str:
|
|
100
|
+
return shape(sql or "")
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def variant_id(sql: str) -> str:
|
|
104
|
+
"""Hash of the normalised text: the same statement from two sources has one id."""
|
|
105
|
+
return hashlib.sha1(normalised(sql).encode("utf-8", "replace")).hexdigest()[:12]
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def stronger(a: str, b: str) -> str:
|
|
109
|
+
return a if RANK.get(a, 99) <= RANK.get(b, 99) else b
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def variant(sql: str, basis: str, *, condition: str = "", exact: bool | None = None, source: str = "",
|
|
113
|
+
production: dict | None = None, notes: list[str] | None = None) -> dict:
|
|
114
|
+
"""One variant from one source. `exact` defaults to False for `part_left_out`, True otherwise."""
|
|
115
|
+
if basis not in RANK:
|
|
116
|
+
raise ValueError(f"unknown basis {basis!r}")
|
|
117
|
+
if exact is None:
|
|
118
|
+
exact = basis != "part_left_out"
|
|
119
|
+
out = {"id": variant_id(sql), "sql": sql, "condition": condition or "", "basis": basis, "bases": [basis],
|
|
120
|
+
"exact": bool(exact), "sources": [source] if source else [], "valid": None, "params": None, "outcome": None}
|
|
121
|
+
if production:
|
|
122
|
+
out["production"] = dict(production)
|
|
123
|
+
if notes:
|
|
124
|
+
out["notes"] = list(notes)[:12]
|
|
125
|
+
out["unverified"] = basis == "agent"
|
|
126
|
+
return out
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def merge(variants: list[dict], new: dict) -> dict:
|
|
130
|
+
"""Add `new` to `variants` (in place): the same normalised text becomes one variant with the strongest basis.
|
|
131
|
+
Returns the variant that now holds the statement."""
|
|
132
|
+
for v in variants:
|
|
133
|
+
if v["id"] != new["id"]:
|
|
134
|
+
continue
|
|
135
|
+
best = stronger(v["basis"], new["basis"])
|
|
136
|
+
if best != v["basis"]:
|
|
137
|
+
# the stronger source's text and condition win; the weaker one is remembered in `bases`
|
|
138
|
+
v["sql"] = new["sql"]
|
|
139
|
+
if new.get("condition"):
|
|
140
|
+
v["condition"] = new["condition"]
|
|
141
|
+
elif not v.get("condition") and new.get("condition"):
|
|
142
|
+
v["condition"] = new["condition"]
|
|
143
|
+
v["basis"] = best
|
|
144
|
+
v["bases"] = sorted(set(v.get("bases") or []) | set(new.get("bases") or [new["basis"]]), key=lambda b: RANK[b])
|
|
145
|
+
v["exact"] = bool(v.get("exact")) or bool(new.get("exact"))
|
|
146
|
+
v["sources"] = list(dict.fromkeys((v.get("sources") or []) + (new.get("sources") or [])))
|
|
147
|
+
if new.get("production"):
|
|
148
|
+
v["production"] = _add_production(v.get("production"), new["production"])
|
|
149
|
+
if new.get("notes") and not v.get("notes"):
|
|
150
|
+
v["notes"] = new["notes"]
|
|
151
|
+
# a win on the agent's text is verified once any stronger basis gave the same text
|
|
152
|
+
v["unverified"] = all(b == "agent" for b in v["bases"])
|
|
153
|
+
return v
|
|
154
|
+
variants.append(new)
|
|
155
|
+
return new
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _add_production(a: dict | None, b: dict) -> dict:
|
|
159
|
+
if not a:
|
|
160
|
+
return dict(b)
|
|
161
|
+
out = dict(a)
|
|
162
|
+
out["hashes"] = list(dict.fromkeys((a.get("hashes") or []) + (b.get("hashes") or [])))
|
|
163
|
+
for k in ("executions", "read_bytes"):
|
|
164
|
+
out[k] = int(a.get(k) or 0) + int(b.get(k) or 0) if set(a.get("hashes") or []) != set(b.get("hashes") or []) \
|
|
165
|
+
else max(int(a.get(k) or 0), int(b.get(k) or 0))
|
|
166
|
+
out["how"] = a.get("how") or b.get("how")
|
|
167
|
+
return out
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def order(variants: list[dict]) -> list[dict]:
|
|
171
|
+
"""Most-run first, then by basis strength, then exact before approximate; the first is the base variant."""
|
|
172
|
+
return sorted(variants, key=lambda v: (-int((v.get("production") or {}).get("executions") or 0), RANK[v["basis"]],
|
|
173
|
+
not v.get("exact"), len(v.get("sql") or "")))
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def family(site: dict, *, mechanism: str = "", template: str | None = None, parts: list[dict] | None = None,
|
|
177
|
+
kind: str = "site") -> dict:
|
|
178
|
+
return {
|
|
179
|
+
"site": {"id": site.get("id", ""), "file": site.get("file", ""), "line": site.get("line", 0), "symbol": site.get("symbol", ""),
|
|
180
|
+
"engine": site.get("engine", ""), "language": site.get("language", ""), "mechanism": mechanism, "kind": kind},
|
|
181
|
+
"template": {"text": site.get("sql") if template is None else template, "parts": parts or []},
|
|
182
|
+
"variants": [], "unbuilt": [], "coverage": None, "rollup": None,
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def add_unbuilt(fam: dict, condition: str, reason: str, detail: str = "") -> None:
|
|
187
|
+
row = {"condition": condition, "reason": reason}
|
|
188
|
+
if detail:
|
|
189
|
+
row["detail"] = detail[:300]
|
|
190
|
+
if row not in fam["unbuilt"]:
|
|
191
|
+
fam["unbuilt"].append(row)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def share_of_site(fam: dict) -> None:
|
|
195
|
+
"""Each variant's share of the site's observed runs."""
|
|
196
|
+
total = sum(int((v.get("production") or {}).get("executions") or 0) for v in fam["variants"])
|
|
197
|
+
for v in fam["variants"]:
|
|
198
|
+
p = v.get("production")
|
|
199
|
+
if p:
|
|
200
|
+
p["share_of_site"] = round(int(p.get("executions") or 0) / total, 4) if total else 0.0
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _tables(sql: str) -> frozenset[str]:
|
|
204
|
+
from ..realdb.match import tables_in
|
|
205
|
+
return frozenset(tables_in(normalised(sql)))
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def effective_state(v: dict) -> str | None:
|
|
209
|
+
"""The state a variant's outcome contributes to its site, after the weak-basis rules. None: no outcome."""
|
|
210
|
+
o = v.get("outcome") or {}
|
|
211
|
+
st = o.get("state")
|
|
212
|
+
if st not in JUDGED:
|
|
213
|
+
return None
|
|
214
|
+
if v.get("basis") == "part_left_out" or not v.get("exact", True):
|
|
215
|
+
# a statement with a part left out is fit for a baseline only: its fix or "needs another fix" is not one
|
|
216
|
+
return "nothing_to_gain" if st == "nothing_to_gain" else None
|
|
217
|
+
return st
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def rollup(fam: dict, settings: dict | None = None) -> dict:
|
|
221
|
+
"""The site's state from its variants. Sets fam['coverage'] and
|
|
222
|
+
fam['rollup'] and returns the roll-up."""
|
|
223
|
+
cfg = {**DEFAULTS, **(settings or {})}
|
|
224
|
+
vs = fam["variants"]
|
|
225
|
+
share_of_site(fam)
|
|
226
|
+
judged = [v for v in vs if effective_state(v)]
|
|
227
|
+
runs = sum(int((v.get("production") or {}).get("executions") or 0) for v in vs)
|
|
228
|
+
runs_judged = sum(int((v.get("production") or {}).get("executions") or 0) for v in judged)
|
|
229
|
+
if runs:
|
|
230
|
+
share = runs_judged / runs
|
|
231
|
+
covered = share >= float(cfg["share_of_runs_judged"])
|
|
232
|
+
rule = f"variants with an outcome cover {share:.0%} of the site's runs (need {float(cfg['share_of_runs_judged']):.0%})"
|
|
233
|
+
else:
|
|
234
|
+
share = None
|
|
235
|
+
base = vs[0] if vs else None
|
|
236
|
+
base_tables = _tables(base["sql"]) if base else frozenset()
|
|
237
|
+
needed = [v for v in vs if v is base or _tables(v["sql"]) != base_tables]
|
|
238
|
+
covered = bool(vs) and all(effective_state(v) for v in needed)
|
|
239
|
+
rule = "not seen in production: the base variant and every variant that changes the table set need an outcome"
|
|
240
|
+
fam["coverage"] = {"variants": len(vs), "judged": len(judged), "unbuilt": len(fam["unbuilt"]),
|
|
241
|
+
"share_of_runs_judged": round(share, 4) if share is not None else None, "covered": covered, "rule": rule}
|
|
242
|
+
states = {v["id"]: effective_state(v) for v in vs}
|
|
243
|
+
fixed = [v for v in vs if states[v["id"]] == "fixed"]
|
|
244
|
+
regress = [v for v in vs if (v.get("outcome") or {}).get("evidence", {}).get("regressed_by_fix")]
|
|
245
|
+
if fixed and covered and not regress:
|
|
246
|
+
verified = [v for v in fixed if not v.get("unverified")]
|
|
247
|
+
out = {"state": "improved", "verified": bool(verified)}
|
|
248
|
+
elif covered and any(states[v["id"]] == "blocked" for v in vs):
|
|
249
|
+
out = {"state": "needs_another_fix"}
|
|
250
|
+
elif covered and judged and all(states[v["id"]] in ("nothing_to_gain", None) for v in judged):
|
|
251
|
+
out = {"state": "nothing_to_gain"}
|
|
252
|
+
else:
|
|
253
|
+
out = {"state": "could_not_be_judged", "reason": unjudged_reason(fam, judged, share)}
|
|
254
|
+
out["next_step"] = REASONS[out["reason"]]
|
|
255
|
+
out["spread"] = spread(fam, fixed, runs)
|
|
256
|
+
fam["rollup"] = out
|
|
257
|
+
return out
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def unjudged_reason(fam: dict, judged: list[dict], share: float | None) -> str:
|
|
261
|
+
vs = fam["variants"]
|
|
262
|
+
if not vs:
|
|
263
|
+
if not (fam["template"].get("text") or "").strip():
|
|
264
|
+
return "no_statement_text"
|
|
265
|
+
return "run_time_parts"
|
|
266
|
+
if all((v.get("valid") or {}).get("planned") is False for v in vs):
|
|
267
|
+
return "does_not_plan"
|
|
268
|
+
if judged:
|
|
269
|
+
return "variants_not_covered"
|
|
270
|
+
return "family_not_benchmarked"
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def spread(fam: dict, fixed: list[dict], runs: int) -> str:
|
|
274
|
+
"""The line under the chip: 'fix helps 3 of 8 variants, 71% of runs'."""
|
|
275
|
+
n = len(fam["variants"])
|
|
276
|
+
if not fixed or not n:
|
|
277
|
+
return ""
|
|
278
|
+
share = sum(int((v.get("production") or {}).get("executions") or 0) for v in fixed) / runs if runs else None
|
|
279
|
+
return f"fix helps {len(fixed)} of {n} variants" + (f", {share:.0%} of runs" if share is not None else "")
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def has_statement(fam: dict) -> bool:
|
|
283
|
+
"""At least one complete statement (any basis)."""
|
|
284
|
+
return bool(fam["variants"])
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def valid_variants(fam: dict) -> list[dict]:
|
|
288
|
+
return [v for v in fam["variants"] if (v.get("valid") or {}).get("planned")]
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
PLACEHOLDER = re.compile(r"«([^»]*)»")
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def template_parts(text: str | None) -> list[dict]:
|
|
295
|
+
"""The «parts» of a template, with their roles (holes.role)."""
|
|
296
|
+
from .holes import role
|
|
297
|
+
out = []
|
|
298
|
+
for m in PLACEHOLDER.finditer(text or ""):
|
|
299
|
+
out.append({"expr": m.group(1)[:200], "role": role(text[max(0, m.start() - 200):m.start()], text[m.end():m.end() + 80]),
|
|
300
|
+
"at": m.start()})
|
|
301
|
+
return out
|