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/patterns_view.py
ADDED
|
@@ -0,0 +1,559 @@
|
|
|
1
|
+
"""How patterns are shown: the CLI summary, the hand-off text for a developer or a coding agent, and the report section.
|
|
2
|
+
|
|
3
|
+
Everything here is built from patterns.json alone (fixed vocabularies, no free text), so `codecop handoff` and `codecop report`
|
|
4
|
+
work on an out dir of any age that has the file.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import html
|
|
10
|
+
import json
|
|
11
|
+
from collections import Counter
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from .patterns import KIND_LABEL, SET_ASIDE
|
|
15
|
+
from .formerly import code as _code # next-step codes stored before the rename
|
|
16
|
+
|
|
17
|
+
CHANGE_TEXT = {
|
|
18
|
+
"batch_into_one_query": "Fetch for all items in one query (IN over the items' keys, or a join), then look each item up in memory",
|
|
19
|
+
"join_into_driver": "Join the per-item table into the query that produces the items",
|
|
20
|
+
"read_only_what_changed": "Read again only the windows whose source rows changed since the last run",
|
|
21
|
+
"run_less_often": "Run the loop less often",
|
|
22
|
+
"move_out_of_loop": "Run the query once before the loop: it takes nothing from the item",
|
|
23
|
+
"cheaper_probe": "Ask a cheaper question first (a count, or the newest change time) before reading rows",
|
|
24
|
+
"longer_interval_or_push": "Poll less often, or be told about changes",
|
|
25
|
+
"one_pass": "Read the rows once and derive the other results from them",
|
|
26
|
+
"cache_or_dictionary": "Keep the answer in memory or a dictionary, with a stated staleness",
|
|
27
|
+
"rollup_or_materialized_view": "Maintain the aggregate incrementally (a rollup or a materialized view)",
|
|
28
|
+
"filter_in_query": "Filter, sort or cut in the query instead of in the code",
|
|
29
|
+
"keyset_paging": "Page by the last key seen instead of OFFSET",
|
|
30
|
+
}
|
|
31
|
+
TOUCHES_TEXT = {"code": "the code", "query": "the query", "table": "the table", "frequency": "how often it runs",
|
|
32
|
+
"source": "where the answer comes from"}
|
|
33
|
+
PROOF_TEXT = {
|
|
34
|
+
"data_side_verifiable": "the data side can be verified: one query against the sandbox, same rows, less work (not run: the pattern benchmark is not built yet)",
|
|
35
|
+
"evidence_only": "evidence only: the same work fewer times, nothing to benchmark",
|
|
36
|
+
"trade_off": "a trade-off against freshness: never a verified win",
|
|
37
|
+
}
|
|
38
|
+
PROOF_TAG = {"data_side_verifiable": "Data side verifiable", "evidence_only": "Evidence only", "trade_off": "Trade-off"}
|
|
39
|
+
UNKNOWN_TEXT = {
|
|
40
|
+
"batched_query_not_benchmarked": "whether one batched query reads less: not benchmarked",
|
|
41
|
+
"items_per_turn": "how many items a run iterates: not in the code",
|
|
42
|
+
"how_often_the_data_changes": "how often the rows change between runs: not read by the pull",
|
|
43
|
+
"senders": "how many processes run this loop",
|
|
44
|
+
"repeated_parameters": "how many runs used the same parameters",
|
|
45
|
+
"which_loop": "which loop sends these queries",
|
|
46
|
+
"what_the_code_does_with_rows": "what the code does with the rows",
|
|
47
|
+
"page_depth": "how deep the pages go",
|
|
48
|
+
}
|
|
49
|
+
CONFIDENCE_TEXT = {"code_and_production": "seen in code and in production", "production_only": "in production only",
|
|
50
|
+
"code_only": "in code only"}
|
|
51
|
+
NOTE_TEXT = {
|
|
52
|
+
"no_workload": "no query log was pulled", "not_in_the_log": "no member was found in the query log",
|
|
53
|
+
"log_disagrees_with_code": "the log disagrees with the code's count", "driver_not_measured": "the driver query is not in the log",
|
|
54
|
+
"inner_bound_not_in_code": "the inner loop's bound is not in the code", "queries_shared_with_other_patterns": "a member query is in other patterns too",
|
|
55
|
+
"source_not_located": "no call site sends these shapes", "sites_in_different_functions": "their call sites are in different functions",
|
|
56
|
+
"filter_looks_like_a_watermark": "the filter looks like 'newer than X': likely a poll",
|
|
57
|
+
}
|
|
58
|
+
GUESS_TEXT = {"guessed_call": "a call on the way was guessed", "named_not_called": "a function is handed over, not called",
|
|
59
|
+
"loop_variable_not_traced": "whether the item reaches the query was not traced",
|
|
60
|
+
"driver_guessed": "the driver query was guessed", "framework_calls_per_row": "the framework calls it once per row",
|
|
61
|
+
"lazy_load_eager_unknown": "a lazy load whose instances were loaded elsewhere: whether that query eager-loads it was not read"}
|
|
62
|
+
COLLECTION_TEXT = {"query": "rows of a query", "parameter": "a parameter", "field": "a field", "local": "a list built here",
|
|
63
|
+
"call": "what a call returns", "literal": "a literal list", "constant": "a constant", "range": "a range",
|
|
64
|
+
"framework": "rows the framework iterates", "unknown": "a collection"}
|
|
65
|
+
SET_ASIDE_TEXT = {
|
|
66
|
+
"already_batches": "loop already batches", "retry": "retry wrappers", "leaves_when_done": "loops that leave when the work is done",
|
|
67
|
+
"long_running": "workers that wait for the next message", "small_fixed_list": "short literal lists", "time_steps_only": "steps through time alone",
|
|
68
|
+
"unknown_loop": "loops of unknown kind", "loop_writes": "the loop also writes (the read may change)",
|
|
69
|
+
"loaded_once_per_instance": "a relation loaded once per object", "guarded_by_loop_variable": "runs for one kind of item only",
|
|
70
|
+
"loop_variable_may_reach": "the item may reach the query", "runs_once_then_leaves": "runs once, then leaves the loop",
|
|
71
|
+
"one_off_code": "migrations and other one-off code",
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def load(out_dir: Path) -> dict | None:
|
|
76
|
+
target = out_dir / "patterns.json"
|
|
77
|
+
return json.loads(target.read_text()) if target.exists() else None
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def find(data: dict, ref: str) -> dict | None:
|
|
81
|
+
"""A pattern by its id in this run (P-001) or its fingerprint (pat_...)."""
|
|
82
|
+
ref = ref.strip()
|
|
83
|
+
for p in data.get("patterns") or []:
|
|
84
|
+
if ref in (p.get("id"), p.get("fingerprint")):
|
|
85
|
+
return p
|
|
86
|
+
return None
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def human_bytes(n) -> str:
|
|
90
|
+
if n is None:
|
|
91
|
+
return "-"
|
|
92
|
+
n = float(n)
|
|
93
|
+
for unit, size in (("TB", 1e12), ("GB", 1e9), ("MB", 1e6), ("KB", 1e3)):
|
|
94
|
+
if abs(n) >= size:
|
|
95
|
+
return f"{n / size:.1f} {unit}" if n / size < 100 else f"{n / size:,.0f} {unit}"
|
|
96
|
+
return f"{n:.0f} B"
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def pct(share) -> str:
|
|
100
|
+
return "-" if share is None else f"{share * 100:.1f}%" if share >= 0.001 else "<0.1%"
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def where(p: dict) -> str:
|
|
104
|
+
if p.get("loops"):
|
|
105
|
+
lp = p["loops"][0]
|
|
106
|
+
return f"{lp.get('file')}:{lp.get('line')}"
|
|
107
|
+
m = (p.get("members") or [{}])[0]
|
|
108
|
+
t = p.get("tables") or []
|
|
109
|
+
return f"{m.get('file')}:{m.get('line')}" if m.get("file") else (", ".join(t[:4]) + (f" +{len(t) - 4}" if len(t) > 4 else "")) or "source not located"
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def loop_words(lp: dict) -> str:
|
|
113
|
+
var = ", ".join(lp.get("vars") or []) or "item"
|
|
114
|
+
if lp.get("kind") == "time-window":
|
|
115
|
+
return f"for each time step ({var})" + (f", {lp['bound']} in the code" if lp.get("bound") else "")
|
|
116
|
+
if lp.get("kind") == "retry-poll":
|
|
117
|
+
return "until stopped, waiting between passes"
|
|
118
|
+
if lp.get("kind") == "fixed":
|
|
119
|
+
return f"for each of {lp.get('bound') or 'a fixed number of'} {var}"
|
|
120
|
+
over = f" in {lp['over']}" if lp.get("over") else ""
|
|
121
|
+
return f"for each {var}{over} ({COLLECTION_TEXT.get(lp.get('collection') or 'unknown', 'a collection')})"
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def not_benchmarkable(p: dict) -> str:
|
|
125
|
+
"""The engine of a pattern CodeCop has no sandbox for ("mysql"), else ""."""
|
|
126
|
+
from . import engines
|
|
127
|
+
eng = p.get("engine") or ""
|
|
128
|
+
return eng if eng and eng != "mixed" and eng not in engines.supported() else ""
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _engine_tag(p: dict) -> str:
|
|
132
|
+
eng = not_benchmarkable(p)
|
|
133
|
+
return _tag(f"engine not benchmarkable ({eng})", "dashed") if eng else ""
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def summary_lines(data: dict, limit: int = 5) -> list[str]:
|
|
137
|
+
"""The patterns stage in a few lines, then the heaviest patterns."""
|
|
138
|
+
s = data.get("summary") or {}
|
|
139
|
+
aside = s.get("set_aside") or {}
|
|
140
|
+
by_conf = s.get("by_confidence") or {}
|
|
141
|
+
out = [f"patterns {s.get('patterns', 0)} patterns from {s.get('loops', 0)} loops above {s.get('select_sites_in_loops', 0)} reads"
|
|
142
|
+
f" · code verified {s.get('code_verified', 0)} · guessed {s.get('patterns', 0) - s.get('code_verified', 0) - by_conf.get('production_only', 0)}"]
|
|
143
|
+
by_kind = s.get("by_kind") or {}
|
|
144
|
+
if by_kind:
|
|
145
|
+
out.append(" " + " · ".join(f"{KIND_LABEL[k].lower()} {n}" for k, n in by_kind.items()))
|
|
146
|
+
if by_conf:
|
|
147
|
+
out.append(" " + " · ".join(f"{CONFIDENCE_TEXT[k]} {n}" for k, n in by_conf.items()))
|
|
148
|
+
if aside:
|
|
149
|
+
out.append(" set aside: " + " · ".join(f"{SET_ASIDE_TEXT.get(k, k)} {v['loops']}" for k, v in aside.items() if k in SET_ASIDE))
|
|
150
|
+
pats = data.get("patterns") or []
|
|
151
|
+
engines_seen = Counter(p.get("engine") or "unknown" for p in pats)
|
|
152
|
+
if engines_seen and set(engines_seen) != {"unknown"}:
|
|
153
|
+
out.append(" engines: " + " · ".join(f"{e} {n}" + (" (engine not benchmarkable)" if not_benchmarkable({"engine": e}) else "")
|
|
154
|
+
for e, n in engines_seen.most_common()))
|
|
155
|
+
# the patterns a sandbox can judge are listed first; one on an engine CodeCop has no sandbox for says so
|
|
156
|
+
for p in sorted(pats, key=lambda p: bool(not_benchmarkable(p)))[:limit]:
|
|
157
|
+
m = p.get("measured") or {}
|
|
158
|
+
code = p.get("code") or {}
|
|
159
|
+
lead = f" {p['id']} {p['label'].lower():34s} {where(p)}"
|
|
160
|
+
out.append(lead)
|
|
161
|
+
n = p.get("member_count", 0)
|
|
162
|
+
bits = [f"{n} quer{'y' if n == 1 else 'ies'}" if n or not m else f"{m.get('shapes', 0)} shapes, no call site sends them"]
|
|
163
|
+
if m:
|
|
164
|
+
bits.append(f"{pct(m.get('share_of_read_bytes'))} of bytes read · {human_bytes(m.get('read_bytes'))} · {m.get('executions', 0):,} runs")
|
|
165
|
+
bits.append(CONFIDENCE_TEXT[p["confidence"]] + (f", code {code['evidence']}" if code else ""))
|
|
166
|
+
if not_benchmarkable(p):
|
|
167
|
+
bits.append(f"engine not benchmarkable ({not_benchmarkable(p)})")
|
|
168
|
+
out.append(" " + " · ".join(bits))
|
|
169
|
+
return out
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def handoff(data: dict, p: dict, repo: dict | None = None) -> str:
|
|
173
|
+
"""Plain text for the developer or their coding agent: where, what happens, what was measured, what is suggested
|
|
174
|
+
and not verified, what is not known, and how to check the change.
|
|
175
|
+
|
|
176
|
+
The text is pinned to one golden text (schemas/fixtures/handoff_pattern.json and .txt) by cli/tests/test_patterns.py."""
|
|
177
|
+
repo = repo or {}
|
|
178
|
+
at = " @ " + str(repo["commit"])[:8] if repo.get("commit") else ""
|
|
179
|
+
lines = [f"CodeCop pattern {p['id']} ({p['fingerprint']}) · {repo.get('name', '')}{at} · {p['label']}", ""]
|
|
180
|
+
lines.append("Where")
|
|
181
|
+
for i, lp in enumerate(p.get("loops") or []):
|
|
182
|
+
lines.append(f" {' ' * i}{lp.get('file')}:{lp.get('line')} {lp.get('function') or ''} {loop_words(lp)}")
|
|
183
|
+
if p.get("driver"):
|
|
184
|
+
d = p["driver"]
|
|
185
|
+
lines.append(f" the items are the rows of the query at {d.get('file')}:{d.get('line')} {d.get('symbol') or ''}".rstrip()
|
|
186
|
+
+ ("" if d.get("verified") else " (guessed)"))
|
|
187
|
+
for ep in p.get("entry_points") or []:
|
|
188
|
+
lines.append(f" reached from {ep.get('kind')} {ep.get('name')}")
|
|
189
|
+
if not p.get("loops") and p.get("tables"):
|
|
190
|
+
lines.append(f" tables: {', '.join(p['tables'])}")
|
|
191
|
+
lines += ["", "What happens (from the code)" if p.get("loops") else "What happens (from the query log)"]
|
|
192
|
+
if p.get("loops"):
|
|
193
|
+
lines.append(f" Each turn of the loop runs {p.get('member_count', 0)} read(s):")
|
|
194
|
+
for mem in p.get("members") or []:
|
|
195
|
+
dep = {True: "takes the item", False: "does not take the item", None: "not traced"}.get(mem.get("depends_on_loop_var"), "")
|
|
196
|
+
meas = mem.get("measured") or {}
|
|
197
|
+
extra = f" · {meas.get('executions', 0):,} runs, {human_bytes(meas.get('read_bytes'))}" if meas else ""
|
|
198
|
+
hop = f" · {mem['hop']} call(s) below the loop" if mem.get("hop") else ""
|
|
199
|
+
lines.append(f" {mem.get('file')}:{mem.get('line')} {mem.get('symbol') or ''} [{', '.join(mem.get('tables') or [])}]"
|
|
200
|
+
+ (f" · {dep}" if p.get("loops") else "") + hop + extra + ("" if mem.get("verified", True) else " (guessed)"))
|
|
201
|
+
if p.get("member_count", 0) > len(p.get("members") or []):
|
|
202
|
+
lines.append(f" and {p['member_count'] - len(p['members'])} more")
|
|
203
|
+
m = p.get("measured")
|
|
204
|
+
if m:
|
|
205
|
+
lines += ["", f"Measured in production (query log, {m.get('window_hours') or '?'} h, read-only; runs of these statements from any caller)"]
|
|
206
|
+
lines.append(f" {m.get('shapes', 0)} statement shape(s), {m.get('executions', 0):,} runs, {human_bytes(m.get('read_bytes'))} read"
|
|
207
|
+
f" ({pct(m.get('share_of_read_bytes'))} of all bytes read)")
|
|
208
|
+
if m.get("executions_per_driver_run") is not None:
|
|
209
|
+
lines.append(f" {m['executions_per_driver_run']:,} runs of the heaviest member per run of the driver query"
|
|
210
|
+
f" ({m.get('driver_executions', 0):,} driver runs, {m.get('driver_rows_per_run')} rows each)"
|
|
211
|
+
+ (f"; the code says {m['expected_per_driver_run']}" if m.get("expected_per_driver_run") is not None else ""))
|
|
212
|
+
if m.get("no_result_share") is not None:
|
|
213
|
+
lines.append(f" the heaviest member returned no rows in {pct(m['no_result_share'])} of its runs")
|
|
214
|
+
elif m.get("no_result_share_at_least") is not None:
|
|
215
|
+
lines.append(f" the heaviest member returned no rows in at least {pct(m['no_result_share_at_least'])} of its runs "
|
|
216
|
+
"(rows returned / runs: the statistics keep no per-run count)")
|
|
217
|
+
lines += ["", "Suggested, not verified by CodeCop"]
|
|
218
|
+
benched = (((p.get("batch") or {}).get("outcome") or {}).get("reason") or "bench_not_run") != "bench_not_run" and bool((p.get("batch") or {}).get("members"))
|
|
219
|
+
for i, c in enumerate(p.get("changes") or [], 1):
|
|
220
|
+
lines.append(f" {i}. {CHANGE_TEXT.get(c['change'], c['change'])}")
|
|
221
|
+
proof = BATCH_PROOF_TEXT if benched and c["change"] == "batch_into_one_query" else PROOF_TEXT.get(c["proof"], c["proof"])
|
|
222
|
+
lines.append(f" changes {TOUCHES_TEXT.get(c['touches'], c['touches'])}; {proof}")
|
|
223
|
+
unknown = [UNKNOWN_TEXT.get(u, u) for u in p.get("unknowns") or []]
|
|
224
|
+
if unknown:
|
|
225
|
+
lines += ["", "Not known"] + [f" {u}" for u in unknown]
|
|
226
|
+
code = p.get("code") or {}
|
|
227
|
+
conf = CONFIDENCE_TEXT[p["confidence"]]
|
|
228
|
+
lines += ["", "Confidence", f" {conf}" + (f"; code {code['evidence']}" if code else "")
|
|
229
|
+
+ (": " + "; ".join(GUESS_TEXT.get(g, g) for g in code.get("guessed_why") or []) if code.get("guessed_why") else "")]
|
|
230
|
+
notes = [NOTE_TEXT.get(n, n) for n in p.get("confidence_notes") or []]
|
|
231
|
+
if notes:
|
|
232
|
+
lines.append(" " + "; ".join(notes))
|
|
233
|
+
if p.get("batch"):
|
|
234
|
+
lines += [""] + batch_lines(p)
|
|
235
|
+
lines += ["", "Check your change",
|
|
236
|
+
f" codecop patterns . : {p['fingerprint']} should no longer be listed, or list fewer members.",
|
|
237
|
+
" A pattern is a candidate with evidence, not a proven win."]
|
|
238
|
+
return "\n".join(lines) + "\n"
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
# --------------------------------------------------------------------------- the loop benchmark (loopbench.py)
|
|
242
|
+
|
|
243
|
+
BATCH_PROOF_TEXT = "the data side was benchmarked in the sandbox: see Batched statement below"
|
|
244
|
+
ITEMS_BASIS_TEXT = {"driver_on_sandbox": "N from the driver query's result on the sandbox data",
|
|
245
|
+
"production_per_driver_run": "N from production's runs per driver run",
|
|
246
|
+
"production_driver_rows": "N from the rows production's driver returned per run", "setting": "N from the setting items_typical"}
|
|
247
|
+
RULE_TEXT = {"in_list": "IN over the items", "in_list_group_by": "IN over the items, GROUP BY the key",
|
|
248
|
+
"in_list_limit_by": "IN over the items, LIMIT n BY the key", "in_list_row_number": "IN over the items, ROW_NUMBER per key",
|
|
249
|
+
"agent": "written by the agent"}
|
|
250
|
+
NO_RULE_NOTE = "a join, a CTE, a subquery, a window, OFFSET or an unclear key is the paid agent step's"
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _reads(before, after, rows_before=None, rows_after=None) -> str:
|
|
254
|
+
if before is None or after is None:
|
|
255
|
+
return "-"
|
|
256
|
+
text = f"{human_bytes(before)} → {human_bytes(after)}"
|
|
257
|
+
if before:
|
|
258
|
+
text += f" ({(after / before - 1) * 100:+.0f}%)"
|
|
259
|
+
return text
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def batch_lines(p: dict) -> list[str]:
|
|
263
|
+
"""The hand-off's section for the loop benchmark: the state, and per member the statements and reads before and
|
|
264
|
+
after, the per-item sameness, the batched statement and how to split its result per item."""
|
|
265
|
+
from .loopbench import NEXT_STEP, STATE_WORDS, WORDS
|
|
266
|
+
b = p.get("batch") or {}
|
|
267
|
+
o = b.get("outcome") or {}
|
|
268
|
+
lines = ["Batched statement (codecop bench, sandbox)"]
|
|
269
|
+
if o:
|
|
270
|
+
lines.append(f" State: {STATE_WORDS.get(o.get('state'), '?')}. {WORDS.get(o.get('reason'), o.get('reason') or '')}."
|
|
271
|
+
+ (f" {o['evidence']['members_fixed']} of {o['evidence']['members']} member(s) fixed."
|
|
272
|
+
if (o.get("evidence") or {}).get("members", 0) > 1 else ""))
|
|
273
|
+
lines.append(" Round trips fall from N to 1 by construction; the reads are measured; fixed only when every item's rows are "
|
|
274
|
+
"reproduced and the reads are no worse.")
|
|
275
|
+
for m in b.get("members") or []:
|
|
276
|
+
lines.append(f" {m.get('file')}:{m.get('line')} {m.get('symbol') or ''}".rstrip()
|
|
277
|
+
+ (f" · item: {m['key']} ({m.get('key_basis')})" if m.get("key") else ""))
|
|
278
|
+
if m.get("reason") and m.get("state") != "fixed":
|
|
279
|
+
lines.append(f" {WORDS.get(m['reason'], m['reason'])}. Next step: {str(_code(m.get('next_step')) or NEXT_STEP.get(m['reason'], '')).replace('_', ' ')}.")
|
|
280
|
+
t, h = m.get("typical") or {}, m.get("heavy") or {}
|
|
281
|
+
if t:
|
|
282
|
+
lines.append(f" statements {t.get('statements_before')} → {t.get('statements_after')} (typical run, {t.get('items')} items: "
|
|
283
|
+
f"{ITEMS_BASIS_TEXT.get(m.get('items_basis'), m.get('items_basis') or '')})"
|
|
284
|
+
+ (f" · {h.get('statements_before')} → {h.get('statements_after')} (heavy run)" if h else ""))
|
|
285
|
+
lines.append(f" reads {_reads(t.get('read_bytes_before'), t.get('read_bytes_after'))} (typical)"
|
|
286
|
+
+ (f" · {_reads(h.get('read_bytes_before'), h.get('read_bytes_after'))} (heavy)" if h else "")
|
|
287
|
+
+ (" · reads more: a trade-off" if t.get("reads_worse") or h.get("reads_worse") else ""))
|
|
288
|
+
mark = {True: "same rows", False: "OTHER ROWS", None: "not shown"}
|
|
289
|
+
lines.append(f" per item {mark[t.get('same_rows')]}: {t.get('items_reproduced', 0)} of {t.get('items_compared', 0)} items "
|
|
290
|
+
f"({t.get('absent', 0)} hold no row, {t.get('repeated', 0)} listed twice)"
|
|
291
|
+
+ (f" · {mark[h.get('same_rows')]}: {h.get('items_reproduced', 0)} of {h.get('items_compared', 0)} (heavy)" if h else ""))
|
|
292
|
+
if m.get("production_per_driver_run") is not None:
|
|
293
|
+
lines.append(f" production {m['production_per_driver_run']:,} runs per driver run (query log), beside the sandbox's N")
|
|
294
|
+
if m.get("sql") and m.get("state") in ("fixed", "blocked"):
|
|
295
|
+
per = m.get("per_item") or {}
|
|
296
|
+
lines.append(" Run once per chunk of items (" + RULE_TEXT.get(m.get("rule"), m.get("rule") or "") + "):")
|
|
297
|
+
lines.append(f" {m['sql']}")
|
|
298
|
+
lines.append(" Split the result per item:")
|
|
299
|
+
lines.append(f" each item's rows are the rows whose codecop_k equals the item; drop {per.get('split') or 'codecop_k'}")
|
|
300
|
+
if per.get("order_by"):
|
|
301
|
+
lines.append(f" within an item, ordered by {per['order_by']}")
|
|
302
|
+
if per.get("limit"):
|
|
303
|
+
lines.append(f" at most {per['limit']} row(s) per item (the batched statement cuts per item)")
|
|
304
|
+
lines.append(" an item no row holds: " + ("the aggregates over no rows (count 0)" if per.get("absent") == "aggregate_over_no_rows" else "no rows"))
|
|
305
|
+
lines.append(" an item listed twice: the same rows again")
|
|
306
|
+
elif m.get("no_rule"):
|
|
307
|
+
lines.append(f" no rule: {m['no_rule']} ({NO_RULE_NOTE})")
|
|
308
|
+
if not b.get("members") and not o:
|
|
309
|
+
lines.append(" Not benchmarked yet.")
|
|
310
|
+
elif not b.get("members") and o.get("next_step"):
|
|
311
|
+
lines.append(f" Next step: {o['next_step'].replace('_', ' ')}.")
|
|
312
|
+
return lines
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def handoff_json(data: dict, p: dict, repo: dict | None = None) -> dict:
|
|
316
|
+
return {"pattern": p, "repo": {k: (repo or {}).get(k, "") for k in ("name", "commit", "branch")},
|
|
317
|
+
"window_hours": data.get("window_hours"),
|
|
318
|
+
"text": {"changes": {c["change"]: CHANGE_TEXT.get(c["change"], c["change"]) for c in p.get("changes") or []},
|
|
319
|
+
"unknowns": {u: UNKNOWN_TEXT.get(u, u) for u in p.get("unknowns") or []}}}
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
# --------------------------------------------------------------------------- report section
|
|
323
|
+
|
|
324
|
+
def _e(x) -> str:
|
|
325
|
+
return html.escape(str(x if x is not None else ""))
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def _tag(text, cls="") -> str:
|
|
329
|
+
return f"<span class='tag {_e(cls)}'>{_e(text)}</span>"
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
CONF_CLASS = {"code_and_production": "verified", "production_only": "unverified", "code_only": ""}
|
|
333
|
+
PROOF_CLASS = {"data_side_verifiable": "", "evidence_only": "unverified dashed", "trade_off": "unverified dashed"}
|
|
334
|
+
CSS = """
|
|
335
|
+
.pat-loop{border:1px solid var(--accent);border-radius:8px;padding:8px 10px;margin:8px 0;background:var(--panel)}
|
|
336
|
+
.pat-loop .pat-loop{margin:8px 0 4px 14px}
|
|
337
|
+
.pat-head{display:flex;gap:8px;align-items:baseline;flex-wrap:wrap;font-size:13.5px}.pat-head b{font-weight:600}
|
|
338
|
+
.pat-rows{display:grid;grid-template-columns:minmax(0,2.2fr) minmax(0,1.2fr) auto auto auto;gap:3px 12px;font-size:13px;margin-top:6px;align-items:center}
|
|
339
|
+
.pat-rows .h{color:var(--muted);font-size:11px;text-transform:uppercase;letter-spacing:.04em}
|
|
340
|
+
.pat-rows>span{overflow-wrap:anywhere;min-width:0}.pat-rows .n{text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap}
|
|
341
|
+
.tag.dashed{border-style:dashed}
|
|
342
|
+
.pat-driver{font-size:13px;color:var(--muted);margin:4px 0}
|
|
343
|
+
@media (max-width:700px){.pat-rows{grid-template-columns:minmax(0,1fr) auto auto}.pat-rows .opt{display:none}}
|
|
344
|
+
"""
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def _bar(share) -> str:
|
|
348
|
+
w = min(100.0, (share or 0) * 100)
|
|
349
|
+
return f"<span class=mini><span class=track style='display:block'><span class='fill read' style='display:block;width:{w:.1f}%'></span></span></span>"
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def _members_html(p: dict) -> str:
|
|
353
|
+
rows = ["<span class=h>Query fired each turn</span><span class='h opt'>Tables</span><span class=h>Takes the outer item</span>"
|
|
354
|
+
"<span class='h n'>Runs</span><span class='h n'>Bytes read</span>"]
|
|
355
|
+
for m in p.get("members") or []:
|
|
356
|
+
meas = m.get("measured") or {}
|
|
357
|
+
dep = {True: _tag("takes the item"), False: _tag("same input every turn", "unverified"), None: _tag("not traced")}.get(
|
|
358
|
+
m.get("depends_on_loop_var"), "") if p.get("loops") else ""
|
|
359
|
+
hop = f" <span class=muted>· {m['hop']} call(s) down</span>" if m.get("hop") else ""
|
|
360
|
+
rows.append(f"<span class=mono>{_e(m.get('symbol') or '')} <span class=muted>{_e(m.get('file'))}:{_e(m.get('line'))}</span>{hop}"
|
|
361
|
+
f"{'' if m.get('verified', True) else ' ' + _tag('guessed', 'unverified')}</span>"
|
|
362
|
+
f"<span class='mono opt'>{_e(', '.join(m.get('tables') or []))}</span><span>{dep}</span>"
|
|
363
|
+
f"<span class=n>{meas.get('executions', 0):,}</span><span class=n>{_e(human_bytes(meas.get('read_bytes'))) if meas else '-'}</span>"
|
|
364
|
+
if meas else
|
|
365
|
+
f"<span class=mono>{_e(m.get('symbol') or '')} <span class=muted>{_e(m.get('file'))}:{_e(m.get('line'))}</span>{hop}"
|
|
366
|
+
f"{'' if m.get('verified', True) else ' ' + _tag('guessed', 'unverified')}</span>"
|
|
367
|
+
f"<span class='mono opt'>{_e(', '.join(m.get('tables') or []))}</span><span>{dep}</span><span class=n>-</span><span class=n>-</span>")
|
|
368
|
+
more = p.get("member_count", 0) - len(p.get("members") or [])
|
|
369
|
+
if more > 0:
|
|
370
|
+
rows.append(f"<span class=muted>+{more} more</span><span></span><span></span><span></span><span></span>")
|
|
371
|
+
return f"<div class=pat-rows>{''.join(rows)}</div>"
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def _loops_html(p: dict) -> str:
|
|
375
|
+
"""The loops drawn as nested boxes, outermost first; the queries fired each turn inside the innermost one."""
|
|
376
|
+
loops = p.get("loops") or []
|
|
377
|
+
inner = _members_html(p)
|
|
378
|
+
for i, lp in reversed(list(enumerate(loops))):
|
|
379
|
+
head = (f"<div class=pat-head><b>{_e(loop_words(lp))}</b><span class=mono>{_e(lp.get('file'))}:{_e(lp.get('line'))}</span>"
|
|
380
|
+
f"<span class=muted>{_e(lp.get('function') or '')}</span>{_tag(lp.get('kind'))}"
|
|
381
|
+
f"{'' if lp.get('verified', True) else _tag('guessed call', 'unverified')}</div>")
|
|
382
|
+
drv = ""
|
|
383
|
+
if i == 0 and p.get("driver"):
|
|
384
|
+
d = p["driver"]
|
|
385
|
+
dm = (p.get("measured") or {})
|
|
386
|
+
meas = f" · {dm['driver_executions']:,} runs, {dm.get('driver_rows_per_run')} rows each" if dm.get("driver_executions") else ""
|
|
387
|
+
drv = (f"<div class=pat-driver>items from the query at <span class=mono>{_e(d.get('file'))}:{_e(d.get('line'))}</span> "
|
|
388
|
+
f"{_e(d.get('symbol') or '')}{meas}{'' if d.get('verified') else ' ' + _tag('guessed', 'unverified')}</div>")
|
|
389
|
+
inner = f"<div class=pat-loop>{head}{drv}{inner}</div>"
|
|
390
|
+
return inner
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def _accounting_html(data: dict) -> str:
|
|
394
|
+
out = []
|
|
395
|
+
for a in data.get("accounting") or []:
|
|
396
|
+
total = a.get("read_bytes_total") or 0
|
|
397
|
+
segs = "".join(f"<i class='pk-{_e(r['kind'])}' title='{_e(KIND_LABEL.get(r['kind'], 'No call-pattern signal'))}: "
|
|
398
|
+
f"{_e(human_bytes(r['read_bytes']))}' style='width:{(r['read_bytes'] / total * 100) if total else 0:.2f}%'></i>"
|
|
399
|
+
for r in a.get("by_kind") or [])
|
|
400
|
+
rows = "".join(f"<tr><td>{_e(KIND_LABEL.get(r['kind'], 'No call-pattern signal'))}</td><td class=num>{r['shapes']:,}</td>"
|
|
401
|
+
f"<td class=num>{r['executions']:,}</td><td class=num>{_e(human_bytes(r['read_bytes']))}</td>"
|
|
402
|
+
f"<td class=num>{_e(pct(r.get('share_of_read_bytes')))}</td></tr>" for r in a.get("by_kind") or [])
|
|
403
|
+
out.append(f"<h4>Each measured byte counted once · {_e(a.get('engine'))}, {_e(a.get('window_hours'))} h of query log</h4>"
|
|
404
|
+
f"<div class=stack>{segs}</div><div class=wrap><table><tr><th>First pattern it fits</th><th class=num>Shapes</th>"
|
|
405
|
+
f"<th class=num>Runs</th><th class=num>Bytes read</th><th class=num>Share</th></tr>{rows}</table></div>")
|
|
406
|
+
return "".join(out)
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
PK_COLORS = {"n_plus_one": "#b3261e", "fan_out": "#d0532f", "per_item": "#e08a3c", "same_input": "#c9a227", "poll": "#2f5fd0",
|
|
410
|
+
"fires_together": "#6a4fc7", "hot_small": "#3d8bd0", "heavy_aggregate": "#1a7f4b", "large_result": "#4f9a6d",
|
|
411
|
+
"offset_paging": "#7a8a99", "no_signal": "#c9ccd1"}
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
BATCH_CSS = """
|
|
415
|
+
.bat-rows{display:grid;grid-template-columns:minmax(0,2fr) auto minmax(0,1.6fr) minmax(0,1.6fr) auto auto;gap:4px 12px;font-size:13px;margin-top:6px;align-items:center}
|
|
416
|
+
.bat-rows .h{color:var(--muted);font-size:11px;text-transform:uppercase;letter-spacing:.04em}
|
|
417
|
+
.bat-rows>span{min-width:0;overflow-wrap:anywhere}.bat-rows .n{text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap}
|
|
418
|
+
.bat-pair{display:grid;grid-template-columns:auto 1fr;gap:1px 6px;align-items:center;font-variant-numeric:tabular-nums;font-size:12px}
|
|
419
|
+
.bat-pair i{display:block;height:6px;border-radius:3px;background:var(--muted);opacity:.55}.bat-pair i.after{background:var(--accent);opacity:1}
|
|
420
|
+
.bat-ok{color:#1a7f4b;font-weight:600}.bat-no{color:#b3261e;font-weight:600}
|
|
421
|
+
@media (max-width:700px){.bat-rows{grid-template-columns:minmax(0,1fr) auto auto}.bat-rows .opt{display:none}}
|
|
422
|
+
"""
|
|
423
|
+
BATCH_STATE_CLASS = {"fixed": "verified", "blocked": "unverified", "not_judged": "", "nothing_to_gain": ""}
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def _batch_cell(p: dict) -> str:
|
|
427
|
+
"""The patterns table's cell: N → 1, the reads' change and the per-item mark, or the state in words. A record it can
|
|
428
|
+
not read is said in the cell ("could not be judged: ..."), never a report that is not written."""
|
|
429
|
+
try:
|
|
430
|
+
return _batch_cell_of(p)
|
|
431
|
+
except (TypeError, ValueError, KeyError, ZeroDivisionError) as e:
|
|
432
|
+
return _tag(f"could not be judged: {type(e).__name__}: {e}"[:160], "dashed")
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def _batch_cell_of(p: dict) -> str:
|
|
436
|
+
b = p.get("batch")
|
|
437
|
+
if not b:
|
|
438
|
+
return ""
|
|
439
|
+
from .loopbench import STATE_WORDS
|
|
440
|
+
o = b.get("outcome") or {}
|
|
441
|
+
m = next((x for x in b.get("members") or [] if x.get("typical")), None)
|
|
442
|
+
if m:
|
|
443
|
+
t = m["typical"]
|
|
444
|
+
mark = {True: "<span class=bat-ok>✓</span>", False: "<span class=bat-no>✗</span>"}.get(t.get("same_rows"), "?")
|
|
445
|
+
reads = ""
|
|
446
|
+
if t.get("read_bytes_before") and t.get("read_bytes_after") is not None:
|
|
447
|
+
# a batched side that did not run records its reads as None: no change is said then
|
|
448
|
+
reads = f" · reads {(t['read_bytes_after'] / t['read_bytes_before'] - 1) * 100:+.0f}%"
|
|
449
|
+
return (f"<span class=mono>{t.get('statements_before')}→{t.get('statements_after')}</span> {mark}{_e(reads)} "
|
|
450
|
+
f"{_tag(STATE_WORDS.get(o.get('state'), ''), BATCH_STATE_CLASS.get(o.get('state'), ''))}")
|
|
451
|
+
if not b.get("qualifies"):
|
|
452
|
+
return _tag("not by rule", "dashed")
|
|
453
|
+
return _tag(STATE_WORDS.get(o.get("state"), "not run"), "dashed")
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
def _pair(before, after) -> str:
|
|
457
|
+
if before is None or after is None:
|
|
458
|
+
return "<span class=muted>-</span>"
|
|
459
|
+
top = max(before, after, 1)
|
|
460
|
+
return (f"<span class=bat-pair><span>{_e(human_bytes(before))}</span><i style='width:{before / top * 100:.1f}%'></i>"
|
|
461
|
+
f"<span>{_e(human_bytes(after))}</span><i class=after style='width:{after / top * 100:.1f}%'></i></span>")
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
def _batch_html(p: dict) -> str:
|
|
465
|
+
"""A pattern card's loop-benchmark block: per member, N statements → the batched one, the reads before and after on
|
|
466
|
+
the typical and the heavy run (two bars each), the per-item sameness and the state."""
|
|
467
|
+
b = p.get("batch")
|
|
468
|
+
if not b:
|
|
469
|
+
return ""
|
|
470
|
+
from .loopbench import STATE_WORDS, WORDS
|
|
471
|
+
o = b.get("outcome") or {}
|
|
472
|
+
head = (f"<h4>Batched statement · {_tag(STATE_WORDS.get(o.get('state'), 'not run'), BATCH_STATE_CLASS.get(o.get('state'), ''))}</h4>"
|
|
473
|
+
f"<p class=muted>{_e(WORDS.get(o.get('reason'), ''))}. Round trips fall to one by construction; reads measured; "
|
|
474
|
+
"a win only with every item's rows reproduced and reads no worse.</p>")
|
|
475
|
+
rows = ["<span class=h>Member · item</span><span class='h n'>Statements</span><span class=h>Reads, typical</span>"
|
|
476
|
+
"<span class='h opt'>Reads, heavy</span><span class=h>Per item</span><span class='h opt'>State</span>"]
|
|
477
|
+
for m in b.get("members") or []:
|
|
478
|
+
t, h = m.get("typical") or {}, m.get("heavy") or {}
|
|
479
|
+
mark = {True: "<span class=bat-ok>✓ same rows</span>", False: "<span class=bat-no>✗ other rows</span>"}.get(t.get("same_rows"), "<span class=muted>not shown</span>")
|
|
480
|
+
if t:
|
|
481
|
+
mark += f" <span class=muted>{t.get('items_reproduced', 0)}/{t.get('items_compared', 0)} · {t.get('absent', 0)} empty · {t.get('repeated', 0)} twice</span>"
|
|
482
|
+
stmts = (f"{t.get('statements_before')}→{t.get('statements_after')}" + (f"<br><span class=muted>{h.get('statements_before')}→{h.get('statements_after')}</span>" if h else "")) if t else "-"
|
|
483
|
+
prod = f" <span class=muted>· prod {m['production_per_driver_run']:,}/driver run</span>" if m.get("production_per_driver_run") is not None else ""
|
|
484
|
+
rows.append(f"<span class=mono>{_e(m.get('symbol') or '')} <span class=muted>{_e(m.get('file'))}:{_e(m.get('line'))}</span>"
|
|
485
|
+
f"{' · ' + _e(m['key']) if m.get('key') else ''}{prod}</span><span class=n>{stmts}</span>"
|
|
486
|
+
f"<span>{_pair(t.get('read_bytes_before'), t.get('read_bytes_after')) if t else '<span class=muted>-</span>'}</span>"
|
|
487
|
+
f"<span class=opt>{_pair(h.get('read_bytes_before'), h.get('read_bytes_after')) if h else '<span class=muted>-</span>'}</span>"
|
|
488
|
+
f"<span>{mark}</span><span class=opt>{_tag(STATE_WORDS.get(m.get('state'), ''), BATCH_STATE_CLASS.get(m.get('state'), ''))}</span>")
|
|
489
|
+
body = f"<div class=bat-rows>{''.join(rows)}</div>" if b.get("members") else ""
|
|
490
|
+
return head + body
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
def html_section(data: dict | None, detail: int = 30) -> str:
|
|
494
|
+
"""The "How queries are called" section of report.html: a dense table of patterns, the loop drawn for the first
|
|
495
|
+
`detail` of them, what was set aside, and (with a workload) each byte counted once."""
|
|
496
|
+
if not data:
|
|
497
|
+
return ""
|
|
498
|
+
s = data.get("summary") or {}
|
|
499
|
+
pats = data.get("patterns") or []
|
|
500
|
+
css = CSS + BATCH_CSS + "".join(f".pk-{k}{{background:{c}}}" for k, c in PK_COLORS.items())
|
|
501
|
+
rows = []
|
|
502
|
+
for p in pats:
|
|
503
|
+
m = p.get("measured") or {}
|
|
504
|
+
code = p.get("code") or {}
|
|
505
|
+
proofs = "".join(_tag(PROOF_TAG[c["proof"]], PROOF_CLASS[c["proof"]]) for c in (p.get("changes") or [])[:2])
|
|
506
|
+
rows.append(
|
|
507
|
+
f"<tr><td><a href='#{_e(p['id'])}'>{_e(p['id'])}</a></td><td>{_e(p['label'])}<div class=muted><code>{_e(where(p))}</code></div>{_engine_tag(p)}</td>"
|
|
508
|
+
f"<td class=num>{p.get('member_count', 0)}</td>"
|
|
509
|
+
f"<td>{_tag(CONFIDENCE_TEXT[p['confidence']], CONF_CLASS[p['confidence']])}"
|
|
510
|
+
f"{_tag('code ' + code['evidence'], 'verified' if code.get('evidence') == 'verified' else 'unverified') if code else ''}</td>"
|
|
511
|
+
f"<td class=num>{(_bar(m.get('share_of_read_bytes')) + _e(pct(m.get('share_of_read_bytes')))) if m else '<span class=muted>not measured</span>'}</td>"
|
|
512
|
+
f"<td class=num>{_e(human_bytes(m.get('read_bytes'))) if m else '-'}</td><td class=num>{m.get('executions', 0):,}</td>"
|
|
513
|
+
f"<td>{proofs}</td><td>{_batch_cell(p)}</td></tr>" if m else
|
|
514
|
+
f"<tr><td><a href='#{_e(p['id'])}'>{_e(p['id'])}</a></td><td>{_e(p['label'])}<div class=muted><code>{_e(where(p))}</code></div>{_engine_tag(p)}</td>"
|
|
515
|
+
f"<td class=num>{p.get('member_count', 0)}</td>"
|
|
516
|
+
f"<td>{_tag(CONFIDENCE_TEXT[p['confidence']], CONF_CLASS[p['confidence']])}"
|
|
517
|
+
f"{_tag('code ' + code['evidence'], 'verified' if code.get('evidence') == 'verified' else 'unverified') if code else ''}</td>"
|
|
518
|
+
f"<td class=num><span class=muted>not measured</span></td><td class=num>-</td><td class=num>-</td><td>{proofs}</td><td>{_batch_cell(p)}</td></tr>")
|
|
519
|
+
cards = []
|
|
520
|
+
for p in pats[:detail]:
|
|
521
|
+
m = p.get("measured") or {}
|
|
522
|
+
code = p.get("code") or {}
|
|
523
|
+
chips = [_tag(CONFIDENCE_TEXT[p["confidence"]], CONF_CLASS[p["confidence"]])] + ([_engine_tag(p)] if not_benchmarkable(p) else [])
|
|
524
|
+
if code:
|
|
525
|
+
chips.append(_tag(f"code {code['evidence']}", "verified" if code.get("evidence") == "verified" else "unverified"))
|
|
526
|
+
chips += [_tag(GUESS_TEXT.get(g, g), "unverified") for g in code.get("guessed_why") or []]
|
|
527
|
+
chips += [_tag(NOTE_TEXT.get(n, n)) for n in p.get("confidence_notes") or []]
|
|
528
|
+
meas = ""
|
|
529
|
+
if m:
|
|
530
|
+
meas = (f"<div class=cards><div class=card><b>{_e(pct(m.get('share_of_read_bytes')))}</b>of all bytes read</div>"
|
|
531
|
+
f"<div class=card><b>{_e(human_bytes(m.get('read_bytes')))}</b>read in {_e(m.get('window_hours'))} h</div>"
|
|
532
|
+
f"<div class=card><b>{m.get('executions', 0):,}</b>runs, {m.get('shapes', 0)} shape(s)</div>"
|
|
533
|
+
+ (f"<div class=card><b>{m['executions_per_driver_run']:,}</b>runs per driver run"
|
|
534
|
+
f"{' · the code says ' + _e(m['expected_per_driver_run']) if m.get('expected_per_driver_run') is not None else ''}</div>"
|
|
535
|
+
if m.get("executions_per_driver_run") is not None else "")
|
|
536
|
+
+ (f"<div class=card><b>{_e(pct(m['no_result_share']))}</b>runs returned nothing</div>" if m.get("no_result_share") is not None else
|
|
537
|
+
f"<div class=card><b>at least {_e(pct(m['no_result_share_at_least']))}</b>runs returned nothing</div>" if m.get("no_result_share_at_least") is not None else "")
|
|
538
|
+
+ "</div><p class=muted>Runs of these statements from any caller, measured; structure from the code. Never multiplied together.</p>")
|
|
539
|
+
body = _loops_html(p) if p.get("loops") else _members_html(p) + (
|
|
540
|
+
f"<div class=chips>{''.join(_tag(t) for t in p.get('tables') or [])}</div>" if p.get("tables") else "")
|
|
541
|
+
changes = "".join(f"<tr><td>{_e(TOUCHES_TEXT.get(c['touches'], c['touches']))}</td><td>{_e(CHANGE_TEXT.get(c['change'], c['change']))}</td>"
|
|
542
|
+
f"<td>{_tag(PROOF_TAG[c['proof']], PROOF_CLASS[c['proof']])}</td></tr>" for c in p.get("changes") or [])
|
|
543
|
+
unknown = "".join(_tag("not known: " + UNKNOWN_TEXT.get(u, u), "dashed") for u in p.get("unknowns") or [])
|
|
544
|
+
cards.append(f"<section class=finding id='{_e(p['id'])}'><header><h3>{_e(p['id'])} · {_e(p['label'])}</h3>"
|
|
545
|
+
f"<span class=muted mono>{_e(p['fingerprint'])}</span></header><div class=chips>{''.join(chips)}</div>{meas}{body}"
|
|
546
|
+
f"<h4>What could change</h4><div class=wrap><table><tr><th>Changes</th><th>Suggestion</th><th>What CodeCop can prove</th></tr>{changes}</table></div>"
|
|
547
|
+
f"{_batch_html(p)}<div class=chips>{unknown}</div><p class=muted>Hand-off text: <code>codecop handoff {_e(p['id'])}</code></p></section>")
|
|
548
|
+
aside = s.get("set_aside") or {}
|
|
549
|
+
aside_html = "".join(_tag(f"{SET_ASIDE_TEXT.get(k, k)}: {v['loops']} loops") for k, v in aside.items())
|
|
550
|
+
more = f"<p class=muted>The loop is drawn for the first {detail} patterns (setting `report_detail`).</p>" if len(pats) > detail else ""
|
|
551
|
+
return (f"<style>{css}</style><h2>How queries are called</h2>"
|
|
552
|
+
f"<div class=cards><div class=card><b>{s.get('patterns', 0)}</b>patterns</div><div class=card><b>{s.get('code_verified', 0)}</b>code verified</div>"
|
|
553
|
+
f"<div class=card><b>{(s.get('by_confidence') or {}).get('code_and_production', 0)}</b>seen in code and production</div>"
|
|
554
|
+
f"<div class=card><b>{s.get('loops', 0)}</b>loops above {s.get('select_sites_in_loops', 0)} reads</div></div>"
|
|
555
|
+
f"<div class=chips>{_tag('set aside')}{aside_html}</div>{_accounting_html(data)}"
|
|
556
|
+
f"<div class=wrap><table><tr><th>Id</th><th>Pattern</th><th class=num>Queries</th><th>Confidence</th><th class=num>Share of bytes read</th>"
|
|
557
|
+
f"<th class=num>Bytes</th><th class=num>Runs</th><th>Proof</th><th>Batched (sandbox)</th></tr>{''.join(rows)}</table></div>"
|
|
558
|
+
f"<p class=muted>A pattern is a candidate with evidence. A pattern's bytes are the sum of its queries from any caller, each shape once; "
|
|
559
|
+
f"they overlap with the per-query findings and are not added to them.</p>{more}{''.join(cards)}")
|