codecop 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- codecop/__init__.py +7 -0
- codecop/access.py +140 -0
- codecop/access_postgres.py +284 -0
- codecop/advisor.py +1512 -0
- codecop/advisor_bench.py +493 -0
- codecop/advisor_ch.py +2080 -0
- codecop/advisor_view.py +381 -0
- codecop/advisors.py +184 -0
- codecop/agent.py +221 -0
- codecop/agentfacts.py +745 -0
- codecop/apply/__init__.py +327 -0
- codecop/apply/check.py +344 -0
- codecop/apply/cli.py +162 -0
- codecop/apply/clickhouse.py +379 -0
- codecop/apply/common.py +238 -0
- codecop/apply/html.py +264 -0
- codecop/apply/patch.py +213 -0
- codecop/apply/postgres.py +102 -0
- codecop/apply/trial.py +166 -0
- codecop/assemble.py +104 -0
- codecop/baseline.py +1043 -0
- codecop/bench.py +2464 -0
- codecop/blockers.py +935 -0
- codecop/budget.py +980 -0
- codecop/catalog_profile.py +525 -0
- codecop/changed.py +261 -0
- codecop/cicmd.py +1002 -0
- codecop/cli.py +5421 -0
- codecop/client.py +729 -0
- codecop/coverage.py +1067 -0
- codecop/coverage_reasons.py +116 -0
- codecop/crashlog.py +70 -0
- codecop/datagen.py +766 -0
- codecop/datagen_postgres.py +630 -0
- codecop/datagen_sqlite.py +323 -0
- codecop/dbcli.py +885 -0
- codecop/definitions.py +457 -0
- codecop/discover/__init__.py +702 -0
- codecop/discover/arms.py +160 -0
- codecop/discover/base.py +234 -0
- codecop/discover/dialect.py +296 -0
- codecop/discover/elixir.py +64 -0
- codecop/discover/engine_go.py +320 -0
- codecop/discover/go.py +1947 -0
- codecop/discover/java.py +1528 -0
- codecop/discover/loops.py +1671 -0
- codecop/discover/named_go.py +258 -0
- codecop/discover/origins.py +4565 -0
- codecop/discover/origins_ts.py +1584 -0
- codecop/discover/orm_django.py +2772 -0
- codecop/discover/orm_django_models.py +814 -0
- codecop/discover/orm_django_sql.py +662 -0
- codecop/discover/orm_ent.py +565 -0
- codecop/discover/orm_ex_ecto.py +2138 -0
- codecop/discover/orm_go.py +2134 -0
- codecop/discover/orm_go_bun.py +602 -0
- codecop/discover/orm_go_run.py +636 -0
- codecop/discover/orm_go_types.py +1082 -0
- codecop/discover/orm_java.py +1450 -0
- codecop/discover/orm_jdbi.py +743 -0
- codecop/discover/orm_jooq.py +806 -0
- codecop/discover/orm_jpa.py +1307 -0
- codecop/discover/orm_mybatis.py +730 -0
- codecop/discover/orm_py.py +557 -0
- codecop/discover/orm_py_peewee.py +1266 -0
- codecop/discover/orm_py_prisma.py +298 -0
- codecop/discover/orm_rb_activerecord.py +1906 -0
- codecop/discover/orm_rust.py +1248 -0
- codecop/discover/orm_rust_seaorm.py +734 -0
- codecop/discover/orm_sqlalchemy.py +2475 -0
- codecop/discover/orm_stats.py +307 -0
- codecop/discover/orm_tables.py +29 -0
- codecop/discover/orm_ts.py +503 -0
- codecop/discover/orm_ts_drizzle.py +697 -0
- codecop/discover/orm_ts_knex.py +1117 -0
- codecop/discover/orm_ts_kysely.py +861 -0
- codecop/discover/orm_ts_prisma.py +1045 -0
- codecop/discover/orm_ts_schema.py +169 -0
- codecop/discover/orm_ts_sequelize.py +1401 -0
- codecop/discover/orm_ts_typeorm.py +1067 -0
- codecop/discover/probes.py +323 -0
- codecop/discover/python.py +595 -0
- codecop/discover/ruby.py +793 -0
- codecop/discover/rust.py +2378 -0
- codecop/discover/schema.py +520 -0
- codecop/discover/schema_ent.py +145 -0
- codecop/discover/schema_ts.py +420 -0
- codecop/discover/tsresolve.py +257 -0
- codecop/discover/typescript.py +1728 -0
- codecop/discover/xml_mapper.py +526 -0
- codecop/engines/__init__.py +515 -0
- codecop/engines/base.py +498 -0
- codecop/engines/clickhouse.py +1558 -0
- codecop/engines/pg_ddl.py +444 -0
- codecop/engines/pg_hints.py +137 -0
- codecop/engines/postgres.py +1060 -0
- codecop/engines/sqlite.py +742 -0
- codecop/families/__init__.py +3 -0
- codecop/families/build.py +280 -0
- codecop/families/cli.py +177 -0
- codecop/families/coverage_hook.py +62 -0
- codecop/families/driver.py +221 -0
- codecop/families/goslice.py +229 -0
- codecop/families/goslice_tool/go.mod +3 -0
- codecop/families/goslice_tool/main.go +403 -0
- codecop/families/holes.py +451 -0
- codecop/families/images/Dockerfile.go +5 -0
- codecop/families/images/Dockerfile.python +4 -0
- codecop/families/images/Dockerfile.rust +4 -0
- codecop/families/isolate.py +171 -0
- codecop/families/locate.py +270 -0
- codecop/families/model.py +301 -0
- codecop/families/plangate.py +271 -0
- codecop/families/tagpatch.py +174 -0
- codecop/fidelity.py +671 -0
- codecop/fixgroups.py +130 -0
- codecop/formerly.py +91 -0
- codecop/grantscript.py +254 -0
- codecop/groupbench.py +1375 -0
- codecop/groups.py +594 -0
- codecop/groups_view.py +186 -0
- codecop/heat.py +1405 -0
- codecop/heatcli.py +219 -0
- codecop/joins.py +1749 -0
- codecop/joins_view.py +127 -0
- codecop/kinds/__init__.py +507 -0
- codecop/kinds/calls/__init__.py +501 -0
- codecop/kinds/calls/extract.py +1097 -0
- codecop/kinds/calls/harness.py +408 -0
- codecop/kinds/calls/measure.py +342 -0
- codecop/kinds/calls/rules.py +139 -0
- codecop/kinds/calls/runners/RunCalls.java +167 -0
- codecop/kinds/calls/runners/run_go.go +141 -0
- codecop/kinds/calls/runners/run_node.js +186 -0
- codecop/kinds/calls/runners/run_python.py +319 -0
- codecop/kinds/calls/runners/run_rust.rs +200 -0
- codecop/kinds/calls/standin.py +340 -0
- codecop/kinds/pipeline.py +288 -0
- codecop/kinds/regex/__init__.py +1167 -0
- codecop/kinds/regex/engines/RegexHarness.java +129 -0
- codecop/kinds/regex/engines/run_go.go +294 -0
- codecop/kinds/regex/engines/run_node.js +99 -0
- codecop/kinds/regex/engines/run_python.py +295 -0
- codecop/kinds/regex/engines/run_rust.rs +149 -0
- codecop/kinds/regex/extract.py +1438 -0
- codecop/kinds/regex/harness.py +235 -0
- codecop/kinds/regex/measure.py +270 -0
- codecop/kinds/regex/shapes.py +418 -0
- codecop/kinds/regex/syntax.py +1721 -0
- codecop/kinds/testkind.py +107 -0
- codecop/kinds/transaction/__init__.py +228 -0
- codecop/kinds/transaction/bind.py +355 -0
- codecop/kinds/transaction/measure.py +264 -0
- codecop/kinds/transaction/plan.py +462 -0
- codecop/kinds/transaction/rules.py +540 -0
- codecop/kinds/transaction/sandbox.py +94 -0
- codecop/kinds/transaction/scenarios.py +520 -0
- codecop/kinds/transaction/schedule.py +483 -0
- codecop/kinds/transaction/shapes.py +418 -0
- codecop/kinds/transaction/verify.py +293 -0
- codecop/live.py +237 -0
- codecop/loopbench.py +2071 -0
- codecop/loopschema.py +591 -0
- codecop/mcpserver.py +120 -0
- codecop/mechanism.py +214 -0
- codecop/members.py +200 -0
- codecop/multi.py +443 -0
- codecop/observed.py +1868 -0
- codecop/parts.py +102 -0
- codecop/patterns.py +830 -0
- codecop/patterns_view.py +559 -0
- codecop/plangate.py +242 -0
- codecop/profile.py +439 -0
- codecop/prompts/areas.md +19 -0
- codecop/prompts/observed_variants.md +20 -0
- codecop/prompts/profile.md +60 -0
- codecop/prompts/profile_postgres.md +68 -0
- codecop/prompts/profile_sizes.md +26 -0
- codecop/prompts/profile_sqlite.md +69 -0
- codecop/prompts/rank.md +84 -0
- codecop/prompts/rank_postgres.md +96 -0
- codecop/prompts/rank_sqlite.md +94 -0
- codecop/prompts/scenario_variants.md +20 -0
- codecop/rank.py +1473 -0
- codecop/realdb/__init__.py +688 -0
- codecop/realdb/clickhouse.py +1223 -0
- codecop/realdb/facts.py +815 -0
- codecop/realdb/locality.py +964 -0
- codecop/realdb/locks.py +355 -0
- codecop/realdb/match.py +531 -0
- codecop/realdb/postgres.py +643 -0
- codecop/realdb/ratios.py +77 -0
- codecop/realdb/sample.py +126 -0
- codecop/relations.py +227 -0
- codecop/report.py +1854 -0
- codecop/resources.py +332 -0
- codecop/resources_view.py +266 -0
- codecop/rules/entry_points.toml +1013 -0
- codecop/rules/sinks.toml +362 -0
- codecop/runsonce.py +8 -0
- codecop/sandboxschema.py +555 -0
- codecop/scenario_agent.py +172 -0
- codecop/scenario_bind.py +507 -0
- codecop/scenario_sql.py +971 -0
- codecop/scenarios.py +675 -0
- codecop/scenarios_view.py +274 -0
- codecop/schemacli.py +67 -0
- codecop/schemas/areas_output.schema.json +21 -0
- codecop/schemas/profile_output.schema.json +362 -0
- codecop/schemas/rank_output.schema.json +385 -0
- codecop/sizes.py +200 -0
- codecop/sqlinfo.py +558 -0
- codecop/typedparams.py +576 -0
- codecop/verdicts.py +212 -0
- codecop/writebench.py +720 -0
- codecop/writecost.py +440 -0
- codecop/writes.py +1208 -0
- codecop-0.1.0.dist-info/METADATA +42 -0
- codecop-0.1.0.dist-info/RECORD +222 -0
- codecop-0.1.0.dist-info/WHEEL +4 -0
- codecop-0.1.0.dist-info/entry_points.txt +2 -0
- codecop-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,525 @@
|
|
|
1
|
+
"""The data an observed statement is benchmarked on, without an agent: table definitions and a data profile from the
|
|
2
|
+
pulled catalog alone.
|
|
3
|
+
|
|
4
|
+
The agent's profile (profile.py) says how values are distributed. For a statement production ran (observed.py) no agent
|
|
5
|
+
was asked, so this profile is mechanical and says so on every column (`source: catalog, no agent`, low confidence):
|
|
6
|
+
- rows, column sizes and the sizes by age come from the real catalog (profile.apply_facts), as for any profile;
|
|
7
|
+
- the generator kind of a column the statement uses comes from its type: a time column spans the table's partitions,
|
|
8
|
+
a string in the sorting key or named as an identifier is a key, a string the code compares with literals takes
|
|
9
|
+
those literals, a number is a range; a column the statement does not use is left to its default, except text that
|
|
10
|
+
is part of the row's width (added by apply_facts at its real size);
|
|
11
|
+
- each candidate gets a fixture of its own: its parameter values and the code's literals on a share of the rows
|
|
12
|
+
worked out from production's median run (rows read per run over the table's rows). fidelity.py then corrects shares,
|
|
13
|
+
gives the heavy run values of its own and makes an empty typical run empty, as for every candidate.
|
|
14
|
+
A table the agent's profile already describes keeps the agent's columns; the candidate only adds its fixture there.
|
|
15
|
+
Each candidate records which description each of its tables has (`observed.profile_basis`: agent profile / catalog
|
|
16
|
+
only); `codecop profile --observed` (paid) has the agent describe the catalog-only ones.
|
|
17
|
+
|
|
18
|
+
What the catalog-only description takes from the real catalog and the statement besides types: the partition key's time
|
|
19
|
+
column follows the real rows per partition (time_shares); a number column the statement reads as a time is a time
|
|
20
|
+
(observed.epoch_units); the time columns one window bounds hold one moment (link_times); two tables the statement joins
|
|
21
|
+
keep the join (link_joins, relations.py); the fixture states production's median rows read and the run's window
|
|
22
|
+
(fixture_for), which bench.target_shares turns into a share of the sandbox table at each scale.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import copy
|
|
28
|
+
import re
|
|
29
|
+
|
|
30
|
+
from . import profile as profile_mod
|
|
31
|
+
from .observed import TIME_TYPE, base_type
|
|
32
|
+
|
|
33
|
+
KEY_NAME = re.compile(r"(?:^|_)(id|uuid|key|hash|email|tenant|subscriber|user|account|org|device|session|request)(?:_|$)", re.I)
|
|
34
|
+
GROUP_NAME = re.compile(r"^(?:\w+_)?(tenant|org|organization|account|workspace|customer|company)(?:_id|_uuid)?$", re.I)
|
|
35
|
+
GROUP_DISTINCT = 50
|
|
36
|
+
KIND_NAME = re.compile(r"(?:^|_)(type|kind|category|status|state|level|provider|channel|mode|action|outcome|origin|surface|source)$", re.I)
|
|
37
|
+
SOURCE = "catalog, no agent: the generator kind follows the column's type; distinct counts are guesses (no sample was read)"
|
|
38
|
+
AGENT, CATALOG = "agent profile", "catalog only" # where a table's data description comes from, per observed candidate
|
|
39
|
+
MIN_SHARE, MAX_SHARE = 1e-5, 0.5
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _literal_equalities(sql: str, columns: set[str], filters_only: bool = False) -> dict[str, list[str]]:
|
|
43
|
+
"""column -> the string literals the statement compares it with (`kind = 'admin'`, `kind IN ('a', 'b')`).
|
|
44
|
+
`filters_only`: only comparisons in WHERE, PREWHERE, ON and HAVING (the ones that decide which rows are read)."""
|
|
45
|
+
from .observed import FILTER_CLAUSES, _clause, tokens
|
|
46
|
+
toks = tokens(sql)
|
|
47
|
+
out: dict[str, list[str]] = {}
|
|
48
|
+
for i, t in enumerate(toks):
|
|
49
|
+
if t["kind"] != "str" or i < 2:
|
|
50
|
+
continue
|
|
51
|
+
if filters_only and _clause(toks, i) not in FILTER_CLAUSES:
|
|
52
|
+
continue
|
|
53
|
+
j = i - 1
|
|
54
|
+
while j > 0 and (toks[j]["text"] in (",", "(") or toks[j]["kind"] == "str"): # inside an IN list
|
|
55
|
+
j -= 1
|
|
56
|
+
op = toks[j]["text"].lower() if toks[j]["text"] in ("=", "==") or toks[j]["key"] == "in" else ""
|
|
57
|
+
if not op or j < 1 or toks[j - 1]["kind"] != "ident":
|
|
58
|
+
continue
|
|
59
|
+
col = toks[j - 1]["key"].rsplit(".", 1)[-1]
|
|
60
|
+
if col in columns:
|
|
61
|
+
out.setdefault(col, []).append(t["text"][1:-1].replace("\\'", "'"))
|
|
62
|
+
return {k: list(dict.fromkeys(v)) for k, v in out.items() if v}
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def column_spec(col: dict, rows: int, *, sorting: list[str], days_back: float, literals: list[str] | None, unique: bool = False,
|
|
66
|
+
epoch: str | None = None, by_age: dict | None = None) -> dict:
|
|
67
|
+
"""A generator description of one real column, from its type, its place in the sorting key and the literals the code
|
|
68
|
+
compares it with. `unique`: the last column of a deduplicating table's key, which makes each generated row its own
|
|
69
|
+
(a ReplacingMergeTree keeps one row per key). `epoch`: a number column the statement reads as a time in this unit
|
|
70
|
+
(observed.epoch_units): generated as times, not as 0..1000. `by_age`: the real rows per period of the partition key's
|
|
71
|
+
time column (time_shares): times follow them instead of an even spread."""
|
|
72
|
+
name, t = col["name"], col.get("type", "")
|
|
73
|
+
b = base_type(t)
|
|
74
|
+
while b.startswith("Array("): # an array is generated as one element of its element type (datagen.into_type)
|
|
75
|
+
b = base_type(b[6:-1])
|
|
76
|
+
spec: dict = {"name": name, "source": SOURCE, "confidence": "low", "evidence": "inferred"}
|
|
77
|
+
if unique and b.startswith(("String", "FixedString")) and not literals:
|
|
78
|
+
spec.update(kind="unique")
|
|
79
|
+
elif literals and b.startswith("Enum") and re.search(r"'\s*=", b):
|
|
80
|
+
# an Enum takes only its labels (any other value fails the whole load): the code's literals that are labels, and
|
|
81
|
+
# the type's other labels as the rest
|
|
82
|
+
labels = re.findall(r"'((?:[^'\\]|\\.)*)'\s*=", b)
|
|
83
|
+
keep = [v for v in literals if v in labels] or labels[:1]
|
|
84
|
+
rest = [v for v in labels if v not in keep]
|
|
85
|
+
spec.update(kind="categorical", values=[{"value": v, "weight": 1} for v in keep + rest[:1]])
|
|
86
|
+
elif b.startswith("Enum") and re.search(r"'\s*=", b):
|
|
87
|
+
# an Enum the code compares with nothing: its labels (text cast to it fails the whole load)
|
|
88
|
+
spec.update(kind="categorical", values=[{"value": v, "weight": 1} for v in re.findall(r"'((?:[^'\\]|\\.)*)'\s*=", b)])
|
|
89
|
+
elif literals and not (GROUP_NAME.search(name) or (KEY_NAME.search(name) and not KIND_NAME.search(name))):
|
|
90
|
+
spec.update(kind="categorical", values=[{"value": v, "weight": 1} for v in literals] + [{"value": f"{name}-other", "weight": 1}])
|
|
91
|
+
# a key-like column (tenant, project, user id) the code compares with a literal keeps many values: as the literal and
|
|
92
|
+
# one other value, an equality on it selected half the table. The literal reaches rows through the fixture.
|
|
93
|
+
elif TIME_TYPE.match(b) or (epoch and re.match(r"U?Int\d+", b)):
|
|
94
|
+
spec.update(kind="timestamp", days_back=round(max(days_back, 1.0), 1), distribution="uniform", **({"epoch": epoch} if epoch else {}))
|
|
95
|
+
if by_age:
|
|
96
|
+
spec.update(by_age=by_age, source=SOURCE + "; the times follow the real rows per partition (catalog)")
|
|
97
|
+
if epoch:
|
|
98
|
+
spec["source"] = spec["source"] + f"; a number the statement reads as {epoch} since the epoch"
|
|
99
|
+
elif b in ("Bool",) or b == "UInt8":
|
|
100
|
+
spec.update(kind="int", min=0, max=1)
|
|
101
|
+
elif re.match(r"U?Int\d+", b):
|
|
102
|
+
spec.update(kind="int", min=0, max=1000)
|
|
103
|
+
elif re.match(r"Float|Decimal", b):
|
|
104
|
+
spec.update(kind="float", min=0, max=1000)
|
|
105
|
+
elif b.startswith(("String", "FixedString", "UUID")) and GROUP_NAME.search(name):
|
|
106
|
+
# a tenant, an organization, an account: a few dozen, a few hold most rows (a guess, said; the statement's own
|
|
107
|
+
# tenant gets its rows from the fixture). As one id per ten rows every tenant had ten rows
|
|
108
|
+
spec.update(kind="key", distinct=GROUP_DISTINCT, distribution="skewed",
|
|
109
|
+
source=SOURCE + f"; a tenant-like name: {GROUP_DISTINCT} values, skewed (a guess)")
|
|
110
|
+
elif b.startswith(("String", "FixedString", "UUID")) and KIND_NAME.search(name) and not KEY_NAME.search(name):
|
|
111
|
+
spec.update(kind="key", distinct=20, distribution="skewed", source=SOURCE + "; a type-like name: 20 values, skewed (a guess)")
|
|
112
|
+
elif b.startswith(("String", "FixedString", "UUID")) and (name in sorting or KEY_NAME.search(name)):
|
|
113
|
+
first = sorting[:1] == [name]
|
|
114
|
+
spec.update(kind="key", distinct=max(min(rows // (20_000 if first else 10), 1_000_000), 20 if first else 100), distribution="skewed" if first else "uniform")
|
|
115
|
+
elif "LowCardinality" in t:
|
|
116
|
+
spec.update(kind="key", distinct=20, distribution="skewed")
|
|
117
|
+
else:
|
|
118
|
+
spec.update(kind="text", avg_len=32)
|
|
119
|
+
return spec
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
MAX_AGE_PERIODS = 120 # periods a time column's spread keeps one by one, newest first; the rest are spread evenly as one
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def time_shares(facts, engine: str, name: str) -> tuple[str | None, dict | None]:
|
|
126
|
+
"""(time column of the partition key, {unit, shares}) from the real rows per partition: `shares[k]` is the share of
|
|
127
|
+
the table's rows in the period k periods before the newest partition. (None, None) when the partitions are not
|
|
128
|
+
periods of time or the pull has no rows per partition."""
|
|
129
|
+
from . import sizes
|
|
130
|
+
when = facts.partition_time(engine, name) if facts and hasattr(facts, "partition_time") else None
|
|
131
|
+
t = (facts.tables(engine).get(name) or {}) if facts else {}
|
|
132
|
+
d = t.get("partition_parts") or {}
|
|
133
|
+
if not when or not when.get("column") or not d.get("ids") or not d.get("rows"):
|
|
134
|
+
return None, None
|
|
135
|
+
by_back: dict[int, int] = {}
|
|
136
|
+
for pid, rows in zip(d["ids"], d["rows"]):
|
|
137
|
+
day = sizes.partition_day(pid)
|
|
138
|
+
if day:
|
|
139
|
+
back = sizes.periods_back(when["unit"], when["newest"], day)
|
|
140
|
+
by_back[back] = by_back.get(back, 0) + int(rows or 0)
|
|
141
|
+
total = sum(by_back.values())
|
|
142
|
+
if not total:
|
|
143
|
+
return None, None
|
|
144
|
+
last = max(by_back)
|
|
145
|
+
shares = [by_back.get(k, 0) / total for k in range(min(last + 1, MAX_AGE_PERIODS))]
|
|
146
|
+
if last + 1 > MAX_AGE_PERIODS:
|
|
147
|
+
shares[-1] += sum(v for k, v in by_back.items() if k >= MAX_AGE_PERIODS) / total
|
|
148
|
+
return when["column"], {"unit": when["unit"], "shares": [round(s, 6) for s in shares], "basis": "real rows per partition"}
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _days_back(t: dict) -> float:
|
|
152
|
+
"""How many days a time column of the table spans: from its partition ids when they are dates, else 30."""
|
|
153
|
+
from . import sizes
|
|
154
|
+
ids = list((t.get("partition_parts") or {}).get("ids") or [])
|
|
155
|
+
days = [d for d in (sizes.partition_day(p) for p in ids) if d]
|
|
156
|
+
if len(days) >= 2:
|
|
157
|
+
return max((max(days) - min(days)).days + 1, 1)
|
|
158
|
+
return 30.0
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
DEDUPLICATING = re.compile(r"(Replacing|Collapsing|VersionedCollapsing|Coalescing|Aggregating|Summing)MergeTree", re.I)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
WHOLE_ROW = re.compile(r"(?:\bselect\s+(?:distinct\s+)?|,\s*|\.)\*|\b(?:to_jsonb?|row_to_json|jsonb?_populate_record|hstore)\s*\(\s*\"?[A-Za-z_]\w*\"?\s*\)",
|
|
165
|
+
re.I)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def whole_row(sql: str) -> bool:
|
|
169
|
+
"""The statement reads whole rows of a table: `SELECT *`, `alias.*`, or a row turned into JSON (`to_jsonb(alias)`)."""
|
|
170
|
+
text = re.sub(r"'(?:[^'\\]|\\.|'')*'", "''", sql or "")
|
|
171
|
+
return bool(WHOLE_ROW.search(text))
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _used_columns(sql: str, columns: list[dict], sorting: list[str]) -> list[dict]:
|
|
175
|
+
"""The columns a statement names, the sorting key's columns (they decide which rows a deduplicating table keeps), and
|
|
176
|
+
every column of a Nested structure one of them belongs to (its arrays must have one length)."""
|
|
177
|
+
words = {w.lower() for w in re.findall(r"[A-Za-z_][\w.]*", sql or "")} | {w.lower().split(".")[-1] for w in re.findall(r"[A-Za-z_][\w.]*", sql or "")}
|
|
178
|
+
if whole_row(sql):
|
|
179
|
+
# `SELECT *`, `t.*`, `to_jsonb(t)`, `row_to_json(t)`: every column is read, though none is named
|
|
180
|
+
return list(columns)
|
|
181
|
+
used = {c["name"] for c in columns if c["name"].lower() in words or c["name"] in sorting}
|
|
182
|
+
if not used and columns:
|
|
183
|
+
# a statement that names none of the table's columns (`count(*)`) still reads its rows: the first column holds them
|
|
184
|
+
return [columns[0]]
|
|
185
|
+
nested = {n.split(".", 1)[0] for n in used if "." in n} | {c["name"].split(".", 1)[0] for c in columns
|
|
186
|
+
if "." in c["name"] and c["name"].split(".", 1)[0].lower() in words}
|
|
187
|
+
used |= {c["name"] for c in columns if "." in c["name"] and c["name"].split(".", 1)[0] in nested}
|
|
188
|
+
return [c for c in columns if c["name"] in used]
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
NUMERIC_TYPE = re.compile(r"^(U?Int\d+|Float\d+|Decimal\w*(\(.*\))?|Bool)$")
|
|
192
|
+
NUMBER = re.compile(r"^\s*[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?\s*$")
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def value_fits(value, ch_type: str) -> bool:
|
|
196
|
+
"""Whether a value can be written into a column of this type as it is: a number for a numeric column (a list of
|
|
197
|
+
numbers for an Array of them), anything for the rest. A value that does not fit is the value of an expression around
|
|
198
|
+
the column, not of the column."""
|
|
199
|
+
bt = base_type(ch_type or "")
|
|
200
|
+
while bt.startswith(("Array(", "LowCardinality(")):
|
|
201
|
+
bt = base_type(bt[bt.index("(") + 1:-1])
|
|
202
|
+
if not NUMERIC_TYPE.match(bt):
|
|
203
|
+
return True
|
|
204
|
+
items = value if isinstance(value, list) else [value]
|
|
205
|
+
return all(isinstance(x, (int, float)) or (isinstance(x, str) and (bool(NUMBER.match(x)) or (bt == "Bool" and x.lower() in ("true", "false"))))
|
|
206
|
+
for x in items if x is not None)
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def fixture_for(cand: dict, real_rows: int, real_columns: list[dict]) -> dict | None:
|
|
210
|
+
"""The candidate's own rows in one table: its parameter values and the code's literals, on a share of the rows from
|
|
211
|
+
production's median run. None when the candidate pins no value of this table."""
|
|
212
|
+
values = []
|
|
213
|
+
pinned = {}
|
|
214
|
+
columns = {c["name"] for c in real_columns}
|
|
215
|
+
types = {c["name"]: c.get("type", "") for c in real_columns}
|
|
216
|
+
# the code's literals in the filters first, then the parameters of the filters: a value compared in the SELECT list
|
|
217
|
+
# (`if(kind = ?, ...)`) decides nothing about which rows are read, and a time column gets its range, not a value
|
|
218
|
+
for col, lits in _literal_equalities(cand.get("baseline_sql") or "", columns, filters_only=True).items():
|
|
219
|
+
if not TIME_TYPE.match(base_type(types.get(col, ""))) and value_fits(lits[0], types.get(col, "")):
|
|
220
|
+
pinned.setdefault(col, lits[0])
|
|
221
|
+
for name, p in ((cand.get("observed") or {}).get("params") or {}).items():
|
|
222
|
+
col = p.get("column")
|
|
223
|
+
# a parameter with a time form is compared with an expression of the column (`toDate(fromUnixTimestamp64Milli(
|
|
224
|
+
# event_time)) IN ({p:String})` on a UInt64 of epoch ms): its value is a day, not a value the column holds, and
|
|
225
|
+
# written into the column it was "Cannot parse string '2026-11-29' as UInt64"
|
|
226
|
+
if (col in columns and p.get("op") in ("=", "==", "in") and name in (cand.get("params") or {}) and not p.get("time")
|
|
227
|
+
and p.get("clause") in ("where", "prewhere", "on", "having") and not TIME_TYPE.match(base_type(types.get(col, "")))
|
|
228
|
+
and value_fits(cand["params"][name], types.get(col, ""))):
|
|
229
|
+
pinned.setdefault(col, cand["params"][name])
|
|
230
|
+
for col, value in pinned.items():
|
|
231
|
+
values.append({"column": col, "value": value})
|
|
232
|
+
if not values:
|
|
233
|
+
return None
|
|
234
|
+
o = cand.get("observed") or {}
|
|
235
|
+
spread = (o.get("production") or {}).get("spread") or {}
|
|
236
|
+
rows_read = (spread.get("rows_read") or [None])[0] if spread else None
|
|
237
|
+
rows_read = rows_read if rows_read is not None else o.get("rows_read_per_run")
|
|
238
|
+
share = min(max(float(rows_read or 0) / real_rows, MIN_SHARE), MAX_SHARE) if real_rows else 0.01
|
|
239
|
+
returned = (spread.get("rows_returned") or [None])[0] if spread else o.get("rows_returned_per_run")
|
|
240
|
+
# the time columns of this table the run's window bounds: the share must hold the rows read inside that window
|
|
241
|
+
hours = float(o.get("time_window_hours") or 24)
|
|
242
|
+
window = sorted({p["column"] for p in (o.get("params") or {}).values() if p.get("time") and p.get("column") in columns
|
|
243
|
+
and p["time"].get("at") in ("start", "end")})
|
|
244
|
+
return {"id": cand["finding"], "values": values, "share": round(share, 6), "min_rows": max(min(int(returned or 1), 10_000), 1),
|
|
245
|
+
# bench.target_shares turns these into the share of the sandbox table at each scale: rows that read like the
|
|
246
|
+
# median run, inside the run's time window (the real table's share would be a few rows of a scaled table)
|
|
247
|
+
"target_rows": int(rows_read or 0), **({"window": {"columns": window, "hours": hours}} if window else {}),
|
|
248
|
+
"basis": "catalog, no agent: production's median rows read per run, inside the run's time window, as rows of the sandbox table"}
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def joins_of(sql: str, tables: list[str]) -> list[tuple[str, str, list[tuple[str, str]]]]:
|
|
252
|
+
"""The joins between two of `tables` a statement makes: [(left table, right table, [(left column, right column)])].
|
|
253
|
+
|
|
254
|
+
`... FROM a ... JOIN (SELECT ... FROM b ...) AS x USING (k1, k2)` and `JOIN b ON a.k = b.k AND ...`. The left table is
|
|
255
|
+
the last of `tables` named before the JOIN, the right one the first named after it."""
|
|
256
|
+
from .observed import tokens
|
|
257
|
+
toks = tokens(sql or "")
|
|
258
|
+
names = {t.lower() for t in tables}
|
|
259
|
+
out = []
|
|
260
|
+
for i, t in enumerate(toks):
|
|
261
|
+
if t["key"] != "join":
|
|
262
|
+
continue
|
|
263
|
+
left = next((x["key"].rsplit(".", 1)[-1] for x in reversed(toks[:i]) if x["kind"] == "ident" and x["key"].rsplit(".", 1)[-1] in names), None)
|
|
264
|
+
right_at = next((j for j in range(i + 1, len(toks)) if toks[j]["kind"] == "ident" and toks[j]["key"].rsplit(".", 1)[-1] in names), None)
|
|
265
|
+
if left is None or right_at is None:
|
|
266
|
+
continue
|
|
267
|
+
right = toks[right_at]["key"].rsplit(".", 1)[-1]
|
|
268
|
+
if left == right:
|
|
269
|
+
continue
|
|
270
|
+
# the join's own condition: the first USING ( ... ) or ON ... at the JOIN's depth after its right side
|
|
271
|
+
depth, k = 0, i + 1
|
|
272
|
+
pairs: list[tuple[str, str]] = []
|
|
273
|
+
while k < len(toks):
|
|
274
|
+
x = toks[k]
|
|
275
|
+
depth += x["text"] == "("
|
|
276
|
+
depth -= x["text"] == ")"
|
|
277
|
+
if depth < 0:
|
|
278
|
+
break
|
|
279
|
+
if depth == 0 and x["key"] == "using" and k + 1 < len(toks) and toks[k + 1]["text"] == "(":
|
|
280
|
+
m = k + 2
|
|
281
|
+
while m < len(toks) and toks[m]["text"] != ")":
|
|
282
|
+
if toks[m]["kind"] == "ident":
|
|
283
|
+
pairs.append((toks[m]["key"], toks[m]["key"]))
|
|
284
|
+
m += 1
|
|
285
|
+
break
|
|
286
|
+
if depth == 0 and x["key"] == "on":
|
|
287
|
+
m = k + 1
|
|
288
|
+
|
|
289
|
+
def operand(at: int) -> tuple[str | None, int]:
|
|
290
|
+
"""A column, qualified or not (`u.user_id`), at token `at`: (its name, the index after it)."""
|
|
291
|
+
if at >= len(toks) or toks[at]["kind"] != "ident":
|
|
292
|
+
return None, at
|
|
293
|
+
while at + 2 < len(toks) and toks[at + 1]["text"] == "." and toks[at + 2]["kind"] == "ident":
|
|
294
|
+
at += 2
|
|
295
|
+
return toks[at]["key"], at + 1
|
|
296
|
+
|
|
297
|
+
while m < len(toks) and toks[m]["key"] not in ("join", "where", "group", "order", "limit", "settings", "union"):
|
|
298
|
+
a, after = operand(m)
|
|
299
|
+
if a and after + 1 < len(toks) and toks[after]["text"] in ("=", "=="):
|
|
300
|
+
b, end = operand(after + 1)
|
|
301
|
+
if b:
|
|
302
|
+
pairs.append((a, b))
|
|
303
|
+
m = end
|
|
304
|
+
continue
|
|
305
|
+
m = max(after, m + 1)
|
|
306
|
+
break
|
|
307
|
+
if depth == 0 and x["key"] in ("join", "where", "group", "order", "limit", "union", "settings"):
|
|
308
|
+
break
|
|
309
|
+
k += 1
|
|
310
|
+
if pairs:
|
|
311
|
+
out.append((left, right, pairs))
|
|
312
|
+
return out
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def join_key_value(cand: dict, column: str, ch_type: str):
|
|
316
|
+
"""One value of a join key both sides of a candidate's own rows hold, of the key's type: `user_id-q-001`, a number,
|
|
317
|
+
or a UUID derived from the finding. None for a type it can not be written as (a time, a container)."""
|
|
318
|
+
import uuid as uuid_mod
|
|
319
|
+
import zlib
|
|
320
|
+
bt = base_type(ch_type or "")
|
|
321
|
+
seed = f"{cand.get('finding', '')}:{column}"
|
|
322
|
+
if bt == "UUID":
|
|
323
|
+
# "qopt:": the seed from before the rename (formerly qopt), kept so the generated values stay the same
|
|
324
|
+
return str(uuid_mod.uuid5(uuid_mod.NAMESPACE_URL, f"qopt:{seed}"))
|
|
325
|
+
if re.match(r"U?Int\d+$", bt):
|
|
326
|
+
return 100 if bt.endswith("Int8") else 1_000_000 + zlib.crc32(seed.encode()) % 1_000_000
|
|
327
|
+
if bt.startswith(("String", "FixedString")) or bt == "":
|
|
328
|
+
return f"{column}-{str(cand.get('finding', '')).lower()}"
|
|
329
|
+
return None
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def pin_join_keys(by_table: dict, cand: dict, types: dict[str, dict[str, str]] | None = None) -> list[str]:
|
|
333
|
+
"""A candidate's own rows in two tables a relation joins meet on the join key: the parent's fixture rows and the
|
|
334
|
+
child's get one key value of their own, unless the child's fixture already pins a column the relation carries.
|
|
335
|
+
Without it the child's fixture rows (`enabled = 7`) pick parents by a hash of the row number, almost never the
|
|
336
|
+
parent's fixture rows (`revoked = 7`), and the join of the candidate's rows returned nothing where production's
|
|
337
|
+
returns rows ("the parameters match no rows")."""
|
|
338
|
+
notes = []
|
|
339
|
+
fid = cand.get("finding")
|
|
340
|
+
tables = [t for t in cand.get("tables") or [] if t in by_table]
|
|
341
|
+
for child_name in tables:
|
|
342
|
+
child = by_table[child_name]
|
|
343
|
+
cfx = next((f for f in child.get("fixtures") or [] if f.get("id") == fid), None)
|
|
344
|
+
if cfx is None:
|
|
345
|
+
continue
|
|
346
|
+
for rel in child.get("relations") or []:
|
|
347
|
+
pname = rel.get("parent_table")
|
|
348
|
+
parent = by_table.get(pname)
|
|
349
|
+
if parent is None or pname not in tables or pname == child_name:
|
|
350
|
+
continue
|
|
351
|
+
pfx = next((f for f in parent.get("fixtures") or [] if f.get("id") == fid), None)
|
|
352
|
+
if pfx is None:
|
|
353
|
+
continue
|
|
354
|
+
carried = {rel["column"]} | {s["column"] for s in rel.get("same_as_parent") or []}
|
|
355
|
+
if {v["column"] for v in cfx.get("values") or []} & carried:
|
|
356
|
+
continue # the child's rows already follow the parent's fixture rows through a shared value
|
|
357
|
+
ptype = ((types or {}).get(pname) or {}).get(rel["parent_column"], "")
|
|
358
|
+
ctype = ((types or {}).get(child_name) or {}).get(rel["column"], "")
|
|
359
|
+
have = next((v["value"] for v in pfx.get("values") or [] if v["column"] == rel["parent_column"]), None)
|
|
360
|
+
value = have if have is not None else join_key_value(cand, rel["parent_column"], ptype or ctype)
|
|
361
|
+
if value is None or (ctype and ptype and base_type(ctype) != base_type(ptype) and not value_fits(value, ctype)):
|
|
362
|
+
continue
|
|
363
|
+
if have is None:
|
|
364
|
+
pfx.setdefault("values", []).append({"column": rel["parent_column"], "value": value})
|
|
365
|
+
cfx.setdefault("values", []).append({"column": rel["column"], "value": value})
|
|
366
|
+
notes.append(f"{fid}: its rows in {child_name} and {pname} share the join key value of {rel['column']}")
|
|
367
|
+
return notes
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def link_joins(by_table: dict, cand: dict, agent_tables: set[str]) -> list[str]:
|
|
371
|
+
"""Rows of two catalog-only tables that a statement joins (`USING (account_id, user_id)`) are made to
|
|
372
|
+
correspond: the right table's first join column follows the left table's rows (relations.py), its other join columns
|
|
373
|
+
and the fixture's columns both tables have (tenant, region) come with the parent row. Generated one by one, the
|
|
374
|
+
join of two such tables found no row, where production's finds the tenant's entities. Returns a note per relation."""
|
|
375
|
+
notes = []
|
|
376
|
+
fixture_cols = [v["column"] for t in by_table.values() for f in t.get("fixtures") or [] if f.get("id") == cand.get("finding")
|
|
377
|
+
for v in f.get("values") or []]
|
|
378
|
+
for left, right, pairs in joins_of(cand.get("baseline_sql") or "", cand.get("tables") or []):
|
|
379
|
+
if left in agent_tables or right in agent_tables or left not in by_table or right not in by_table:
|
|
380
|
+
continue
|
|
381
|
+
|
|
382
|
+
def own_key(table: str, cols: list[str]) -> bool:
|
|
383
|
+
specs_ = {c["name"]: c for c in by_table[table].get("columns") or []}
|
|
384
|
+
return any((specs_.get(c) or {}).get("kind") == "unique" for c in cols)
|
|
385
|
+
if own_key(right, [b for _, b in pairs]) and not own_key(left, [a for a, _ in pairs]):
|
|
386
|
+
# the right table holds one row per key (users by user_id): it is the parent, the left one follows it
|
|
387
|
+
left, right, pairs = right, left, [(b, a) for a, b in pairs]
|
|
388
|
+
child = by_table[right]
|
|
389
|
+
left_cols = {c["name"] for c in by_table[left].get("columns") or []}
|
|
390
|
+
specs = {c["name"]: c for c in child.get("columns") or []}
|
|
391
|
+
pairs = [(a, b) for a, b in pairs if a in left_cols and b in specs]
|
|
392
|
+
if not pairs:
|
|
393
|
+
continue
|
|
394
|
+
# the identifying column: the join column with the most distinct values (an id, not a type or a tenant)
|
|
395
|
+
ident = max(pairs, key=lambda p: (specs[p[1]].get("kind") == "unique", int(specs[p[1]].get("distinct") or 0) if specs[p[1]].get("kind") == "key" else -1))
|
|
396
|
+
if any(r.get("parent_table") == left or r.get("column") == ident[1] for r in child.get("relations") or []):
|
|
397
|
+
continue
|
|
398
|
+
shared = [(c, c) for c in dict.fromkeys(fixture_cols) if c in left_cols and c in specs and c != ident[1]]
|
|
399
|
+
shared += [(a, b) for a, b in pairs if (a, b) != ident and (a, b) not in shared]
|
|
400
|
+
child.setdefault("relations", []).append({
|
|
401
|
+
"column": ident[1], "parent_table": left, "parent_column": ident[0],
|
|
402
|
+
"same_as_parent": [{"column": b, "parent_column": a} for a, b in shared],
|
|
403
|
+
"basis": f"catalog, no agent: the statement production ran ({cand.get('finding')}) joins {left} and {right} on "
|
|
404
|
+
+ ", ".join(a if a == b else f"{a} = {b}" for a, b in pairs)})
|
|
405
|
+
notes.append(f"{right}.{ident[1]} follows {left}'s rows (the statement production ran joins them)")
|
|
406
|
+
return notes
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def link_times(table: dict, cand: dict, name: str) -> None:
|
|
410
|
+
"""The time columns of this table that one candidate's window bounds together (`created_at` and `event_time`) hold
|
|
411
|
+
the same moment: they get one spread and one draw (datagen `time_seed`). Drawn independently, a window of 24 h on
|
|
412
|
+
two columns spread over 30 days meets one row in 900. The first of them with the real spread by partition leads."""
|
|
413
|
+
o = cand.get("observed") or {}
|
|
414
|
+
bounded = [p["column"] for p in (o.get("params") or {}).values() if p.get("time") and p["time"].get("at") in ("start", "end") and p.get("column")]
|
|
415
|
+
specs = {c["name"]: c for c in table["columns"] if c.get("kind") == "timestamp"}
|
|
416
|
+
together = list(dict.fromkeys(c for c in bounded if c in specs))
|
|
417
|
+
if len(together) < 2:
|
|
418
|
+
return
|
|
419
|
+
lead = next((c for c in together if specs[c].get("by_age")), together[0])
|
|
420
|
+
seed = specs[lead].get("time_seed") or f"{name}:{lead}"
|
|
421
|
+
for c in together:
|
|
422
|
+
s = specs[c]
|
|
423
|
+
s.update(time_seed=seed, days_back=specs[lead].get("days_back"), distribution=specs[lead].get("distribution"))
|
|
424
|
+
if specs[lead].get("by_age"):
|
|
425
|
+
s["by_age"] = specs[lead]["by_age"]
|
|
426
|
+
if c != lead and "one moment with" not in s.get("source", ""):
|
|
427
|
+
s["source"] = s.get("source", "") + f"; one moment with {lead} (a statement bounds both by one window)"
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
def augment(rank: dict | None, profile: dict | None, observed: dict, facts, engine: str) -> tuple[dict, dict, list[str]]:
|
|
431
|
+
"""rank.json and profile.json with the observed candidates added: their tables' real definitions, a mechanical data
|
|
432
|
+
profile for each table the agent's profile does not describe, and a fixture of each candidate's own. Copies; the
|
|
433
|
+
files on disk are not changed. Returns (rank, profile, notes)."""
|
|
434
|
+
rank = copy.deepcopy(rank) if rank else {"engine": engine, "engine_version": "", "candidates": [], "table_definitions": [],
|
|
435
|
+
"agent": {"runner": "", "model": "", "cost_usd": 0.0}, "shortlist": [], "rejected": []}
|
|
436
|
+
profile = copy.deepcopy(profile) if profile else {"engine": engine, "tables": []}
|
|
437
|
+
notes: list[str] = []
|
|
438
|
+
have = {d["name"] for d in rank.get("table_definitions") or []}
|
|
439
|
+
by_table = {t["name"]: t for t in profile.get("tables") or []}
|
|
440
|
+
told: set[str] = set()
|
|
441
|
+
real = facts.tables(engine)
|
|
442
|
+
agent_tables = {t["name"] for t in profile.get("tables") or [] if t.get("basis") != "catalog, no agent"}
|
|
443
|
+
for cand in observed.get("candidates") or []:
|
|
444
|
+
if any(c.get("finding") == cand["finding"] for c in rank["candidates"]):
|
|
445
|
+
continue
|
|
446
|
+
cand = copy.deepcopy(cand)
|
|
447
|
+
# which description each table's data comes from: the agent's profile where it has one, else the catalog alone
|
|
448
|
+
cand.setdefault("observed", {})["profile_basis"] = {n: AGENT if n in agent_tables else CATALOG for n in cand.get("tables") or []}
|
|
449
|
+
epochs = (cand.get("observed") or {}).get("epoch_columns") or {}
|
|
450
|
+
rank["candidates"].append(cand)
|
|
451
|
+
for name in cand.get("tables") or []:
|
|
452
|
+
if name not in have:
|
|
453
|
+
d = facts.definition(engine, name)
|
|
454
|
+
if d:
|
|
455
|
+
rank["table_definitions"].append(d)
|
|
456
|
+
have.add(name)
|
|
457
|
+
t = real.get(name) or {}
|
|
458
|
+
cols = t.get("columns") or []
|
|
459
|
+
names = {c["name"] for c in cols}
|
|
460
|
+
if t and (name not in by_table or name not in agent_tables):
|
|
461
|
+
# catalog only: the first candidate on the table builds it, a later one adds the columns it uses besides
|
|
462
|
+
sorting = [s.strip() for s in re.split(r",\s*", t.get("sorting_key") or "") if s.strip()]
|
|
463
|
+
lits = _literal_equalities(cand.get("baseline_sql") or "", names)
|
|
464
|
+
# columns of the partition key: their distinct values multiply into the partitions, so together they make
|
|
465
|
+
# about as many as the real table has (a guessed count per column would make one partition per row)
|
|
466
|
+
keyed = [c["name"] for c in cols if c.get("in_partition_key") and not TIME_TYPE.match(base_type(c.get("type", "")))]
|
|
467
|
+
used = _used_columns(cand.get("baseline_sql") or "", cols, sorting + keyed + [c["name"] for c in cols if c.get("in_partition_key")])
|
|
468
|
+
last = sorting[-1] if sorting and DEDUPLICATING.search(t.get("engine") or "") else None
|
|
469
|
+
per = max(round(int(t.get("partitions") or 1) ** (1 / len(keyed))), 1) if keyed else None
|
|
470
|
+
timed, shares = time_shares(facts, engine, name)
|
|
471
|
+
table = by_table.get(name)
|
|
472
|
+
if table is None:
|
|
473
|
+
table = {"name": name, "rows": int(t.get("rows") or 0), "rows_basis": "real catalog", "rows_confidence": "high",
|
|
474
|
+
"basis": "catalog, no agent", "columns": [], "fixtures": [], "relations": []}
|
|
475
|
+
described = {c["name"] for c in table["columns"] if not c.get("filler")}
|
|
476
|
+
for c in used:
|
|
477
|
+
if c["name"] in described:
|
|
478
|
+
continue
|
|
479
|
+
spec = column_spec(c, int(t.get("rows") or 0), sorting=sorting, days_back=_days_back(t), literals=lits.get(c["name"]),
|
|
480
|
+
unique=c["name"] == last, epoch=epochs.get(c["name"]), by_age=shares if c["name"] == timed else None)
|
|
481
|
+
if c["name"] in keyed and spec.get("kind") == "key":
|
|
482
|
+
spec["distinct"] = per
|
|
483
|
+
spec["source"] = SOURCE + f"; a column of the partition key: {per} values, so the partitions are about the real {t.get('partitions')}"
|
|
484
|
+
# a filler at the column's real size gives way to the column's own description
|
|
485
|
+
table["columns"] = [x for x in table["columns"] if x["name"] != c["name"]] + [spec]
|
|
486
|
+
link_times(table, cand, name)
|
|
487
|
+
profile_mod.apply_facts(table, engine, facts) # safe again: the real sizes of the columns added
|
|
488
|
+
if name not in by_table:
|
|
489
|
+
profile.setdefault("tables", []).append(table)
|
|
490
|
+
by_table[name] = table
|
|
491
|
+
notes.append(f"{name}: catalog only (no agent profile describes it): {len(table['columns'])} columns")
|
|
492
|
+
elif name in by_table and t:
|
|
493
|
+
# the agent's profile describes the table: its description is used. A column the statement compares with
|
|
494
|
+
# literals, or reads as a time, that the profile does not describe is added, so the candidate's rows exist
|
|
495
|
+
described = {c["name"] for c in by_table[name].get("columns") or []}
|
|
496
|
+
for col, lits in _literal_equalities(cand.get("baseline_sql") or "", names).items():
|
|
497
|
+
if col not in described:
|
|
498
|
+
c = next(x for x in cols if x["name"] == col)
|
|
499
|
+
by_table[name]["columns"].append(column_spec(c, int(t.get("rows") or 0), sorting=[], days_back=30, literals=lits))
|
|
500
|
+
described.add(col)
|
|
501
|
+
for col, unit in epochs.items():
|
|
502
|
+
if col not in described and col in names:
|
|
503
|
+
c = next(x for x in cols if x["name"] == col)
|
|
504
|
+
by_table[name]["columns"].append(column_spec(c, int(t.get("rows") or 0), sorting=[], days_back=30, literals=None, epoch=unit))
|
|
505
|
+
if name not in told and name in agent_tables:
|
|
506
|
+
told.add(name)
|
|
507
|
+
notes.append(f"{name}: agent profile (profile.json) describes it; the statements production ran use it")
|
|
508
|
+
if name in by_table:
|
|
509
|
+
fx = fixture_for(cand, int(t.get("rows") or by_table[name].get("rows") or 0), cols)
|
|
510
|
+
if fx:
|
|
511
|
+
by_table[name].setdefault("fixtures", []).append(fx)
|
|
512
|
+
notes += link_joins(by_table, cand, agent_tables)
|
|
513
|
+
notes += pin_join_keys(by_table, cand, {n: {c["name"]: c.get("type", "") for c in (real.get(n) or {}).get("columns") or []}
|
|
514
|
+
for n in cand.get("tables") or []})
|
|
515
|
+
return rank, profile, notes
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
def production(observed: dict) -> dict[str, dict]:
|
|
519
|
+
"""finding -> what the query log measured per run of the shape, for the fidelity grade and the fit (bench)."""
|
|
520
|
+
out = {}
|
|
521
|
+
for c in observed.get("candidates") or []:
|
|
522
|
+
p = (c.get("observed") or {}).get("production")
|
|
523
|
+
if p and p.get("rows_read_per_run") is not None:
|
|
524
|
+
out[c["finding"]] = dict(p)
|
|
525
|
+
return out
|