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/report.py
ADDED
|
@@ -0,0 +1,1854 @@
|
|
|
1
|
+
"""Stage 6, report: merge rank, profile and bench into findings, and render the local HTML report.
|
|
2
|
+
|
|
3
|
+
findings.json is the machine-readable result (the part of the run bundle the
|
|
4
|
+
dashboard shows). report.html is a single self-contained file.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import html
|
|
10
|
+
import math
|
|
11
|
+
import re
|
|
12
|
+
from collections import Counter
|
|
13
|
+
from datetime import datetime, timezone
|
|
14
|
+
|
|
15
|
+
from . import __version__, blockers as blockers_mod, coverage as coverage_mod, engines, joins_view
|
|
16
|
+
from . import fidelity as fidelity_mod, fixgroups, resources as resources_mod
|
|
17
|
+
from .realdb.facts import resources_measured, spread_upload
|
|
18
|
+
from .realdb.match import RESOURCE_KEYS
|
|
19
|
+
from .realdb.ratios import RATIO_KEYS, classify, ratios
|
|
20
|
+
|
|
21
|
+
VERDICT_ORDER = {"win": 0, "mixed": 1, "no_change": 2, "slower": 3, "rejected": 4, "failed": 5}
|
|
22
|
+
STATUS_LABEL = {
|
|
23
|
+
"verified": "Tested: reads less", "unverified": "Not verified", "rejected": "Rejected", "failed": "Could not be tested",
|
|
24
|
+
}
|
|
25
|
+
CAUSE_LABEL = {
|
|
26
|
+
"key_not_used": "Filter can't use the sorting key", "no_partition_pruning": "No partition pruning", "final_merge": "FINAL merge",
|
|
27
|
+
"wide_read": "Reads unused columns", "heavy_columns": "Heavy columns read", "per_row_function": "Function run per row",
|
|
28
|
+
"full_sort": "Sorts everything", "offset_paging": "OFFSET paging", "leading_wildcard": "Leading-wildcard LIKE",
|
|
29
|
+
"in_loop": "Query in a loop", "unbounded_result": "Unbounded result", "repeated_read": "Same data read twice",
|
|
30
|
+
"join_order": "Join order", "skip_index_ineffective": "Skip index can't prune", "cross_tenant_scan": "Cross-tenant scan", "other": "Other",
|
|
31
|
+
# PostgreSQL
|
|
32
|
+
"seq_scan": "Sequential scan", "non_sargable": "Index can't be used", "missing_join_index": "Join key not indexed",
|
|
33
|
+
"partial_index_match": "Index covers part of the filter", "not_covering": "Index doesn't cover the query",
|
|
34
|
+
"or_conditions": "OR across columns", "count_scan": "Exact count over many rows", "correlated_subquery": "Subquery run per row",
|
|
35
|
+
"no_gin_index": "No GIN index for the predicate",
|
|
36
|
+
}
|
|
37
|
+
TRADEOFF_LABEL = {
|
|
38
|
+
"extra_storage": "extra storage", "slower_inserts": "slower inserts", "backfill": "backfill needed", "code_change": "code change",
|
|
39
|
+
"schema_migration": "schema migration", "changes_results": "changes results", "needs_setting": "needs a setting",
|
|
40
|
+
}
|
|
41
|
+
REJECT_LABEL = {
|
|
42
|
+
"small_table": "Small table", "already_cheap": "Already cheap", "duplicate": "Same as another candidate", "one_off": "One-off script",
|
|
43
|
+
"unresolved_sql": "SQL could not be resolved", "other_engine": "Different engine", "cached": "Behind a cache", "other": "Other",
|
|
44
|
+
}
|
|
45
|
+
TRIGGER_LABEL = {
|
|
46
|
+
"per_request": "per request", "per_item": "per item", "scheduled": "scheduled", "on_event": "per event", "startup": "at startup",
|
|
47
|
+
"manual": "run by hand", "unknown": "frequency unknown",
|
|
48
|
+
}
|
|
49
|
+
DELIVERY = {
|
|
50
|
+
"rewrite": "code patch", "skip_index": "migration", "projection": "migration + storage cost",
|
|
51
|
+
"ordering_key": "migration plan, manual", "materialized_view": "migration + code patch", "column_type": "migration",
|
|
52
|
+
"index": "migration", "partitioning": "migration plan, manual",
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def duration(seconds: int) -> str:
|
|
57
|
+
for unit, size in (("d", 86400), ("h", 3600), ("min", 60)):
|
|
58
|
+
if seconds >= size:
|
|
59
|
+
return f"{seconds / size:g} {unit}"
|
|
60
|
+
return f"{seconds} s"
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def frequency_chips(freq) -> list[str]:
|
|
64
|
+
"""Short labels for how often a query runs. Accepts the old one-sentence form too."""
|
|
65
|
+
if not isinstance(freq, dict):
|
|
66
|
+
return [str(freq)[:60]] if freq and freq != "unknown" else ["frequency unknown"]
|
|
67
|
+
chips = [TRIGGER_LABEL.get(freq.get("trigger"), "frequency unknown")]
|
|
68
|
+
if freq.get("every_seconds"):
|
|
69
|
+
chips.append(f"every {duration(int(freq['every_seconds']))}")
|
|
70
|
+
if freq.get("in_loop"):
|
|
71
|
+
chips.append("in a loop")
|
|
72
|
+
if freq.get("cache_seconds"):
|
|
73
|
+
chips.append(f"cached {duration(int(freq['cache_seconds']))}")
|
|
74
|
+
elif freq.get("trigger") == "per_request":
|
|
75
|
+
chips.append("no cache")
|
|
76
|
+
if freq.get("note"):
|
|
77
|
+
chips.append(str(freq["note"])[:40])
|
|
78
|
+
return chips
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def measured(row: dict | None, window_hours, ctx: dict | None = None) -> dict | None:
|
|
82
|
+
"""What the real query log says about a finding's query: numbers only. `ctx`: the engine's db_match entry, for the
|
|
83
|
+
resource figures' windows and totals (facts.resources_measured)."""
|
|
84
|
+
if not row:
|
|
85
|
+
return None
|
|
86
|
+
return {"match": row["match"], "window_hours": window_hours, "executions": row["executions"],
|
|
87
|
+
"executions_per_day": row.get("executions_per_day"), "read_bytes": row["read_bytes"], "read_rows": row["read_rows"],
|
|
88
|
+
"avg_read_bytes": row.get("avg_read_bytes", 0), "avg_ms": row["avg_ms"], "p95_ms": row.get("p95_ms"),
|
|
89
|
+
"share_of_read_bytes": row["share_of_read_bytes"], "rank_by_bytes": row.get("rank_by_bytes"),
|
|
90
|
+
# per run: what is read against what is returned, and whether the shape is an aggregate (realdb/ratios.py)
|
|
91
|
+
**{k: row[k] for k in RATIO_KEYS if k in row},
|
|
92
|
+
# the spread of the runs when the pull asked for it: quantiles, the shares of runs that read or returned
|
|
93
|
+
# nothing, parts and marks selected per run. Rebuilt as numbers (facts.spread_upload), never passed through.
|
|
94
|
+
**spread_upload(row),
|
|
95
|
+
# CPU, peak memory, time, disk wait, spill and threads per run, a day and as a share: rebuilt as
|
|
96
|
+
# numbers (facts.resources_measured); absent where the pull did not have them
|
|
97
|
+
**resources_measured(row, {**(ctx or {}), "window_hours": window_hours})}
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
ESTIMATE_GRADES = ("close", "near")
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _production_of(cand: dict, by_finding: dict) -> dict:
|
|
104
|
+
"""What production measured per run for a candidate: its call site's (facts.production) or its observed shape's own."""
|
|
105
|
+
p = dict(by_finding.get(cand["finding"]) or {})
|
|
106
|
+
if cand.get("observed"):
|
|
107
|
+
p.update((cand["observed"].get("production") or {}))
|
|
108
|
+
return p
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def resource_grades(findings: list[dict], records: dict, by_finding: dict, cfg: dict, estimate: bool) -> dict | None:
|
|
112
|
+
"""Grade each finding's sandbox CPU and memory against production (fidelity.resource_check) beside its read grade, and,
|
|
113
|
+
unless `[report] production_estimate = false`, put the gated production estimate on it (`resource_estimate`). Returns
|
|
114
|
+
the run's machine factor (None when no candidate has a CPU figure on both sides)."""
|
|
115
|
+
factors = []
|
|
116
|
+
for f in findings:
|
|
117
|
+
rec, cand = records.get(f["finding"]) or (None, None)
|
|
118
|
+
if rec and (rec.get("baseline") or {}).get("ok") and f.get("fidelity"):
|
|
119
|
+
factors.append(((f["fidelity"] or {}).get("grade"), fidelity_mod.cpu_factor(rec["baseline"], _production_of(cand, by_finding))))
|
|
120
|
+
machine = fidelity_mod.machine_factor(factors, int(cfg["machine_factor_min_candidates"])) if any(x for _, x in factors) else None
|
|
121
|
+
for f in findings:
|
|
122
|
+
rec, cand = records.get(f["finding"]) or (None, None)
|
|
123
|
+
if not rec or not f.get("fidelity"):
|
|
124
|
+
continue
|
|
125
|
+
prod = _production_of(cand, by_finding)
|
|
126
|
+
rc = fidelity_mod.resource_check(rec, prod, machine)
|
|
127
|
+
fid = dict(f["fidelity"])
|
|
128
|
+
fid["ratios"] = {**(fid.get("ratios") or {}), **rc["ratios"]}
|
|
129
|
+
fid["resources"] = rc["resources"]
|
|
130
|
+
if "cpu_factor" in rc:
|
|
131
|
+
fid["cpu_factor"] = rc["cpu_factor"]
|
|
132
|
+
f["fidelity"] = fid
|
|
133
|
+
if estimate:
|
|
134
|
+
for f in findings:
|
|
135
|
+
f["resource_estimate"] = production_estimate(f, machine)
|
|
136
|
+
return machine
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
RESOURCE_RATIOS = {"cpu": ("cpu_per_byte",), "memory": ("memory", "memory_heavy")}
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _widen(fid: dict, keys: tuple[str, ...] | None = None) -> float:
|
|
143
|
+
"""How far a grade's worst ratio is from 1 (a factor >= 1): the width a near grade adds to an estimate's range.
|
|
144
|
+
`keys`: the ratios of one resource (RESOURCE_RATIOS); None for the read grade's own ratios."""
|
|
145
|
+
own = {k for ks in RESOURCE_RATIOS.values() for k in ks}
|
|
146
|
+
rs = [r for k, r in (fid.get("ratios") or {}).items() if (k in keys if keys else k not in own)]
|
|
147
|
+
return max([fidelity_mod.spread(r) for r in rs if r is not None and fidelity_mod.spread(r) != float("inf")] or [1.0])
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def production_estimate(f: dict, machine: dict | None) -> dict:
|
|
151
|
+
"""In production with the fix: production x the sandbox ratio, for a change the sandbox
|
|
152
|
+
verified returns the same rows. Made by default (`[report] production_estimate = false` turns it off) and gated per
|
|
153
|
+
resource: the read grade must be close or near for any figure, and CPU or memory each needs its own grade close or
|
|
154
|
+
near; a resource whose grade is off or absent is "not judged" (`not_judged {cpu, memory}`: graded_off | not_graded |
|
|
155
|
+
not_measured), never estimated. Every figure is {value, low, high, from, ratio}; a near grade (the read grade or the
|
|
156
|
+
resource's own) widens low and high by that grade's worst ratio. A memory max is estimated only from the heavy run.
|
|
157
|
+
Time is never estimated. An estimate is never a verified saving and is never summed into one."""
|
|
158
|
+
fid, real = f.get("fidelity") or {}, f.get("real") or {}
|
|
159
|
+
best = next((v for v in f.get("variants") or [] if v.get("verdict") == "win"), None)
|
|
160
|
+
if not real:
|
|
161
|
+
return {"judged": False, "why": "no_production"}
|
|
162
|
+
if best is None:
|
|
163
|
+
return {"judged": False, "why": "no_verified_change"}
|
|
164
|
+
grade = fid.get("grade")
|
|
165
|
+
if grade not in ESTIMATE_GRADES:
|
|
166
|
+
return {"judged": False, "why": "graded_off" if grade == "off" else "not_graded", "grade": grade or "unchecked"}
|
|
167
|
+
read_widen = 1.0 if grade == "close" else _widen(fid)
|
|
168
|
+
res = best.get("resources") or {}
|
|
169
|
+
grades = fid.get("resources") or {}
|
|
170
|
+
out: dict = {"judged": True, "basis": "production x sandbox ratio", "change": best.get("change") or best.get("kind"), "grade": grade,
|
|
171
|
+
"grades": {"read": grade, "cpu": grades.get("cpu") or "unchecked", "memory": grades.get("memory") or "unchecked"},
|
|
172
|
+
"window_hours": real.get("window_hours"), "not_judged": {}}
|
|
173
|
+
|
|
174
|
+
def widen_for(resource: str | None) -> float:
|
|
175
|
+
w = read_widen
|
|
176
|
+
if resource and grades.get(resource) == "near":
|
|
177
|
+
w = max(w, _widen(fid, RESOURCE_RATIOS[resource]))
|
|
178
|
+
return w
|
|
179
|
+
|
|
180
|
+
def put(name: str, value, m: dict | None, resource: str | None = None) -> None:
|
|
181
|
+
if value is None or not m or m.get("ratio") is None or m.get("low") is None:
|
|
182
|
+
return
|
|
183
|
+
w = widen_for(resource)
|
|
184
|
+
out[name] = {"value": round(value * m["ratio"], 3), "low": round(value * m["low"] / w, 3), "high": round(value * m["high"] * w, 3),
|
|
185
|
+
"from": round(value, 3), "ratio": m["ratio"]}
|
|
186
|
+
|
|
187
|
+
def gate(resource: str) -> bool:
|
|
188
|
+
g = grades.get(resource)
|
|
189
|
+
if g in ESTIMATE_GRADES:
|
|
190
|
+
return True
|
|
191
|
+
out["not_judged"][resource] = "graded_off" if g == "off" else "not_graded"
|
|
192
|
+
return False
|
|
193
|
+
|
|
194
|
+
days = (real.get("window_hours") or 0) / 24
|
|
195
|
+
last = (best.get("scales") or [None])[-1] or {}
|
|
196
|
+
b, v = last.get("baseline") or {}, last.get("variant") or {}
|
|
197
|
+
if days and b.get("read_bytes") and v.get("read_bytes") is not None:
|
|
198
|
+
r = v["read_bytes"] / b["read_bytes"]
|
|
199
|
+
put("read_bytes_per_day", real["read_bytes"] / days, {"ratio": r, "low": r, "high": r})
|
|
200
|
+
put("result_bytes_per_day", (real.get("result") or {}).get("bytes_per_day"), res.get("result"))
|
|
201
|
+
if (real.get("cpu") or {}).get("seconds_per_day") is not None:
|
|
202
|
+
if res.get("cpu_kind") != "rusage":
|
|
203
|
+
out["not_judged"]["cpu"] = "not_measured"
|
|
204
|
+
elif gate("cpu"):
|
|
205
|
+
put("cpu_seconds_per_day", real["cpu"]["seconds_per_day"], res.get("cpu"), "cpu")
|
|
206
|
+
if (real.get("memory") or {}).get("typical_bytes") is not None:
|
|
207
|
+
if res.get("memory_kind") != "tracker":
|
|
208
|
+
out["not_judged"]["memory"] = "not_measured"
|
|
209
|
+
elif gate("memory"):
|
|
210
|
+
put("memory_typical_bytes", real["memory"]["typical_bytes"], res.get("memory"), "memory")
|
|
211
|
+
put("memory_max_bytes", (real.get("memory") or {}).get("max_bytes"), (res.get("heavy") or {}).get("memory"), "memory")
|
|
212
|
+
if not out["not_judged"]:
|
|
213
|
+
del out["not_judged"]
|
|
214
|
+
return out
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def profile_for_findings(tables: list[dict]) -> list[dict]:
|
|
218
|
+
"""The data profile as findings.json carries it. A column's sizes by age (`width_by_age`) are per-partition detail
|
|
219
|
+
of the real database: the file keeps that the column has them, the period and how many bands, not the bands."""
|
|
220
|
+
out = []
|
|
221
|
+
for t in tables:
|
|
222
|
+
columns = []
|
|
223
|
+
for c in t.get("columns") or []:
|
|
224
|
+
by_age = c.get("width_by_age")
|
|
225
|
+
if isinstance(by_age, dict):
|
|
226
|
+
c = {**c, "width_by_age": {"unit": by_age.get("unit"), "bands": len(by_age.get("bands") or [])}}
|
|
227
|
+
columns.append(c)
|
|
228
|
+
out.append({**t, "columns": columns})
|
|
229
|
+
return out
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def measured_chips(real: dict | None) -> list[str]:
|
|
233
|
+
if not real:
|
|
234
|
+
return []
|
|
235
|
+
per = f"{human(real['executions_per_day'])} runs a day" if real.get("executions_per_day") else f"{human(real['executions'])} runs"
|
|
236
|
+
chips = [f"measured: {per}", f"{human_bytes(real['read_bytes'])} read", f"{real['share_of_read_bytes']:.2%} of all bytes read",
|
|
237
|
+
f"avg {real['avg_ms']:.0f} ms"]
|
|
238
|
+
return chips + (["matched through a template"] if real["match"] == "template" else ["part of a longer statement"] if real["match"] == "part"
|
|
239
|
+
else ["likely match"] if real["match"] == "likely" else [])
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def build_findings(rank: dict, profile: dict | None, bench: dict | None, inventory: dict | None = None, facts=None,
|
|
243
|
+
settings: dict | None = None, gates: dict | None = None, observed: dict | None = None, joins: dict | None = None,
|
|
244
|
+
bench_settings: dict | None = None, report_settings: dict | None = None) -> dict:
|
|
245
|
+
"""`facts`: the pulled real-database files (realdb.facts.Facts), when the run had them. `settings`: the `[blockers]`
|
|
246
|
+
table of codecop.toml (blockers.DEFAULTS). `gates`: call-site id -> why its observed statement could not be made
|
|
247
|
+
runnable (observed.py), for the sites that have no observed candidate."""
|
|
248
|
+
scales = bench["scales"] if bench else []
|
|
249
|
+
blocker_settings = blockers_mod.settings_of(settings)
|
|
250
|
+
floors = blockers_mod.engine_floors(rank["engine"], bench)
|
|
251
|
+
loaded_rows = blockers_mod.table_rows_of(scales[-1] if scales else None)
|
|
252
|
+
short_definitions = {blockers_mod.short(d["name"]): d for d in rank.get("table_definitions", [])}
|
|
253
|
+
findings = []
|
|
254
|
+
definitions = {t["name"]: t for t in rank.get("table_definitions", [])}
|
|
255
|
+
estimates = {t["name"]: t.get("rows") for t in (profile or {}).get("tables", [])}
|
|
256
|
+
engine = engines.get(rank["engine"])
|
|
257
|
+
matched = (facts.match(rank["engine"]) if facts else None) or {}
|
|
258
|
+
site_rows = matched.get("sites") or {}
|
|
259
|
+
bench_tier = (bench or {}).get("evidence_tier", "static only")
|
|
260
|
+
run_tier = facts.evidence_tier(rank["engine"], rank.get("table_definitions") or [], bench_tier) if facts and bench else bench_tier
|
|
261
|
+
for t, d in definitions.items(): # a real row count beats the profile's estimate
|
|
262
|
+
if d.get("source") == "real catalog" and d.get("rows"):
|
|
263
|
+
estimates[t] = d["rows"]
|
|
264
|
+
data_basis = describe_data(rank, profile, bench, bool(facts))
|
|
265
|
+
by_site = {c["id"]: c for c in (inventory or {}).get("call_sites") or [] if c.get("id")}
|
|
266
|
+
from . import joins as joins_mod
|
|
267
|
+
from . import observed as observed_mod
|
|
268
|
+
records: dict[str, tuple] = {} # finding -> (its bench record at the largest scale, the candidate)
|
|
269
|
+
for cand in rank["candidates"]:
|
|
270
|
+
cand = {**cand, "sql_from": observed_mod.sql_from_of(cand, by_site.get(cand["id"])), "located": observed_mod.located_of(cand)}
|
|
271
|
+
per_scale = []
|
|
272
|
+
for s in scales:
|
|
273
|
+
f = next((x for x in s["findings"] if x["finding"] == cand["finding"]), None)
|
|
274
|
+
if f and "carried_from" not in f: # carried to a scale it was not measured at (cli.bench, follow-up)
|
|
275
|
+
per_scale.append({"fraction": s["fraction"], "rows": max((t.get("rows", 0) for t in s["tables"]), default=0), **f})
|
|
276
|
+
largest = per_scale[-1] if per_scale else None
|
|
277
|
+
records[cand["finding"]] = (largest, cand)
|
|
278
|
+
variants = []
|
|
279
|
+
for i, v in enumerate(cand["variants"]):
|
|
280
|
+
runs = [{"rows": ps["rows"], "baseline": ps["baseline"], **ps["variants"][i]} for ps in per_scale
|
|
281
|
+
if ps["baseline"]["ok"] and i < len(ps["variants"])]
|
|
282
|
+
last = runs[-1] if runs else None
|
|
283
|
+
variants.append({
|
|
284
|
+
**v, "change": v.get("change") or v["kind"].replace("_", " "), "tradeoffs": v.get("tradeoffs") or [],
|
|
285
|
+
**engine.variant_extras(v),
|
|
286
|
+
"delivery": DELIVERY.get(v["kind"], "suggestion"),
|
|
287
|
+
"verdict": last["verdict"] if last else "untested",
|
|
288
|
+
"reason": last["reason"] if last else "",
|
|
289
|
+
"compared": last.get("compared", "") if last else "",
|
|
290
|
+
"results_match": last.get("results_match") if last else None,
|
|
291
|
+
# what the sandbox had to add for the setup to run, which the migration needs too (a table setting)
|
|
292
|
+
"setup_notes": (last.get("setup_notes") or []) if last else [],
|
|
293
|
+
"storage_delta_bytes": last["storage_delta_bytes"] if last else 0,
|
|
294
|
+
# the write side of a table-level variant, measured beside its read verdict (writecost.py)
|
|
295
|
+
**({"insert_cost": last["insert_cost"]} if last and last.get("insert_cost") else {}),
|
|
296
|
+
# CPU, memory, time, spill and result size against the baseline on the same sandbox (resources.py): ratios of
|
|
297
|
+
# medians with the range of the repeated runs, typical and heavy run, and whether they take the win away
|
|
298
|
+
**({"resources": resources_mod.for_upload(last["resources"])} if last and isinstance(last.get("resources"), dict) else {}),
|
|
299
|
+
"scales": [{"rows": r["rows"], "verdict": r["verdict"],
|
|
300
|
+
"baseline": _slim(r["baseline"]), "variant": _slim(r["measurement"]),
|
|
301
|
+
**({"resources": resources_mod.for_upload(r["resources"])} if isinstance(r.get("resources"), dict) else {})}
|
|
302
|
+
for r in runs],
|
|
303
|
+
# measured on the typical and on the heavy run as well (bench.bench_candidate, `variants_on`)
|
|
304
|
+
**({run: {k: last[run].get(k) for k in ("verdict", "reason", "compared", "results_match") if k in last[run]}
|
|
305
|
+
for run in ("typical", "heavy") if last and isinstance(last.get(run), dict)}),
|
|
306
|
+
})
|
|
307
|
+
prof = variants[-1].get("resources") or {}
|
|
308
|
+
if prof.get("measured"):
|
|
309
|
+
# the console's names: the heavy run's ratios under variants[].heavy.resources, and the judgement as resource_cost
|
|
310
|
+
if isinstance(prof.get("heavy"), dict):
|
|
311
|
+
variants[-1]["heavy"] = {**(variants[-1].get("heavy") or {}), "resources": prof["heavy"]}
|
|
312
|
+
variants[-1]["resource_cost"] = resources_mod.cost_of(prof)
|
|
313
|
+
blocked = (largest or {}).get("not_benchmarked")
|
|
314
|
+
if largest is not None and not largest["baseline"]["ok"]:
|
|
315
|
+
# Nothing was measured at the largest scale. What a smaller scale measured stays in `scales`; it is not
|
|
316
|
+
# this variant's verdict, or a finding that says "not benchmarked" would list a win under it.
|
|
317
|
+
for v in variants:
|
|
318
|
+
if v["verdict"] != "untested":
|
|
319
|
+
v.update(verdict="untested", results_match=None, compared="",
|
|
320
|
+
reason="not measured at the largest scale" + (f" (it was at a smaller one: {v['verdict']})" if v["scales"] else ""))
|
|
321
|
+
variants.sort(key=lambda v: VERDICT_ORDER.get(v["verdict"], 9))
|
|
322
|
+
if largest is None:
|
|
323
|
+
status, summary = "unverified", "No benchmark was run."
|
|
324
|
+
elif blocked:
|
|
325
|
+
# a table this query reads was not built: nothing was measured, and the build error is the reason
|
|
326
|
+
status, summary = "failed", blocked.get("detail") or "Not benchmarked: a table could not be built in the sandbox."
|
|
327
|
+
elif not largest["baseline"]["ok"]:
|
|
328
|
+
status, summary = "failed", f"The baseline query did not run on the sandbox: {largest['baseline']['error'][:2000]}"
|
|
329
|
+
elif any(v["verdict"] == "win" for v in variants):
|
|
330
|
+
best = variants[0]
|
|
331
|
+
status, summary = "verified", f"{best['kind']}: {best['reason']}"
|
|
332
|
+
elif variants and all(v["verdict"] in ("rejected", "failed") for v in variants):
|
|
333
|
+
status, summary = "rejected", variants[0]["reason"]
|
|
334
|
+
else:
|
|
335
|
+
status, summary = "unverified", variants[0]["reason"] if variants else "No variant was proposed."
|
|
336
|
+
origin = dict(cand.get("origin") or {"role": "unknown", "kind": "unknown", "entry_points": [], "verified": False})
|
|
337
|
+
origin.setdefault("path", [])
|
|
338
|
+
origin.setdefault("frequency", {"trigger": "unknown", "every_seconds": 0, "in_loop": False, "cache_seconds": 0, "note": ""})
|
|
339
|
+
origin["frequency_label"] = " · ".join(frequency_chips(origin["frequency"]))
|
|
340
|
+
access = [{**engine.table_access(definitions[t]["create_sql"], t, cand["baseline_sql"], estimates.get(t)),
|
|
341
|
+
# where the row count comes from: the real catalog, or the profile's estimate
|
|
342
|
+
"rows_evidence": "real catalog" if definitions[t].get("source") == "real catalog" and definitions[t].get("rows") else "inferred"}
|
|
343
|
+
for t in cand["tables"] if t in definitions]
|
|
344
|
+
for a in access:
|
|
345
|
+
# `rows_estimate` keeps its name; `rows_label` is the sentence to show, and never says "in production"
|
|
346
|
+
# for a number nobody read from a database
|
|
347
|
+
a["rows_label"] = rows_label(a.get("rows_estimate"), a["rows_evidence"])
|
|
348
|
+
scan = None
|
|
349
|
+
if largest and largest["baseline"]["ok"]:
|
|
350
|
+
b = largest["baseline"]
|
|
351
|
+
scan = {"table_rows": largest["rows"], **{k: b.get(k) for k in ("read_rows", "result_rows", "read_bytes", "selected_marks", "total_marks")},
|
|
352
|
+
**_ratio_pair(b)}
|
|
353
|
+
if "scans" in b: # Postgres: the plan's scan nodes and the buffers they touched; SQLite: its SCAN / SEARCH lines and pages
|
|
354
|
+
scan.update(nodes=b["scans"], buffers=b["pages"] if "pages" in b else b["shared_hit_blocks"] + b["shared_read_blocks"],
|
|
355
|
+
rows_removed=b.get("rows_removed", 0))
|
|
356
|
+
findings.append({
|
|
357
|
+
"finding": cand["finding"], "id": cand["id"], "title": cand["title"], "severity": cand["severity"],
|
|
358
|
+
"confidence": cand["confidence"], "status": status, "summary": summary,
|
|
359
|
+
"causes": cand.get("causes") or [], "assumptions": cand.get("assumptions") or [],
|
|
360
|
+
"origin": origin, "access": access, "scan": scan,
|
|
361
|
+
"site": cand["site"], "tables": cand["tables"],
|
|
362
|
+
# the values the baseline ran with: the fit to production may have given this query values of its own
|
|
363
|
+
"params": {**cand["params"], **(((scales[-1].get("param_overrides") if scales else None) or {}).get(cand["finding"]) or {})},
|
|
364
|
+
"baseline_sql": cand["baseline_sql"], "original_sql": cand.get("original_sql") or "",
|
|
365
|
+
"evidence_tier": run_tier if bench and largest and largest["baseline"]["ok"] else "static only",
|
|
366
|
+
"real": measured(site_rows.get(cand["id"]), matched.get("window_hours"), matched),
|
|
367
|
+
# the sandbox baseline against production per run (fidelity.py): grade, ratios; None when production is not known
|
|
368
|
+
"fidelity": (largest or {}).get("fidelity") if largest and largest["baseline"]["ok"] else None,
|
|
369
|
+
# the shape of the benchmarked query: an aggregate reads many rows to return few on purpose
|
|
370
|
+
"read_shape": classify(cand["baseline_sql"]),
|
|
371
|
+
"variants": variants,
|
|
372
|
+
**({"variants_on": largest["variants_on"]} if largest and largest.get("variants_on") else {}),
|
|
373
|
+
# None when it was measured (or no benchmark ran); else {reason, tables: [{table, error}], detail}
|
|
374
|
+
"not_benchmarked": blocked or None,
|
|
375
|
+
# the baseline hit the statement time limit at the largest scale (bench.judge_timeouts): where, at how many rows,
|
|
376
|
+
# and the scale it was judged at instead (None when it finished nowhere)
|
|
377
|
+
**({"timed_out": largest["timed_out"], "judged_at": largest.get("judged_at")} if largest and largest.get("timed_out") else {}),
|
|
378
|
+
# what about the sandbox's tables can move this verdict: an index that was left out, an invariant not kept
|
|
379
|
+
"sandbox_notes": (largest or {}).get("sandbox_notes") or [],
|
|
380
|
+
# what the numbers stand on, in words a page can print as they are
|
|
381
|
+
"evidence": {"table_rows": ("real catalog" if access and all(a["rows_evidence"] == "real catalog" for a in access)
|
|
382
|
+
else "agent estimate" if access else "none"),
|
|
383
|
+
"data": data_basis["generator"], "database_connected": data_basis["database_connected"],
|
|
384
|
+
"label": data_basis["label"]},
|
|
385
|
+
})
|
|
386
|
+
# where the SQL text comes from and where the place in code comes from (observed.py): two claims, two labels
|
|
387
|
+
findings[-1]["sql_from"], findings[-1]["located"] = cand["sql_from"], cand["located"]
|
|
388
|
+
if cand.get("assembled"):
|
|
389
|
+
# written out from its builder by `codecop rank --focus assembled` (assemble.py): the choices the agent made
|
|
390
|
+
findings[-1]["assembled"] = cand["assembled"]
|
|
391
|
+
if cand.get("observed"):
|
|
392
|
+
findings[-1]["observed"] = observed_for_findings(cand["observed"])
|
|
393
|
+
findings[-1]["real"] = observed_load(cand["observed"], matched) # the shape's own load, never a piece's or the site's sum
|
|
394
|
+
findings[-1]["load"] = findings[-1]["real"] # the same object under the name the contract documents
|
|
395
|
+
# why it did or did not end with a verified win: state, reason code and the numbers behind it (blockers.py)
|
|
396
|
+
findings[-1]["outcome"] = blockers_mod.candidate_outcome(
|
|
397
|
+
rank["engine"], cand, largest, blockers_mod.variants_from_findings(variants), access, loaded_rows, short_definitions,
|
|
398
|
+
blocker_settings, floors, site_rows.get(cand["id"]), benched=bool(scales))
|
|
399
|
+
if isinstance(cand.get("write"), dict):
|
|
400
|
+
# a write statement (writes.py): what it does, the values it ran with, rows changed, WAL, the final-state check
|
|
401
|
+
from .writes import finding_block
|
|
402
|
+
findings[-1]["write"] = finding_block(cand, largest)
|
|
403
|
+
if joins:
|
|
404
|
+
# the join drawn compactly: its two sides, which filters reach which side, what CodeCop's variant changes (joins.py)
|
|
405
|
+
got = joins_mod.finding_block(joins, cand, variants)
|
|
406
|
+
if got:
|
|
407
|
+
findings[-1]["join"] = got
|
|
408
|
+
machine = resource_grades(findings, records, facts.production(rank["engine"], rank["candidates"]) if facts else {},
|
|
409
|
+
resources_mod.settings_of(bench_settings), bool((report_settings or {}).get("production_estimate", True)))
|
|
410
|
+
rank_weight = {"verified": 0, "unverified": 1, "rejected": 2, "failed": 3}
|
|
411
|
+
sev = {"high": 0, "medium": 1, "low": 2}
|
|
412
|
+
kind_weight = {"http": 0, "workflow": 1, "activity": 1, "job": 1, "consumer": 1}
|
|
413
|
+
findings.sort(key=lambda f: (rank_weight[f["status"]], sev.get(f["severity"], 3), kind_weight.get(f["origin"].get("kind"), 2)))
|
|
414
|
+
listed = {s["id"]: s for s in rank.get("shortlist", [])}
|
|
415
|
+
# an `already_cheap` rejection the computed access analysis does not support (rank.audit_rejections): the agent
|
|
416
|
+
# said "primary-key lookups" of a query that reaches a partitioned table through a join
|
|
417
|
+
from .rank import audit_rejections
|
|
418
|
+
audit = audit_rejections(rank, inventory)
|
|
419
|
+
rejected = [{"id": r["id"], "code": r.get("code") or "other", "detail": (r.get("detail") or r.get("reason") or "")[:120],
|
|
420
|
+
"file": listed.get(r["id"], {}).get("file", "") or r.get("file", ""), "line": listed.get(r["id"], {}).get("line", 0) or r.get("line", 0),
|
|
421
|
+
# rejected by rule before the agent (rank.skip_rules): the measured numbers decided, not the agent
|
|
422
|
+
**({"by_rule": True, "rule_evidence": r.get("evidence") or {}} if r.get("by_rule") else {}),
|
|
423
|
+
**({"unconfirmed": audit[r["id"]]["reasons"], "access_checked": audit[r["id"]]["checked"]} if r["id"] in audit else {})}
|
|
424
|
+
for r in rank.get("rejected", [])]
|
|
425
|
+
from .rank import sql_cut_of
|
|
426
|
+
# a call site whose statement production ran became a candidate leaves the rejections: its finding says what happened.
|
|
427
|
+
# A piece's rejection goes too when the whole statement it is part of is a candidate.
|
|
428
|
+
replaced = {pid for c in rank["candidates"] if c.get("sql_from") == "query_log"
|
|
429
|
+
for pid in [c["id"], *((c.get("observed") or {}).get("places") or [])]}
|
|
430
|
+
rejected = [r for r in rejected if not (r["code"] == "unresolved_sql" and r["id"] in replaced)]
|
|
431
|
+
for r in rejected:
|
|
432
|
+
assembled = None
|
|
433
|
+
if r["code"] == "unresolved_sql":
|
|
434
|
+
assembled = _assembled(by_site.get(r["id"]), matched, sql_cut_of(rank), (gates or {}).get(r["id"]), facts, rank["engine"])
|
|
435
|
+
r["outcome"] = blockers_mod.rejection_outcome(r, site_rows.get(r["id"]), blocker_settings, disputed=bool(r.get("unconfirmed")),
|
|
436
|
+
assembled=assembled)
|
|
437
|
+
if r.get("by_rule") and r["outcome"]["reason"] in blockers_mod.CHEAP_CODES:
|
|
438
|
+
r["outcome"]["from"] = "measured"
|
|
439
|
+
r["outcome"]["evidence"] = {**r["outcome"]["evidence"], "by_rule": True, **r["rule_evidence"]}
|
|
440
|
+
elif r["outcome"]["state"] == "nothing_to_gain" and r["outcome"]["from"] == "agent":
|
|
441
|
+
r["outcome"]["evidence"].update(blockers_mod.catalog_basis(r["code"], by_site.get(r["id"]), facts, rank["engine"],
|
|
442
|
+
blocker_settings))
|
|
443
|
+
outcomes = _outcomes(rank, findings, rejected, inventory, site_rows, blocker_settings, matched.get("window_hours"))
|
|
444
|
+
# everything the agent was paid for in this out dir, earlier invocations included (rank.py keeps the ledger)
|
|
445
|
+
rank_cost = rank["agent"].get("cost_total_usd", rank["agent"].get("cost_usd", 0)) or 0
|
|
446
|
+
agent_cost = rank_cost + ((profile or {}).get("agent", {}).get("cost_usd", 0) or 0)
|
|
447
|
+
agent_cost += float(((observed or {}).get("agent") or {}).get("cost_total_usd") or 0) # `codecop rank --observed-variants`
|
|
448
|
+
from .bench import summary as bench_summary
|
|
449
|
+
tables = scales[-1]["tables"] if scales else []
|
|
450
|
+
invariants = [{"table": t["name"], **r} for t in tables for r in t.get("relations") or []]
|
|
451
|
+
listed_invariants = {(i["table"], i["column"]) for i in invariants}
|
|
452
|
+
invariants += [{**r, "enforced": False} for r in (bench or {}).get("relations_skipped") or []
|
|
453
|
+
if (r.get("table"), r.get("column")) not in listed_invariants]
|
|
454
|
+
return {
|
|
455
|
+
"schema_version": 1, "tool_version": __version__,
|
|
456
|
+
"generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
|
457
|
+
"repo": (inventory or {}).get("repo", {}),
|
|
458
|
+
# the version that was benchmarked; `engine_version_requested` is what the repository targets, and
|
|
459
|
+
# `engine_version_note` says why they differ ("" when they do not)
|
|
460
|
+
"engine": rank["engine"], "engine_version": (bench or {}).get("engine_version") or rank["engine_version"],
|
|
461
|
+
"engine_version_requested": (bench or {}).get("engine_version_requested") or rank.get("engine_version_requested")
|
|
462
|
+
or rank["engine_version"],
|
|
463
|
+
"engine_version_note": (bench or {}).get("engine_version_note") or (rank.get("engine_version_note", "") if not bench else ""),
|
|
464
|
+
"sandbox_image": (bench or {}).get("sandbox_image", ""),
|
|
465
|
+
"server_version": (bench or {}).get("server_version", ""),
|
|
466
|
+
"evidence_tier": run_tier,
|
|
467
|
+
# what the generated data is and where the table sizes come from, as text (`evidence_tier` keeps its values)
|
|
468
|
+
"evidence_label": data_basis["label"], "data": data_basis,
|
|
469
|
+
# at the largest scale: candidates, benchmarked, not_benchmarked (a table was not built), baseline_failed
|
|
470
|
+
"benchmark": ((bench or {}).get("summary") or bench_summary(bench)) if bench else None,
|
|
471
|
+
# relations between tables the generated data was made to keep, each with its source and what was counted after the load
|
|
472
|
+
"invariants": invariants,
|
|
473
|
+
"limits": (bench or {}).get("limits", []),
|
|
474
|
+
"billing": rank["agent"].get("billing", ""),
|
|
475
|
+
"database": {
|
|
476
|
+
"real_definitions": sum(1 for d in rank.get("table_definitions", []) if d.get("source") == "real catalog"),
|
|
477
|
+
"inferred_definitions": sum(1 for d in rank.get("table_definitions", []) if d.get("source") != "real catalog"),
|
|
478
|
+
"scoring": rank.get("scoring", "static heuristics"), "workload_window_hours": matched.get("window_hours"),
|
|
479
|
+
"findings_with_measured_load": sum(1 for f in findings if f.get("real")),
|
|
480
|
+
} if facts else None,
|
|
481
|
+
"inventory_summary": (inventory or {}).get("summary", {}),
|
|
482
|
+
"select_sites": rank.get("select_sites", 0), "shortlisted": len(rank.get("shortlist", [])),
|
|
483
|
+
"agent": {"runner": rank["agent"].get("runner", ""), "model": rank["agent"].get("model", ""), "cost_usd": round(agent_cost, 2),
|
|
484
|
+
"rank_invocations": rank["agent"].get("invocations", 1)},
|
|
485
|
+
"table_definitions": rank.get("table_definitions", []),
|
|
486
|
+
"profile": profile_for_findings((profile or {}).get("tables", [])),
|
|
487
|
+
"sandbox_tables": scales[-1]["tables"] if scales else [],
|
|
488
|
+
# how the generated data was made realistic, and what the fit to the real workload changed (bench.py)
|
|
489
|
+
"realism": (bench or {}).get("realism"),
|
|
490
|
+
"fit": scales[-1].get("fit") if scales else None,
|
|
491
|
+
# scales not loaded because no table could grow over the previous one, and typical runs made to return nothing
|
|
492
|
+
**({"scales_skipped": bench["scales_skipped"]} if (bench or {}).get("scales_skipped") else {}),
|
|
493
|
+
**({"empty_runs": bench["empty_runs"]} if (bench or {}).get("empty_runs") else {}),
|
|
494
|
+
"rejected_by_agent": rejected,
|
|
495
|
+
# statements production ran, used as baselines (observed.py): what became a candidate, what the gate refused, the
|
|
496
|
+
# shapes below the line, and production statements with no place in code
|
|
497
|
+
"observed": observed_summary(observed) if observed else None,
|
|
498
|
+
# every ranked query in one of four states, counted per reason, and the tables that block the most (blockers.py)
|
|
499
|
+
"outcomes": outcomes,
|
|
500
|
+
# join statements CodeCop flagged (joins.py), each drawn, with the finding that carries it or its next step; None without
|
|
501
|
+
**({"joins": joins_mod.report_block(joins, findings)} if joins else {}),
|
|
502
|
+
# None when there is no inventory to count from (an out dir with only rank.json)
|
|
503
|
+
"coverage": coverage_mod.compute(inventory, rank, bench, {f["id"]: f["status"] for f in findings}, matched or None) if inventory else None,
|
|
504
|
+
# the run's CPU machine factor (fidelity.machine_factor): what CPU grades are relative to; absent without one
|
|
505
|
+
**({"summary": {"machine_factor": machine}} if machine else {}),
|
|
506
|
+
"findings": findings,
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
OBSERVED_KEYS = ("hash", "located", "how", "window_hours", "executions", "read_bytes", "share_of_read_bytes", "share_of_site_bytes",
|
|
511
|
+
"shapes_of_site", "places", "pieces", "joining_function", "fixed_share", "fragments", "filled", "params", "text_chars",
|
|
512
|
+
"normalized_text", "fragments_text", "aggregate", "aggregate_kind", "tag", "one_of", "possible_places")
|
|
513
|
+
|
|
514
|
+
|
|
515
|
+
def observed_summary(obs: dict) -> dict:
|
|
516
|
+
"""findings.observed: counts, the gate's refusals (codes and numbers), the shapes below the line, and the production
|
|
517
|
+
statements with no place in code (observed.unlocated)."""
|
|
518
|
+
cands = obs.get("candidates") or []
|
|
519
|
+
return {
|
|
520
|
+
"window_hours": obs.get("window_hours"), "settings": obs.get("settings") or {},
|
|
521
|
+
"candidates": len(cands), "by_located": dict(Counter(c.get("located") for c in cands).most_common()),
|
|
522
|
+
"read_bytes": sum(int((c.get("observed") or {}).get("read_bytes") or 0) for c in cands),
|
|
523
|
+
"rejected": [{k: r[k] for k in ("site_id", "hash", "located", "reason", "detail", "read_bytes", "executions") if k in r}
|
|
524
|
+
for r in obs.get("rejected") or []],
|
|
525
|
+
"below_line": obs.get("below_line") or [],
|
|
526
|
+
"unlocated": obs.get("unlocated"),
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
|
|
530
|
+
def observed_for_findings(o: dict) -> dict:
|
|
531
|
+
"""What findings.json keeps of an observed statement: numbers, labels, the places in code, and the normalized text
|
|
532
|
+
(every literal is `?`; database prefixes removed). `codecop push` leaves the text out when [push] observed_text is off."""
|
|
533
|
+
return {k: o[k] for k in OBSERVED_KEYS if k in o}
|
|
534
|
+
|
|
535
|
+
|
|
536
|
+
def observed_load(o: dict, ctx: dict | None = None) -> dict:
|
|
537
|
+
"""The measured load of one observed shape, in the form `findings[].real` has."""
|
|
538
|
+
p = o.get("production") or {}
|
|
539
|
+
days = (o.get("window_hours") or 0) / 24.0
|
|
540
|
+
row = {"match": o.get("located") or "exact", "executions": int(o.get("executions") or 0),
|
|
541
|
+
"executions_per_day": round(o["executions"] / days, 1) if days and o.get("executions") else None,
|
|
542
|
+
"read_bytes": int(o.get("read_bytes") or 0), "read_rows": int((p.get("rows_read_per_run") or 0) * (o.get("executions") or 0)),
|
|
543
|
+
"avg_read_bytes": int((o.get("read_bytes") or 0) / max(o.get("executions") or 1, 1)), "avg_ms": float(o.get("avg_ms") or 0),
|
|
544
|
+
"p95_ms": o.get("p95_ms"), "share_of_read_bytes": float(o.get("share_of_read_bytes") or 0), "rank_by_bytes": None,
|
|
545
|
+
**{k: p[k] for k in RATIO_KEYS if k in p}, **{k: v for k, v in p.items() if k in ("spread", "no_result_share", "no_read_share",
|
|
546
|
+
"selected_parts_per_run", "selected_marks_per_run")},
|
|
547
|
+
**{k: p[k] for k in RESOURCE_KEYS if k in p}}
|
|
548
|
+
if "resources" not in p and o.get("hash"):
|
|
549
|
+
# an observed.json written before the resource facts (it may carry max_ms or total_ms, never `resources`): the
|
|
550
|
+
# shape's own row of the match file has them (PostgreSQL busy time, CPU, memory)
|
|
551
|
+
q = next((q for q in (ctx or {}).get("queries") or [] if q.get("hash") == o["hash"]), None) or {}
|
|
552
|
+
row.update({k: q[k] for k in RESOURCE_KEYS if k in q and k not in row})
|
|
553
|
+
return measured(row, o.get("window_hours"), ctx)
|
|
554
|
+
|
|
555
|
+
|
|
556
|
+
def _assembled(site: dict | None, matched: dict, sql_cut: int, gate: dict | None, facts=None, engine: str = "") -> tuple[str, dict]:
|
|
557
|
+
"""Which of the `sql_assembled_at_run_time` reasons a rejection of unresolved SQL is (blockers.assembled_reason), with
|
|
558
|
+
what the pull says: whether one was read, its window, the shapes no call site sends on the site's tables, likely matches.
|
|
559
|
+
With a catalog: how many of the site's tables the pulled database has (`tables_in_pull` of `tables_named`). None of
|
|
560
|
+
them means the statement runs on a database the pull did not read: a longer window would not show it
|
|
561
|
+
(`next_step: pull_its_database`)."""
|
|
562
|
+
pulled = bool(matched.get("queries"))
|
|
563
|
+
unlocated, likely = None, 0
|
|
564
|
+
if pulled and site:
|
|
565
|
+
from .realdb.match import short_tables
|
|
566
|
+
mine = short_tables(site.get("tables") or [])
|
|
567
|
+
free = [q for q in matched.get("queries") or [] if q.get("match") == "none" and mine & set(q.get("tables") or [])]
|
|
568
|
+
if free:
|
|
569
|
+
unlocated = {"shapes": len(free), "read_bytes": sum(int(q.get("read_bytes") or 0) for q in free)}
|
|
570
|
+
likely = int(((matched.get("sites") or {}).get(site.get("id")) or {}).get("match") == "likely")
|
|
571
|
+
reason, ev = blockers_mod.assembled_reason(site, sql_cut=sql_cut, pulled=pulled, gate=gate, window_hours=matched.get("window_hours"),
|
|
572
|
+
unlocated=unlocated, likely=likely)
|
|
573
|
+
named = [t for t in (site or {}).get("tables") or [] if t and "«" not in t]
|
|
574
|
+
if reason == "assembled_not_seen" and facts and named:
|
|
575
|
+
from .rank import _catalog_table
|
|
576
|
+
try:
|
|
577
|
+
real = facts.tables(engine)
|
|
578
|
+
except Exception:
|
|
579
|
+
real = {}
|
|
580
|
+
if real:
|
|
581
|
+
known = sum(1 for t in named if _catalog_table(real, t, engine) is not None)
|
|
582
|
+
ev = {**ev, "tables_named": len(named), "tables_in_pull": known}
|
|
583
|
+
if not known:
|
|
584
|
+
ev["next_step"] = "pull_its_database"
|
|
585
|
+
return reason, ev
|
|
586
|
+
|
|
587
|
+
|
|
588
|
+
def _sites_per_query(inventory: dict | None) -> dict[str, int]:
|
|
589
|
+
"""Call-site id -> how many non-test call sites run the same SQL (the shortlist keeps one site per distinct SQL)."""
|
|
590
|
+
sites = [s for s in (inventory or {}).get("call_sites") or [] if not s.get("is_test") and s.get("role") != "test"]
|
|
591
|
+
per_hash = Counter(s.get("sql_hash") for s in sites if s.get("sql_hash"))
|
|
592
|
+
return {s["id"]: max(per_hash.get(s.get("sql_hash"), 0), 1) for s in sites if s.get("id")}
|
|
593
|
+
|
|
594
|
+
|
|
595
|
+
def _outcomes(rank: dict, findings: list[dict], rejected: list[dict], inventory: dict | None, site_rows: dict, settings: dict,
|
|
596
|
+
window_hours) -> dict:
|
|
597
|
+
"""Every ranked query in exactly one state, and the roll-up.
|
|
598
|
+
|
|
599
|
+
The ranked queries are the shortlist the agent was shown. One in a batch that did not finish is `not_judged`
|
|
600
|
+
(`agent_failed` or `budget_reached`); one the agent answered for is its finding or its rejection; one it left out
|
|
601
|
+
is `agent_no_answer`. Candidates and rejections that are not on the shortlist (kept from an earlier rank) count too.
|
|
602
|
+
`unanswered` lists the queries that are neither a finding nor a rejection, with their state."""
|
|
603
|
+
per_site = _sites_per_query(inventory)
|
|
604
|
+
listed = {s["id"]: s for s in rank.get("shortlist") or []}
|
|
605
|
+
batches = rank.get("batches")
|
|
606
|
+
done = {b["index"] for b in batches or [] if b.get("status") == "done"} if batches is not None else None
|
|
607
|
+
why = {b["index"]: ("budget_reached" if b.get("reason") == "budget" else "agent_failed") for b in batches or [] if b.get("status") != "done"}
|
|
608
|
+
queries, seen = [], set()
|
|
609
|
+
|
|
610
|
+
def load_bytes(qid: str):
|
|
611
|
+
row = site_rows.get(qid) or {}
|
|
612
|
+
return int(row.get("read_bytes") or 0) if row.get("match") in ("exact", "template", "tag") else None
|
|
613
|
+
|
|
614
|
+
for f in findings:
|
|
615
|
+
seen.add(f["id"])
|
|
616
|
+
load = load_bytes(f["id"])
|
|
617
|
+
if f.get("observed"): # one shape of the site: its own bytes; a statement located as a piece carries no cost of a site
|
|
618
|
+
load = int(f["observed"].get("read_bytes") or 0) if f["observed"].get("located") in ("exact", "template", "tag") else None
|
|
619
|
+
queries.append({"id": f["id"], "finding": f["finding"], "outcome": f["outcome"], "load_read_bytes": load, "sql_from": f.get("sql_from"),
|
|
620
|
+
"sites": per_site.get(f["id"]) or int((f.get("site") or {}).get("same_sql_sites") or 1),
|
|
621
|
+
"sandbox_read_bytes": (f.get("scan") or {}).get("read_bytes") or 0})
|
|
622
|
+
for r in rejected:
|
|
623
|
+
if r["id"] in seen:
|
|
624
|
+
continue
|
|
625
|
+
seen.add(r["id"])
|
|
626
|
+
queries.append({"id": r["id"], "finding": None, "outcome": r["outcome"], "load_read_bytes": load_bytes(r["id"]),
|
|
627
|
+
"sites": per_site.get(r["id"], 1)})
|
|
628
|
+
unanswered = []
|
|
629
|
+
for qid, s in listed.items():
|
|
630
|
+
if qid in seen:
|
|
631
|
+
continue
|
|
632
|
+
seen.add(qid)
|
|
633
|
+
reason = why.get(s.get("batch")) if done is not None and s.get("batch") not in done else "agent_no_answer"
|
|
634
|
+
o = blockers_mod.outcome("not_judged", reason or "agent_no_answer", "run")
|
|
635
|
+
unanswered.append({"id": qid, "file": s.get("file", ""), "line": s.get("line", 0), **o})
|
|
636
|
+
queries.append({"id": qid, "finding": None, "outcome": o, "load_read_bytes": load_bytes(qid), "sites": per_site.get(qid, 1)})
|
|
637
|
+
_part_of(queries, rejected)
|
|
638
|
+
return {**blockers_mod.rollup(queries, settings, window_hours), "unanswered": unanswered}
|
|
639
|
+
|
|
640
|
+
|
|
641
|
+
PART_OF = re.compile(r"\bpart of\s+([A-Za-z0-9_-]+)", re.I)
|
|
642
|
+
|
|
643
|
+
|
|
644
|
+
def _part_of(queries: list[dict], rejected: list[dict]) -> None:
|
|
645
|
+
"""A piece the agent rejected as `duplicate` of a longer statement it named (`part of <id>`, assemble.FOCUS_TEXT)
|
|
646
|
+
is judged with that statement: nothing to gain apart from it when the statement was judged, could not be judged when
|
|
647
|
+
the statement could not (its reason, with `part_of`). Changes the outcomes in place."""
|
|
648
|
+
by_ref = {}
|
|
649
|
+
for q in queries:
|
|
650
|
+
by_ref[q["id"]] = q
|
|
651
|
+
if q.get("finding"):
|
|
652
|
+
by_ref[q["finding"]] = q
|
|
653
|
+
for r in rejected:
|
|
654
|
+
o = r.get("outcome") or {}
|
|
655
|
+
if (o.get("evidence") or {}).get("agent_code") != "duplicate":
|
|
656
|
+
continue
|
|
657
|
+
m = PART_OF.search(r.get("detail") or "")
|
|
658
|
+
whole = by_ref.get(m.group(1)) if m else None
|
|
659
|
+
if not whole or whole["id"] == r.get("id"):
|
|
660
|
+
continue
|
|
661
|
+
o.setdefault("evidence", {})["part_of"] = whole.get("finding") or whole["id"]
|
|
662
|
+
w = whole.get("outcome") or {}
|
|
663
|
+
if w.get("state") == "not_judged":
|
|
664
|
+
o.update(state="not_judged", reason=w.get("reason"), **{"from": w.get("from") or o.get("from")})
|
|
665
|
+
|
|
666
|
+
|
|
667
|
+
def rows_label(rows, evidence: str) -> str:
|
|
668
|
+
"""A table's size as a sentence. "in production" only for a number read from a real database."""
|
|
669
|
+
if not rows:
|
|
670
|
+
return ""
|
|
671
|
+
if evidence == "real catalog":
|
|
672
|
+
return f"{human(rows)} rows in production (real catalog)"
|
|
673
|
+
return f"about {human(rows)} rows assumed (the agent's estimate: no database was read)"
|
|
674
|
+
|
|
675
|
+
|
|
676
|
+
REALISM_WORDS = {"sizes": "column sizes from the profile", "content": "text shaped like its content", "physical": "parts and duplicate versions as on a live table",
|
|
677
|
+
"fit": "fitted to the real workload"}
|
|
678
|
+
|
|
679
|
+
|
|
680
|
+
def describe_data(rank: dict, profile: dict | None, bench: dict | None, database_connected: bool) -> dict:
|
|
681
|
+
"""What a run's numbers stand on: {database_connected, rows, generator, realism, label}.
|
|
682
|
+
|
|
683
|
+
`rows` is where the table sizes come from: "real catalog", "agent estimate" or "mixed". `generator` is "plain"
|
|
684
|
+
(`--realism none`: random text of a fixed length, nothing shaped), "realistic" (the realism parts in `realism`)
|
|
685
|
+
or "none" when nothing was benchmarked. `label` is the one sentence to print: it never calls generated data
|
|
686
|
+
"shaped like production" when the plain generator made it, nor an estimate a production figure."""
|
|
687
|
+
tables = (profile or {}).get("tables") or []
|
|
688
|
+
real = sum(1 for t in tables if t.get("rows_evidence") == "real catalog")
|
|
689
|
+
rows = "none" if not tables else "real catalog" if real == len(tables) else "mixed" if real else "agent estimate"
|
|
690
|
+
realism = list((bench or {}).get("realism") or [])
|
|
691
|
+
generator = "none" if not bench else "realistic" if realism else "plain"
|
|
692
|
+
if not bench:
|
|
693
|
+
label = "Not benchmarked: static analysis only"
|
|
694
|
+
else:
|
|
695
|
+
made = ("Generated data from the plain generator (--realism none): values have the profiled distributions, text is random "
|
|
696
|
+
"characters of one length, nothing is shaped like real payloads") if not realism else (
|
|
697
|
+
"Generated data (" + ", ".join(REALISM_WORDS.get(x, x) for x in realism if x != "fit" or database_connected) + ")")
|
|
698
|
+
sizes = {"real catalog": "table sizes read from the real database catalog",
|
|
699
|
+
"mixed": f"table sizes read from the real database catalog for {real} of {len(tables)} tables, the agent's estimates for the rest",
|
|
700
|
+
"agent estimate": "table sizes and value distributions are the agent's estimates: no database was connected",
|
|
701
|
+
"none": "no data profile"}[rows]
|
|
702
|
+
label = f"{made}; {sizes}"
|
|
703
|
+
return {"database_connected": database_connected, "rows": rows, "generator": generator, "realism": realism, "label": label}
|
|
704
|
+
|
|
705
|
+
|
|
706
|
+
def status_label(f: dict) -> str:
|
|
707
|
+
"""The status as shown: a finding whose tables were not built is "Not benchmarked", not a failed test."""
|
|
708
|
+
if f.get("not_benchmarked"):
|
|
709
|
+
return "Not benchmarked"
|
|
710
|
+
if f["status"] == "verified" and fixgroups.proof_state(f) in ("trade_off", "write_cost_unknown"):
|
|
711
|
+
# read less in the sandbox, but not a proven fix: said as the finding's outcome says it
|
|
712
|
+
return fixgroups.PROOF_WORDS[fixgroups.proof_state(f)]
|
|
713
|
+
return STATUS_LABEL[f["status"]]
|
|
714
|
+
|
|
715
|
+
|
|
716
|
+
MEASUREMENT_RESOURCES = ("cpu_ms", "cpu_user_ms", "cpu_system_ms", "cpu_kind", "io_wait_ms", "threads", "result_bytes", "spill_bytes",
|
|
717
|
+
"memory_kind", "noisy", "vm_steps")
|
|
718
|
+
|
|
719
|
+
|
|
720
|
+
def _slim(m: dict | None) -> dict | None:
|
|
721
|
+
if not m:
|
|
722
|
+
return None
|
|
723
|
+
out = {k: m.get(k) for k in ("ok", "error", "read_rows", "read_bytes", "result_rows", "memory_bytes", "duration_ms",
|
|
724
|
+
"selected_marks", "total_marks", "explain")}
|
|
725
|
+
# the resource profile of the run (engines.base.Measurement), only where it was measured: an older bench has none
|
|
726
|
+
out.update({k: m[k] for k in MEASUREMENT_RESOURCES if m.get(k) is not None})
|
|
727
|
+
if isinstance(m.get("runs_detail"), dict):
|
|
728
|
+
out["runs_detail"] = {k: [x if isinstance(x, (int, float)) and not isinstance(x, bool) else None for x in (m["runs_detail"].get(k) or [])][:50]
|
|
729
|
+
for k in ("cpu_ms", "memory_bytes", "duration_ms")}
|
|
730
|
+
out.update({k: m[k] for k in PG_FIELDS if k in m})
|
|
731
|
+
if m.get("ok"):
|
|
732
|
+
out.update(_ratio_pair(m))
|
|
733
|
+
return out
|
|
734
|
+
|
|
735
|
+
|
|
736
|
+
def _ratio_pair(m: dict) -> dict:
|
|
737
|
+
"""The two read-against-returned ratios of one sandbox measurement."""
|
|
738
|
+
r = ratios(m.get("read_rows"), m.get("read_bytes"), m.get("result_rows"))
|
|
739
|
+
return {"rows_read_per_row_returned": r["rows_read_per_row_returned"], "bytes_read_per_row_read": r["bytes_read_per_row_read"]}
|
|
740
|
+
|
|
741
|
+
|
|
742
|
+
PG_FIELDS = ("shared_hit_blocks", "shared_read_blocks", "temp_blocks", "rows_removed", "planning_ms", "execution_ms", "node_types", "scans",
|
|
743
|
+
# SQLite (engines/sqlite.py)
|
|
744
|
+
"pages", "page_size", "full_scan_rows", "vm_steps", "sorts", "autoindexes", "repeatable")
|
|
745
|
+
|
|
746
|
+
|
|
747
|
+
# ---- HTML ---------------------------------------------------------------
|
|
748
|
+
|
|
749
|
+
def human(n) -> str:
|
|
750
|
+
if n is None:
|
|
751
|
+
return "-"
|
|
752
|
+
n = float(n)
|
|
753
|
+
for unit, size in (("B", 1e9), ("M", 1e6), ("K", 1e3)):
|
|
754
|
+
if abs(n) >= size:
|
|
755
|
+
return f"{n / size:.1f}{unit}"
|
|
756
|
+
return f"{n:.0f}"
|
|
757
|
+
|
|
758
|
+
|
|
759
|
+
def human_bytes(n) -> str:
|
|
760
|
+
if n is None:
|
|
761
|
+
return "-"
|
|
762
|
+
n = float(n)
|
|
763
|
+
for unit, size in (("GB", 1e9), ("MB", 1e6), ("KB", 1e3)):
|
|
764
|
+
if abs(n) >= size:
|
|
765
|
+
return f"{n / size:.1f} {unit}"
|
|
766
|
+
return f"{n:.0f} B"
|
|
767
|
+
|
|
768
|
+
|
|
769
|
+
def e(text) -> str:
|
|
770
|
+
return html.escape(str(text if text is not None else ""))
|
|
771
|
+
|
|
772
|
+
|
|
773
|
+
|
|
774
|
+
|
|
775
|
+
CSS = """
|
|
776
|
+
:root{--bg:#fbfbfa;--panel:#fff;--ink:#1c1d1f;--muted:#6b6f76;--line:#e4e4e1;--accent:#2f5fd0;--good:#1a7f4b;--bad:#b3261e;--warn:#9a6700;--code:#f4f4f1;
|
|
777
|
+
--good-bg:#e3f4ea;--bad-bg:#fbe6e4;--warn-bg:#fbf0d3;--track:#ecece8;--base:#9aa0a8}
|
|
778
|
+
@media (prefers-color-scheme:dark){:root{--bg:#131416;--panel:#1b1c1f;--ink:#e8e8e6;--muted:#9a9ea6;--line:#2c2e33;--accent:#8fb0ff;--good:#5fd39a;--bad:#ff8a80;--warn:#e3b341;--code:#222428;
|
|
779
|
+
--good-bg:#16301f;--bad-bg:#3a1c1a;--warn-bg:#33290f;--track:#26282c;--base:#6b7079}}
|
|
780
|
+
*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink);font:15px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",Inter,sans-serif}
|
|
781
|
+
main{max-width:1060px;margin:0 auto;padding:32px 16px 80px}
|
|
782
|
+
h1{font-size:26px;margin:0 0 4px}h2{font-size:18px;margin:36px 0 12px}h3{font-size:16px;margin:0}
|
|
783
|
+
h4{font-size:11.5px;text-transform:uppercase;letter-spacing:.05em;color:var(--muted);margin:18px 0 8px;font-weight:600}
|
|
784
|
+
.sub{color:var(--muted);margin:0 0 20px}.muted{color:var(--muted)}.mono,code,pre{font:13px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
785
|
+
.cards{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:10px;margin:18px 0}
|
|
786
|
+
.card{background:var(--panel);border:1px solid var(--line);border-radius:8px;padding:12px 14px;color:var(--muted);font-size:13px}.card b{display:block;font-size:22px;color:var(--ink)}
|
|
787
|
+
table{width:100%;border-collapse:collapse;background:var(--panel);border:1px solid var(--line);border-radius:8px;overflow:hidden;font-size:14px}
|
|
788
|
+
th,td{padding:8px 10px;text-align:left;border-bottom:1px solid var(--line);vertical-align:middle}th{font-weight:600;color:var(--muted);font-size:12px;text-transform:uppercase;letter-spacing:.03em}
|
|
789
|
+
td.num,th.num{text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap}tr:last-child td{border-bottom:0}
|
|
790
|
+
.wrap{overflow-x:auto}
|
|
791
|
+
.finding{background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:18px 20px;margin:16px 0}
|
|
792
|
+
.finding>header,.variant>header{display:flex;gap:8px;align-items:center;flex-wrap:wrap}
|
|
793
|
+
.tag{font-size:12px;padding:2px 8px;border-radius:999px;border:1px solid var(--line);white-space:nowrap;display:inline-block}
|
|
794
|
+
.verified,.win,.used,.partition{color:var(--good);border-color:var(--good);background:var(--good-bg)}
|
|
795
|
+
.rejected,.failed,.none{color:var(--bad);border-color:var(--bad);background:var(--bad-bg)}
|
|
796
|
+
.unverified,.no_change,.mixed,.slower,.untested,.skipped{color:var(--warn);border-color:var(--warn);background:var(--warn-bg)}
|
|
797
|
+
.sev{display:inline-flex;gap:3px;align-items:center;font-size:12px;color:var(--muted)}.sev i{width:8px;height:8px;border-radius:50%;background:var(--track)}.sev i.on{background:var(--bad)}
|
|
798
|
+
.flow{display:flex;flex-wrap:wrap;align-items:center;gap:6px}
|
|
799
|
+
.node{border:1px solid var(--line);border-radius:6px;padding:4px 9px;background:var(--bg);max-width:100%;overflow-wrap:anywhere}
|
|
800
|
+
.node small{display:block;color:var(--muted);font:11px/1.3 ui-monospace,Menlo,monospace}.node.entry{border-color:var(--accent)}.node.table{border-style:dashed}
|
|
801
|
+
.node .k{font-size:11px;text-transform:uppercase;letter-spacing:.05em;color:var(--accent);margin-right:6px}
|
|
802
|
+
.arrow{color:var(--muted)}
|
|
803
|
+
.chips{display:flex;flex-wrap:wrap;gap:6px;margin-top:8px}
|
|
804
|
+
.keyrow{display:flex;flex-wrap:wrap;gap:6px;align-items:center;margin:6px 0}
|
|
805
|
+
.keyrow>span.lbl{font-size:12px;color:var(--muted);min-width:78px}
|
|
806
|
+
.key{border:1px solid var(--line);border-radius:6px;padding:3px 8px;background:var(--bg);overflow-wrap:anywhere}
|
|
807
|
+
.key b{font:600 11px/1 ui-monospace,Menlo,monospace;color:var(--muted);margin-right:6px}
|
|
808
|
+
.key.used,.key.partition{border-color:var(--good);background:var(--good-bg)}.key.skipped{border-color:var(--warn);background:var(--warn-bg)}.key.none{border-color:var(--bad);background:var(--bad-bg)}
|
|
809
|
+
.key.new{border-color:var(--accent)}
|
|
810
|
+
.key em{font-style:normal;font-size:11px;color:var(--muted);margin-left:6px}
|
|
811
|
+
.cause{border:1px solid var(--line);border-left:3px solid var(--bad);border-radius:6px;padding:6px 10px;background:var(--bg);max-width:100%}
|
|
812
|
+
.cause b{font-size:13.5px}.cause small{display:block;color:var(--muted);font-size:12px;overflow-wrap:anywhere}
|
|
813
|
+
.bars{display:grid;grid-template-columns:minmax(84px,auto) 1fr minmax(96px,auto);gap:5px 10px;align-items:center;font-size:13px}
|
|
814
|
+
.bars .v{text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap}.bars .l{color:var(--muted)}
|
|
815
|
+
.track{background:var(--track);border-radius:4px;height:14px;overflow:hidden}.fill{height:100%;border-radius:4px;background:var(--base);min-width:2px}
|
|
816
|
+
.fill.win{background:var(--good)}.fill.bad{background:var(--bad)}.fill.warn{background:var(--warn)}.fill.read{background:var(--bad)}.fill.out{background:var(--accent)}
|
|
817
|
+
.grid2{display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:4px 28px}
|
|
818
|
+
pre{background:var(--code);border-radius:6px;padding:10px 12px;overflow-x:auto;white-space:pre-wrap;word-break:break-word;margin:8px 0}
|
|
819
|
+
details{margin:8px 0}summary{cursor:pointer;color:var(--accent);font-size:13.5px}
|
|
820
|
+
.variant{border-top:1px solid var(--line);margin-top:18px;padding-top:16px}
|
|
821
|
+
.mini{display:inline-block;vertical-align:middle;width:70px;margin-right:8px}
|
|
822
|
+
a{color:var(--accent);white-space:nowrap}table .mono{overflow-wrap:anywhere}
|
|
823
|
+
.stack{display:flex;height:18px;border-radius:4px;overflow:hidden;background:var(--track);margin:8px 0}.stack i{display:block;height:100%;min-width:2px}
|
|
824
|
+
.st-fixed{background:var(--good)}.st-blocked{background:var(--bad)}.st-not_judged{background:var(--warn)}.st-nothing_to_gain{background:var(--base)}
|
|
825
|
+
.tag.fixed{color:var(--good);border-color:var(--good);background:var(--good-bg)}.tag.blocked{color:var(--bad);border-color:var(--bad);background:var(--bad-bg)}
|
|
826
|
+
.tag.not_judged{color:var(--warn);border-color:var(--warn);background:var(--warn-bg)}.tag.nothing_to_gain{color:var(--muted)}
|
|
827
|
+
.cause.no-evidence{border-left-color:var(--base)}
|
|
828
|
+
"""
|
|
829
|
+
|
|
830
|
+
|
|
831
|
+
def tag(text, cls="") -> str:
|
|
832
|
+
return f"<span class='tag {e(cls)}'>{e(text)}</span>"
|
|
833
|
+
|
|
834
|
+
|
|
835
|
+
def pct(part, whole) -> float:
|
|
836
|
+
return 100.0 * float(part or 0) / float(whole) if whole else 0.0
|
|
837
|
+
|
|
838
|
+
|
|
839
|
+
def bar(label, part, whole, value, cls="") -> str:
|
|
840
|
+
return (f"<span class=l>{e(label)}</span><div class=track><div class='fill {e(cls)}' style='width:{min(pct(part, whole), 100):.1f}%'></div></div>"
|
|
841
|
+
f"<span class=v>{e(value)}</span>")
|
|
842
|
+
|
|
843
|
+
|
|
844
|
+
def _severity(level: str) -> str:
|
|
845
|
+
n = {"high": 3, "medium": 2, "low": 1}.get(level, 0)
|
|
846
|
+
return f"<span class=sev title='severity'>{''.join('<i class=on></i>' if i < n else '<i></i>' for i in range(3))} {e(level)}</span>"
|
|
847
|
+
|
|
848
|
+
|
|
849
|
+
def origin_label(origin: dict) -> str:
|
|
850
|
+
eps = origin.get("entry_points") or []
|
|
851
|
+
if not eps:
|
|
852
|
+
return f"{origin.get('role', 'unknown')} code"
|
|
853
|
+
return f"{eps[0]['kind']} {eps[0]['name']}" + (f" +{len(eps) - 1}" if len(eps) > 1 else "")
|
|
854
|
+
|
|
855
|
+
|
|
856
|
+
def _where(file, line) -> str:
|
|
857
|
+
return f"<small>{e(str(file).split('/')[-1])}:{e(line)}</small>" if file else ""
|
|
858
|
+
|
|
859
|
+
|
|
860
|
+
def _flow_html(f: dict) -> str:
|
|
861
|
+
"""Entry point -> call chain -> the function with the query -> tables, as one strip."""
|
|
862
|
+
origin, site = f["origin"], f["site"]
|
|
863
|
+
arrow = "<span class=arrow>→</span>"
|
|
864
|
+
nodes = []
|
|
865
|
+
eps = origin.get("entry_points") or []
|
|
866
|
+
if eps:
|
|
867
|
+
p = eps[0]
|
|
868
|
+
more = f" <span class=muted>+{len(eps) - 1}</span>" if len(eps) > 1 else ""
|
|
869
|
+
nodes.append(f"<div class='node entry'><span class=k>{e(p.get('kind'))}</span><span class=mono>{e(p.get('name'))}</span>{more}{_where(p.get('file'), p.get('line'))}</div>")
|
|
870
|
+
else:
|
|
871
|
+
nodes.append(f"<div class='node entry'><span class=k>{e(origin.get('role', 'unknown'))}</span>no entry point found</div>")
|
|
872
|
+
for step in origin.get("path") or []:
|
|
873
|
+
if step.get("symbol") == site.get("symbol") and step.get("line") == site.get("line"):
|
|
874
|
+
continue
|
|
875
|
+
nodes.append(f"<div class=node><span class=mono>{e(step.get('symbol'))}</span>{_where(step.get('file'), step.get('line'))}</div>")
|
|
876
|
+
nodes.append(f"<div class=node><span class=mono>{e(site.get('symbol') or 'module')}</span>{_where(site['file'], site['line'])}</div>")
|
|
877
|
+
nodes.append("".join(f"<div class='node table'><span class=k>table</span><span class=mono>{e(t)}</span></div>" for t in f["tables"]))
|
|
878
|
+
chips = [tag(c) for c in frequency_chips(origin.get("frequency"))]
|
|
879
|
+
chips.append(tag(f"{origin.get('role', 'unknown')} code"))
|
|
880
|
+
chips.append(tag("call path checked by the agent", "verified") if origin.get("verified") else tag("static guess", "unverified"))
|
|
881
|
+
if site.get("same_sql_sites", 1) > 1:
|
|
882
|
+
chips.append(tag(f"same SQL at {site['same_sql_sites'] - 1} other site(s)"))
|
|
883
|
+
return f"<div class=flow>{arrow.join(nodes)}</div><div class=chips>{''.join(chips)}</div>"
|
|
884
|
+
|
|
885
|
+
|
|
886
|
+
OP_SIGN = {"eq": "=", "in": "IN", "range": "range", "like": "LIKE", "other": "f(x)", "join": "join key", "contains": "@>", "fts": "@@"}
|
|
887
|
+
KEY_WORD = {"used": "uses the key", "partition": "prunes partitions", "skipped": "in key, not reachable", "none": "not in key"}
|
|
888
|
+
|
|
889
|
+
|
|
890
|
+
def _key_boxes(order_by: list[str], state: dict[str, str] | None = None, cls: str = "") -> str:
|
|
891
|
+
if not order_by:
|
|
892
|
+
return "<span class=muted>no sorting key</span>"
|
|
893
|
+
out = []
|
|
894
|
+
for i, part in enumerate(order_by, start=1):
|
|
895
|
+
hit = next((s for col, s in (state or {}).items() if col in part), "")
|
|
896
|
+
out.append(f"<span class='key mono {e(hit)} {e(cls)}'><b>{i}</b>{e(part)}</span>")
|
|
897
|
+
return "".join(out)
|
|
898
|
+
|
|
899
|
+
|
|
900
|
+
INDEX_WORD = {"used": "can narrow the scan", "sort": "returns rows in ORDER BY order", "unused": "not usable by this query"}
|
|
901
|
+
PG_KEY_WORD = {"used": "served by an index", "partition": "prunes partitions", "skipped": "in an index, not reachable", "none": "in no index"}
|
|
902
|
+
|
|
903
|
+
|
|
904
|
+
def _indexes_html(a: dict) -> str:
|
|
905
|
+
"""Postgres: one row of numbered boxes per index, the columns this query can use in green."""
|
|
906
|
+
rows = []
|
|
907
|
+
for ix in a.get("indexes") or []:
|
|
908
|
+
boxes = "".join(
|
|
909
|
+
f"<span class='key mono {'used' if i < ix['used_columns'] else ''}'><b>{i + 1}</b>{e(col)}</span>" for i, col in enumerate(ix["columns"]))
|
|
910
|
+
extra = "".join(f"<span class='key mono'><b>+</b>{e(col)}</span>" for col in ix.get("include") or [])
|
|
911
|
+
notes = [tag("primary key") if ix.get("primary") else (tag("unique") if ix.get("unique") else "")]
|
|
912
|
+
if ix.get("method") and ix["method"] != "btree":
|
|
913
|
+
notes.append(tag(ix["method"]))
|
|
914
|
+
if ix.get("where"):
|
|
915
|
+
notes.append(tag(f"WHERE {ix['where']}"[:80]))
|
|
916
|
+
cls = {"used": "used", "sort": "partition", "unused": "skipped"}[ix["state"]]
|
|
917
|
+
notes.append(tag(INDEX_WORD[ix["state"]], cls))
|
|
918
|
+
rows.append(f"<div class=keyrow><span class=lbl title='{e(ix['name'])}'>index</span><span class=mono>{e(ix['name'])}</span>{boxes}{extra}{''.join(notes)}</div>")
|
|
919
|
+
return "".join(rows) or "<div class=keyrow><span class=lbl>indexes</span><span class=muted>none</span></div>"
|
|
920
|
+
|
|
921
|
+
|
|
922
|
+
def _access_html(a: dict) -> str:
|
|
923
|
+
if a.get("indexes") is not None:
|
|
924
|
+
badges = [tag(f"PARTITION BY {a['partition_by']}")] if a.get("partition_by") else []
|
|
925
|
+
if a.get("rows_estimate"):
|
|
926
|
+
badges.append(_rows_badge(a))
|
|
927
|
+
filters = "".join(
|
|
928
|
+
f"<span class='key mono {e(x['key'])}'>{e(x['column'])}<em>{e(OP_SIGN.get(x['op'], x['op']))} · {e(PG_KEY_WORD.get(x['key'], x['key']))}</em></span>"
|
|
929
|
+
for x in a["filters"]) or "<span class=muted>no filter on this table</span>"
|
|
930
|
+
sort = "".join(f"<span class='key mono'>{e(s['column'])}{' DESC' if s.get('desc') else ''}</span>" for s in a.get("sort") or [])
|
|
931
|
+
return (f"<div class=keyrow><span class=lbl>table</span><span class=mono><b>{e(a['table'])}</b></span>{''.join(badges)}</div>"
|
|
932
|
+
+ _indexes_html(a) + f"<div class=keyrow><span class=lbl>query filters</span>{filters}</div>"
|
|
933
|
+
+ (f"<div class=keyrow><span class=lbl>order by</span>{sort}</div>" if sort else ""))
|
|
934
|
+
state = {x["column"]: x["key"] for x in a["filters"]}
|
|
935
|
+
badges = [tag(a["engine"])] if a.get("engine") else []
|
|
936
|
+
if a.get("partition_by"):
|
|
937
|
+
badges.append(tag(f"PARTITION BY {a['partition_by']}"))
|
|
938
|
+
else:
|
|
939
|
+
badges.append(tag("not partitioned"))
|
|
940
|
+
if a.get("rows_estimate"):
|
|
941
|
+
badges.append(_rows_badge(a))
|
|
942
|
+
filters = "".join(
|
|
943
|
+
f"<span class='key mono {e(x['key'])}'>{e(x['column'])}<em>{e(OP_SIGN.get(x['op'], x['op']))} · {e(KEY_WORD.get(x['key'], x['key']))}</em></span>"
|
|
944
|
+
for x in a["filters"]) or "<span class=muted>no filter on this table</span>"
|
|
945
|
+
return (f"<div class=keyrow><span class=lbl>table</span><span class=mono><b>{e(a['table'])}</b></span>{''.join(badges)}</div>"
|
|
946
|
+
f"<div class=keyrow><span class=lbl>sorted by</span>{_key_boxes(a['order_by'], state)}</div>"
|
|
947
|
+
f"<div class=keyrow><span class=lbl>query filters</span>{filters}</div>")
|
|
948
|
+
|
|
949
|
+
|
|
950
|
+
def _causes_html(causes: list[dict]) -> str:
|
|
951
|
+
return "".join(
|
|
952
|
+
f"<div class=cause><b>{e(CAUSE_LABEL.get(c.get('code'), c.get('code')))}</b>"
|
|
953
|
+
f"{' <code>' + e(c['column']) + '</code>' if c.get('column') else ''}<small>{e(c.get('detail'))}</small></div>" for c in causes)
|
|
954
|
+
|
|
955
|
+
|
|
956
|
+
def _scan_html(scan: dict | None) -> str:
|
|
957
|
+
if not scan or not scan.get("table_rows"):
|
|
958
|
+
return ""
|
|
959
|
+
whole = max(scan["table_rows"], scan.get("read_rows") or 0)
|
|
960
|
+
marks = f" · {scan['selected_marks']}/{scan['total_marks']} marks" if scan.get("total_marks") else ""
|
|
961
|
+
if scan.get("nodes") is not None:
|
|
962
|
+
marks = f" · {scan.get('buffers', 0):,} buffers"
|
|
963
|
+
nodes = "".join(
|
|
964
|
+
tag(f"{n['node']}{' using ' + n['index'] if n.get('index') else ''} on {n['relation']}: {human(n['rows'])} rows fetched"
|
|
965
|
+
+ (f", {human(n['removed'])} thrown away" if n.get("removed") else "") + (f", x{n['loops']}" if n.get("loops", 1) > 1 else ""),
|
|
966
|
+
"none" if n["node"] == "Seq Scan" else "") for n in scan.get("nodes") or [] if n.get("loops"))
|
|
967
|
+
return ("<h4>What one run reads (sandbox, largest scale)</h4>" + (f"<div class=chips>{nodes}</div>" if nodes else "") + "<div class=bars>"
|
|
968
|
+
+ bar("rows in table", whole, whole, human(scan["table_rows"]))
|
|
969
|
+
+ bar("rows read", scan.get("read_rows"), whole, f"{human(scan.get('read_rows'))} · {human_bytes(scan.get('read_bytes'))}{marks}", "read")
|
|
970
|
+
+ bar("rows returned", scan.get("result_rows"), whole, human(scan.get("result_rows")), "out") + "</div>")
|
|
971
|
+
|
|
972
|
+
|
|
973
|
+
def _measure_table(v: dict) -> str:
|
|
974
|
+
rows = []
|
|
975
|
+
for s in v["scales"]:
|
|
976
|
+
b, m = s["baseline"], s["variant"]
|
|
977
|
+
if not m or not m.get("ok"):
|
|
978
|
+
rows.append(f"<tr><td class=num>{human(s['rows'])}</td><td colspan=6>{e((m or {}).get('error') or v['reason'])}</td></tr>")
|
|
979
|
+
continue
|
|
980
|
+
rows.append(
|
|
981
|
+
f"<tr><td class=num>{human(s['rows'])}</td>"
|
|
982
|
+
f"<td class=num>{human(b['read_rows'])} → {human(m['read_rows'])}</td>"
|
|
983
|
+
f"<td class=num>{human_bytes(b['read_bytes'])} → {human_bytes(m['read_bytes'])}</td>"
|
|
984
|
+
+ (f"<td class=num>{', '.join(b['node_types']) or '-'} → {', '.join(m.get('node_types') or []) or '-'}</td>" if "node_types" in b else
|
|
985
|
+
f"<td class=num>{b['selected_marks']}/{b['total_marks']} → {m['selected_marks']}/{m['total_marks']}</td>") +
|
|
986
|
+
f"<td class=num>{human_bytes(b['memory_bytes'])} → {human_bytes(m['memory_bytes'])}</td>"
|
|
987
|
+
f"<td class=num>{b['duration_ms']:.0f} → {m['duration_ms']:.0f} ms</td>"
|
|
988
|
+
f"<td>{tag(s['verdict'].replace('_', ' '), s['verdict'])}</td></tr>")
|
|
989
|
+
if not rows:
|
|
990
|
+
return ""
|
|
991
|
+
return ("<details><summary>All measurements</summary><div class=wrap><table><tr><th class=num>Table rows</th><th class=num>Rows read</th><th class=num>Bytes read</th>"
|
|
992
|
+
+ ("<th class=num>Scan nodes</th>" if any("node_types" in s["baseline"] for s in v["scales"]) else "<th class=num>Marks</th>") + "<th class=num>Peak memory</th><th class=num>Time (laptop)</th><th>Result</th></tr>"
|
|
993
|
+
+ "".join(rows) + "</table></div></details>")
|
|
994
|
+
|
|
995
|
+
|
|
996
|
+
def _fill_class(verdict: str) -> str:
|
|
997
|
+
return {"win": "win", "slower": "bad", "rejected": "bad", "failed": "bad"}.get(verdict, "warn")
|
|
998
|
+
|
|
999
|
+
|
|
1000
|
+
def _rows_badge(a: dict) -> str:
|
|
1001
|
+
"""A table's production row count: a fact when it came from the real catalog, an estimate otherwise."""
|
|
1002
|
+
if a.get("rows_evidence") == "real catalog":
|
|
1003
|
+
return tag(f"{human(a['rows_estimate'])} rows in production", "verified")
|
|
1004
|
+
return tag(f"~{human(a['rows_estimate'])} rows assumed (agent estimate, no database read)")
|
|
1005
|
+
|
|
1006
|
+
|
|
1007
|
+
def _ratio_row(label: str, share: float, value: str, detail: str, cls: str) -> str:
|
|
1008
|
+
"""One bar of the read-against-returned block: the ratio stands out, the absolutes sit beside it in muted text."""
|
|
1009
|
+
return (f"<span class=l>{e(label)}</span><div class=track><div class='fill {e(cls)}' style='width:{min(share, 100):.1f}%'></div></div>"
|
|
1010
|
+
f"<span class=v><b>{e(value)}</b> <span class=muted>{e(detail)}</span></span>")
|
|
1011
|
+
|
|
1012
|
+
|
|
1013
|
+
def _ratio_html(f: dict) -> str:
|
|
1014
|
+
"""Read against returned, as bars on a log scale: production (when measured), the sandbox baseline, and the best variant.
|
|
1015
|
+
|
|
1016
|
+
Two rows of bars and their absolutes. One chip says when the query is an aggregate, where a high first ratio is expected."""
|
|
1017
|
+
real = f.get("real") or {}
|
|
1018
|
+
best = next((v for v in f.get("variants") or [] if any(s.get("variant") and s["variant"].get("ok") for s in v.get("scales") or [])), None)
|
|
1019
|
+
after = next((s for s in reversed(best["scales"]) if s.get("variant") and s["variant"].get("ok")), None) if best else None
|
|
1020
|
+
before = after["baseline"] if after else None
|
|
1021
|
+
scan = f.get("scan") or {}
|
|
1022
|
+
rows = []
|
|
1023
|
+
for label, key, unit in (("rows read per row returned", "rows_read_per_row_returned", ""), ("bytes read per row read", "bytes_read_per_row_read", "B")):
|
|
1024
|
+
points = []
|
|
1025
|
+
if real.get(key) is not None:
|
|
1026
|
+
detail = (f"{human(real.get('rows_read_per_run'))} rows → {human(real.get('rows_returned_per_run'))} per run" if not unit
|
|
1027
|
+
else f"{human_bytes(real.get('bytes_read_per_run'))} / {human(real.get('rows_read_per_run'))} rows per run")
|
|
1028
|
+
points.append(("production", real[key], detail, "read"))
|
|
1029
|
+
base = before or scan
|
|
1030
|
+
if base.get(key) is not None:
|
|
1031
|
+
detail = (f"{human(base.get('read_rows'))} rows → {human(base.get('result_rows'))}" if not unit
|
|
1032
|
+
else f"{human_bytes(base.get('read_bytes'))} / {human(base.get('read_rows'))} rows")
|
|
1033
|
+
points.append(("sandbox before", base[key], detail, ""))
|
|
1034
|
+
if after and after["variant"].get(key) is not None:
|
|
1035
|
+
m = after["variant"]
|
|
1036
|
+
detail = (f"{human(m.get('read_rows'))} rows → {human(m.get('result_rows'))}" if not unit
|
|
1037
|
+
else f"{human_bytes(m.get('read_bytes'))} / {human(m.get('read_rows'))} rows")
|
|
1038
|
+
points.append(("sandbox after", m[key], detail, _fill_class(after["verdict"])))
|
|
1039
|
+
if not points:
|
|
1040
|
+
continue
|
|
1041
|
+
top = max(math.log10(max(v, 1) + 1) for _, v, _, _ in points) or 1
|
|
1042
|
+
value = (lambda v: f"{human(v)}x") if not unit else (lambda v: human_bytes(v))
|
|
1043
|
+
rows.append(f"<div><h4>{e(label)}</h4><div class=bars>" + "".join(
|
|
1044
|
+
_ratio_row(name, 100 * math.log10(max(v, 1) + 1) / top, value(v), detail, cls) for name, v, detail, cls in points) + "</div></div>")
|
|
1045
|
+
if not rows:
|
|
1046
|
+
return ""
|
|
1047
|
+
shape = real if real.get("aggregate") is not None else (f.get("read_shape") or {})
|
|
1048
|
+
chips = tag({"group_by": "aggregate: GROUP BY", "count": "aggregate: count only", "aggregate": "aggregate"}.get(shape.get("aggregate_kind"), "aggregate"),
|
|
1049
|
+
"unverified") + tag("few rows out of many is expected") if shape.get("aggregate") else ""
|
|
1050
|
+
return f"<h4>Read against returned</h4><div class=grid2>{''.join(rows)}</div>" + (f"<div class=chips>{chips}</div>" if chips else "")
|
|
1051
|
+
|
|
1052
|
+
|
|
1053
|
+
def _share(part, whole, lead: str = "") -> str:
|
|
1054
|
+
"""'17%' for a share that means something; '' against a zero baseline or beyond ten times it (the figures say it)."""
|
|
1055
|
+
if not whole or float(part or 0) / float(whole) > 10:
|
|
1056
|
+
return ""
|
|
1057
|
+
return f"{lead}{pct(part, whole):.0f}%"
|
|
1058
|
+
|
|
1059
|
+
|
|
1060
|
+
def _before_after(v: dict) -> str:
|
|
1061
|
+
done = [s for s in v["scales"] if s["variant"] and s["variant"].get("ok")]
|
|
1062
|
+
if not done:
|
|
1063
|
+
return f"<div class=chips>{tag(v['reason'][:160] or 'not measured', 'failed')}</div>" if v.get("reason") else ""
|
|
1064
|
+
s = done[-1]
|
|
1065
|
+
b, m = s["baseline"], s["variant"]
|
|
1066
|
+
cls = _fill_class(s["verdict"])
|
|
1067
|
+
blocks = []
|
|
1068
|
+
pg = "node_types" in b
|
|
1069
|
+
for title, key, fmt in (("Rows scanned" if pg else "Rows read", "read_rows", human),
|
|
1070
|
+
("Buffers touched (x 8 kB)" if pg else "Bytes read", "read_bytes", human_bytes)):
|
|
1071
|
+
whole = max(b[key] or 0, m[key] or 0)
|
|
1072
|
+
blocks.append(f"<div><h4>{title} at {human(s['rows'])} table rows</h4><div class=bars>"
|
|
1073
|
+
+ bar("before", b[key], whole, fmt(b[key]))
|
|
1074
|
+
+ bar("after", m[key], whole, f"{fmt(m[key])}{_share(m[key], b[key], ' · ')}", cls) + "</div></div>")
|
|
1075
|
+
smaller = "".join(
|
|
1076
|
+
tag(f"at {human(x['rows'])} rows: " + (
|
|
1077
|
+
f"{_share(x['variant']['read_rows'], x['baseline']['read_rows'])} of rows, "
|
|
1078
|
+
f"{_share(x['variant']['read_bytes'], x['baseline']['read_bytes'])} of bytes"
|
|
1079
|
+
if _share(x["variant"]["read_rows"], x["baseline"]["read_rows"]) and _share(x["variant"]["read_bytes"], x["baseline"]["read_bytes"])
|
|
1080
|
+
else f"{human(x['variant']['read_rows'])} rows and {human_bytes(x['variant']['read_bytes'])} against "
|
|
1081
|
+
f"{human(x['baseline']['read_rows'])} rows and {human_bytes(x['baseline']['read_bytes'])}"), x["verdict"]) for x in done[:-1])
|
|
1082
|
+
return f"<div class=grid2>{''.join(blocks)}</div>" + (f"<div class=chips>{smaller}</div>" if smaller else "")
|
|
1083
|
+
|
|
1084
|
+
|
|
1085
|
+
def insert_cost_chips(v: dict) -> list[str]:
|
|
1086
|
+
"""The write side of a table-level variant beside its read verdict (writecost.py); never part of the verdict."""
|
|
1087
|
+
ic = v.get("insert_cost")
|
|
1088
|
+
if v.get("kind") not in blockers_mod.TABLE_LEVEL:
|
|
1089
|
+
return []
|
|
1090
|
+
if not ic:
|
|
1091
|
+
return [tag("insert side not measured", "unverified")]
|
|
1092
|
+
if not ic.get("measured"):
|
|
1093
|
+
return [tag(f"insert side not measured: {str(ic.get('reason') or '').replace('_', ' ')}", "unverified")]
|
|
1094
|
+
cls = "verified" if ic.get("within") else "failed"
|
|
1095
|
+
out = [tag(f"inserts x{ic['insert_time_ratio']:g} time" if ic.get("insert_time_ratio") is not None else "inserts: time not measured", cls)]
|
|
1096
|
+
if ic.get("storage_ratio") is not None:
|
|
1097
|
+
out.append(tag(f"storage x{ic['storage_ratio']:g}", cls))
|
|
1098
|
+
if ic.get("written_bytes_ratio") is not None:
|
|
1099
|
+
out.append(tag(f"bytes written x{ic['written_bytes_ratio']:g}"))
|
|
1100
|
+
if ic.get("rows"):
|
|
1101
|
+
out.append(tag(f"{human(ic['rows'])} rows in {ic.get('blocks')} inserts, each side"))
|
|
1102
|
+
return out
|
|
1103
|
+
|
|
1104
|
+
|
|
1105
|
+
def _variant_html(v: dict, f: dict) -> str:
|
|
1106
|
+
chips = [tag(f"delivered as {v['delivery']}")] + [tag(TRADEOFF_LABEL.get(x, x)) for x in v.get("tradeoffs") or []]
|
|
1107
|
+
if v.get("storage_delta_bytes", 0) > 0:
|
|
1108
|
+
chips.append(tag(f"+{human_bytes(v['storage_delta_bytes'])} storage in the sandbox"))
|
|
1109
|
+
chips += [tag(n, "unverified") for n in v.get("setup_notes") or []]
|
|
1110
|
+
chips += insert_cost_chips(v)
|
|
1111
|
+
if v.get("scenario"):
|
|
1112
|
+
chips.append(tag(f"scenario rule: {str(v.get('change') or v.get('rule') or '').replace('_', ' ')}"))
|
|
1113
|
+
if v.get("compared"):
|
|
1114
|
+
match = v.get("results_match")
|
|
1115
|
+
if match is None and "results_match" in v:
|
|
1116
|
+
# sameness was not decided: by design, or because nothing could be compared. Never "same results".
|
|
1117
|
+
chips.append(tag(v["compared"] if v["compared"].startswith("not compared") else "sameness not shown: " + v["compared"],
|
|
1118
|
+
"" if not v.get("same_results", True) else "unverified"))
|
|
1119
|
+
else:
|
|
1120
|
+
ok = v["verdict"] not in ("rejected", "failed") if match is None else bool(match)
|
|
1121
|
+
chips.append(tag(("same results: " if ok else "results differ: ") + v["compared"],
|
|
1122
|
+
"verified" if ok and v.get("same_results", True) else ("rejected" if not ok else "")))
|
|
1123
|
+
key = ""
|
|
1124
|
+
if v.get("new_order_by"):
|
|
1125
|
+
old = next((a for a in f.get("access") or [] if a["order_by"]), None)
|
|
1126
|
+
state = {x["column"]: "used" for a in f.get("access") or [] for x in a["filters"] if x["op"] != "other"}
|
|
1127
|
+
label = {"projection": "projection key", "index": "new index"}.get(v["kind"], "new key")
|
|
1128
|
+
key = ((f"<div class=keyrow><span class=lbl>current key</span>{_key_boxes(old['order_by'])}</div>" if old else "")
|
|
1129
|
+
+ f"<div class=keyrow><span class=lbl>{label}</span>{_key_boxes(v['new_order_by'], state, 'new')}</div>")
|
|
1130
|
+
setup = "".join(f"<pre>{e(s)}</pre>" for s in v.get("setup_sql") or [])
|
|
1131
|
+
explain = ""
|
|
1132
|
+
last = v["scales"][-1] if v["scales"] else None
|
|
1133
|
+
if last and last["variant"] and last["variant"].get("explain"):
|
|
1134
|
+
explain = (f"<details><summary>Plans ({'EXPLAIN ANALYZE, BUFFERS' if 'node_types' in last['baseline'] else 'EXPLAIN indexes = 1'})</summary><b>Before</b><pre>{e(last['baseline']['explain'])}</pre>"
|
|
1135
|
+
f"<b>After</b><pre>{e(last['variant']['explain'])}</pre></details>")
|
|
1136
|
+
return (
|
|
1137
|
+
f"<div class=variant><header>{tag(v['verdict'].replace('_', ' '), v['verdict'])}<h3>{e(v['change'])}</h3>"
|
|
1138
|
+
f"<span class=muted>{e(v['kind'].replace('_', ' '))}</span></header>"
|
|
1139
|
+
f"<div class=chips>{''.join(chips)}</div>{key}{_before_after(v)}{_measure_table(v)}"
|
|
1140
|
+
+ (f"<details><summary>Setup statements</summary>{setup}</details>" if setup else "")
|
|
1141
|
+
+ (f"<details><summary>Query for this variant</summary><pre>{e(v['sql'])}</pre></details>" if v["sql"].strip() else "")
|
|
1142
|
+
+ explain + "</div>")
|
|
1143
|
+
|
|
1144
|
+
|
|
1145
|
+
FIDELITY_CLASS = {"close": "verified", "near": "unverified", "off": "failed"}
|
|
1146
|
+
FIDELITY_LABEL = {"close": "sandbox reads like production (within x1.5)", "near": "sandbox near production (within x3)",
|
|
1147
|
+
"off": "sandbox reads unlike production", "unchecked": "not compared with production"}
|
|
1148
|
+
|
|
1149
|
+
|
|
1150
|
+
def _times(r) -> str:
|
|
1151
|
+
if r is None:
|
|
1152
|
+
return "-"
|
|
1153
|
+
if r == 0 or r == float("inf"):
|
|
1154
|
+
return "x0" if r == 0 else "far more"
|
|
1155
|
+
return f"x{r:.2g}" if r >= 1 else f"1/{1 / r:.2g}"
|
|
1156
|
+
|
|
1157
|
+
|
|
1158
|
+
def _fidelity_html(f: dict) -> str:
|
|
1159
|
+
"""One line: does the sandbox baseline read what production reads per run."""
|
|
1160
|
+
fid = f.get("fidelity") or {}
|
|
1161
|
+
if not fid.get("ratios"):
|
|
1162
|
+
return ""
|
|
1163
|
+
names = {"rows_read": "rows read", "bytes_read": "bytes read", "rows_returned": "rows returned", "selected_parts": "parts selected",
|
|
1164
|
+
"selected_marks": "marks selected"}
|
|
1165
|
+
chips = tag(FIDELITY_LABEL.get(fid["grade"], fid["grade"]), FIDELITY_CLASS.get(fid["grade"], ""))
|
|
1166
|
+
chips += "".join(tag(f"{names.get(k, k)} {_times(v)} of production") for k, v in fid["ratios"].items() if v is not None)
|
|
1167
|
+
# a target of zero is no ratio: what the sandbox did beside production's nothing (fidelity.check)
|
|
1168
|
+
chips += "".join(tag(f"{names.get(k, k)}: none in production's typical run, "
|
|
1169
|
+
f"{(human_bytes if k == 'bytes_read' else human)(z.get('sandbox') or 0)} in the sandbox",
|
|
1170
|
+
"" if not z.get("sandbox") else "unverified") for k, z in (fid.get("zero_targets") or {}).items())
|
|
1171
|
+
if fid.get("scale_bound"):
|
|
1172
|
+
chips += tag("production reads more rows a run than the sandbox table holds: rows read can not match at this scale", "unverified")
|
|
1173
|
+
if fid.get("graded_against") == "median":
|
|
1174
|
+
chips += tag("graded against production's median run")
|
|
1175
|
+
sp = fid.get("spread") or {}
|
|
1176
|
+
if sp.get("bytes_read"):
|
|
1177
|
+
p50, p90, p99 = sp["bytes_read"]
|
|
1178
|
+
chips += tag(f"production bytes read per run: median {human_bytes(p50)}, 90% under {human_bytes(p90)}, 99% under {human_bytes(p99)}"
|
|
1179
|
+
+ (" (approximate)" if sp.get("method") == "tdigest" else ""))
|
|
1180
|
+
if sp.get("of_executions") is not None and sp["of_executions"] < 1:
|
|
1181
|
+
chips += tag(f"the spread is that of the heaviest of several matched shapes ({sp['of_executions']:.0%} of the runs)", "unverified")
|
|
1182
|
+
mean = (fid.get("ratios_to_mean") or {}).get("bytes_read")
|
|
1183
|
+
if mean is not None:
|
|
1184
|
+
chips += tag(f"against the mean run: bytes read {_times(mean)}")
|
|
1185
|
+
elif fid.get("mean_hides_spread"):
|
|
1186
|
+
chips += tag(f"production's heaviest run read {fid['production_spread']:,.0f}x its mean run: the mean mixes light and heavy runs", "unverified")
|
|
1187
|
+
for key, what in (("no_result_share", "return nothing"), ("no_read_share", "read nothing")):
|
|
1188
|
+
if fid.get(key):
|
|
1189
|
+
chips += tag(f"{fid[key]:.0%} of production's runs {what}")
|
|
1190
|
+
heavy = fid.get("heavy") or {}
|
|
1191
|
+
if heavy.get("built") and heavy.get("ratios"):
|
|
1192
|
+
chips += tag("heavy run (production's 99th percentile): " + ", ".join(
|
|
1193
|
+
f"{names.get(k, k)} {_times(v)}" for k, v in heavy["ratios"].items() if v is not None), FIDELITY_CLASS.get(heavy.get("grade"), ""))
|
|
1194
|
+
elif heavy.get("built") is False and heavy.get("reason"):
|
|
1195
|
+
chips += tag(f"no heavy run: {heavy['reason']}")
|
|
1196
|
+
chosen = (fid.get("selected") or {}).get("ratios") or {}
|
|
1197
|
+
if chosen.get("parts") is not None:
|
|
1198
|
+
s, p = fid["selected"]["sandbox"], fid["selected"]["production"]
|
|
1199
|
+
chips += tag(f"parts selected {s['parts']:,} against {p['parts']:,.1f} a run in production; marks {s['marks']:,} against {p['marks']:,.1f}"
|
|
1200
|
+
+ ("" if fid["selected"].get("graded", True) else " (not graded: " + str(fid["selected"].get("not_graded") or "") + ")"))
|
|
1201
|
+
return f"<h4>Sandbox against production, per run</h4><div class=chips>{chips}</div>"
|
|
1202
|
+
|
|
1203
|
+
|
|
1204
|
+
def _sizes_cell(t: dict) -> str:
|
|
1205
|
+
"""Where a profiled table's column sizes came from, and the row width they add up to."""
|
|
1206
|
+
from . import sizes as sizes_mod
|
|
1207
|
+
sized = [c for c in t.get("columns") or [] if sizes_mod.mean_bytes(c)]
|
|
1208
|
+
if not sized:
|
|
1209
|
+
return tag("no sizes stated: generator defaults")
|
|
1210
|
+
real = sum(1 for c in sized if str(c.get("size_evidence") or "").startswith("real catalog"))
|
|
1211
|
+
aged = sum(1 for c in sized if c.get("size_evidence") == sizes_mod.REAL_PARTITIONS)
|
|
1212
|
+
width = sum(sizes_mod.mean_bytes(c) or 0 for c in sized)
|
|
1213
|
+
return (tag(f"about {human_bytes(width)} a row") + (tag(f"{real} column sizes from the real catalog", "verified") if real else "")
|
|
1214
|
+
+ (tag(f"{aged} of them by the age of the row, from the real partitions", "verified") if aged else "")
|
|
1215
|
+
+ (tag(f"{len(sized) - real} estimated by the agent") if len(sized) - real else ""))
|
|
1216
|
+
|
|
1217
|
+
|
|
1218
|
+
def _table_fidelity(t: dict) -> str:
|
|
1219
|
+
fid = t.get("fidelity") or {}
|
|
1220
|
+
if not fid.get("ratios"):
|
|
1221
|
+
return ""
|
|
1222
|
+
names = {"row_bytes": "row width", "compression": "compression"}
|
|
1223
|
+
return tag("real table: " + ", ".join(f"{names.get(k, k)} {_times(v)}" for k, v in fid["ratios"].items() if v is not None),
|
|
1224
|
+
FIDELITY_CLASS.get(fid.get("grade"), "")) + _layout_tag(t)
|
|
1225
|
+
|
|
1226
|
+
|
|
1227
|
+
def _layout_tag(t: dict) -> str:
|
|
1228
|
+
"""Parts per partition as built against the real layout, when the pull had it."""
|
|
1229
|
+
lay = t.get("part_layout") or {}
|
|
1230
|
+
if not lay:
|
|
1231
|
+
return ""
|
|
1232
|
+
timed = (tag(f"each part holds one range of {lay['time_column']} (part size ratio {lay.get('part_size_ratio', 0):g}, "
|
|
1233
|
+
f"{lay.get('part_size_basis') or 'default'})") if lay.get("parts_hold") == "time ranges" else "")
|
|
1234
|
+
if lay.get("basis") != "real parts per partition, by age":
|
|
1235
|
+
return timed
|
|
1236
|
+
return tag(f"parts by the partition's age, from the real layout: {lay['newest_parts']} in the newest partition "
|
|
1237
|
+
f"({lay.get('real_newest_parts') or 0:g} in the real one), {lay['oldest_parts']} in the oldest", "verified") + timed
|
|
1238
|
+
|
|
1239
|
+
|
|
1240
|
+
STATE_LABEL = {"fixed": "Fixed", "blocked": "Needs another fix", "not_judged": "Could not be judged", "nothing_to_gain": "Nothing to gain"}
|
|
1241
|
+
# A state after a count, lowercase: (one, many). The one place the CLI joins a count and a state word (the console has
|
|
1242
|
+
# the same table and helper).
|
|
1243
|
+
STATE_COUNT_WORDS = {"fixed": ("fixed", "fixed"), "blocked": ("needs another fix", "need another fix"),
|
|
1244
|
+
"not_judged": ("could not be judged", "could not be judged"),
|
|
1245
|
+
"nothing_to_gain": ("nothing to gain", "nothing to gain")}
|
|
1246
|
+
|
|
1247
|
+
|
|
1248
|
+
def state_count(n, state: str) -> str:
|
|
1249
|
+
"""A count and its state, agreeing: '1 needs another fix', '3 need another fix', '2 fixed'."""
|
|
1250
|
+
one, many = STATE_COUNT_WORDS.get(state, (state, state))
|
|
1251
|
+
return f"{int(n or 0):,} {one if n == 1 else many}"
|
|
1252
|
+
|
|
1253
|
+
REASON_LABEL = {
|
|
1254
|
+
"verified": "a variant reads less, same results",
|
|
1255
|
+
"no_variant_reads_less": "no variant reads meaningfully less", "fix_changes_results": "only a fix that changes the results reads less",
|
|
1256
|
+
"fix_results_differ": "a fix returned different results", "no_variant_proposed": "no variant was proposed",
|
|
1257
|
+
"heavy_by_count": "cheap per run, heavy in total",
|
|
1258
|
+
"fix_costs_inserts": "reads less, costs more on every insert (a trade-off)",
|
|
1259
|
+
"insert_cost_near_limit": "reads less; insert cost near the limit: the measured spread of the insert time crosses it (a trade-off)",
|
|
1260
|
+
"insert_cost_not_measured": "read side verified, insert side not measured",
|
|
1261
|
+
"fix_costs_memory": "reads less, holds more memory per run (a trade-off)",
|
|
1262
|
+
"fix_costs_cpu": "reads less, uses more CPU per run (a trade-off)",
|
|
1263
|
+
"resource_cost_near_limit": "reads less; memory or CPU near the limit: the spread of the runs crosses it (a trade-off)",
|
|
1264
|
+
"evidence_only": "the change is outside one statement: evidence only",
|
|
1265
|
+
"not_a_candidate": "no runnable statement for it",
|
|
1266
|
+
"sql_assembled_at_run_time": "SQL assembled at run time", "other_engine": "SQL for another engine",
|
|
1267
|
+
"assembled_needs_pull": "SQL assembled at run time, no database connected", "assembled_not_seen": "SQL assembled at run time, not seen in the query log",
|
|
1268
|
+
"assembled_shape_rejected": "production's statement found, could not be made runnable",
|
|
1269
|
+
"variants_not_asked": "production's statement measured, no variant asked for yet",
|
|
1270
|
+
"join_not_asked": "a join CodeCop flagged, no variant it could prove; no agent asked yet",
|
|
1271
|
+
"sql_from_outside_code": "SQL comes from outside the code", "sql_too_long_for_agent": "SQL longer than the agent was shown",
|
|
1272
|
+
"agent_no_answer": "examined, the agent returned nothing", "agent_failed": "its agent batch failed",
|
|
1273
|
+
"budget_reached": "budget reached before its batch", "bench_not_run": "no benchmark was run",
|
|
1274
|
+
"sandbox_table_not_loaded": "sandbox could not load a table", "sandbox_could_not_run": "sandbox could not run it",
|
|
1275
|
+
"sandbox_lost": "the sandbox was lost before it was measured",
|
|
1276
|
+
"parameters_match_no_rows": "parameters matched no rows", "sameness_not_shown": "reads less, sameness not shown",
|
|
1277
|
+
"sandbox_unlike_production": "sandbox reads unlike production",
|
|
1278
|
+
"small_table": "small table (agent)", "already_cheap": "already cheap (agent)", "same_as_another": "same as another candidate",
|
|
1279
|
+
"one_off": "one-off script", "cached": "behind a cache", "already_cheap_measured": "already cheap (measured)",
|
|
1280
|
+
"rejected_other": "agent gave no code",
|
|
1281
|
+
"engine_not_benchmarkable": "engine not benchmarkable",
|
|
1282
|
+
"definition_incomplete": "reads a table or column no table definition has",
|
|
1283
|
+
"baseline_timed_out": "baseline hit the time limit at the largest scale",
|
|
1284
|
+
}
|
|
1285
|
+
BLOCKER_LABEL = {"key_not_usable": "Filter can't use the key", "join_side_unfiltered": "Joined table read whole",
|
|
1286
|
+
"dedup_read_required": "Deduplicating read (FINAL)", "full_partition_range_read": "Every partition read",
|
|
1287
|
+
"heavy_by_count": "Cheap per run, heavy in total", "no_fix_found": "No table-level cause shown"}
|
|
1288
|
+
PG_BLOCKER_LABEL = {**BLOCKER_LABEL, "key_not_usable": "No index serves the filter"}
|
|
1289
|
+
# What to do next, per blockers.NEXT_STEP code
|
|
1290
|
+
NEXT_STEP_LABEL = {
|
|
1291
|
+
"connect_read_only_pull": "Connect a read-only pull (codecop db pull): the statement is then read from the query log",
|
|
1292
|
+
"longer_window_or_add_tag": "Pull a longer window, or tag the code that builds it (log_comment codecop:<tag>) so the log ties it here",
|
|
1293
|
+
"none_codecop_side": "Nothing for you to do: CodeCop could not make production's statement runnable (the gate's output is shown)",
|
|
1294
|
+
"nothing_at_this_site": "Nothing to fix at this site: its statements appear under their own shapes when a pull exists",
|
|
1295
|
+
"raise_rank_max_sql_chars": "Raise rank.max_sql_chars in codecop.toml and rank again: the agent was shown only the start",
|
|
1296
|
+
"ask_agent_for_variants": "Ask an agent for faster variants of the statement as it ran: codecop rank --observed-variants (paid, estimate shown first)",
|
|
1297
|
+
"ask_agent_for_join_variants": "Ask an agent about the join, with CodeCop's facts in the prompt: codecop rank --focus join (paid; --dry-run shows the estimate)",
|
|
1298
|
+
}
|
|
1299
|
+
|
|
1300
|
+
|
|
1301
|
+
def _state_tag(r: dict) -> str:
|
|
1302
|
+
o = r.get("outcome") or {}
|
|
1303
|
+
return tag(STATE_LABEL.get(o["state"], o["state"]), o["state"]) if o.get("state") else ""
|
|
1304
|
+
|
|
1305
|
+
|
|
1306
|
+
def _ratio_chip(name: str, r) -> str:
|
|
1307
|
+
return tag(f"{name} {_times(r)}") if r is not None else ""
|
|
1308
|
+
|
|
1309
|
+
|
|
1310
|
+
def _blocker_html(b: dict, engine: str) -> str:
|
|
1311
|
+
"""One blocker as a cause box: what it is, on which table, and the engine's own counts."""
|
|
1312
|
+
read = b.get("read") or {}
|
|
1313
|
+
if "granules_total" in read:
|
|
1314
|
+
counts = f"{read['granules_read']:,}/{read['granules_total']:,} granules read"
|
|
1315
|
+
elif "rows_fetched" in read:
|
|
1316
|
+
counts = f"{human(read['rows_fetched'])} of {human(read['table_rows'])} rows fetched · {', '.join(read.get('nodes') or [])}"
|
|
1317
|
+
elif "table_rows" in read:
|
|
1318
|
+
counts = f"{human(read.get('rows_read'))} of {human(read['table_rows'])} rows read"
|
|
1319
|
+
elif "share_of_read_bytes" in read:
|
|
1320
|
+
counts = f"{read['share_of_read_bytes']:.1%} of all bytes read in production · {human(read.get('executions'))} runs"
|
|
1321
|
+
else:
|
|
1322
|
+
counts = f"{human(read.get('read_rows'))} rows read → {human(read.get('result_rows'))} returned"
|
|
1323
|
+
parts = [counts]
|
|
1324
|
+
if read.get("partition_parts_total"):
|
|
1325
|
+
parts.append(f"{read['partition_parts_read']}/{read['partition_parts_total']} partitions")
|
|
1326
|
+
if b.get("columns"):
|
|
1327
|
+
parts.append("filters " + ", ".join(b["columns"][:6]))
|
|
1328
|
+
if b.get("wanted_key_prefix"):
|
|
1329
|
+
parts.append("would need a key prefix " + ", ".join(b["wanted_key_prefix"]))
|
|
1330
|
+
if b.get("partition_by"):
|
|
1331
|
+
parts.append(f"PARTITION BY {b['partition_by'][:60]}")
|
|
1332
|
+
if b.get("code") == "dedup_read_required":
|
|
1333
|
+
parts.append("a variant without FINAL returned other rows" if b.get("confirmed") else "not confirmed by a variant")
|
|
1334
|
+
if b.get("definition") == "assembled":
|
|
1335
|
+
parts.append("definition assembled by the agent")
|
|
1336
|
+
label = (PG_BLOCKER_LABEL if engine in ("postgres", "sqlite") else BLOCKER_LABEL).get(b["code"], b["code"])
|
|
1337
|
+
cls = "cause no-evidence" if b["code"] == "no_fix_found" else "cause"
|
|
1338
|
+
table = f" <code>{e(b['table'])}</code>" if b.get("table") else ""
|
|
1339
|
+
return f"<div class='{cls}'><b>{e(label)}</b>{table}<small>{e(' · '.join(parts))}</small></div>"
|
|
1340
|
+
|
|
1341
|
+
|
|
1342
|
+
def _next_step_chips(ev: dict) -> list[str]:
|
|
1343
|
+
"""For a query whose SQL was not known: what was found, and the one next step (blockers.NEXT_STEP)."""
|
|
1344
|
+
out = []
|
|
1345
|
+
if ev.get("sql_chars") and ev.get("cut_at"):
|
|
1346
|
+
out.append(tag(f"{ev['sql_chars']:,} characters, the prompt showed {ev['cut_at']:,}", "unverified"))
|
|
1347
|
+
if ev.get("window_hours"):
|
|
1348
|
+
out.append(tag(f"query log window: {ev['window_hours']} h"))
|
|
1349
|
+
u = ev.get("unlocated_on_its_tables")
|
|
1350
|
+
if u:
|
|
1351
|
+
out.append(tag(f"{u['shapes']} production statements on its tables have no place in code · {human_bytes(u['read_bytes'])} read"))
|
|
1352
|
+
if ev.get("likely_matches"):
|
|
1353
|
+
out.append(tag("a likely match only: not used as a place"))
|
|
1354
|
+
gate = ev.get("gate") or {}
|
|
1355
|
+
if gate.get("reason"):
|
|
1356
|
+
out.append(tag(f"gate: {gate['reason'].replace('_', ' ')}" + (f" · {gate['detail'][:120]}" if gate.get("detail") else ""), "failed"))
|
|
1357
|
+
if ev.get("next_step"):
|
|
1358
|
+
from .formerly import code as _code # a next step stored before the rename reads as the new one
|
|
1359
|
+
step = _code(ev["next_step"])
|
|
1360
|
+
out.append(tag("Next: " + NEXT_STEP_LABEL.get(step, step), "verified"))
|
|
1361
|
+
return out
|
|
1362
|
+
|
|
1363
|
+
|
|
1364
|
+
def _outcome_html(f: dict, engine: str) -> str:
|
|
1365
|
+
"""The finding's state and reason, its numbers as chips, and the table-level blockers."""
|
|
1366
|
+
o = f.get("outcome")
|
|
1367
|
+
if not o:
|
|
1368
|
+
return f"<div class=chips>{tag('state unknown: findings.json from an older CodeCop')}</div>"
|
|
1369
|
+
ev = o.get("evidence") or {}
|
|
1370
|
+
chips = [tag(STATE_LABEL.get(o["state"], o["state"]), o["state"]), tag(REASON_LABEL.get(o["reason"], o["reason"]))]
|
|
1371
|
+
if ev.get("kind"):
|
|
1372
|
+
chips.append(tag(str(ev["kind"]).replace("_", " ")))
|
|
1373
|
+
chips += [_ratio_chip("rows", ev.get("rows_ratio")), _ratio_chip("bytes", ev.get("bytes_ratio")), _ratio_chip("memory", ev.get("memory_ratio"))]
|
|
1374
|
+
if ev.get("verdicts"):
|
|
1375
|
+
chips.append(tag(" · ".join(f"{n} {k.replace('_', ' ')}" for k, n in ev["verdicts"].items())))
|
|
1376
|
+
chips += [tag(c, "failed") for c in [ev.get("error_class")] + list(ev.get("error_classes") or []) if c]
|
|
1377
|
+
if isinstance(ev.get("tables"), list):
|
|
1378
|
+
chips += [tag(f"{t.get('table')}: {t.get('error_class')}", "failed") for t in ev["tables"]]
|
|
1379
|
+
if ev.get("why"):
|
|
1380
|
+
chips.append(tag(str(ev["why"]).replace("_", " ")))
|
|
1381
|
+
if ev.get("insert_cost"):
|
|
1382
|
+
chips += insert_cost_chips({"kind": ev.get("kind"), "insert_cost": ev["insert_cost"] if ev["insert_cost"].get("reason") != "not_measured" else None})
|
|
1383
|
+
if ev.get("trade_off"):
|
|
1384
|
+
chips.append(tag("trade-off: not counted as fixed", "unverified"))
|
|
1385
|
+
if ev.get("selected_marks"):
|
|
1386
|
+
chips.append(tag(f"{ev['selected_marks']} of {ev.get('total_marks') or 0:,} granules read"))
|
|
1387
|
+
if ev.get("floor_bytes"):
|
|
1388
|
+
chips.append(tag(f"at or under {human_bytes(ev['floor_bytes'])} and {ev['floor_rows']} rows"))
|
|
1389
|
+
if ev.get("fidelity"):
|
|
1390
|
+
chips.append(tag(f"sandbox {ev['fidelity']} to production", FIDELITY_CLASS.get(ev["fidelity"], "")))
|
|
1391
|
+
unlike = ev.get("data_unlike_production")
|
|
1392
|
+
if unlike:
|
|
1393
|
+
# Fixed stays Fixed, the size of the gain is not production's (blockers.unlike_production)
|
|
1394
|
+
chips.append(tag(unlike.get("label") or "measured on data that does not resemble production", "unverified"))
|
|
1395
|
+
if unlike.get("catalog_only_tables"):
|
|
1396
|
+
chips.append(tag("data from the catalog only: " + ", ".join(unlike["catalog_only_tables"][:4])))
|
|
1397
|
+
if (ev.get("other_run") or {}).get("reason"):
|
|
1398
|
+
chips.append(tag(f"on a run that returns rows: {ev['other_run']['reason']}"))
|
|
1399
|
+
chips += _next_step_chips(ev)
|
|
1400
|
+
blockers = "".join(_blocker_html(b, engine) for b in o.get("blockers") or [])
|
|
1401
|
+
return f"<div class=chips>{''.join(c for c in chips if c)}</div>" + (f"<div class=chips>{blockers}</div>" if blockers else "")
|
|
1402
|
+
|
|
1403
|
+
|
|
1404
|
+
def _outcomes_html(data: dict) -> str:
|
|
1405
|
+
"""Every ranked query in one of four states: a stacked bar, the reasons, and the tables that block the most."""
|
|
1406
|
+
o = data.get("outcomes")
|
|
1407
|
+
if not o or not o.get("ranked"):
|
|
1408
|
+
return ""
|
|
1409
|
+
from .blockers import STATES
|
|
1410
|
+
total = o["ranked"]
|
|
1411
|
+
stack = "".join(f"<i class='st-{s}' style='width:{pct(o['states'].get(s, 0), total):.2f}%' title='{e(STATE_LABEL[s])}'></i>"
|
|
1412
|
+
for s in STATES if o["states"].get(s))
|
|
1413
|
+
legend = "".join(tag(f"{state_count(o['states'].get(s, 0), s)} · {o['sites'].get(s, 0)} site{'' if o['sites'].get(s, 0) == 1 else 's'}", s)
|
|
1414
|
+
for s in STATES)
|
|
1415
|
+
if o.get("unknown"):
|
|
1416
|
+
legend += tag(f"{o['unknown']} state unknown")
|
|
1417
|
+
top = max((r["queries"] for r in o.get("reasons") or []), default=1)
|
|
1418
|
+
reasons = "".join(
|
|
1419
|
+
f"<tr><td>{tag(STATE_LABEL.get(r['state'], r['state']), r['state'])}</td><td>{e(REASON_LABEL.get(r['reason'], r['reason']))} "
|
|
1420
|
+
f"<span class='muted mono'>{e(r['reason'])}</span></td>"
|
|
1421
|
+
f"<td class=num><div class='track mini'><div class='fill st-{e(r['state'])}' style='width:{pct(r['queries'], top):.0f}%'></div></div>{r['queries']}</td>"
|
|
1422
|
+
f"<td class=num>{r['sites']}</td></tr>" for r in o.get("reasons") or [])
|
|
1423
|
+
labels = PG_BLOCKER_LABEL if data.get("engine") in ("postgres", "sqlite") else BLOCKER_LABEL
|
|
1424
|
+
window = o.get("window_hours")
|
|
1425
|
+
|
|
1426
|
+
def codes(t: dict) -> str:
|
|
1427
|
+
return "".join(tag(f"{labels.get(c, c)} · {n}", "blocked") for c, n in t["codes"].items()) + (
|
|
1428
|
+
tag("definition assembled by the agent", "unverified") if t.get("definition") == "assembled" else "")
|
|
1429
|
+
|
|
1430
|
+
tables = "".join(
|
|
1431
|
+
f"<tr><td class=mono>{e(t['table'])}</td><td>{codes(t)}</td>"
|
|
1432
|
+
f"<td>{' '.join(f'<a href=#{e(x)}>{e(x)}</a>' for x in t.get('findings') or [])}</td><td class=num>{t['sites']}</td>"
|
|
1433
|
+
f"<td class=num>{human_bytes(t['measured_read_bytes']) if t.get('measured_read_bytes') is not None else '-'}</td>"
|
|
1434
|
+
f"<td class=num>{human_bytes(t.get('sandbox_read_bytes'))}</td></tr>" for t in o.get("tables") or [])
|
|
1435
|
+
measured_head = f"Measured read, {window} h" if window else "Measured read"
|
|
1436
|
+
return ("<h2>Every ranked query, and what stopped it</h2>"
|
|
1437
|
+
f"<div class=stack>{stack}</div><div class=chips>{legend}</div>"
|
|
1438
|
+
"<p></p><div class=wrap><table><tr><th>State</th><th>Reason</th><th class=num>Queries</th><th class=num>Call sites</th></tr>"
|
|
1439
|
+
+ reasons + "</table></div>"
|
|
1440
|
+
+ ("<h4>Needs another fix, by table</h4><div class=wrap><table><tr><th>Table</th><th>What stands in the way</th><th>Findings</th><th class=num>Call sites</th>"
|
|
1441
|
+
f"<th class=num>{e(measured_head)}</th><th class=num>Sandbox read, one run</th></tr>" + tables + "</table></div>" if tables else "")
|
|
1442
|
+
+ (f"<div class=chips>{tag(str(o['blocked_without_table']) + ' with no table-level cause in the engine output')}</div>"
|
|
1443
|
+
if o.get("blocked_without_table") else "")
|
|
1444
|
+
+ _no_text_html(data))
|
|
1445
|
+
|
|
1446
|
+
|
|
1447
|
+
def _repository_coverage_html(data: dict) -> str:
|
|
1448
|
+
"""The judged share of every query and write site of the repository (coverage.repository): the funnel and the reasons."""
|
|
1449
|
+
r = (data.get("coverage") or {}).get("repository")
|
|
1450
|
+
if not isinstance(r, dict) or not r.get("sites"):
|
|
1451
|
+
return ""
|
|
1452
|
+
n = r["sites"]
|
|
1453
|
+
def lost(f: dict) -> str:
|
|
1454
|
+
return ", ".join("%s %s" % (x["label"], format(x["sites"], ",")) for x in (f.get("lost") or [])[:3])
|
|
1455
|
+
|
|
1456
|
+
steps = "".join(
|
|
1457
|
+
f"<tr><td>{e(f['label'])}</td><td class=num><div class='track mini'><div class='fill st-fixed' style='width:{pct(f['sites'], n):.0f}%'>"
|
|
1458
|
+
f"</div></div>{f['sites']:,}</td><td>{e(lost(f))}</td></tr>"
|
|
1459
|
+
for f in r["funnel"])
|
|
1460
|
+
reasons = "".join(f"<tr><td>{e(x['label'])}</td><td class=num>{x['sites']:,}</td><td>{e(x['next_step'])}</td></tr>" for x in r["not_judged"])
|
|
1461
|
+
engines_ = " + ".join(r.get("engines_scanned") or []) or "no engine"
|
|
1462
|
+
judged = "%s of %s query and write sites" % (format(r["judged"], ","), format(n, ","))
|
|
1463
|
+
measured = "%.1f%% by measurement" % r["judged_measured_share"]
|
|
1464
|
+
word = "%.1f%% on the agent's word or catalog" % r["judged_on_word_share"]
|
|
1465
|
+
return (f"<h2>Repository coverage: {r['judged_share']:.1f}% judged</h2>"
|
|
1466
|
+
f"<div class=chips>{tag(judged, 'fixed')}{tag(measured, 'verified')}{tag(word, 'unverified')}{tag('engines scanned: ' + engines_)}</div>"
|
|
1467
|
+
"<div class=wrap><table><tr><th>Stage</th><th class=num>Sites</th><th>Lost before it</th></tr>" + steps + "</table></div>"
|
|
1468
|
+
"<h4>Could not be judged</h4><div class=wrap><table><tr><th>Reason</th><th class=num>Sites</th><th>Next step</th></tr>"
|
|
1469
|
+
+ reasons + "</table></div>")
|
|
1470
|
+
|
|
1471
|
+
|
|
1472
|
+
def _no_text_html(data: dict) -> str:
|
|
1473
|
+
"""Call sites with no SQL text: they reach neither the agent nor the query log match, so no state above counts them."""
|
|
1474
|
+
nt = (data.get("coverage") or {}).get("no_text") or {}
|
|
1475
|
+
if not nt.get("sites"):
|
|
1476
|
+
return ""
|
|
1477
|
+
engines_ = ", ".join(f"{k} {v:,}" for k, v in (nt.get("by_engine") or {}).items())
|
|
1478
|
+
return ("<div class=chips>" + tag(f"{nt['sites']:,} call sites hold no SQL text (never ranked, never matched to the query log): "
|
|
1479
|
+
f"{nt['unresolved']:,} unresolved, {nt['wrapper']:,} wrappers · {engines_}", "unverified") + "</div>")
|
|
1480
|
+
|
|
1481
|
+
|
|
1482
|
+
SQL_FROM_LABEL = {"code": "SQL written in code", "orm": "SQL translated from an ORM call", "query_log": "SQL observed in production",
|
|
1483
|
+
"code_variants": "SQL assembled from code, not observed", "agent": "SQL written by the agent from code"}
|
|
1484
|
+
LOCATED_LABEL = {"exact": "located: same text", "template": "located through its template", "tag": "located by the application's tag",
|
|
1485
|
+
"part": "contains text from these files", "likely": "possible places only", "none": "no place in code found",
|
|
1486
|
+
"site": "at this call site"}
|
|
1487
|
+
|
|
1488
|
+
|
|
1489
|
+
def _labels_html(f: dict) -> str:
|
|
1490
|
+
"""The two claims every candidate makes, apart: where its SQL comes from, and where its place in code comes from."""
|
|
1491
|
+
if not f.get("sql_from"):
|
|
1492
|
+
return ""
|
|
1493
|
+
sure = f.get("located") in ("exact", "template", "tag", "site")
|
|
1494
|
+
return (tag(SQL_FROM_LABEL.get(f["sql_from"], f["sql_from"]), "verified" if f["sql_from"] in ("code", "orm", "query_log") else "unverified")
|
|
1495
|
+
+ tag(LOCATED_LABEL.get(f.get("located"), f.get("located") or ""), "verified" if sure else "unverified"))
|
|
1496
|
+
|
|
1497
|
+
|
|
1498
|
+
def _observed_html(f: dict) -> str:
|
|
1499
|
+
"""For a statement production ran: its share of the call site, what each run-time part was filled with, where the
|
|
1500
|
+
values came from, the places in code (pieces: each as a piece), and the normalized text as the server logged it."""
|
|
1501
|
+
o = f.get("observed")
|
|
1502
|
+
if not o:
|
|
1503
|
+
return ""
|
|
1504
|
+
chips = [tag(f"{o['executions']:,} runs in {o.get('window_hours') or '?'} h"), tag(f"{o['share_of_read_bytes']:.3%} of all bytes read"),
|
|
1505
|
+
tag(f"{o.get('share_of_site_bytes', 1):.0%} of this call site's bytes · {o.get('shapes_of_site', 1)} shapes")]
|
|
1506
|
+
if o.get("fixed_share") is not None:
|
|
1507
|
+
chips.append(tag(f"fixed text covers {o['fixed_share']:.0%} of the statement", "verified"))
|
|
1508
|
+
filled = o.get("filled") or {}
|
|
1509
|
+
chips.append(tag(f"values: {filled.get('code', 0)} from the code, {filled.get('catalog', 0)} typed from the catalog, "
|
|
1510
|
+
f"{filled.get('neutral', 0)} neutral outside the filters"))
|
|
1511
|
+
frags = "".join(tag(f"{x['marker']} → {x['tokens']} tokens, as production sent it") for x in o.get("fragments") or [])
|
|
1512
|
+
if f.get("located") == "part":
|
|
1513
|
+
joiner = o.get("joining_function")
|
|
1514
|
+
places = "".join(f"<li><code>{e(p['file'])}:{p['line']}</code> {e(p.get('symbol') or '')}</li>" for p in o.get("pieces") or [])
|
|
1515
|
+
where = (f"<h4>Where it is built</h4><p class=muted>One of the places that build it: each file below holds a piece of this statement. "
|
|
1516
|
+
+ (f"The pieces share one caller: <code>{e(joiner['symbol'])}</code> ({e(joiner['file'])}:{joiner['line']})."
|
|
1517
|
+
if joiner else "The code that joins the pieces was not found.") + " The cost is the whole statement's, never a piece's.</p>"
|
|
1518
|
+
f"<ul>{places}</ul>")
|
|
1519
|
+
elif len(o.get("places") or []) > 1:
|
|
1520
|
+
where = "<div class=chips>" + tag(f"sent from {len(o['places'])} places with the same SQL") + "</div>"
|
|
1521
|
+
else:
|
|
1522
|
+
where = ""
|
|
1523
|
+
text = (f"<details><summary>Statement production ran (normalized by the server: every value is ?)</summary><pre>{e(o['normalized_text'])}</pre></details>"
|
|
1524
|
+
if o.get("normalized_text") else "")
|
|
1525
|
+
return f"<h4>Observed in production</h4><div class=chips>{''.join(chips)}{frags}</div>{where}{text}"
|
|
1526
|
+
|
|
1527
|
+
|
|
1528
|
+
WHO_LABEL = {"your_tables": "on tables your code reads", "system": "the server's own catalog: tooling, not app load", "mixed": "your tables joined with others",
|
|
1529
|
+
"other_service": "tables no scanned repository names"}
|
|
1530
|
+
|
|
1531
|
+
|
|
1532
|
+
def _unlocated_html(data: dict) -> str:
|
|
1533
|
+
"""Production statements with no place in code: measured, never placed. A likely match is a possible place, not a location."""
|
|
1534
|
+
u = ((data.get("observed") or {}).get("unlocated")) or {}
|
|
1535
|
+
if not u.get("shapes"):
|
|
1536
|
+
return ""
|
|
1537
|
+
who = "".join(tag(f"{WHO_LABEL[w]}: {v['shapes']} · {v['share_of_read_bytes']:.2%}") for w, v in (u.get("by_who") or {}).items() if v.get("shapes"))
|
|
1538
|
+
rows = "".join(
|
|
1539
|
+
f"<tr><td class=mono>{e(', '.join(s['tables'][:3]) or '-')}</td><td>{tag(WHO_LABEL.get(s['who'], s['who']))}</td>"
|
|
1540
|
+
f"<td class=num>{human(s['executions'])}</td><td class=num>{human_bytes(s['read_bytes'])}</td><td class=num>{s['share_of_read_bytes']:.3%}</td>"
|
|
1541
|
+
f"<td>{''.join(tag('possible: ' + p['file'].split('/')[-1], 'unverified') for p in s.get('possible_places') or []) or tag('place in code not found')}</td></tr>"
|
|
1542
|
+
for s in (u.get("statements") or [])[:40])
|
|
1543
|
+
return (f"<h2>In production, place in code not found</h2><p class=muted>{u['shapes']:,} statements · {u['share_of_read_bytes']:.2%} of bytes read · "
|
|
1544
|
+
f"{u['share_of_executions']:.1%} of runs. Measured in the query log; no call site in the scanned code sends them. A possible place is a "
|
|
1545
|
+
"likely match by tables and tokens, never a location. Tagging the code that builds them (log_comment codecop:<tag>) places them.</p>"
|
|
1546
|
+
f"<div class=chips>{who}</div><div class=wrap><table><tr><th>Tables</th><th>Who</th><th class=num>Runs</th><th class=num>Read</th>"
|
|
1547
|
+
f"<th class=num>Share</th><th>Place in code</th></tr>{rows}</table></div>")
|
|
1548
|
+
|
|
1549
|
+
|
|
1550
|
+
RESOURCE_AXIS = 1.5 # the ratio axis of the profile's bars runs from 0 to x1.5 (today is 1); a ratio past it fills the bar
|
|
1551
|
+
|
|
1552
|
+
|
|
1553
|
+
def _resources_html(f: dict, engine: str) -> str:
|
|
1554
|
+
"""The resource profile (resources_view.rows): one row per resource, production today beside the sandbox's ratio for the
|
|
1555
|
+
change on a shared axis (0 to x1.5, today at 1), the pair it came from and the runs, and whether the sandbox is like
|
|
1556
|
+
production for that measure. Nothing when neither side has a figure."""
|
|
1557
|
+
from . import resources_view as rv
|
|
1558
|
+
rows = rv.rows(f, engine or "clickhouse")
|
|
1559
|
+
if not any(r.get("sandbox") for r in rows[1:]) and not (f.get("real") or {}).get("memory") and not (f.get("real") or {}).get("cpu"):
|
|
1560
|
+
return ""
|
|
1561
|
+
v = rv.best_variant(f)
|
|
1562
|
+
body = []
|
|
1563
|
+
for r in rows:
|
|
1564
|
+
sb = r.get("sandbox")
|
|
1565
|
+
if sb and sb.get("ratio") is not None:
|
|
1566
|
+
q = float(sb["ratio"])
|
|
1567
|
+
cls = "win" if q < 0.95 else "bad" if q > 1.05 else ""
|
|
1568
|
+
whisker = (f" <span class=muted>{rv.ratio(sb['low'])} to {rv.ratio(sb['high'])}, {sb['runs']} runs</span>"
|
|
1569
|
+
if sb.get("runs") and sb["runs"] > 1 and sb.get("low") != sb.get("high") else "")
|
|
1570
|
+
cell = (f"<div class=track><div class='fill {cls}' style='width:{min(q / RESOURCE_AXIS, 1) * 100:.1f}%'></div></div>"
|
|
1571
|
+
f"<span class=mono><b>{e(rv.ratio(q))}</b></span> <span class=muted>{e(sb.get('pair') or '')}</span>{whisker}"
|
|
1572
|
+
+ (" " + tag("beside other containers", "unverified") if r.get("noisy") else ""))
|
|
1573
|
+
elif sb and sb.get("pair"):
|
|
1574
|
+
cell = e(sb["pair"])
|
|
1575
|
+
else:
|
|
1576
|
+
cell = f"<span class=muted>{e(r.get('sandbox_note') or 'Not measured in the sandbox')}</span>"
|
|
1577
|
+
grade = r.get("grade")
|
|
1578
|
+
like = (tag(f"{grade} {_times(r['grade_ratio'])}" if r.get("grade_ratio") is not None else grade, FIDELITY_CLASS.get(grade, ""))
|
|
1579
|
+
if grade and grade != "unchecked" else "<span class=muted>Not graded</span>" if r["key"] in ("read", "cpu", "memory") else "")
|
|
1580
|
+
est = r.get("estimate")
|
|
1581
|
+
est_cell = ""
|
|
1582
|
+
if "resource_estimate" in f:
|
|
1583
|
+
fmt = rv.hours if r["key"] == "cpu" else rv.size
|
|
1584
|
+
nj = r.get("not_judged")
|
|
1585
|
+
est_cell = (f"<td>{tag('Estimate', 'unverified')} ≈{e(fmt(est['value']))} <span class=muted>({e(fmt(est['low']))} to {e(fmt(est['high']))}"
|
|
1586
|
+
+ (f"; {e(fmt(est['from']))} × {est['ratio']:.2g}" if est.get("from") is not None and est.get("ratio") is not None else "")
|
|
1587
|
+
+ ")</span></td>" if est else
|
|
1588
|
+
f"<td class=muted>Not judged{(' · ' + e(str(nj).replace('_', ' '))) if nj else ''}</td>" if r["key"] in ("read", "cpu", "memory")
|
|
1589
|
+
else "<td class=muted>Not estimated</td>")
|
|
1590
|
+
body.append(f"<tr><td><b>{e(r['resource'])}</b><br><span class=muted>{e(r['qualifier'])}</span></td>"
|
|
1591
|
+
f"<td>{'<br>'.join(e(x) for x in r['production'])}</td><td>{cell}</td><td>{like}</td>{est_cell}</tr>")
|
|
1592
|
+
words = rv.judged_words(v)
|
|
1593
|
+
head = (f"<h4>Resource profile{(' · ' + e(v.get('change') or v.get('kind'))) if v else ''}</h4>"
|
|
1594
|
+
+ (f"<div class=chips>{tag(words, 'failed' if 'trade-off' in words else '')}</div>" if words else ""))
|
|
1595
|
+
return (head + "<div class=wrap><table><tr><th>Resource</th><th>Production today</th><th>With the fix, against today · sandbox</th>"
|
|
1596
|
+
"<th>Sandbox like production?</th>" + ("<th>In production with the fix</th>" if "resource_estimate" in f else "") + "</tr>"
|
|
1597
|
+
+ "".join(body) + "</table></div>")
|
|
1598
|
+
|
|
1599
|
+
|
|
1600
|
+
def _finding_html(f: dict, engine: str = "") -> str:
|
|
1601
|
+
params = "".join(tag(f"{k} = {v}") for k, v in f["params"].items())
|
|
1602
|
+
assumptions = "".join(tag(a) for a in f.get("assumptions") or [])
|
|
1603
|
+
access = "".join(_access_html(a) for a in f.get("access") or [])
|
|
1604
|
+
causes = _causes_html(f.get("causes") or [])
|
|
1605
|
+
blocked = f.get("not_benchmarked") or {}
|
|
1606
|
+
why_not = ("<h4>Not benchmarked</h4><div class=chips>" + "".join(
|
|
1607
|
+
tag(f"table {t['table']} could not be built in the sandbox", "failed") for t in blocked.get("tables") or []) + "</div>"
|
|
1608
|
+
+ "".join(f"<pre>{e(t['table'])}: {e(t['error'])}</pre>" for t in blocked.get("tables") or [])) if blocked else ""
|
|
1609
|
+
notes = ("<h4>About the sandbox tables</h4><div class=chips>" + "".join(tag(n[:220], "unverified") for n in f["sandbox_notes"]) + "</div>"
|
|
1610
|
+
) if f.get("sandbox_notes") else ""
|
|
1611
|
+
return (
|
|
1612
|
+
f"<section class=finding id='{e(f['finding'])}'><header><h3>{e(f['finding'])} · {e(f['title'])}</h3>"
|
|
1613
|
+
f"{tag(status_label(f), f['status'])}{_severity(f['severity'])}{tag(f['evidence_tier'])}{_labels_html(f)}</header>"
|
|
1614
|
+
f"<h4>Outcome</h4>{_outcome_html(f, engine)}"
|
|
1615
|
+
f"{why_not}{notes}{_observed_html(f)}{joins_view.finding_html(f)}"
|
|
1616
|
+
f"<h4>Where it runs</h4>{_flow_html(f)}"
|
|
1617
|
+
+ (f"<div class=chips>{''.join(tag(c, 'verified' if i == 0 else '') for i, c in enumerate(measured_chips(f.get('real'))))}</div>" if f.get("real") else "")
|
|
1618
|
+
+ (f"<h4>Why it reads too much</h4>{access}<div class=chips>{causes}</div>" if access or causes else "")
|
|
1619
|
+
+ _scan_html(f.get("scan")) + _ratio_html(f) + _fidelity_html(f) + _resources_html(f, engine)
|
|
1620
|
+
+ f"<details><summary>Query as benchmarked</summary><pre>{e(f['baseline_sql'])}</pre><div class=chips>{assumptions}{params}</div></details>"
|
|
1621
|
+
+ "".join(_variant_html(v, f) for v in f["variants"]) + "</section>")
|
|
1622
|
+
|
|
1623
|
+
|
|
1624
|
+
def _best_cell(f: dict) -> str:
|
|
1625
|
+
"""The best variant's rows read as a share of the baseline, as a small bar."""
|
|
1626
|
+
v = f["variants"][0] if f["variants"] else None
|
|
1627
|
+
done = [s for s in (v["scales"] if v else []) if s["variant"] and s["variant"].get("ok")]
|
|
1628
|
+
if not done:
|
|
1629
|
+
return tag(status_label(f), f["status"])
|
|
1630
|
+
s = done[-1]
|
|
1631
|
+
if not s["baseline"]["read_rows"]:
|
|
1632
|
+
# a baseline that scanned no rows has no share to draw: give the two figures
|
|
1633
|
+
return (f"{human(s['variant']['read_rows'])} rows <span class=muted>against {human(s['baseline']['read_rows'])} · "
|
|
1634
|
+
f"{e(v['kind'].replace('_', ' '))}</span>")
|
|
1635
|
+
share = pct(s["variant"]["read_rows"], s["baseline"]["read_rows"])
|
|
1636
|
+
if share > 1000:
|
|
1637
|
+
return (f"{human(s['variant']['read_rows'])} rows <span class=muted>against {human(s['baseline']['read_rows'])} · "
|
|
1638
|
+
f"{e(v['kind'].replace('_', ' '))}</span>")
|
|
1639
|
+
return (f"<div class='track mini'><div class='fill {_fill_class(s['verdict'])}' style='width:{min(share, 100):.0f}%'></div></div>"
|
|
1640
|
+
f"{share:.0f}% <span class=muted>{e(v['kind'].replace('_', ' '))}</span>")
|
|
1641
|
+
|
|
1642
|
+
|
|
1643
|
+
BILLING_NOTE = {"plan": "; this run used a Claude plan login, so nothing was billed per token",
|
|
1644
|
+
"api_key": "; billed to an API key"}
|
|
1645
|
+
|
|
1646
|
+
|
|
1647
|
+
def _database_chips(data: dict) -> str:
|
|
1648
|
+
db = data.get("database")
|
|
1649
|
+
if not db:
|
|
1650
|
+
return ""
|
|
1651
|
+
chips = [tag(f"{db['real_definitions']} table definitions from the real database", "verified")] if db["real_definitions"] else []
|
|
1652
|
+
if db["inferred_definitions"]:
|
|
1653
|
+
chips.append(tag(f"{db['inferred_definitions']} assembled by the agent", "unverified"))
|
|
1654
|
+
if db.get("scoring") == "measured load":
|
|
1655
|
+
window = f"last {db['workload_window_hours']} h" if db.get("workload_window_hours") else "statement statistics"
|
|
1656
|
+
chips.append(tag(f"ranked by measured load ({window})", "verified"))
|
|
1657
|
+
return "".join(chips)
|
|
1658
|
+
|
|
1659
|
+
|
|
1660
|
+
def patterns_findings(patterns: dict | None, loops: dict | None, groups: dict | None, repo: dict | None, bench: dict | None = None) -> dict:
|
|
1661
|
+
"""findings.json for a run with no ranked statement (a SQLite repository, a scan whose loops ran on the repository's
|
|
1662
|
+
own schema): no statement findings, the loop and group outcomes and the patterns' counts, so the bundle, `codecop ci` and
|
|
1663
|
+
the budget summary have a file to read. Labels and numbers only."""
|
|
1664
|
+
lo = (loops or {}).get("outcomes") or {}
|
|
1665
|
+
go = (groups or {}).get("outcomes") or {}
|
|
1666
|
+
fixed = [{"pattern": e.get("id"), "site_id": m.get("site_id"), "file": m.get("file"), "line": m.get("line")}
|
|
1667
|
+
for e in (loops or {}).get("patterns") or [] for m in e.get("members") or [] if (m.get("outcome") or {}).get("state") == "fixed"]
|
|
1668
|
+
return {"schema_version": 1, "tool_version": __version__, "generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
|
1669
|
+
"repo": repo or {}, "engine": (bench or {}).get("engine") or "", "engine_version": (bench or {}).get("engine_version") or "",
|
|
1670
|
+
"server_version": (bench or {}).get("server_version") or "", "findings": [], "patterns_only": True,
|
|
1671
|
+
"evidence_label": "loop members run on generated data from the repository's own schema" if bench else "call patterns, no sandbox",
|
|
1672
|
+
"patterns": {"summary": (patterns or {}).get("summary")},
|
|
1673
|
+
"loops": {"outcomes": lo, "fixed": fixed, "members": sum(len(e.get("members") or []) for e in (loops or {}).get("patterns") or [])},
|
|
1674
|
+
"groups": {"outcomes": go},
|
|
1675
|
+
"benchmark": (bench or {}).get("summary")}
|
|
1676
|
+
|
|
1677
|
+
|
|
1678
|
+
def render_patterns_page(patterns: dict, repo: dict | None = None, detail: int = 30, budget: dict | None = None) -> str:
|
|
1679
|
+
"""report.html for an out dir with an inventory and no scan: the call patterns alone."""
|
|
1680
|
+
from .patterns_view import html_section
|
|
1681
|
+
|
|
1682
|
+
repo = repo or {}
|
|
1683
|
+
return f"""<!doctype html><html lang=en><head><meta charset=utf-8><meta name=viewport content="width=device-width,initial-scale=1">
|
|
1684
|
+
<title>codecop report · {e(repo.get('name', ''))}</title><style>{CSS}{joins_view.CSS}</style></head><body><main>
|
|
1685
|
+
<h1>codecop report · {e(repo.get('name', ''))}</h1>
|
|
1686
|
+
<p class=sub>call patterns from the inventory{' and the pulled query log' if patterns.get('accounting') else ''} · {e(patterns.get('generated_at', ''))} · commit {e((repo.get('commit') or '')[:10])}{'' if budget else ' · no agent, no sandbox'}</p>
|
|
1687
|
+
{budget_strip(budget)}
|
|
1688
|
+
{html_section(patterns, detail)}
|
|
1689
|
+
<p class=muted>CodeCop {e(__version__)}</p>
|
|
1690
|
+
</main></body></html>"""
|
|
1691
|
+
|
|
1692
|
+
|
|
1693
|
+
STEP_LABEL = {"rank": "statements", "observed": "observed variants", "scenario": "scenario variants", "loops": "loops", "groups": "scan groups",
|
|
1694
|
+
"profile": "table sizes", "areas": "code areas", "other": "other"}
|
|
1695
|
+
NEXT_COMMAND = {"ask_agent_to_rank": "codecop scan", "ask_agent_for_observed_variant": "codecop scan", "ask_agent_for_scenario_variant": "codecop scan",
|
|
1696
|
+
"ask_agent_for_loop_variant": "codecop scan", "ask_agent_for_group_variant": "codecop scan",
|
|
1697
|
+
"ask_agent_for_table_profile": "codecop scan", "ask_agent_for_areas": "codecop scan"}
|
|
1698
|
+
|
|
1699
|
+
|
|
1700
|
+
def budget_strip(s: dict | None) -> str:
|
|
1701
|
+
"""The run budget on the report: what was spent by step, what it bought (sandbox-verified fixes only), and what was not
|
|
1702
|
+
asked, with its estimate and the command that asks it. Every figure is an estimate at API rates unless billed to a key.
|
|
1703
|
+
Wrapped in BUDGET_START/BUDGET_END so a scan can put the strip in after its summary (with_budget_strip)."""
|
|
1704
|
+
return BUDGET_START + _budget_strip(s) + BUDGET_END
|
|
1705
|
+
|
|
1706
|
+
|
|
1707
|
+
BUDGET_START, BUDGET_END = "<!--codecop-budget-->", "<!--/codecop-budget-->"
|
|
1708
|
+
|
|
1709
|
+
|
|
1710
|
+
def with_budget_strip(page: str, s: dict | None) -> str:
|
|
1711
|
+
"""report.html with its budget strip replaced (a page written before the scan's summary existed)."""
|
|
1712
|
+
import re as _re
|
|
1713
|
+
if BUDGET_START not in page:
|
|
1714
|
+
return page
|
|
1715
|
+
return _re.sub(_re.escape(BUDGET_START) + ".*?" + _re.escape(BUDGET_END), lambda _m: budget_strip(s), page, count=1, flags=_re.S)
|
|
1716
|
+
|
|
1717
|
+
|
|
1718
|
+
def _budget_strip(s: dict | None) -> str:
|
|
1719
|
+
if not s:
|
|
1720
|
+
return ""
|
|
1721
|
+
billed = s.get("billing") == "api_key"
|
|
1722
|
+
noun = "cost" if billed else "usage ≈"
|
|
1723
|
+
basis = "billed to the API key" if billed else "est. at API rates" + ("; plan login, not billed per token" if s.get("billing") == "plan" else "")
|
|
1724
|
+
budget = "no limit" if s.get("budget_usd") is None else f"${float(s['budget_usd']):,.2f}"
|
|
1725
|
+
by_step = s.get("spent_by_step") or {}
|
|
1726
|
+
top = max(by_step.values(), default=0) or 1
|
|
1727
|
+
steps = "".join(f"<tr><td>{e(STEP_LABEL.get(k, k))}</td><td class=num>${float(v):,.2f}</td>"
|
|
1728
|
+
f"<td><span class=bar style='display:inline-block;height:.6em;background:currentColor;opacity:.5;width:{max(int(120 * float(v) / top), 2)}px'></span></td></tr>"
|
|
1729
|
+
for k, v in sorted(by_step.items(), key=lambda kv: -kv[1]) if v)
|
|
1730
|
+
bought = [f"{s.get('verified_fixes', 0)} verified fix{'es' if s.get('verified_fixes') != 1 else ''} (sandbox: same rows, reads less)"]
|
|
1731
|
+
if s.get("cost_per_verified_fix_usd"):
|
|
1732
|
+
bought.append(f"${s['cost_per_verified_fix_usd']:,.2f} per verified fix" + (" over every run" if s.get("cost_per_verified_fix_basis") == "all runs" else ""))
|
|
1733
|
+
if s.get("reads_covered_by_verified_fixes") is not None:
|
|
1734
|
+
bought.append(f"{float(s['reads_covered_by_verified_fixes']):.1%} of measured database reads covered by a verified fix")
|
|
1735
|
+
if s.get("reused_items"):
|
|
1736
|
+
bought.append(f"{s['reused_items']:,} answered before, not paid again")
|
|
1737
|
+
na = s.get("not_asked") or {}
|
|
1738
|
+
left_rows = "".join(
|
|
1739
|
+
f"<tr><td>{e(KIND_WORDS.get(k, k))}</td><td class=num>{v['items']:,}</td><td class=num>est. ${v['est_low_usd']:,.2f}–{v['est_high_usd']:,.2f}</td>"
|
|
1740
|
+
f"<td><code>{e(NEXT_COMMAND.get(v.get('next_step'), 'codecop scan'))}</code></td></tr>"
|
|
1741
|
+
for k, v in sorted((na.get("by_kind") or {}).items(), key=lambda kv: -kv[1]["est_high_usd"]))
|
|
1742
|
+
why = ""
|
|
1743
|
+
ul = na.get("usage_limit")
|
|
1744
|
+
if ul:
|
|
1745
|
+
stop = s.get("stopped_by_usage_limit") or {}
|
|
1746
|
+
why = (f"<p class=muted>{ul['items']:,} of these were not asked because the agent's usage limit was reached (not the budget)"
|
|
1747
|
+
+ (f"; it resets {e(stop['resets_at'])}" if stop.get("resets_at") else "") + ". <code>codecop scan</code> continues from what is stored; nothing is paid twice.</p>")
|
|
1748
|
+
elif na.get("items") and (s.get("stopped_by_budget") or (s.get("planned") or {}).get("over_budget")):
|
|
1749
|
+
why = "<p class=muted>The budget was reached: <code>codecop scan --budget N</code> continues from what is stored; nothing is paid twice.</p>"
|
|
1750
|
+
lim = s.get("usage_limits") or {}
|
|
1751
|
+
pauses = (f"<p class=muted>The agent's limits paused the run {lim['events']} time(s) ({e(', '.join(k.replace('_', ' ') for k in lim.get('kinds') or []))}); "
|
|
1752
|
+
f"waited {float(lim.get('waited_s') or 0) / 60:.0f} min; then {lim.get('concurrency_after')} call(s) at a time.</p>") if lim else ""
|
|
1753
|
+
return (f"<h2>Run budget</h2><p class=sub>{noun} ${float(s.get('spent_usd') or 0):,.2f} of {budget} · {e(basis)}"
|
|
1754
|
+
+ (" · free look: nothing asked" if s.get("no_agent") else "") + "</p>"
|
|
1755
|
+
+ f"<div class=chips>{''.join(tag(b, 'verified' if i == 0 and s.get('verified_fixes') else '') for i, b in enumerate(bought))}</div>"
|
|
1756
|
+
+ (f"<h4>Spent by step</h4><div class=wrap><table><tr><th>Step</th><th class=num>{'Cost' if billed else 'Usage (est.)'}</th><th></th></tr>{steps}</table></div>" if steps else "")
|
|
1757
|
+
+ (f"<h4>Not asked yet · {na.get('items', 0):,} · est. ${na.get('est_low_usd', 0):,.2f}–{na.get('est_high_usd', 0):,.2f}</h4>"
|
|
1758
|
+
f"<div class=wrap><table><tr><th>What</th><th class=num>Items</th><th class=num>Estimate</th><th>Asks it</th></tr>{left_rows}</table></div>"
|
|
1759
|
+
if na.get("items") else "<p class=muted>Not asked: nothing. The next scan pays only for what changes.</p>")
|
|
1760
|
+
+ why + pauses)
|
|
1761
|
+
|
|
1762
|
+
|
|
1763
|
+
KIND_WORDS = {"statement": "statements", "observed_variant": "observed variants", "scenario_variant": "scenario variants", "loop": "loop members",
|
|
1764
|
+
"group": "scan groups", "table_profile": "table sizes", "areas": "code areas"}
|
|
1765
|
+
|
|
1766
|
+
|
|
1767
|
+
def render_html(data: dict, patterns_html: str = "") -> str:
|
|
1768
|
+
findings = [f for f in data["findings"] if (f.get("kind") or "query") == "query"] # the other kinds: kinds/pipeline.report_html
|
|
1769
|
+
counts = {s: sum(1 for f in findings if f["status"] == s) for s in STATUS_LABEL}
|
|
1770
|
+
fx = fixgroups.summary(findings, data.get("engine") or "")
|
|
1771
|
+
shared_rows = "".join(
|
|
1772
|
+
f"<tr><td>{tag(g['label'])}<code>{e(g['text'][:300])}</code></td><td class=num>{len(g['sites'])}</td>"
|
|
1773
|
+
f"<td>{', '.join(f'<code>{e(str(fl).split(chr(47))[-1])}:{ln}</code>' for fl, ln in g['sites'][:12] if fl != '#')}</td></tr>"
|
|
1774
|
+
for g in fx["shared"])
|
|
1775
|
+
inv = data.get("inventory_summary") or {}
|
|
1776
|
+
rows = "".join(
|
|
1777
|
+
f"<tr><td><a href='#{e(f['finding'])}'>{e(f['finding'])}</a></td><td>{_severity(f['severity'])}</td><td class=mono>{e(origin_label(f['origin']))}</td>"
|
|
1778
|
+
f"<td>{e(f['title'])}<div class=muted><code>{e(f['site']['file'].split('/')[-1])}:{f['site']['line']}</code>"
|
|
1779
|
+
f"{' · one of the places that build it' if f.get('located') == 'part' else ''}</div><div class=chips>{_labels_html(f)}</div></td>"
|
|
1780
|
+
f"<td>{tag(status_label(f), f['status'])}</td><td class=num>{_best_cell(f)}</td></tr>"
|
|
1781
|
+
for f in findings)
|
|
1782
|
+
prof_rows = "".join(
|
|
1783
|
+
f"<tr><td class=mono>{e(t['name'])}</td><td class=num>{t['rows']:,}</td>"
|
|
1784
|
+
f"<td title='{e(t['rows_basis'])}'>{tag('real catalog', 'verified') if t.get('rows_evidence') == 'real catalog' else tag('agent estimate')}"
|
|
1785
|
+
f"{tag(t['rows_confidence'] + ' confidence')}</td>"
|
|
1786
|
+
f"<td class=num>{sum(1 for c in t['columns'] if c.get('confidence') == 'low')} / {len(t['columns'])}</td><td>{_sizes_cell(t)}</td></tr>"
|
|
1787
|
+
for t in data["profile"])
|
|
1788
|
+
sandbox_rows = "".join(
|
|
1789
|
+
f"<tr><td class=mono>{e(t['name'])}</td><td class=num>{t.get('rows', 0):,}</td><td class=num>{human_bytes(t.get('bytes_on_disk'))}</td>"
|
|
1790
|
+
f"<td class=num>{t.get('parts', t.get('indexes', '-'))}</td><td>{tag('real database catalog', 'verified') if t.get('source') == 'real catalog' else tag('assembled from evidence', 'unverified') if t.get('inferred') else tag('copied from code', 'verified')}"
|
|
1791
|
+
f"{_table_fidelity(t)}{tag(str(round(t['duplicate_share'] * 100)) + '% duplicate versions') if t.get('duplicate_share') else ''}"
|
|
1792
|
+
f"{tag(t['error'][:120], 'failed') if t.get('error') else ''}{''.join(tag(x[:120]) for x in t.get('stripped') or [])}</td></tr>" for t in data["sandbox_tables"])
|
|
1793
|
+
rejected = "".join(
|
|
1794
|
+
f"<tr><td>{tag(REJECT_LABEL.get(r.get('code'), r.get('code')))}{_state_tag(r)}</td><td><code>{e(str(r.get('file', '')).split('/')[-1])}{':' + str(r['line']) if r.get('line') else ''}</code></td>"
|
|
1795
|
+
f"<td class=muted>{e(r.get('detail'))}"
|
|
1796
|
+
+ (f"<div class=chips>{tag(REASON_LABEL.get(r['outcome']['reason'], r['outcome']['reason']))}"
|
|
1797
|
+
+ "".join(_next_step_chips(r["outcome"].get("evidence") or {})) + "</div>"
|
|
1798
|
+
if (r.get("outcome") or {}).get("reason") in blockers_mod.ASSEMBLED else "")
|
|
1799
|
+
+ ("<div class=chips>" + tag("not confirmed by the computed access analysis", "unverified")
|
|
1800
|
+
+ "".join(tag(x[:200], "unverified") for x in r["unconfirmed"]) + "</div>" if r.get("unconfirmed") else "")
|
|
1801
|
+
+ "</td></tr>" for r in sorted(data["rejected_by_agent"], key=lambda r: not r.get("unconfirmed")))
|
|
1802
|
+
limits = "".join(f"<li>{e(x)}</li>" for x in data["limits"])
|
|
1803
|
+
repo = data.get("repo") or {}
|
|
1804
|
+
bm = data.get("benchmark") or {}
|
|
1805
|
+
measured = bm.get("benchmarked", sum(1 for f in findings if f.get("scan")))
|
|
1806
|
+
skipped = bm.get("not_benchmarked", 0) + bm.get("baseline_failed", 0)
|
|
1807
|
+
version_note = data.get("engine_version_note") or ""
|
|
1808
|
+
data_label = data.get("evidence_label") or "tested on generated data, not production"
|
|
1809
|
+
invariant_rows = "".join(
|
|
1810
|
+
f"<tr><td class=mono>{e(i.get('table'))}.{e(i.get('column'))}</td><td>a row of <span class=mono>{e(i.get('parent'))} ({e(i.get('parent_column'))})</span>"
|
|
1811
|
+
+ "".join(f"; <span class=mono>{e(s['column'])}</span> is that row's <span class=mono>{e(s['parent_column'])}</span>" for s in i.get("same_as_parent") or [])
|
|
1812
|
+
+ f"</td><td title='{e(i.get('basis'))}'>{tag(i.get('source') or '')}</td><td>"
|
|
1813
|
+
+ (tag(f"kept: {i.get('checked', 0):,} rows checked, {i.get('orphans', 0) + i.get('mismatched', 0):,} break it",
|
|
1814
|
+
"verified" if not (i.get("orphans") or i.get("mismatched")) else "failed") if i.get("enforced")
|
|
1815
|
+
else tag("not applied: " + str(i.get("reason") or "")[:140], "unverified")) + "</td></tr>" for i in data.get("invariants") or [])
|
|
1816
|
+
cost = data["agent"]["cost_usd"]
|
|
1817
|
+
runs = data["agent"].get("rank_invocations") or 1
|
|
1818
|
+
across = f", over {runs} rank runs" if runs > 1 else ""
|
|
1819
|
+
return f"""<!doctype html><html lang=en><head><meta charset=utf-8><meta name=viewport content="width=device-width,initial-scale=1">
|
|
1820
|
+
<title>codecop report · {e(repo.get('name', ''))}</title><style>{CSS}</style></head><body><main>
|
|
1821
|
+
<h1>codecop report · {e(repo.get('name', ''))}</h1>
|
|
1822
|
+
<p class=sub>{e(data['engine'])} {e(data['server_version'] or data['engine_version'])} · evidence tier: {e(data['evidence_tier'])} ·
|
|
1823
|
+
{e(data['generated_at'])} · commit {e((repo.get('commit') or '')[:10])} · agent {e(data['agent']['model'])}, {f"cost ${cost:.2f}{across} (billed to an API key)" if data.get('billing') == 'api_key' else f"est. cost ${cost:.2f}{across} (API rates{e(BILLING_NOTE.get(data.get('billing') or '', ''))})"}</p>
|
|
1824
|
+
{f"<div class=chips>{tag(version_note, 'unverified')}</div>" if version_note else ''}
|
|
1825
|
+
<div class=cards>
|
|
1826
|
+
<div class=card><b>{inv.get('sites', '-')}</b>SQL call sites found</div>
|
|
1827
|
+
<div class=card><b>{data['select_sites']}</b>{e(data['engine'])} SELECT sites</div>
|
|
1828
|
+
<div class=card><b>{data['shortlisted']}</b>shown to the agent</div>
|
|
1829
|
+
<div class=card><b>{len(findings)}</b>candidates</div>
|
|
1830
|
+
<div class=card><b>{measured}</b>benchmarked</div>
|
|
1831
|
+
<div class=card><b>{skipped}</b>not benchmarked</div>
|
|
1832
|
+
<div class=card><b>{counts['verified']}</b>tested: read less</div>
|
|
1833
|
+
<div class=card title="Findings that share one fix (the same index, key, layout or rewrite) count once; trade-offs never"><b>{fx['fixes']}</b>verified fix{'es' if fx['fixes'] != 1 else ''} at {fx['call_sites']} call site{'s' if fx['call_sites'] != 1 else ''}</div>
|
|
1834
|
+
<div class=card><b>{counts['rejected'] + counts['unverified']}</b>not verified or rejected</div>
|
|
1835
|
+
</div>
|
|
1836
|
+
<div class=chips>{tag(data_label)}{_database_chips(data)}{tag(engines.get(data['engine']).evidence)}{tag('laptop timings matter least')}</div>
|
|
1837
|
+
{budget_strip(data.get('agent_budget'))}
|
|
1838
|
+
{_repository_coverage_html(data)}
|
|
1839
|
+
{_outcomes_html(data)}
|
|
1840
|
+
{patterns_html}
|
|
1841
|
+
{joins_view.section(data, _state_tag, _next_step_chips)}
|
|
1842
|
+
<h2>Findings</h2>
|
|
1843
|
+
{'<h4>One fix, several call sites</h4><div class=wrap><table><tr><th>Fix</th><th class=num>Verified call sites</th><th>Where</th></tr>' + shared_rows + '</table></div><p></p>' if shared_rows else ''}
|
|
1844
|
+
<div class=wrap><table><tr><th>Id</th><th>Severity</th><th>Runs from</th><th>Finding</th><th>Status</th><th class=num>Rows read vs before</th></tr>{rows}</table></div>
|
|
1845
|
+
{''.join(_finding_html(f, data.get('engine', '')) for f in findings)}
|
|
1846
|
+
<h2>Data the benchmark ran on</h2>
|
|
1847
|
+
<div class=wrap><table><tr><th>Table</th><th class=num>Rows assumed</th><th>Where the number comes from</th><th class=num>Guessed columns</th><th>Row width</th></tr>{prof_rows}</table></div>
|
|
1848
|
+
<p></p><div class=wrap><table><tr><th>Sandbox table</th><th class=num>Rows loaded</th><th class=num>On disk</th><th class=num>{'Indexes' if data['engine'] == 'postgres' else 'Parts'}</th><th>Definition</th></tr>{sandbox_rows}</table></div>
|
|
1849
|
+
{'<h4>Invariants the generated data keeps</h4><p class=muted>Rows an application never writes (a child whose tenant is not its parent's) make a correct rewrite return different results. These relations were assumed and applied when the data was generated; each says where it comes from and what was counted after the load.</p><div class=wrap><table><tr><th>Column</th><th>Is</th><th>Source</th><th>In the loaded data</th></tr>' + invariant_rows + '</table></div>' if invariant_rows else ''}
|
|
1850
|
+
<details><summary>Limits of this run</summary><ul>{limits}</ul></details>
|
|
1851
|
+
{'<h2>Looked at and not benchmarked</h2><div class=wrap><table><tr><th>Why</th><th>Location</th><th></th></tr>' + rejected + '</table></div>' if rejected else ''}
|
|
1852
|
+
{_unlocated_html(data)}
|
|
1853
|
+
<p class=muted>CodeCop {e(data['tool_version'])}</p>
|
|
1854
|
+
</main></body></html>"""
|