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/scenario_bind.py
ADDED
|
@@ -0,0 +1,507 @@
|
|
|
1
|
+
"""Scenario candidates bound to a statement the benchmark can run, the variants rules write for them, and how those
|
|
2
|
+
variants reach `codecop bench` and `codecop report` (scenarios.py has the detection).
|
|
3
|
+
|
|
4
|
+
A candidate is bound to, in this order: the observed candidate of the same pulled statement (observed.json, O-001), the
|
|
5
|
+
ranked candidate of the call site it is matched to exactly or through its template (rank.json, Q-001), or a statement
|
|
6
|
+
built here from production's text by the observed stage's own steps (fill, gate, values: `SB-001`, `sql_from:
|
|
7
|
+
query_log`). Its rule variants are added first to that statement's variants, each tagged with the candidate's
|
|
8
|
+
fingerprint (`scenario`), rule and change; the bench record keeps the tags, so the report reads each record against the
|
|
9
|
+
variant it measured (`align`).
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import copy
|
|
15
|
+
import re
|
|
16
|
+
from collections import Counter, defaultdict
|
|
17
|
+
from datetime import datetime, timezone
|
|
18
|
+
|
|
19
|
+
from . import engines as engines_mod
|
|
20
|
+
from . import scenario_sql as Q
|
|
21
|
+
from .scenarios import TABLE_LEVEL, _info, _short, _workload_texts, settings_of
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _candidate_maps(rank: dict | None, observed: dict | None) -> tuple[dict, dict, dict]:
|
|
25
|
+
by_site = {c["id"]: c for c in (rank or {}).get("candidates") or [] if c.get("sql_from") != "query_log"}
|
|
26
|
+
by_hash, by_place = {}, {}
|
|
27
|
+
for c in (observed or {}).get("candidates") or []:
|
|
28
|
+
o = c.get("observed") or {}
|
|
29
|
+
if o.get("hash"):
|
|
30
|
+
by_hash.setdefault(str(o["hash"]), c)
|
|
31
|
+
for sid in o.get("places") or [c.get("id")]:
|
|
32
|
+
by_place.setdefault(sid, c)
|
|
33
|
+
return by_site, by_hash, by_place
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _bound(c: dict, by_site: dict, by_hash: dict, by_place: dict) -> dict | None:
|
|
37
|
+
st = c["statement"]
|
|
38
|
+
if st["sql_from"] == "query_log":
|
|
39
|
+
if st.get("hash") and st["hash"] in by_hash:
|
|
40
|
+
return by_hash[st["hash"]]
|
|
41
|
+
if st["located"] in ("exact", "template"):
|
|
42
|
+
return next((by_site[s] for s in st["site_ids"] if s in by_site), None)
|
|
43
|
+
return None
|
|
44
|
+
sid = (st.get("site_ids") or [None])[0]
|
|
45
|
+
return by_site.get(sid) or by_place.get(sid)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _definition(name: str, rank: dict | None, facts, engine: str) -> str:
|
|
49
|
+
for d in (rank or {}).get("table_definitions") or []:
|
|
50
|
+
if _short(d["name"]).lower() == name.lower():
|
|
51
|
+
return d.get("create_sql") or ""
|
|
52
|
+
d = facts.definition(engine, name) if facts else None
|
|
53
|
+
return (d or {}).get("create_sql") or ""
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def variants_for(c: dict, bound: dict, tables: dict, rank: dict | None, facts, cfg: dict) -> list[dict]:
|
|
57
|
+
"""The variants rules write for one candidate, from the baseline of the statement it is bound to."""
|
|
58
|
+
eng = c["statement"].get("engine") or "clickhouse"
|
|
59
|
+
sql = bound.get("baseline_sql") or ""
|
|
60
|
+
out: list[dict] = []
|
|
61
|
+
infos = [i for i in (_info(tables, n) for n in bound.get("tables") or []) if i is not None]
|
|
62
|
+
safe = set(cfg["key_safe_functions"]) if eng == "clickhouse" else set()
|
|
63
|
+
|
|
64
|
+
def add(kind: str, change: str, rule: str, new_sql: str | None, setup: list[str] | None, note: str, table_level: bool = False):
|
|
65
|
+
if not new_sql or any(v["sql"] == new_sql and v.get("setup_sql") == (setup or []) for v in out):
|
|
66
|
+
return
|
|
67
|
+
out.append({"kind": kind, "sql": new_sql, "setup_sql": setup or [], "same_results": True, "change": change, "rule": rule,
|
|
68
|
+
"scenario": c["fingerprint"], "origin": "scenario", "rationale": note, "table_level": table_level, "tradeoffs": []})
|
|
69
|
+
|
|
70
|
+
changes = {x["change"] for x in c["changes"] if x["proof"] == "sandbox"}
|
|
71
|
+
if eng == "postgres":
|
|
72
|
+
# empty reads on PostgreSQL: a cheap existence probe (query) and an index that serves the predicate (table-level)
|
|
73
|
+
made = 0
|
|
74
|
+
for info in sorted(infos, key=lambda i: -(i.rows or 0)):
|
|
75
|
+
if "probe_before_wide_read" in changes:
|
|
76
|
+
got = Q.pg_probe_first(sql, info)
|
|
77
|
+
if got:
|
|
78
|
+
add("rewrite", "probe_before_wide_read", "empty_runs", got[0], [], got[1])
|
|
79
|
+
if "index_for_filter" in changes and made < cfg["max_table_variants"]:
|
|
80
|
+
name = next((d["name"] for d in (rank or {}).get("table_definitions") or [] if _short(d["name"]).lower() == info.name.lower()), info.name)
|
|
81
|
+
create = _definition(info.name, rank, facts, eng)
|
|
82
|
+
got = Q.pg_index_for_filter(sql, info, create, name) if create else None
|
|
83
|
+
if got:
|
|
84
|
+
add("index", "index_for_filter", "empty_runs", sql, got[0], got[1], True)
|
|
85
|
+
made += 1
|
|
86
|
+
return out
|
|
87
|
+
for info in infos:
|
|
88
|
+
if "filter_first_prewhere" in changes and eng == "clickhouse":
|
|
89
|
+
got = Q.prewhere_keys(sql, eng, info)
|
|
90
|
+
if got:
|
|
91
|
+
add("rewrite", "filter_first_prewhere", "empty_runs", got[0], [], got[1])
|
|
92
|
+
if "probe_before_wide_read" in changes and eng == "clickhouse":
|
|
93
|
+
got = Q.probe_first(sql, eng, info)
|
|
94
|
+
if got:
|
|
95
|
+
add("rewrite", "probe_before_wide_read", "empty_runs", got[0], [], got[1])
|
|
96
|
+
if "unwrap_key_column" in changes:
|
|
97
|
+
got = Q.unwrap_identity(sql, eng, info, safe)
|
|
98
|
+
if got:
|
|
99
|
+
add("rewrite", "unwrap_key_column", "key_wrapped", got[0], [], got[1])
|
|
100
|
+
if "late_materialization" in changes:
|
|
101
|
+
got = Q.late_materialize(sql, eng, info)
|
|
102
|
+
if got:
|
|
103
|
+
add("rewrite", "late_materialization", "wide_before_limit", got[0], [], got[1])
|
|
104
|
+
if "drop_inner_order" in changes:
|
|
105
|
+
got = Q.count_without_inner_order(sql, eng)
|
|
106
|
+
if got:
|
|
107
|
+
add("rewrite", "drop_inner_order", "count_over_sorted_subquery", got[0], [], got[1])
|
|
108
|
+
if changes & {"skip_index", "projection", "sorting_key"} and eng == "clickhouse":
|
|
109
|
+
first = next((e.get("table") for e in c["evidence"] if e["rule"] == "reads_far_above_returns"), None)
|
|
110
|
+
_table_variants(bound, infos, rank, facts, cfg, add, first)
|
|
111
|
+
if "read_narrow_copy" in changes and eng == "clickhouse" and facts:
|
|
112
|
+
for e in c["evidence"]:
|
|
113
|
+
if e["rule"] == "narrow_copy" and not e.get("not_verified"):
|
|
114
|
+
got = _copy_variant(e, sql, eng, facts)
|
|
115
|
+
if got:
|
|
116
|
+
add("materialized_view", "read_narrow_copy", "narrow_copy", got[0], got[1], got[2])
|
|
117
|
+
return out
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _table_variants(bound, infos, rank, facts, cfg, add, first_table) -> None:
|
|
121
|
+
"""A skip index on the first filter column the key does not serve (a range column first), a projection and a
|
|
122
|
+
re-keyed copy whose key starts with the filters' wanted prefix (equality columns, then the first range column)."""
|
|
123
|
+
from .access import table_access
|
|
124
|
+
from .blockers import _wanted_prefix
|
|
125
|
+
sql = bound.get("baseline_sql") or ""
|
|
126
|
+
made = 0
|
|
127
|
+
for info in sorted(infos, key=lambda i: (i.name != first_table, -(i.rows or 0))):
|
|
128
|
+
create = _definition(info.name, rank, facts, "clickhouse")
|
|
129
|
+
if not create:
|
|
130
|
+
continue
|
|
131
|
+
try:
|
|
132
|
+
a = table_access(create, info.name, sql)
|
|
133
|
+
except Exception: # a definition the access analysis can not read: no variant, never a guess
|
|
134
|
+
continue
|
|
135
|
+
filters = [f for f in a.get("filters") or [] if f.get("op") in ("eq", "in", "range")]
|
|
136
|
+
unserved = [f for f in filters if f.get("key") in ("none", "skipped", "partition")]
|
|
137
|
+
if not unserved:
|
|
138
|
+
continue
|
|
139
|
+
f0 = next((f for f in unserved if f["op"] == "range"), unserved[0])
|
|
140
|
+
setup, kind = Q.skip_index_setup(info.name, f0["column"], f0["op"], info.columns.get(f0["column"], ""))
|
|
141
|
+
add("skip_index", "skip_index", "reads_far_above_returns", sql, setup,
|
|
142
|
+
f"a {kind} skip index on {f0['column']}, which the sorting key does not serve", True)
|
|
143
|
+
made += 1
|
|
144
|
+
prefix = _wanted_prefix(filters)
|
|
145
|
+
if prefix and prefix != info.sorting_key[:len(prefix)] and made < cfg["max_table_variants"]:
|
|
146
|
+
add("projection", "projection", "reads_far_above_returns", sql, Q.projection_setup(info.name, prefix),
|
|
147
|
+
f"a projection ordered by ({', '.join(prefix)})", True)
|
|
148
|
+
made += 1
|
|
149
|
+
rk = Q.rekey_setup(info, create, prefix)
|
|
150
|
+
if rk and made < cfg["max_table_variants"]:
|
|
151
|
+
add("ordering_key", "sorting_key", "reads_far_above_returns", Q.rename_table(sql, "clickhouse", info.name, rk[1]), rk[0],
|
|
152
|
+
f"a copy whose sorting key starts with ({', '.join(prefix)})", True)
|
|
153
|
+
made += 1
|
|
154
|
+
if made >= cfg["max_table_variants"]:
|
|
155
|
+
break
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _copy_variant(e: dict, sql: str, eng: str, facts) -> tuple[str, list[str], str] | None:
|
|
159
|
+
"""Read the narrow copy instead. In the sandbox the copy is built from the generated source rows through the view's
|
|
160
|
+
own SELECT, so the rewrite is proved on a copy known to be complete; production's completeness is what the catalog
|
|
161
|
+
showed (`verified`)."""
|
|
162
|
+
from .observed import _databases, strip_databases
|
|
163
|
+
mv = facts.tables("clickhouse").get(e["view"]) or {}
|
|
164
|
+
target = facts.definition("clickhouse", e["copy"])
|
|
165
|
+
body = re.search(r"\bAS\s+(SELECT\b.*)$", mv.get("create_sql") or "", re.I | re.S)
|
|
166
|
+
if not target or not body:
|
|
167
|
+
return None
|
|
168
|
+
twin = f"{e['copy']}__codecop_twin"
|
|
169
|
+
create = re.sub(r"^(\s*CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?)[`\"\w.]+", lambda m: m.group(1) + twin, target["create_sql"], count=1, flags=re.I)
|
|
170
|
+
new_sql = Q.rename_table(sql, eng, e["table"], twin)
|
|
171
|
+
if not new_sql:
|
|
172
|
+
return None
|
|
173
|
+
return new_sql, [create, f"INSERT INTO {twin} {strip_databases(body.group(1), _databases(facts.catalog))}"], \
|
|
174
|
+
f"reads {e['copy']}, the view {e['view']}'s target, instead of {e['table']}"
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def runnable(st: dict, facts, inventory: dict | None, engine: str, finding: str, dyn: dict) -> tuple[dict | None, str]:
|
|
178
|
+
"""A benchmark candidate built from production's statement, for a scenario candidate no ranked or observed
|
|
179
|
+
candidate covers. (candidate, '') or (None, the gate's reason)."""
|
|
180
|
+
from . import observed as O
|
|
181
|
+
from .realdb import match as match_mod
|
|
182
|
+
m = facts.match(engine) or {}
|
|
183
|
+
q = next((x for x in m.get("queries") or [] if str(x.get("hash")) == st["hash"]), None)
|
|
184
|
+
w = _workload_texts(facts, engine).get(st["hash"]) or {}
|
|
185
|
+
text = w.get("text") or ""
|
|
186
|
+
if q is None or not text:
|
|
187
|
+
return None, "no_text"
|
|
188
|
+
if match_mod.TEMP_TABLE.search(text):
|
|
189
|
+
return None, "external_data"
|
|
190
|
+
if w.get("text_truncated") and len(text) >= int(w.get("text_max_chars") or O.TEXT_CUT_BEFORE_SETTING):
|
|
191
|
+
return None, "text_cut_at_limit"
|
|
192
|
+
tables = sorted(match_mod.short_tables(q.get("tables") or w.get("tables") or []))
|
|
193
|
+
user = [t for t in tables if not (t.startswith("system") or t in ("one", "numbers"))]
|
|
194
|
+
if not user or any(facts.definition(engine, t) is None for t in user):
|
|
195
|
+
return None, "table_not_in_catalog"
|
|
196
|
+
clean = O.strip_databases(text, O._databases(facts.catalog))
|
|
197
|
+
columns = O._columns_of(facts, engine, user)
|
|
198
|
+
sites = {c["id"]: c for c in (inventory or {}).get("call_sites") or [] if c.get("id")}
|
|
199
|
+
places = [sites[s] for s in st["site_ids"] if s in sites]
|
|
200
|
+
code = [p["sql"] for p in places if p.get("sql")] if st["located"] in ("exact", "template") else []
|
|
201
|
+
built = O.runnable(clean, code or [""], columns, neutral_values=dyn["neutral_values"], least=1 if code else 3)
|
|
202
|
+
g = O.gate(built["sql"], text, w.get("tables") or q.get("tables") or [])
|
|
203
|
+
if not g["ok"]:
|
|
204
|
+
return None, g["reason"]
|
|
205
|
+
now = datetime.now(timezone.utc).replace(minute=0, second=0, microsecond=0)
|
|
206
|
+
values, notes = O.choose_values(built["params"], columns, finding, now=now, window_hours=float(dyn["time_window_hours"]))
|
|
207
|
+
site = places[0] if places else {}
|
|
208
|
+
total = int((m.get("workload") or {}).get("read_bytes") or 0)
|
|
209
|
+
place = f"{site['file'].split('/')[-1]}:{site.get('line', 0)}" if site else "a statement with no place in code"
|
|
210
|
+
cand = {
|
|
211
|
+
"finding": finding, "id": site.get("id") or f"shape-{st['hash']}", "title": f"Production statement of {place} (built for a scenario)",
|
|
212
|
+
"severity": "medium", "confidence": "high" if st["located"] in O.PLACES else "medium",
|
|
213
|
+
"baseline_sql": built["sql"], "params": values, "tables": user, "variants": [], "causes": [],
|
|
214
|
+
"assumptions": ["the statement is the one production ran (query log); values are chosen, the log has none"] + built["notes"] + notes,
|
|
215
|
+
"origin": {"role": site.get("role") or "unknown", "kind": ((site.get("origins") or [{}])[0]).get("kind", "unknown"),
|
|
216
|
+
"entry_points": [{k: o.get(k) for k in ("kind", "name", "file", "line")} for o in (site.get("origins") or [])[:3]],
|
|
217
|
+
"path": [], "frequency": {"trigger": "unknown", "every_seconds": 0, "in_loop": bool(site.get("in_loop")),
|
|
218
|
+
"cache_seconds": 0, "note": ""}, "verified": False},
|
|
219
|
+
"site": {"file": site.get("file", ""), "line": site.get("line", 0), "symbol": site.get("symbol", ""), "sink": site.get("sink", ""),
|
|
220
|
+
"resolution": site.get("resolution", ""), "flags": site.get("flags") or [], "sql_hash": site.get("sql_hash", ""),
|
|
221
|
+
"same_sql_sites": 1, "score": 0.0, "role": site.get("role") or "unknown", "origins": site.get("origins") or [],
|
|
222
|
+
"origin_count": site.get("origin_count", 0)},
|
|
223
|
+
"original_sql": site.get("sql") or "", "sql_from": "query_log", "located": st["located"] if st["located"] in O.LOCATED else "none",
|
|
224
|
+
"observed": {"hash": st["hash"], "located": st["located"], "how": q.get("how") or "", "window_hours": m.get("window_hours"),
|
|
225
|
+
"executions": int(q.get("executions") or 0), "read_bytes": int(q.get("read_bytes") or 0),
|
|
226
|
+
"share_of_read_bytes": round(int(q.get("read_bytes") or 0) / total, 6) if total else 0.0,
|
|
227
|
+
"share_of_site_bytes": 1.0, "shapes_of_site": 1, "places": list(st["site_ids"]), "pieces": [], "joining_function": None,
|
|
228
|
+
"fixed_share": None, "fragments": [], "fragments_text": [], "filled": built["filled"],
|
|
229
|
+
"params": {k: {x: v[x] for x in ("type", "column", "op", "source", "clause") if v.get(x) is not None}
|
|
230
|
+
for k, v in built["params"].items()},
|
|
231
|
+
"text_chars": len(text),
|
|
232
|
+
"production": {**{k: q[k] for k in ("rows_read_per_run", "bytes_read_per_run", "rows_returned_per_run", "read_bytes",
|
|
233
|
+
"executions", "aggregate", *match_mod.SPREAD_KEYS) if q.get(k) is not None},
|
|
234
|
+
**({"max_bytes_read_per_run": int(w["max_read_bytes"])} if w.get("max_read_bytes") else {})},
|
|
235
|
+
"normalized_text": clean[:200_000]},
|
|
236
|
+
"built_for": "scenario",
|
|
237
|
+
}
|
|
238
|
+
return cand, ""
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def bind(doc: dict, inventory: dict | None, facts=None, rank: dict | None = None, observed: dict | None = None,
|
|
242
|
+
engine: str = "clickhouse", dynamic: dict | None = None, previous: dict | None = None) -> dict:
|
|
243
|
+
"""Bind every candidate and write its rule variants: candidates[].bench {finding, built, why_not}, variants[]; and
|
|
244
|
+
`runnable`, the statements built here (SB-001...; a statement keeps its id across runs through `previous`)."""
|
|
245
|
+
from .observed import settings_of as dyn_settings
|
|
246
|
+
cfg = doc.get("settings") or settings_of(None)
|
|
247
|
+
dyn = dyn_settings(dynamic)
|
|
248
|
+
tables = Q.tables_from_inventory(inventory or {})
|
|
249
|
+
if facts:
|
|
250
|
+
tables.update(Q.tables_from_catalog(facts, engine))
|
|
251
|
+
by_site, by_hash, by_place = _candidate_maps(rank, observed)
|
|
252
|
+
asked = {c["fingerprint"]: c for c in (previous or {}).get("candidates") or [] if c.get("agent_asked")}
|
|
253
|
+
ids = {str((r.get("observed") or {}).get("hash")): r["finding"] for r in (previous or {}).get("runnable") or []}
|
|
254
|
+
used_ids = set(ids.values())
|
|
255
|
+
want = []
|
|
256
|
+
for c in doc["candidates"]:
|
|
257
|
+
old = asked.get(c["fingerprint"])
|
|
258
|
+
if old:
|
|
259
|
+
c["agent_asked"], c["agent_variants"] = True, old.get("agent_variants") or []
|
|
260
|
+
b = _bound(c, by_site, by_hash, by_place)
|
|
261
|
+
provable = any(x["proof"] == "sandbox" for x in c["changes"]) or bool(c.get("agent_variants"))
|
|
262
|
+
if b is None and provable and c["statement"]["sql_from"] == "query_log" and facts and cfg.get("build_runnable", True) \
|
|
263
|
+
and c["statement"].get("engine") == engine:
|
|
264
|
+
want.append(c)
|
|
265
|
+
c["bench"] = {"finding": b["finding"] if b else None, "built": False,
|
|
266
|
+
"why_not": None if b else ("not_provable" if not provable else "not_a_candidate")}
|
|
267
|
+
if not b and (c["statement"].get("engine") or "") not in ("", *engines_mod.supported()):
|
|
268
|
+
c["bench"]["why_not"] = "engine_not_benchmarkable" # an engine CodeCop has no sandbox for (MySQL, say)
|
|
269
|
+
want.sort(key=lambda c: -int((c["measured"] or {}).get("read_bytes") or 0))
|
|
270
|
+
built: dict[str, dict] = {}
|
|
271
|
+
failed: dict[str, str] = {}
|
|
272
|
+
limit = int(cfg.get("max_runnable", 40))
|
|
273
|
+
n = 0
|
|
274
|
+
for c in want:
|
|
275
|
+
h = c["statement"]["hash"]
|
|
276
|
+
if h in built:
|
|
277
|
+
c["bench"].update(finding=built[h]["finding"], built=True, why_not=None)
|
|
278
|
+
continue
|
|
279
|
+
if h in failed:
|
|
280
|
+
c["bench"]["why_not"] = failed[h]
|
|
281
|
+
continue
|
|
282
|
+
if len(built) >= limit:
|
|
283
|
+
c["bench"]["why_not"] = "over_max_runnable"
|
|
284
|
+
continue
|
|
285
|
+
finding = ids.get(h)
|
|
286
|
+
if finding is None:
|
|
287
|
+
n += 1
|
|
288
|
+
while f"SB-{n:03d}" in used_ids:
|
|
289
|
+
n += 1
|
|
290
|
+
finding = f"SB-{n:03d}"
|
|
291
|
+
used_ids.add(finding)
|
|
292
|
+
cand, why = runnable(c["statement"], facts, inventory, engine, finding, dyn)
|
|
293
|
+
if cand is None:
|
|
294
|
+
failed[h] = why
|
|
295
|
+
c["bench"]["why_not"] = why
|
|
296
|
+
continue
|
|
297
|
+
built[h] = cand
|
|
298
|
+
c["bench"].update(finding=cand["finding"], built=True, why_not=None)
|
|
299
|
+
doc["runnable"] = list(built.values())
|
|
300
|
+
by_finding = {**{x["finding"]: x for x in (rank or {}).get("candidates") or []},
|
|
301
|
+
**{x["finding"]: x for x in (observed or {}).get("candidates") or []}, **{x["finding"]: x for x in built.values()}}
|
|
302
|
+
for c in doc["candidates"]:
|
|
303
|
+
b = by_finding.get(c["bench"]["finding"]) if c["bench"]["finding"] else None
|
|
304
|
+
c["variants"] = variants_for(c, b, tables, rank, facts, cfg) if b else []
|
|
305
|
+
c["variants"] += [{**v, "scenario": c["fingerprint"], "origin": "scenario_agent", "change": v.get("change") or "agent_variant",
|
|
306
|
+
"table_level": v.get("kind") in TABLE_LEVEL} for v in c.get("agent_variants") or [] if v.get("sql")]
|
|
307
|
+
if b and not c["variants"] and c["bench"]["why_not"] is None:
|
|
308
|
+
c["bench"]["why_not"] = "no_rule_variant"
|
|
309
|
+
s = doc.setdefault("summary", {})
|
|
310
|
+
s["bound"] = sum(1 for c in doc["candidates"] if c["bench"]["finding"])
|
|
311
|
+
s["with_variants"] = sum(1 for c in doc["candidates"] if c["variants"])
|
|
312
|
+
s["runnable_built"] = len(built)
|
|
313
|
+
s["not_bound"] = dict(sorted(((k, sum(1 for c in doc["candidates"] if c["bench"]["why_not"] == k))
|
|
314
|
+
for k in {c["bench"]["why_not"] for c in doc["candidates"] if c["bench"]["why_not"]}), key=lambda kv: -kv[1]))
|
|
315
|
+
return doc
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def _variant_key(v: dict) -> tuple:
|
|
319
|
+
return (v.get("scenario"), v.get("change"), v.get("kind"))
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def attach(rank: dict | None, doc: dict | None, scenarios_only: bool = False) -> dict | None:
|
|
323
|
+
"""rank.json (already with the observed candidates) with the scenario variants added, first, to the statements they
|
|
324
|
+
are bound to, and the statements built for the scenarios added. `scenarios_only`: only the candidates that carry a
|
|
325
|
+
scenario variant, with only those variants (a bench of the scenarios alone). A copy."""
|
|
326
|
+
if rank is None and not (doc or {}).get("runnable"):
|
|
327
|
+
return rank
|
|
328
|
+
rank = copy.deepcopy(rank) if rank else {"engine": "clickhouse", "engine_version": "", "candidates": [], "table_definitions": [],
|
|
329
|
+
"agent": {"runner": "", "model": "", "cost_usd": 0.0}, "shortlist": [], "rejected": []}
|
|
330
|
+
if not doc:
|
|
331
|
+
return rank
|
|
332
|
+
extra: dict[str, list[dict]] = defaultdict(list)
|
|
333
|
+
for c in doc.get("candidates") or []:
|
|
334
|
+
f = (c.get("bench") or {}).get("finding")
|
|
335
|
+
for v in c.get("variants") or []:
|
|
336
|
+
if f and _variant_key(v) not in {_variant_key(x) for x in extra[f]}:
|
|
337
|
+
extra[f].append({k: x for k, x in v.items() if k != "table_level"})
|
|
338
|
+
have = {c["finding"] for c in rank.get("candidates") or []}
|
|
339
|
+
for r in doc.get("runnable") or []:
|
|
340
|
+
if r["finding"] not in have:
|
|
341
|
+
rank.setdefault("candidates", []).append(copy.deepcopy(r))
|
|
342
|
+
out = []
|
|
343
|
+
for c in rank.get("candidates") or []:
|
|
344
|
+
mine = extra.get(c["finding"]) or []
|
|
345
|
+
if scenarios_only:
|
|
346
|
+
if not mine:
|
|
347
|
+
continue
|
|
348
|
+
c["variants"] = mine
|
|
349
|
+
else:
|
|
350
|
+
c["variants"] = mine + [v for v in c.get("variants") or [] if not v.get("scenario")]
|
|
351
|
+
out.append(c)
|
|
352
|
+
rank["candidates"] = out
|
|
353
|
+
if scenarios_only:
|
|
354
|
+
used = {_short(t).lower() for c in out for t in c.get("tables") or []}
|
|
355
|
+
rank["table_definitions"] = [d for d in rank.get("table_definitions") or [] if _short(d["name"]).lower() in used]
|
|
356
|
+
return rank
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def align(rank: dict | None, doc: dict | None, bench: dict | None) -> dict | None:
|
|
360
|
+
"""rank.json with each candidate's variants in the order its bench record measured them: a record tagged with a
|
|
361
|
+
scenario takes that scenario's variant, an untagged one the next variant the agent proposed; the variants not
|
|
362
|
+
measured follow. The report then reads every bench record against the variant it measured."""
|
|
363
|
+
scales = (bench or {}).get("scales") or []
|
|
364
|
+
records = {f["finding"]: f for f in (scales[-1].get("findings") if scales else None) or []}
|
|
365
|
+
if scales and doc:
|
|
366
|
+
# a statement built for a scenario is a finding only when the bench measured it
|
|
367
|
+
doc = {**doc, "runnable": [r for r in doc.get("runnable") or [] if r["finding"] in records]}
|
|
368
|
+
attached = attach(rank, doc)
|
|
369
|
+
if attached is None:
|
|
370
|
+
return None
|
|
371
|
+
for c in attached.get("candidates") or []:
|
|
372
|
+
rec = records.get(c["finding"])
|
|
373
|
+
if not rec:
|
|
374
|
+
if scales:
|
|
375
|
+
c["variants"] = [v for v in c["variants"] if not v.get("scenario")] # not in this bench: not shown as untested
|
|
376
|
+
continue
|
|
377
|
+
scen = {_variant_key(v): v for v in c["variants"] if v.get("scenario")}
|
|
378
|
+
agent = [v for v in c["variants"] if not v.get("scenario")]
|
|
379
|
+
ordered, used = [], set()
|
|
380
|
+
for r in rec.get("variants") or []:
|
|
381
|
+
if r.get("scenario"):
|
|
382
|
+
key = (r.get("scenario"), r.get("change"), r.get("kind"))
|
|
383
|
+
v = scen.get(key) or {"kind": r.get("kind"), "sql": "", "setup_sql": [], "same_results": True, "scenario": r.get("scenario"),
|
|
384
|
+
"change": r.get("change"), "rule": r.get("rule"), "origin": "scenario", "stale": True}
|
|
385
|
+
used.add(key)
|
|
386
|
+
else:
|
|
387
|
+
v = agent.pop(0) if agent else {"kind": r.get("kind"), "sql": "", "setup_sql": [], "same_results": True, "stale": True}
|
|
388
|
+
ordered.append(v)
|
|
389
|
+
c["variants"] = ordered + agent # a scenario variant this bench did not measure is left out
|
|
390
|
+
return attached
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def complete_nested(profile: dict | None, facts, engine: str) -> list[str]:
|
|
394
|
+
"""Every column of a Nested structure gets a generator once one of them has one: the arrays of one structure must
|
|
395
|
+
have one length, and a profiled column (one element) beside a default one (none) is refused by the server
|
|
396
|
+
(SIZES_OF_ARRAYS_DONT_MATCH). Changes `profile` in place; returns a note per table."""
|
|
397
|
+
from .catalog_profile import _days_back, column_spec
|
|
398
|
+
notes = []
|
|
399
|
+
real = facts.tables(engine) if facts else {}
|
|
400
|
+
for t in (profile or {}).get("tables") or []:
|
|
401
|
+
cols = (real.get(t["name"]) or {}).get("columns") or []
|
|
402
|
+
have = {c["name"] for c in t.get("columns") or []}
|
|
403
|
+
groups = {n.split(".", 1)[0] for n in have if "." in n}
|
|
404
|
+
missing = [c for c in cols if "." in c["name"] and c["name"].split(".", 1)[0] in groups and c["name"] not in have]
|
|
405
|
+
if not missing:
|
|
406
|
+
continue
|
|
407
|
+
rows = int((real.get(t["name"]) or {}).get("rows") or 0)
|
|
408
|
+
for c in missing:
|
|
409
|
+
t.setdefault("columns", []).append(column_spec(c, rows, sorting=[], days_back=_days_back(real.get(t["name"]) or {}), literals=None))
|
|
410
|
+
notes.append(f"{t['name']}: {len(missing)} columns of a Nested structure profiled too (their arrays must have one length)")
|
|
411
|
+
return notes
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
GATE_REASONS = ("shape_differs", "value_type_open", "identifier_masked", "external_data", "text_cut_at_limit", "no_text",
|
|
415
|
+
"ambiguous_template", "table_not_in_catalog")
|
|
416
|
+
AGENT_NEXT_STEP = "ask_agent_for_scenario_variants"
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
def outcomes(doc: dict, rank: dict | None, bench: dict | None, settings: dict | None = None) -> dict:
|
|
420
|
+
"""Each scenario candidate in one of the four states (blockers.py), from its own variants' bench records only; and
|
|
421
|
+
what each of its variants measured. Changes `doc` in place (candidates[].outcome, candidates[].measured_variants,
|
|
422
|
+
summary.states) and returns it.
|
|
423
|
+
|
|
424
|
+
a variant was benchmarked blockers.candidate_outcome over this candidate's variants alone: Fixed only on a
|
|
425
|
+
verified win (a table-level one also within its measured insert cost)
|
|
426
|
+
no variant, the agent could Could not be judged, `variants_not_asked` (next step: the paid step)
|
|
427
|
+
production's text not runnable Could not be judged, `assembled_shape_rejected` with the gate's reason
|
|
428
|
+
no statement to run Could not be judged, `not_a_candidate`
|
|
429
|
+
evidence or trade-off only Could not be judged, `evidence_only` (the change is to the application or a table
|
|
430
|
+
whose equivalence the catalog can not show)"""
|
|
431
|
+
from . import blockers as B
|
|
432
|
+
from . import engines
|
|
433
|
+
cfg = B.settings_of(settings)
|
|
434
|
+
scales = (bench or {}).get("scales") or []
|
|
435
|
+
largest = scales[-1] if scales else {}
|
|
436
|
+
records = {f["finding"]: f for f in largest.get("findings") or []}
|
|
437
|
+
cands = {c["finding"]: c for c in (rank or {}).get("candidates") or []}
|
|
438
|
+
definitions = {B.short(d["name"]): d for d in (rank or {}).get("table_definitions") or []}
|
|
439
|
+
rows = B.table_rows_of(largest)
|
|
440
|
+
engine = (rank or {}).get("engine") or (bench or {}).get("engine") or "clickhouse"
|
|
441
|
+
floors = B.engine_floors(engine, bench) if bench else (0, 0)
|
|
442
|
+
for c in doc.get("candidates") or []:
|
|
443
|
+
fp = c["fingerprint"]
|
|
444
|
+
finding = (c.get("bench") or {}).get("finding")
|
|
445
|
+
why = (c.get("bench") or {}).get("why_not")
|
|
446
|
+
kinds = {x["proof"] for x in c["changes"]}
|
|
447
|
+
c["measured_variants"] = []
|
|
448
|
+
if not c.get("variants"):
|
|
449
|
+
if not kinds & {"sandbox", "needs_agent"}:
|
|
450
|
+
c["outcome"] = B.outcome("not_judged", "evidence_only", "run", {"proofs": sorted(kinds)})
|
|
451
|
+
elif finding and "needs_agent" in kinds and not c.get("agent_asked"):
|
|
452
|
+
c["outcome"] = B.outcome("not_judged", "variants_not_asked", "run", {"next_step": AGENT_NEXT_STEP})
|
|
453
|
+
elif why == "engine_not_benchmarkable":
|
|
454
|
+
c["outcome"] = B.outcome("not_judged", "engine_not_benchmarkable", "run", {"engine": c["statement"].get("engine")})
|
|
455
|
+
elif why in GATE_REASONS:
|
|
456
|
+
c["outcome"] = B.outcome("not_judged", "assembled_shape_rejected", "run", {"gate": {"reason": why}, "next_step": "none_codecop_side"})
|
|
457
|
+
elif why in ("not_a_candidate", "over_max_runnable") or (why == "not_provable" and "needs_agent" in kinds):
|
|
458
|
+
c["outcome"] = B.outcome("not_judged", "not_a_candidate", "run", {"why": why, **({"next_step": AGENT_NEXT_STEP} if "needs_agent" in kinds else {})})
|
|
459
|
+
else:
|
|
460
|
+
c["outcome"] = B.outcome("not_judged", "evidence_only", "run", {"proofs": sorted(kinds)})
|
|
461
|
+
continue
|
|
462
|
+
rec = records.get(finding)
|
|
463
|
+
cand = cands.get(finding)
|
|
464
|
+
if not scales or rec is None or cand is None:
|
|
465
|
+
c["outcome"] = B.outcome("not_judged", "bench_not_run", "run")
|
|
466
|
+
continue
|
|
467
|
+
mine = [r for r in rec.get("variants") or [] if r.get("scenario") == fp]
|
|
468
|
+
if not mine and rec.get("variants") is not None and not rec.get("not_benchmarked") and (rec.get("baseline") or {}).get("ok"):
|
|
469
|
+
c["outcome"] = B.outcome("not_judged", "bench_not_run", "run", {"why": "variants_not_in_this_bench"})
|
|
470
|
+
continue
|
|
471
|
+
proposed = {(_variant_key(v)): v for v in cand.get("variants") or [] if v.get("scenario") == fp}
|
|
472
|
+
normalized = []
|
|
473
|
+
for r in mine:
|
|
474
|
+
v = proposed.get((r.get("scenario"), r.get("change"), r.get("kind"))) or {}
|
|
475
|
+
normalized.append({"kind": r.get("kind"), "verdict": r.get("verdict") or "untested", "same_results": v.get("same_results", True),
|
|
476
|
+
"results_match": r.get("results_match"), "compared": r.get("compared") or "", "sql": v.get("sql") or "",
|
|
477
|
+
"reason": r.get("reason") or "", "var": r.get("measurement"),
|
|
478
|
+
**({"insert_cost": r["insert_cost"]} if r.get("insert_cost") else {})})
|
|
479
|
+
base = (rec.get("baseline") or {})
|
|
480
|
+
m = r.get("measurement") or {}
|
|
481
|
+
c["measured_variants"].append({
|
|
482
|
+
"change": r.get("change"), "kind": r.get("kind"), "verdict": r.get("verdict"), "reason": (r.get("reason") or "")[:300],
|
|
483
|
+
"rows_ratio": B._ratio(m.get("read_rows"), base.get("read_rows")) if m.get("ok") else None,
|
|
484
|
+
"bytes_ratio": B._ratio(m.get("read_bytes"), base.get("read_bytes")) if m.get("ok") else None,
|
|
485
|
+
"results_match": r.get("results_match"),
|
|
486
|
+
**({run: {k: r[run].get(k) for k in ("verdict", "reason") if k in r[run]} for run in ("typical", "heavy") if isinstance(r.get(run), dict)}),
|
|
487
|
+
**({"heavy_bytes_ratio": B._ratio((r["heavy"].get("measurement") or {}).get("read_bytes"),
|
|
488
|
+
((rec.get("fidelity") or {}).get("heavy") or {}).get("measured", {}).get("read_bytes"))}
|
|
489
|
+
if isinstance(r.get("heavy"), dict) and r["heavy"].get("measurement") else {}),
|
|
490
|
+
**({"insert_cost": r["insert_cost"]} if r.get("insert_cost") else {})})
|
|
491
|
+
access = []
|
|
492
|
+
for t in cand.get("tables") or []:
|
|
493
|
+
d = definitions.get(B.short(t))
|
|
494
|
+
if d and d.get("create_sql"):
|
|
495
|
+
try:
|
|
496
|
+
access.append(engines.get(engine).table_access(d["create_sql"], d["name"], cand["baseline_sql"], None))
|
|
497
|
+
except Exception: # a definition the access analysis can not read is no evidence either way
|
|
498
|
+
continue
|
|
499
|
+
filtered = {**rec, "variants": mine}
|
|
500
|
+
c["outcome"] = B.candidate_outcome(engine, cand, filtered, normalized, access, rows, definitions, cfg, floors, benched=True)
|
|
501
|
+
if rec.get("variants_on"):
|
|
502
|
+
c["outcome"]["evidence"]["variants_on"] = rec["variants_on"]
|
|
503
|
+
states = Counter(c["outcome"]["state"] for c in doc.get("candidates") or [] if c.get("outcome"))
|
|
504
|
+
doc.setdefault("summary", {})["states"] = {s: states.get(s, 0) for s in B.STATES}
|
|
505
|
+
doc["summary"]["reasons"] = dict(Counter(c["outcome"]["reason"] for c in doc.get("candidates") or [] if c.get("outcome")).most_common())
|
|
506
|
+
return doc
|
|
507
|
+
|