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/observed.py
ADDED
|
@@ -0,0 +1,1868 @@
|
|
|
1
|
+
"""The statement production ran, as the baseline: for SQL that code assembles at run time. Local only: no database, no agent.
|
|
2
|
+
|
|
3
|
+
A pulled query log (`codecop db pull`) holds, per query shape, the server's normalized text: the statement as it ran with
|
|
4
|
+
every literal and parameter replaced by `?`. For a call site matched to such a shape (realdb/match.py), that text is
|
|
5
|
+
what the code really sends, and it is used as the baseline in four steps:
|
|
6
|
+
|
|
7
|
+
1 · pick the shapes tied to a call site, heaviest first: every shape with at least `shape_min_share` of the site's
|
|
8
|
+
measured bytes, at most `max_shapes_per_site` (settings under `[dynamic]` in codecop.toml). The rest is counted.
|
|
9
|
+
2 · fill put back what the server wrote as `?`, from three sources in this order: the code's own text, aligned with
|
|
10
|
+
the shape token by token (a literal such as 'UTC', a parameter such as {tenant:String}); the catalog (a `?`
|
|
11
|
+
compared with a column takes that column's type and becomes a named parameter; LIMIT ? is a count); and,
|
|
12
|
+
outside the filters only, a neutral value of the type the position needs (`neutral_values`). A `?` that
|
|
13
|
+
none of them types stays open.
|
|
14
|
+
3 · gate the runnable text, normalized again by the matcher's own `shape`, must equal the observed shape. Nothing
|
|
15
|
+
that fills a value can change the structure of the statement production ran. A candidate that fails the gate,
|
|
16
|
+
or keeps an open value, is not benchmarked; the gate's output says why (`assembled_shape_rejected`).
|
|
17
|
+
4 · values each named parameter gets a value the sandbox data holds (catalog_profile.py builds that data); the existing
|
|
18
|
+
fit (fidelity.py) then moves shares, gives the heavy run its own values and makes empty typical runs empty, so
|
|
19
|
+
the typical run and the heavy run read and return like the shape's median and 99th-percentile run. A time is
|
|
20
|
+
kept as where it falls in the run's window (`time`: start, end or middle, and its form); bench.anchor_times
|
|
21
|
+
ends the window at the newest row the sandbox holds.
|
|
22
|
+
|
|
23
|
+
Typing a `?` (place_of): the column it is compared with, through a function whose result type is known (RETURNS) and
|
|
24
|
+
never through one whose is not; the function it is passed to (FUNCTION_ARGS: `toUUID(?)`, a time zone); a sibling
|
|
25
|
+
value (`coalesce(col, ?)`, the else of a multiIf); the alias it is compared with (`day IN ?` where `toDate(ts) AS day`);
|
|
26
|
+
a number column the statement itself reads as a time (epoch_units). What none of them types stays open, and the gate
|
|
27
|
+
refuses it.
|
|
28
|
+
|
|
29
|
+
Every candidate carries two labels. `sql_from`: where its SQL text comes from (`code`, `orm`, `query_log`,
|
|
30
|
+
`code_variants`, `agent`). `located`: where its place in code comes from (`exact`, `template`, `tag`, `part`, `likely`,
|
|
31
|
+
`none`; `site` for SQL written at the call site itself). Only `exact`, `template` and `tag` put a file and line on a
|
|
32
|
+
finding; `part` names the files whose text is inside the statement ("one of the places that build it"); `likely` is
|
|
33
|
+
only ever a list of possible places.
|
|
34
|
+
|
|
35
|
+
Pieces: a call site whose whole SQL is one piece of a longer statement gets that whole statement as its
|
|
36
|
+
candidate, located `part`. The cost is the statement's, never a piece's.
|
|
37
|
+
|
|
38
|
+
Production statements with no place in code are listed with their load and tables, and the `likely` matches
|
|
39
|
+
as possible places, never as a file and line.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
from __future__ import annotations
|
|
43
|
+
|
|
44
|
+
import difflib
|
|
45
|
+
import json
|
|
46
|
+
import re
|
|
47
|
+
from datetime import datetime, timedelta, timezone
|
|
48
|
+
|
|
49
|
+
from .agent import AgentError, UsageLimitError
|
|
50
|
+
from .realdb import match as match_mod
|
|
51
|
+
from .realdb.facts import production_resources
|
|
52
|
+
|
|
53
|
+
SCHEMA_VERSION = 1
|
|
54
|
+
DEFAULTS = {
|
|
55
|
+
"shape_min_share": 0.05, # a shape with at least this share of its call site's measured bytes becomes a candidate
|
|
56
|
+
"max_shapes_per_site": 8, # ... heaviest first, at most this many per call site
|
|
57
|
+
"neutral_values": True, # outside the filters, a `?` no source types gets a neutral value of the type its place needs
|
|
58
|
+
"observed_for": "unresolved", # unresolved: call sites the agent could not resolve (or never saw); all: every sure match
|
|
59
|
+
"time_window_hours": 24, # a time range compared with a parameter is given this many hours, ending now
|
|
60
|
+
"unlocated_min_share": 0.0, # production statements with no place in code: listed from this share of all bytes read
|
|
61
|
+
"unlocated_max": 500, # ... at most this many, heaviest first
|
|
62
|
+
# a read with no place in code (or only a likely one) becomes a benchmark candidate too: on these engines (postgres,
|
|
63
|
+
# all, none). ClickHouse's are built per scenario (scenario_bind, SB-001) and its tables can be large
|
|
64
|
+
"unlocated_candidates": "postgres",
|
|
65
|
+
"unlocated_candidate_min_share": 0.001, # ... from this share of all bytes read
|
|
66
|
+
"unlocated_candidates_max": 200, # ... at most this many, heaviest first
|
|
67
|
+
}
|
|
68
|
+
TEXT_CUT_BEFORE_SETTING = 20_000 # the texts statement cut every text here before db_pull.text_max_chars existed
|
|
69
|
+
SQL_FROM = ("code", "orm", "query_log", "code_variants", "agent")
|
|
70
|
+
LOCATED = ("exact", "template", "tag", "part", "likely", "none", "site")
|
|
71
|
+
PLACES = ("exact", "template", "tag") # the grades that may put a file and line on a finding
|
|
72
|
+
GATE_REASONS = ("shape_differs", "value_type_open", "identifier_masked", "external_data", "text_cut_at_limit", "no_text",
|
|
73
|
+
"ambiguous_template", "table_not_in_catalog")
|
|
74
|
+
# why a pulled statement is not a candidate before the gate: candidates are reads only (a write changes the data the
|
|
75
|
+
# benchmark compares results on), and a statement that reads only the server's own catalog is tooling, not app load
|
|
76
|
+
NOT_CANDIDATE = ("not_a_read", "tooling")
|
|
77
|
+
WRITES_IN_WITH = re.compile(r"\b(?:insert\s+into|update\s+[\w.\"`]+(?:\s+(?:as\s+)?\w+)?\s+set|delete\s+from|merge\s+into)\b", re.I)
|
|
78
|
+
READ_FIRST_WORDS = ("select", "with", "(", "values", "table")
|
|
79
|
+
CATALOG_NAMES = ("one", "numbers", "tables", "columns", "parts", "query_log") # ClickHouse system tables read unqualified
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def is_read(text: str, kind: str | None = None) -> bool:
|
|
83
|
+
"""A statement that only reads: SELECT, or WITH ... SELECT whose CTEs change nothing. The pull's `kind` decides
|
|
84
|
+
first when it says a write; the text decides the rest (a WITH can hold an INSERT, UPDATE or DELETE)."""
|
|
85
|
+
k = (kind or "").strip().lower()
|
|
86
|
+
if k and k not in ("select", "with"):
|
|
87
|
+
return False
|
|
88
|
+
body = re.sub(r"'(?:[^'\\]|\\.|'')*'", "''", re.sub(r"/\*.*?\*/|--[^\n]*", " ", text or "", flags=re.S)).strip().lower()
|
|
89
|
+
first = re.match(r"\(|[a-z]+", body)
|
|
90
|
+
if not first or first.group(0) not in READ_FIRST_WORDS:
|
|
91
|
+
return False
|
|
92
|
+
return not WRITES_IN_WITH.search(body)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def catalog_table(name: str, text: str = "") -> bool:
|
|
96
|
+
"""A table of the server's own catalog: ClickHouse system.*, PostgreSQL pg_* and information_schema.* (the log
|
|
97
|
+
often names information_schema views unqualified in its table list: `columns`, so the text decides)."""
|
|
98
|
+
n = (name or "").strip('`"').lower()
|
|
99
|
+
short = n.rsplit(".", 1)[-1]
|
|
100
|
+
if n.startswith(("system.", "information_schema.", "pg_catalog.")) or short.startswith("pg_") or n == "system":
|
|
101
|
+
return True
|
|
102
|
+
if text and re.search(r"\b(?:information_schema|pg_catalog)\s*\.\s*\"?" + re.escape(short) + r"\b", text, re.I):
|
|
103
|
+
return True
|
|
104
|
+
return short in CATALOG_NAMES and not text
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def tables_of(text: str, listed: list[str] | None, engine: str) -> list[str]:
|
|
108
|
+
"""The tables a pulled statement reads, without database or quotes. The pull's list when it has one; else, for
|
|
109
|
+
PostgreSQL (pg_stat_statements lists no tables), the statement parsed: every table it names that is not one of its
|
|
110
|
+
own CTEs (a regex over FROM and JOIN also takes `EXTRACT(EPOCH FROM col)` and CTE names for tables). The matcher's
|
|
111
|
+
FROM/JOIN reading when the text does not parse."""
|
|
112
|
+
got = sorted(match_mod.short_tables(listed or []))
|
|
113
|
+
if engine != "postgres" and (got or not text):
|
|
114
|
+
return got or sorted(match_mod.tables_in(match_mod.shape(text)))
|
|
115
|
+
if engine == "postgres" and text:
|
|
116
|
+
# the matched row's list for PostgreSQL is the matcher's FROM/JOIN reading of the text, not the server's
|
|
117
|
+
try:
|
|
118
|
+
import sqlglot
|
|
119
|
+
from sqlglot import exp
|
|
120
|
+
tree = sqlglot.parse_one(text, read="postgres")
|
|
121
|
+
ctes = {c.alias_or_name.lower() for c in tree.find_all(exp.CTE)}
|
|
122
|
+
names = {t.name.lower() for t in tree.find_all(exp.Table) if t.name and t.name.lower() not in ctes}
|
|
123
|
+
if names:
|
|
124
|
+
return sorted(names)
|
|
125
|
+
except Exception: # a statement sqlglot can not read: the matcher's reading
|
|
126
|
+
pass
|
|
127
|
+
return got or sorted(match_mod.tables_in(match_mod.shape(text)))
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def tooling(tables: list[str], text: str = "", user_tables: set[str] | None = None) -> bool:
|
|
131
|
+
"""A statement that reads the server's own catalog only (a schema browser, a migration tool, a monitoring query):
|
|
132
|
+
tooling, not the application's load. A name the log lists that is not a catalog table counts as the application's
|
|
133
|
+
only when it is a table of the pulled catalog (`user_tables`); a CTE's name is not."""
|
|
134
|
+
named = [str(t).strip('`"').lower() for t in tables or [] if t]
|
|
135
|
+
cat = {t for t in named if catalog_table(t, text)}
|
|
136
|
+
if not cat:
|
|
137
|
+
return False
|
|
138
|
+
return all(t in cat or (user_tables is not None and t.rsplit(".", 1)[-1] not in user_tables) for t in named)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def settings_of(config: dict | None) -> dict:
|
|
142
|
+
"""The `[dynamic]` table of codecop.toml over the defaults. A value of the wrong kind is refused."""
|
|
143
|
+
out = dict(DEFAULTS)
|
|
144
|
+
for key, default in DEFAULTS.items():
|
|
145
|
+
value = (config or {}).get(key)
|
|
146
|
+
if value is None:
|
|
147
|
+
continue
|
|
148
|
+
if isinstance(default, bool):
|
|
149
|
+
if not isinstance(value, bool):
|
|
150
|
+
raise ValueError(f"dynamic.{key} must be true or false.")
|
|
151
|
+
elif isinstance(default, str):
|
|
152
|
+
allowed = ("postgres", "clickhouse", "all", "none") if key == "unlocated_candidates" else ("unresolved", "all")
|
|
153
|
+
if value not in allowed:
|
|
154
|
+
raise ValueError(f"dynamic.{key} must be one of {', '.join(allowed)}.")
|
|
155
|
+
elif isinstance(value, bool) or not isinstance(value, (int, float)) or value < 0:
|
|
156
|
+
raise ValueError(f"dynamic.{key} must be a number of zero or more.")
|
|
157
|
+
elif isinstance(default, int) and not isinstance(value, int):
|
|
158
|
+
raise ValueError(f"dynamic.{key} must be a whole number.")
|
|
159
|
+
out[key] = value
|
|
160
|
+
return out
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
# ---- the labels on every candidate ---------------------------------------------------------------------------------
|
|
164
|
+
|
|
165
|
+
def sql_from_of(cand: dict, site: dict | None) -> str:
|
|
166
|
+
"""Where a candidate's SQL text comes from. An observed statement says so itself; for the agent's candidates the call
|
|
167
|
+
site decides: ORM calls are translated, fixed text is the code's, and run-time parts were written out by the agent."""
|
|
168
|
+
if cand.get("sql_from") in SQL_FROM:
|
|
169
|
+
return cand["sql_from"]
|
|
170
|
+
s = site or cand.get("site") or {}
|
|
171
|
+
if s.get("resolution") == "orm":
|
|
172
|
+
return "orm"
|
|
173
|
+
if s.get("resolution") in ("template", "unresolved", "parameter") or has_fragment(s.get("sql") or cand.get("original_sql") or ""):
|
|
174
|
+
return "agent"
|
|
175
|
+
return "code"
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def located_of(cand: dict) -> str:
|
|
179
|
+
"""Where a candidate's place in code comes from. SQL written at its call site is located by construction (`site`)."""
|
|
180
|
+
return cand["located"] if cand.get("located") in LOCATED else "site"
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def has_fragment(sql: str) -> bool:
|
|
184
|
+
return bool(re.search(r"«[^»]*»|…|\{\{.*?\}\}|\{%.*?%\}", sql or "", re.S))
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
# ---- tokens and alignment ------------------------------------------------------------------------------------------
|
|
188
|
+
|
|
189
|
+
TOKEN = re.compile(r"""
|
|
190
|
+
(?P<ws>\s+)
|
|
191
|
+
| (?P<comment>/\*.*?\*/|--[^\n]*)
|
|
192
|
+
| (?P<str>'(?:[^'\\]|\\.|'')*')
|
|
193
|
+
| (?P<frag>«[^»]*»|\{\{.*?\}\}|\{%.*?%\}|…)
|
|
194
|
+
| (?P<param>\{\w+\s*:[^{}]*\}|%\(\w+\)s|%s|\$\d+|(?<![:\w]):[A-Za-z_]\w*)
|
|
195
|
+
| (?P<qlist>\?\s*\.\.)
|
|
196
|
+
| (?P<q>\?)
|
|
197
|
+
| (?P<num>(?<![\w.])\d+(?:\.\d+)?(?:[eE][+-]?\d+)?(?![\w.]))
|
|
198
|
+
| (?P<ident>`[^`]*`|"[^"]*"|[A-Za-z_][\w$]*)
|
|
199
|
+
| (?P<op>::|<=|>=|<>|!~\*|!~|~\*|!=|&&|\|\||->>|\#>>|->|\#>|@>|<@|.)
|
|
200
|
+
""", re.S | re.X)
|
|
201
|
+
VALUE_KINDS = ("str", "num", "param", "q", "qlist")
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
MASKED = "¤" # an identifier the server masked (normalizeQuery prints a long quoted name as `?`)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def tokens(sql: str) -> list[dict]:
|
|
208
|
+
"""The statement as tokens: {kind, text, key}. `key` is what alignment compares: every value is `?`, a run-time part
|
|
209
|
+
is «», an identifier is compared without quotes or case, a masked identifier is ¤.
|
|
210
|
+
|
|
211
|
+
`_CAST(?.., )`: the server logs a typed parameter ({name:Type}) as `_CAST(value, 'Type')`, which normalizeQuery turns
|
|
212
|
+
into `_CAST(?..)`. It is one value, so it is one token (`cast`), and aligns with the code's {name:Type}."""
|
|
213
|
+
out = []
|
|
214
|
+
for m in TOKEN.finditer(sql or ""):
|
|
215
|
+
kind = m.lastgroup
|
|
216
|
+
if kind in ("ws", "comment"):
|
|
217
|
+
continue
|
|
218
|
+
text = m.group(0)
|
|
219
|
+
key = "?" if kind in VALUE_KINDS else "«»" if kind == "frag" else text.strip('`"').lower() if kind == "ident" else text
|
|
220
|
+
if kind == "ident" and text in ("`?`", '"?"'):
|
|
221
|
+
key = MASKED
|
|
222
|
+
out.append({"kind": kind, "text": text, "key": key})
|
|
223
|
+
merged: list[dict] = []
|
|
224
|
+
i = 0
|
|
225
|
+
while i < len(out):
|
|
226
|
+
t = out[i]
|
|
227
|
+
if t["key"] == "_cast" and i + 1 < len(out) and out[i + 1]["text"] == "(":
|
|
228
|
+
depth, j = 0, i + 1
|
|
229
|
+
while j < len(out):
|
|
230
|
+
depth += out[j]["text"] == "("
|
|
231
|
+
depth -= out[j]["text"] == ")"
|
|
232
|
+
if depth == 0:
|
|
233
|
+
break
|
|
234
|
+
j += 1
|
|
235
|
+
inner = out[i + 2:j]
|
|
236
|
+
if j < len(out) and inner and all(x["kind"] in ("q", "qlist") or x["text"] in ("[", "]", ",") for x in inner):
|
|
237
|
+
merged.append({"kind": "q", "text": "?", "key": "?", "cast": True, "list": any(x["text"] == "[" for x in inner)})
|
|
238
|
+
i = j + 1
|
|
239
|
+
continue
|
|
240
|
+
merged.append(t)
|
|
241
|
+
i += 1
|
|
242
|
+
return merged
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def align(observed: list[dict], code: list[dict], least: int = 1) -> dict[int, int]:
|
|
246
|
+
"""observed token index -> code token index, for the stretches where the two agree (difflib, no junk heuristic).
|
|
247
|
+
A stretch shorter than `least` tokens is not trusted (pieces of a longer statement need several to be the piece)."""
|
|
248
|
+
sm = difflib.SequenceMatcher(None, [t["key"] for t in observed], [t["key"] for t in code], autojunk=False)
|
|
249
|
+
out = {}
|
|
250
|
+
for a, b, n in sm.get_matching_blocks():
|
|
251
|
+
if n >= least:
|
|
252
|
+
for i in range(n):
|
|
253
|
+
out[a + i] = b + i
|
|
254
|
+
return out
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
# ---- typing a `?` from its place ------------------------------------------------------------------------------------
|
|
258
|
+
|
|
259
|
+
COMPARE = ("=", "==", "!=", "<>", "<", ">", "<=", ">=")
|
|
260
|
+
CLAUSES = ("select", "where", "prewhere", "having", "on", "using", "group", "order", "limit", "offset", "settings", "from", "join", "by")
|
|
261
|
+
FILTER_CLAUSES = ("where", "prewhere", "having", "on")
|
|
262
|
+
# function -> {argument position (0 based): type} for arguments that are values, not columns
|
|
263
|
+
FUNCTION_ARGS = {
|
|
264
|
+
"substring": {1: "UInt64", 2: "UInt64"}, "substr": {1: "UInt64", 2: "UInt64"}, "left": {1: "UInt64"}, "right": {1: "UInt64"},
|
|
265
|
+
"leftpad": {1: "UInt64", 2: "String"}, "rightpad": {1: "UInt64", 2: "String"}, "round": {1: "UInt8"}, "truncate": {1: "UInt8"},
|
|
266
|
+
"jsonextractstring": {"*": "String"}, "jsonextractint": {"*": "String"}, "jsonextractfloat": {"*": "String"}, "jsonextractbool": {"*": "String"},
|
|
267
|
+
"jsonextractraw": {"*": "String"}, "jsonextract": {"*": "String"}, "jsonhas": {"*": "String"}, "jsonextractkeys": {"*": "String"},
|
|
268
|
+
"match": {1: "String"}, "like": {1: "String"}, "ilike": {1: "String"}, "extract": {1: "String"}, "extractall": {1: "String"},
|
|
269
|
+
"replaceregexpall": {1: "String", 2: "String"}, "replaceregexpone": {1: "String", 2: "String"}, "replaceall": {1: "String", 2: "String"},
|
|
270
|
+
"replaceone": {1: "String", 2: "String"}, "position": {1: "String"}, "positioncaseinsensitive": {1: "String"},
|
|
271
|
+
"splitbychar": {0: "String"}, "splitbystring": {0: "String"}, "startswith": {1: "String"}, "endswith": {1: "String"},
|
|
272
|
+
"totimezone": {1: "String"}, "formatdatetime": {1: "String", 2: "String"}, "todatetime": {0: "String", 1: "String"},
|
|
273
|
+
"todatetime64": {0: "String", 1: "UInt8", 2: "String"}, "parsedatetime64besteffort": {0: "String", 1: "UInt8", 2: "String"},
|
|
274
|
+
"parsedatetimebesteffort": {0: "String", 1: "String"}, "parsedatetime64besteffortornull": {0: "String", 1: "UInt8", 2: "String"},
|
|
275
|
+
"todate": {0: "String", 1: "String"}, "tostartofinterval": {}, "adddays": {1: "Int64"}, "addhours": {1: "Int64"}, "addminutes": {1: "Int64"},
|
|
276
|
+
"subtractdays": {1: "Int64"}, "subtracthours": {1: "Int64"}, "subtractminutes": {1: "Int64"}, "tointervalhour": {0: "Int64"},
|
|
277
|
+
"tointervalday": {0: "Int64"}, "tointervalminute": {0: "Int64"}, "tointervalsecond": {0: "Int64"}, "quantile": {0: "Float64"},
|
|
278
|
+
"arrayelement": {1: "Int64"}, "topk": {0: "UInt64"}, "multisearchany": {}, "concat": {"*": "String"}, "lower": {0: "String"},
|
|
279
|
+
"upper": {0: "String"}, "has": {}, "hasany": {}, "ifnull": {}, "coalesce": {}, "if": {}, "multiif": {},
|
|
280
|
+
"fromunixtimestamp64micro": {0: "Int64"}, "fromunixtimestamp64milli": {0: "Int64"}, "fromunixtimestamp64nano": {0: "Int64"},
|
|
281
|
+
"fromunixtimestamp": {0: "UInt32"}, "intdiv": {1: "UInt64"}, "modulo": {1: "UInt64"}, "tostartofinterval_": {},
|
|
282
|
+
"datediff": {0: "String"}, "date_diff": {0: "String"}, "datetrunc": {0: "String"}, "date_trunc": {0: "String"},
|
|
283
|
+
# conversions of one value: the value's own type (`tenant = toUUID(?)`, `event_time >= toUInt64(?)`)
|
|
284
|
+
"touuid": {0: "String"}, "touuidornull": {0: "String"}, "touuidorzero": {0: "String"}, "toipv4": {0: "String"}, "toipv6": {0: "String"},
|
|
285
|
+
"touint8": {0: "UInt8"}, "touint16": {0: "UInt16"}, "touint32": {0: "UInt32"}, "touint64": {0: "UInt64"},
|
|
286
|
+
"toint8": {0: "Int8"}, "toint16": {0: "Int16"}, "toint32": {0: "Int32"}, "toint64": {0: "Int64"},
|
|
287
|
+
"tofloat32": {0: "Float32"}, "tofloat64": {0: "Float64"}, "tostring": {0: "String"}, "tofixedstring": {0: "String", 1: "UInt64"},
|
|
288
|
+
}
|
|
289
|
+
# The time zone argument of a time function. The log does not keep it (normalizeQuery prints every literal as `?`); it
|
|
290
|
+
# only says how the time is shown, so it is run as 'UTC' and said (`timezone` in runnable).
|
|
291
|
+
TIMEZONE = "Timezone"
|
|
292
|
+
for _fn, _at in (("fromunixtimestamp64milli", 1), ("fromunixtimestamp64micro", 1), ("fromunixtimestamp64nano", 1), ("totimezone", 1),
|
|
293
|
+
("todatetime", 1), ("todatetime64", 2), ("parsedatetime64besteffort", 2), ("parsedatetime64besteffortornull", 2),
|
|
294
|
+
("parsedatetimebesteffort", 1), ("todate", 1), ("formatdatetime", 2), ("tostartofday", 1), ("tostartofhour", 1),
|
|
295
|
+
("tostartofmonth", 1), ("toyyyymm", 1), ("toyyyymmdd", 1)):
|
|
296
|
+
FUNCTION_ARGS.setdefault(_fn, {})[_at] = TIMEZONE
|
|
297
|
+
# Functions whose value arguments share one type: a `?` among them takes the type of a sibling that has one
|
|
298
|
+
# (`coalesce(kind, ?)`, `ifNull(source, ?)`, `multiIf(a != '', concat('c:', a), ?)`). `if` and `multiIf` take it
|
|
299
|
+
# only in their value positions; a condition is not a value of that type.
|
|
300
|
+
SAME_TYPE_ARGS = ("coalesce", "ifnull", "nullif", "greatest", "least", "if", "multiif", "assumenotnull", "any", "anylast")
|
|
301
|
+
# what a function returns, for an expression's type (an alias compared with a value: `day IN ?` where `toDate(ts) AS day`)
|
|
302
|
+
RETURNS = {**dict.fromkeys(("concat", "concatws", "tostring", "lower", "upper", "lowerutf8", "upperutf8", "trim", "trimboth", "trimleft",
|
|
303
|
+
"trimright", "substring", "substr", "substringutf8", "replaceall", "replaceone", "replaceregexpall",
|
|
304
|
+
"replaceregexpone", "formatdatetime", "leftpad", "rightpad", "jsonextractstring", "jsonextractraw", "hex",
|
|
305
|
+
"base64encode", "domain", "domainwithoutwww", "path", "extract", "tostringcuttozero", "reverse"), "String"),
|
|
306
|
+
**dict.fromkeys(("todate", "tostartofmonth", "tostartofweek", "tostartofyear", "tostartofquarter", "tomonday", "today",
|
|
307
|
+
"yesterday"), "Date"),
|
|
308
|
+
**dict.fromkeys(("todatetime", "tostartofhour", "tostartofminute", "tostartofday", "tostartoffiveminutes", "now",
|
|
309
|
+
"fromunixtimestamp", "parsedatetimebesteffort", "parsedatetimebesteffortornull"), "DateTime"),
|
|
310
|
+
**dict.fromkeys(("todatetime64", "fromunixtimestamp64milli", "fromunixtimestamp64micro", "fromunixtimestamp64nano",
|
|
311
|
+
"parsedatetime64besteffort", "parsedatetime64besteffortornull", "now64"), "DateTime64(6)"),
|
|
312
|
+
**dict.fromkeys(("count", "uniq", "uniqexact", "uniqcombined", "length", "lengthutf8", "cityhash64", "siphash64",
|
|
313
|
+
"touint64", "tounixtimestamp64milli", "tounixtimestamp64micro"), "UInt64"),
|
|
314
|
+
**dict.fromkeys(("toint64", "datediff", "date_diff"), "Int64"), **dict.fromkeys(("touint32", "tounixtimestamp", "toyyyymm",
|
|
315
|
+
"toyyyymmdd"), "UInt32"),
|
|
316
|
+
**dict.fromkeys(("tofloat64", "avg", "sum"), "Float64"), "touuid": "UUID",
|
|
317
|
+
**dict.fromkeys(("has", "hasany", "hasall", "empty", "notempty", "isnull", "isnotnull", "like", "ilike", "match",
|
|
318
|
+
"startswith", "endswith", "in", "notin"), "UInt8")}
|
|
319
|
+
RETURNS["jsontype"] = "Enum8('Null' = 0, 'String' = 34, 'Array' = 91, 'Object' = 123, 'Number' = 100, 'Bool' = 98)"
|
|
320
|
+
# functions whose result has the type of the column they wrap (`abs(delta) > ?`, `toLowCardinality(kind) = ?`)
|
|
321
|
+
TYPE_KEEPING = ("abs", "round", "floor", "ceil", "truncate", "negate", "tolowcardinality", "assumenotnull", "tonullable")
|
|
322
|
+
PASS_THROUGH = ("if", "multiif", "coalesce", "ifnull", "assumenotnull", "any", "anylast", "argmax", "argmin", "min", "max", "greatest",
|
|
323
|
+
"least", "argmaxif", "argminif", "anyif", "minif", "maxif", "nullif", "tonullable")
|
|
324
|
+
EPOCH_FUNCTIONS = {"fromunixtimestamp64milli": "ms", "fromunixtimestamp64micro": "us", "fromunixtimestamp64nano": "ns",
|
|
325
|
+
"fromunixtimestamp": "s", "todatetime": "s"}
|
|
326
|
+
# a point in time stored as a number: `event_time_ms`, `created_at_ms`, `ts_us` (not `duration_ms`, which is a length)
|
|
327
|
+
EPOCH_SUFFIX = re.compile(r"(?:time|_at|^at|ts|timestamp|date|epoch)_(ms|millis|us|micros|ns|nanos)$", re.I)
|
|
328
|
+
# functions whose last argument is a type name (`JSONExtract(data, 'k', 'Nullable(Bool)')`): when the log joined their
|
|
329
|
+
# arguments into `?..` no neutral value can stand for the type, which decides what the call returns, so it stays open
|
|
330
|
+
TYPE_NAME_LAST = ("jsonextract", "jsonextractkeysandvalues")
|
|
331
|
+
DATETIME64_PARSERS = ("todatetime64", "parsedatetime64besteffort", "parsedatetime64besteffortornull", "todatetime64ornull")
|
|
332
|
+
NOT_FUNCTIONS = ("from", "join", "in", "as", "select", "where", "prewhere", "having", "and", "or", "not", "exists", "union", "all",
|
|
333
|
+
"on", "using", "with", "by", "values", "array", "tuple_")
|
|
334
|
+
BOOLEAN_BEFORE = ("and", "or", "not", "where", "prewhere", "having", "(")
|
|
335
|
+
BOOLEAN_AFTER = ("and", "or", ")", "group", "order", "limit", "settings", "union", "")
|
|
336
|
+
TIME_TYPE = re.compile(r"DateTime|Date")
|
|
337
|
+
NUMBER_TYPE = re.compile(r"U?Int\d+|Float\d+|Decimal|Bool")
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def base_type(t: str) -> str:
|
|
341
|
+
s = (t or "").strip()
|
|
342
|
+
while True:
|
|
343
|
+
m = re.match(r"^(?:Nullable|LowCardinality|SimpleAggregateFunction\(\w+,\s*)\((.*)\)$", s, re.S) or re.match(r"^SimpleAggregateFunction\(\w+,\s*(.*)\)$", s, re.S)
|
|
344
|
+
if not m:
|
|
345
|
+
return s
|
|
346
|
+
s = m.group(1).strip()
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def scalar_type(t: str) -> str:
|
|
350
|
+
"""The type a value compared with a column of type `t` is bound as: strings stay String, a LowCardinality or Nullable
|
|
351
|
+
wrapper is dropped, a date or time becomes a String the server parses, an Array or Map compares with its element."""
|
|
352
|
+
b = base_type(t)
|
|
353
|
+
if b.startswith("Array("):
|
|
354
|
+
return scalar_type(b[6:-1])
|
|
355
|
+
if b.startswith("Map("):
|
|
356
|
+
return "String"
|
|
357
|
+
if TIME_TYPE.match(b) or b in ("UUID", "IPv4", "IPv6") or b.startswith(("FixedString", "Enum", "JSON", "Object")):
|
|
358
|
+
return "String"
|
|
359
|
+
if NUMBER_TYPE.match(b):
|
|
360
|
+
return b if not b.startswith("Decimal") else "Float64"
|
|
361
|
+
return "String"
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def _call(tokens_: list[dict], i: int) -> tuple[str, int] | None:
|
|
365
|
+
"""For a token inside a function call's argument list: (function name, argument position), else None."""
|
|
366
|
+
depth, position = 0, 0
|
|
367
|
+
for j in range(i - 1, -1, -1):
|
|
368
|
+
t = tokens_[j]["text"]
|
|
369
|
+
if t == ")":
|
|
370
|
+
depth += 1
|
|
371
|
+
elif t == "(":
|
|
372
|
+
if depth == 0:
|
|
373
|
+
subquery = j + 1 < len(tokens_) and tokens_[j + 1]["key"] in ("select", "with")
|
|
374
|
+
if j > 0 and tokens_[j - 1]["kind"] == "ident" and not subquery and tokens_[j - 1]["key"] not in NOT_FUNCTIONS:
|
|
375
|
+
return tokens_[j - 1]["key"], position
|
|
376
|
+
return None
|
|
377
|
+
depth -= 1
|
|
378
|
+
elif t == "," and depth == 0:
|
|
379
|
+
position += 1
|
|
380
|
+
return None
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def _enclosing(tokens_: list[dict], i: int) -> tuple[str, int, int] | None:
|
|
384
|
+
"""For a token inside a function call's argument list: (function name, argument position, index of its `(`)."""
|
|
385
|
+
depth, position = 0, 0
|
|
386
|
+
for j in range(i - 1, -1, -1):
|
|
387
|
+
t = tokens_[j]["text"]
|
|
388
|
+
if t == ")":
|
|
389
|
+
depth += 1
|
|
390
|
+
elif t == "(":
|
|
391
|
+
if depth == 0:
|
|
392
|
+
subquery = j + 1 < len(tokens_) and tokens_[j + 1]["key"] in ("select", "with")
|
|
393
|
+
if j > 0 and tokens_[j - 1]["kind"] == "ident" and not subquery and tokens_[j - 1]["key"] not in NOT_FUNCTIONS:
|
|
394
|
+
return tokens_[j - 1]["key"], position, j
|
|
395
|
+
return None
|
|
396
|
+
depth -= 1
|
|
397
|
+
elif t == "," and depth == 0:
|
|
398
|
+
position += 1
|
|
399
|
+
return None
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def _arg_spans(tokens_: list[dict], open_at: int) -> list[tuple[int, int]]:
|
|
403
|
+
"""The arguments of the call whose `(` is at `open_at`, as [start, end) token spans."""
|
|
404
|
+
spans, depth, start = [], 0, open_at + 1
|
|
405
|
+
for j in range(open_at, len(tokens_)):
|
|
406
|
+
t = tokens_[j]["text"]
|
|
407
|
+
if t in ("(", "["):
|
|
408
|
+
depth += 1
|
|
409
|
+
elif t in (")", "]"):
|
|
410
|
+
depth -= 1
|
|
411
|
+
if depth == 0:
|
|
412
|
+
spans.append((start, j))
|
|
413
|
+
return [s for s in spans if s[1] > s[0]]
|
|
414
|
+
elif t == "," and depth == 1:
|
|
415
|
+
spans.append((start, j))
|
|
416
|
+
start = j + 1
|
|
417
|
+
return [s for s in spans if s[1] > s[0]]
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
def _value_positions(fn: str, n: int) -> set[int]:
|
|
421
|
+
"""The argument positions of a SAME_TYPE_ARGS function that are values of the shared type."""
|
|
422
|
+
if fn == "if":
|
|
423
|
+
return {1, 2}
|
|
424
|
+
if fn == "multiif":
|
|
425
|
+
return {k for k in range(n) if k % 2 == 1 or k == n - 1}
|
|
426
|
+
return set(range(n))
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
def aliases_of(tokens_: list[dict]) -> dict[str, tuple[int, int]]:
|
|
430
|
+
"""alias -> the token span of the expression it names (`toDate(ts) AS day`), for every `expr AS name` of the
|
|
431
|
+
statement. A CAST's `AS Type` and a WITH's `name AS (SELECT ...)` are not aliases."""
|
|
432
|
+
out: dict[str, tuple[int, int]] = {}
|
|
433
|
+
for k, t in enumerate(tokens_):
|
|
434
|
+
if t["key"] != "as" or k + 1 >= len(tokens_) or tokens_[k + 1]["kind"] != "ident" or k == 0:
|
|
435
|
+
continue
|
|
436
|
+
around = _enclosing(tokens_, k)
|
|
437
|
+
if around and around[0] == "cast":
|
|
438
|
+
continue
|
|
439
|
+
depth, start = 0, k
|
|
440
|
+
for j in range(k - 1, -1, -1):
|
|
441
|
+
x = tokens_[j]
|
|
442
|
+
if x["text"] in (")", "]"):
|
|
443
|
+
depth += 1
|
|
444
|
+
elif x["text"] in ("(", "["):
|
|
445
|
+
if depth == 0:
|
|
446
|
+
break
|
|
447
|
+
depth -= 1
|
|
448
|
+
elif depth == 0 and (x["text"] == "," or (x["kind"] == "ident" and x["key"] in ("select", "distinct", "with", "by", "where",
|
|
449
|
+
"prewhere", "having", "on"))):
|
|
450
|
+
break
|
|
451
|
+
start = j
|
|
452
|
+
if start < k:
|
|
453
|
+
out.setdefault(tokens_[k + 1]["key"], (start, k))
|
|
454
|
+
return out
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
def expr_type(tokens_: list[dict], span: tuple[int, int], columns: dict[str, str], aliases: dict | None = None, depth: int = 0) -> str | None:
|
|
458
|
+
"""The ClickHouse type of the expression at `span`, when it is a column, a literal, an alias of a typeable expression,
|
|
459
|
+
or a function whose result type is known (RETURNS) or follows its arguments (PASS_THROUGH). None otherwise."""
|
|
460
|
+
a, b = span
|
|
461
|
+
while b - a >= 2 and tokens_[a]["text"] == "(" and tokens_[b - 1]["text"] == ")" and _arg_spans(tokens_, a) == [(a + 1, b - 1)]:
|
|
462
|
+
a, b = a + 1, b - 1
|
|
463
|
+
if b <= a or depth > 6:
|
|
464
|
+
return None
|
|
465
|
+
if b - a >= 3 and tokens_[b - 2]["text"] == "::" and tokens_[b - 1]["kind"] == "ident":
|
|
466
|
+
# `(state ->> 'k')::integer`: the cast says the type (a ClickHouse type name keeps its case)
|
|
467
|
+
cast = tokens_[b - 1]["text"].strip('"')
|
|
468
|
+
return cast if re.match(r"[A-Z]", cast) else pg_internal(cast)
|
|
469
|
+
first = tokens_[a]
|
|
470
|
+
if b - a == 1:
|
|
471
|
+
if first["kind"] == "str":
|
|
472
|
+
return "String"
|
|
473
|
+
if first["kind"] == "num":
|
|
474
|
+
return "Float64" if "." in first["text"] else "Int64"
|
|
475
|
+
if first["kind"] == "ident":
|
|
476
|
+
name = first["key"].rsplit(".", 1)[-1]
|
|
477
|
+
if name in columns:
|
|
478
|
+
return columns[name]
|
|
479
|
+
if aliases and name in aliases and aliases[name] != span:
|
|
480
|
+
return expr_type(tokens_, aliases[name], columns, aliases, depth + 1)
|
|
481
|
+
return None
|
|
482
|
+
if b - a == 3 and first["kind"] == "ident" and tokens_[a + 1]["text"] == "." and tokens_[a + 2]["kind"] == "ident":
|
|
483
|
+
return columns.get(tokens_[a + 2]["key"]) # t.col
|
|
484
|
+
if first["kind"] == "ident" and tokens_[a + 1]["text"] == "(" and tokens_[b - 1]["text"] == ")":
|
|
485
|
+
spans = _arg_spans(tokens_, a + 1)
|
|
486
|
+
if not spans or spans[-1][1] != b - 1:
|
|
487
|
+
return None # f(x) + g(y): more than one call
|
|
488
|
+
fn = first["key"]
|
|
489
|
+
if fn in RETURNS:
|
|
490
|
+
return RETURNS[fn]
|
|
491
|
+
if fn in PASS_THROUGH:
|
|
492
|
+
positions = _value_positions(fn, len(spans)) if fn in ("if", "multiif") else {0} if fn.startswith(("argm", "any", "min", "max")) else set(range(len(spans)))
|
|
493
|
+
for k in sorted(positions):
|
|
494
|
+
if k < len(spans):
|
|
495
|
+
t = expr_type(tokens_, spans[k], columns, aliases, depth + 1)
|
|
496
|
+
if t:
|
|
497
|
+
return t
|
|
498
|
+
return None
|
|
499
|
+
|
|
500
|
+
|
|
501
|
+
def epoch_units(tokens_: list[dict], columns: dict[str, str]) -> dict[str, str]:
|
|
502
|
+
"""Number columns the statement itself reads as a time, and the unit: column -> s, ms, us or ns.
|
|
503
|
+
|
|
504
|
+
`fromUnixTimestamp64Milli(toInt64(e.event_time), 'UTC')` says event_time holds milliseconds since the epoch, so a
|
|
505
|
+
range on it (`event_time >= toUInt64(?)`) is a time range and its values are times in milliseconds, not numbers. A
|
|
506
|
+
name ending in _ms, _us or _ns says the same. Without either, a number column stays a number."""
|
|
507
|
+
out: dict[str, str] = {}
|
|
508
|
+
for k, t in enumerate(tokens_):
|
|
509
|
+
unit = EPOCH_FUNCTIONS.get(t["key"]) if t["kind"] == "ident" else None
|
|
510
|
+
if not unit or k + 1 >= len(tokens_) or tokens_[k + 1]["text"] != "(":
|
|
511
|
+
continue
|
|
512
|
+
spans = _arg_spans(tokens_, k + 1)
|
|
513
|
+
if not spans:
|
|
514
|
+
continue
|
|
515
|
+
idents = [x["key"].rsplit(".", 1)[-1] for x in tokens_[spans[0][0]:spans[0][1]] if x["kind"] == "ident"]
|
|
516
|
+
cols = [c for c in idents if c in columns and NUMBER_TYPE.match(base_type(columns[c]))]
|
|
517
|
+
if len(cols) == 1 and all(x in cols or x in ("toint64", "touint64", "toint32", "touint32", "assumenotnull", "ifnull")
|
|
518
|
+
or x not in columns for x in idents):
|
|
519
|
+
out.setdefault(cols[0], unit)
|
|
520
|
+
named = {x["key"].rsplit(".", 1)[-1] for x in tokens_ if x["kind"] == "ident"}
|
|
521
|
+
for name, t in columns.items():
|
|
522
|
+
m = EPOCH_SUFFIX.search(name)
|
|
523
|
+
if m and name in named and NUMBER_TYPE.match(base_type(t)) and name not in out:
|
|
524
|
+
out[name] = {"ms": "ms", "millis": "ms", "us": "us", "micros": "us", "ns": "ns", "nanos": "ns"}[m.group(1).lower()]
|
|
525
|
+
return out
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
TIME_SHIFTS = ("adddays", "addhours", "addminutes", "addseconds", "addweeks", "addmonths", "subtractdays", "subtracthours", "subtractminutes",
|
|
529
|
+
"subtractseconds", "subtractweeks", "subtractmonths", "date_add", "date_sub", "tostartofday", "tostartofhour", "tostartofminute")
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
def _bound_through(tokens_: list[dict], i: int, columns: dict[str, str]) -> tuple[str, str, str, str] | None:
|
|
533
|
+
"""`ts < addDays(parseDateTime64BestEffort(?), 1)`: the time column a value at i bounds through functions that shift
|
|
534
|
+
or round a time: (column, operator, the outermost shifting function, column type), or None."""
|
|
535
|
+
around = _enclosing(tokens_, i)
|
|
536
|
+
shift = None
|
|
537
|
+
while around:
|
|
538
|
+
fn_at = around[2] - 1
|
|
539
|
+
bound = _column_before(tokens_, fn_at) if fn_at > 0 else None
|
|
540
|
+
if bound and bound[0] in columns and bound[1] in COMPARE and TIME_TYPE.match(base_type(columns[bound[0]])):
|
|
541
|
+
return bound[0], bound[1], shift, base_type(columns[bound[0]])
|
|
542
|
+
outer = _enclosing(tokens_, fn_at)
|
|
543
|
+
if not outer or outer[0] not in TIME_SHIFTS or outer[1] != 0:
|
|
544
|
+
return None
|
|
545
|
+
shift, around = outer[0], outer
|
|
546
|
+
return None
|
|
547
|
+
|
|
548
|
+
|
|
549
|
+
def _clause(tokens_: list[dict], i: int) -> str:
|
|
550
|
+
"""The clause a token sits in: the nearest clause word before it at its own depth or an outer one."""
|
|
551
|
+
depth = 0
|
|
552
|
+
for j in range(i - 1, -1, -1):
|
|
553
|
+
t = tokens_[j]
|
|
554
|
+
if t["text"] == ")":
|
|
555
|
+
depth += 1
|
|
556
|
+
elif t["text"] == "(":
|
|
557
|
+
depth = max(depth - 1, 0)
|
|
558
|
+
elif t["kind"] == "ident" and t["key"] in CLAUSES and depth == 0:
|
|
559
|
+
return "group" if t["key"] == "by" and j and tokens_[j - 1]["key"] == "group" else "order" if t["key"] == "by" else t["key"]
|
|
560
|
+
return "select"
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
def _column_before(tokens_: list[dict], i: int) -> tuple[str, str] | None:
|
|
564
|
+
"""`col <op> ?` or `col IN ?`: (column name, operator). The column may be qualified (`a.col`) or wrapped once
|
|
565
|
+
(`lower(col) = ?`)."""
|
|
566
|
+
j = i - 1
|
|
567
|
+
if j < 0:
|
|
568
|
+
return None
|
|
569
|
+
op = tokens_[j]["text"].lower()
|
|
570
|
+
if op in ("(", "[") and j > 0 and tokens_[j - 1]["key"] in ("in",):
|
|
571
|
+
j, op = j - 1, "in"
|
|
572
|
+
if op in ("in", "like", "ilike", "~", "~*", "!~", "!~*"): # PostgreSQL's regular expression matches too
|
|
573
|
+
if j > 0 and tokens_[j - 1]["key"] == "not":
|
|
574
|
+
j -= 1
|
|
575
|
+
elif op not in COMPARE:
|
|
576
|
+
return None
|
|
577
|
+
k = j - 1
|
|
578
|
+
if k >= 0 and tokens_[k]["text"] == ")": # lower(col) = ?
|
|
579
|
+
depth = 0
|
|
580
|
+
for m in range(k, -1, -1):
|
|
581
|
+
if tokens_[m]["text"] == ")":
|
|
582
|
+
depth += 1
|
|
583
|
+
elif tokens_[m]["text"] == "(":
|
|
584
|
+
depth -= 1
|
|
585
|
+
if depth == 0:
|
|
586
|
+
inner = [t for t in tokens_[m + 1:k] if t["kind"] == "ident"]
|
|
587
|
+
return (inner[-1]["key"].rsplit(".", 1)[-1], op) if inner else None
|
|
588
|
+
return None
|
|
589
|
+
if k >= 0 and tokens_[k]["kind"] == "ident":
|
|
590
|
+
name = tokens_[k]["key"]
|
|
591
|
+
if k >= 2 and tokens_[k - 1]["text"] == ".":
|
|
592
|
+
name = tokens_[k]["key"]
|
|
593
|
+
return name.rsplit(".", 1)[-1], op
|
|
594
|
+
return None
|
|
595
|
+
|
|
596
|
+
|
|
597
|
+
TIME_WRAPPERS = {"toyyyymm": ("UInt32", "%Y%m"), "toyyyymmdd": ("UInt32", "%Y%m%d"), "toyear": ("UInt16", "%Y"),
|
|
598
|
+
"todate": ("String", "%Y-%m-%d"), "tostartofday": ("String", "%Y-%m-%d 00:00:00"),
|
|
599
|
+
"tostartofhour": ("String", "%Y-%m-%d %H:00:00"), "tostartofmonth": ("String", "%Y-%m-01")}
|
|
600
|
+
|
|
601
|
+
|
|
602
|
+
def _wrapper_before(tokens_: list[dict], i: int) -> str | None:
|
|
603
|
+
"""`f(col) <op> ?` or `f(col) IN ?`: the function wrapping the column compared with the value at i, or None."""
|
|
604
|
+
j = i - 1
|
|
605
|
+
if j >= 1 and tokens_[j]["text"] in ("(", "[") and tokens_[j - 1]["key"] == "in":
|
|
606
|
+
j -= 1
|
|
607
|
+
if j < 1 or (tokens_[j]["text"].lower() not in COMPARE and tokens_[j]["key"] != "in"):
|
|
608
|
+
return None
|
|
609
|
+
if tokens_[j]["key"] == "in" and j >= 2 and tokens_[j - 1]["key"] == "not":
|
|
610
|
+
j -= 1
|
|
611
|
+
k = j - 1
|
|
612
|
+
if tokens_[k]["text"] != ")":
|
|
613
|
+
return None
|
|
614
|
+
depth = 0
|
|
615
|
+
for m in range(k, -1, -1):
|
|
616
|
+
if tokens_[m]["text"] == ")":
|
|
617
|
+
depth += 1
|
|
618
|
+
elif tokens_[m]["text"] == "(":
|
|
619
|
+
depth -= 1
|
|
620
|
+
if depth == 0:
|
|
621
|
+
return tokens_[m - 1]["key"] if m > 0 and tokens_[m - 1]["kind"] == "ident" else None
|
|
622
|
+
return None
|
|
623
|
+
|
|
624
|
+
|
|
625
|
+
def _column_after(tokens_: list[dict], i: int) -> tuple[str, str] | None:
|
|
626
|
+
"""`? <op> col`."""
|
|
627
|
+
if i + 2 < len(tokens_) and tokens_[i + 1]["text"] in COMPARE and tokens_[i + 2]["kind"] == "ident":
|
|
628
|
+
k = i + 2
|
|
629
|
+
while k + 2 < len(tokens_) and tokens_[k + 1]["text"] == ".":
|
|
630
|
+
k += 2
|
|
631
|
+
return tokens_[k]["key"].rsplit(".", 1)[-1], tokens_[i + 1]["text"]
|
|
632
|
+
return None
|
|
633
|
+
|
|
634
|
+
|
|
635
|
+
def place_of(tokens_: list[dict], i: int, columns: dict[str, str], aliases: dict[str, tuple[int, int]] | None = None) -> dict:
|
|
636
|
+
"""What a `?` at token i is: {type, column, op, clause, filter, open}. `columns`: column name -> type, of the
|
|
637
|
+
statement's tables (real catalog). `aliases`: aliases_of(tokens_), for a value compared with an alias."""
|
|
638
|
+
if aliases is None:
|
|
639
|
+
aliases = aliases_of(tokens_)
|
|
640
|
+
clause = _clause(tokens_, i)
|
|
641
|
+
# `list`: the value is a list of values for IN; a `?..` anywhere else stands for several arguments of a function
|
|
642
|
+
prev_key = tokens_[i - 1]["key"] if i else ""
|
|
643
|
+
in_list = prev_key == "in" or (prev_key in ("(", "[") and i >= 2 and tokens_[i - 2]["key"] == "in")
|
|
644
|
+
out = {"clause": clause, "filter": clause in FILTER_CLAUSES, "column": None, "op": None, "type": None,
|
|
645
|
+
"list": bool(tokens_[i].get("list")) or (tokens_[i]["kind"] == "qlist" and in_list)}
|
|
646
|
+
prev = tokens_[i - 1]["key"] if i else ""
|
|
647
|
+
if prev in ("limit", "offset") or (prev == "," and i >= 3 and tokens_[i - 2]["kind"] in VALUE_KINDS and tokens_[i - 3]["key"] == "limit"):
|
|
648
|
+
out.update(type="UInt64", op="limit")
|
|
649
|
+
return out
|
|
650
|
+
if prev == "interval":
|
|
651
|
+
out.update(type="UInt32", op="interval")
|
|
652
|
+
return out
|
|
653
|
+
found = _column_before(tokens_, i) or _column_after(tokens_, i)
|
|
654
|
+
if found and found[0] in columns:
|
|
655
|
+
out.update(column=found[0], op=found[1], type=scalar_type(columns[found[0]]))
|
|
656
|
+
wrapper = _wrapper_before(tokens_, i)
|
|
657
|
+
if wrapper in TIME_WRAPPERS:
|
|
658
|
+
# `toYYYYMM(ts) = ?`: the value has the wrapper's type and is a time of the window, in the wrapper's form
|
|
659
|
+
out.update(type=TIME_WRAPPERS[wrapper][0], wrapper=wrapper, column_type=base_type(columns[found[0]]))
|
|
660
|
+
elif wrapper:
|
|
661
|
+
out["wrapper"] = wrapper
|
|
662
|
+
if wrapper in RETURNS:
|
|
663
|
+
# `JSONType(data, 'k') = ?`, `length(name) > ?`: the value has the function's type, not the column's
|
|
664
|
+
out.update(type=scalar_type(RETURNS[wrapper]), value_type=base_type(RETURNS[wrapper]))
|
|
665
|
+
elif wrapper not in PASS_THROUGH and wrapper not in TYPE_KEEPING:
|
|
666
|
+
# a function nothing says the result type of: the column's type would be a guess, so the value stays open
|
|
667
|
+
out.update(type=None, open=True)
|
|
668
|
+
return out
|
|
669
|
+
if found[1] in ("in", "not in"):
|
|
670
|
+
out["list"] = True
|
|
671
|
+
return out
|
|
672
|
+
if found and found[0] in aliases:
|
|
673
|
+
# `day IN ?` where `toDate(ts) AS day`: the value has the type of the expression the alias names
|
|
674
|
+
named = expr_type(tokens_, aliases[found[0]], columns, aliases)
|
|
675
|
+
if named:
|
|
676
|
+
out.update(op=found[1], type=scalar_type(named), alias=found[0], alias_type=base_type(named))
|
|
677
|
+
if found[1] in ("in", "not in"):
|
|
678
|
+
out["list"] = True
|
|
679
|
+
wrapper = _wrapper_before(tokens_, i)
|
|
680
|
+
if wrapper in TIME_WRAPPERS:
|
|
681
|
+
out.update(type=TIME_WRAPPERS[wrapper][0], wrapper=wrapper, column_type=base_type(named))
|
|
682
|
+
elif wrapper in RETURNS:
|
|
683
|
+
out.update(wrapper=wrapper, type=scalar_type(RETURNS[wrapper]), value_type=base_type(RETURNS[wrapper]), alias_type=None)
|
|
684
|
+
elif wrapper and wrapper not in PASS_THROUGH and wrapper not in TYPE_KEEPING:
|
|
685
|
+
out.update(type=None, open=True)
|
|
686
|
+
return out
|
|
687
|
+
around = _enclosing(tokens_, i)
|
|
688
|
+
if around and around[0] in SAME_TYPE_ARGS:
|
|
689
|
+
# `coalesce(kind, ?)`, `multiIf(..., concat('c:', id), ?)`: the type of a sibling value
|
|
690
|
+
spans = _arg_spans(tokens_, around[2])
|
|
691
|
+
positions = _value_positions(around[0], len(spans))
|
|
692
|
+
if around[1] in positions:
|
|
693
|
+
for k in sorted(positions - {around[1]}):
|
|
694
|
+
sibling = expr_type(tokens_, spans[k], columns, aliases) if k < len(spans) else None
|
|
695
|
+
if sibling:
|
|
696
|
+
out.update(type=scalar_type(sibling), op=f"{around[0]}()", function=around[0], argument=around[1], sibling_type=base_type(sibling))
|
|
697
|
+
return out
|
|
698
|
+
nxt = tokens_[i + 1]["key"] if i + 1 < len(tokens_) else ""
|
|
699
|
+
if out["filter"] and ((prev in COMPARE and i >= 2 and tokens_[i - 2]["kind"] in ("q", "qlist"))
|
|
700
|
+
or (nxt in COMPARE and i + 2 < len(tokens_) and tokens_[i + 2]["kind"] in ("q", "qlist"))):
|
|
701
|
+
# `(? = ? OR ...)`: two values the code binds and compares, a switch: both sides get the same value
|
|
702
|
+
out.update(type="String", op="flag_compare")
|
|
703
|
+
return out
|
|
704
|
+
call = _call(tokens_, i)
|
|
705
|
+
if call and (FUNCTION_ARGS.get(call[0]) or {}).get(call[1]) or (call and (FUNCTION_ARGS.get(call[0]) or {}).get("*")):
|
|
706
|
+
known = FUNCTION_ARGS[call[0]]
|
|
707
|
+
out.update(type=known.get(call[1]) or known.get("*"), op=f"{call[0]}()", function=call[0], argument=call[1])
|
|
708
|
+
# `ts >= fromUnixTimestamp64Micro(?)`: the value is a bound of a time range on the column before the function
|
|
709
|
+
if call[1] == 0:
|
|
710
|
+
k = i - 1
|
|
711
|
+
while k > 0 and tokens_[k]["text"] != "(":
|
|
712
|
+
k -= 1
|
|
713
|
+
bound = _column_before(tokens_, k - 1) if k > 0 else None
|
|
714
|
+
if bound and bound[0] in columns and bound[1] in COMPARE:
|
|
715
|
+
out.update(column=bound[0], bound=bound[1], column_type=base_type(columns[bound[0]]))
|
|
716
|
+
elif bound and bound[0] in aliases and bound[1] in COMPARE:
|
|
717
|
+
# `HAVING event_time >= fromUnixTimestamp64Milli(?)` where `argMax(time, _version) AS event_time`
|
|
718
|
+
named = expr_type(tokens_, aliases[bound[0]], columns, aliases)
|
|
719
|
+
if named and TIME_TYPE.match(base_type(named)):
|
|
720
|
+
out.update(bound=bound[1], alias=bound[0], alias_type=base_type(named))
|
|
721
|
+
return out
|
|
722
|
+
if out["filter"] and call is None and prev in BOOLEAN_BEFORE and nxt in BOOLEAN_AFTER:
|
|
723
|
+
# `WHERE tenant_id = ? AND ? AND ...`: a condition the code binds as a value (a flag)
|
|
724
|
+
out.update(type="Bool", op="flag")
|
|
725
|
+
return out
|
|
726
|
+
if prev == "[" and i >= 2 and tokens_[i - 2]["kind"] == "ident" and tokens_[i - 2]["key"] != "in":
|
|
727
|
+
col = tokens_[i - 2]["key"].rsplit(".", 1)[-1]
|
|
728
|
+
t = base_type(columns.get(col, ""))
|
|
729
|
+
out.update(type="String" if t.startswith("Map(") or not t else "UInt64", op="index")
|
|
730
|
+
return out
|
|
731
|
+
call = _call(tokens_, i)
|
|
732
|
+
if call:
|
|
733
|
+
fn, position = call
|
|
734
|
+
known = FUNCTION_ARGS.get(fn)
|
|
735
|
+
if known:
|
|
736
|
+
t = known.get(position) or known.get("*")
|
|
737
|
+
if t:
|
|
738
|
+
out.update(type=t, op=f"{fn}()")
|
|
739
|
+
return out
|
|
740
|
+
nxt = tokens_[i + 1]["text"] if i + 1 < len(tokens_) else ""
|
|
741
|
+
if prev in ("+", "-", "*", "/", "%") or nxt in ("+", "*", "/", "%"):
|
|
742
|
+
out.update(type="Float64", op="arithmetic")
|
|
743
|
+
return out
|
|
744
|
+
if clause == "settings" and i >= 2 and prev == "=":
|
|
745
|
+
out.update(type="setting", op="setting", setting=tokens_[i - 2]["key"])
|
|
746
|
+
return out
|
|
747
|
+
out["open"] = True
|
|
748
|
+
return out
|
|
749
|
+
|
|
750
|
+
|
|
751
|
+
NEUTRAL = {"String": "''", "UInt64": "1", "UInt32": "1", "UInt8": "1", "Int64": "1", "Float64": "1", TIMEZONE: "'UTC'"}
|
|
752
|
+
|
|
753
|
+
|
|
754
|
+
def neutral(type_: str, engine: str = "clickhouse") -> str:
|
|
755
|
+
"""A value that decides nothing about which rows are read: for a value outside the filters. PostgreSQL parses a
|
|
756
|
+
text literal into the type its place needs, so the text must be of that type's form (a UUID, a time)."""
|
|
757
|
+
if engine == "postgres" and type_ in PG_NEUTRAL:
|
|
758
|
+
return PG_NEUTRAL[type_]
|
|
759
|
+
return NEUTRAL.get(type_, "1" if NUMBER_TYPE.match(type_ or "") else "''")
|
|
760
|
+
|
|
761
|
+
|
|
762
|
+
# ---- PostgreSQL: pg_stat_statements writes every constant and parameter as $n; types are the catalog's own ---------
|
|
763
|
+
#
|
|
764
|
+
# The typing above speaks ClickHouse's type names. A PostgreSQL column type is read into that vocabulary (pg_internal)
|
|
765
|
+
# so the same rules type a `$n`; the placeholder the benchmark binds carries the PostgreSQL type (the compared column's
|
|
766
|
+
# own type where there is one), which engines.postgres.render_params casts the chosen value to.
|
|
767
|
+
|
|
768
|
+
PG_NEUTRAL = {"UUID": "'00000000-0000-0000-0000-000000000000'", "DateTime64(6)": "'2000-01-01 00:00:00'",
|
|
769
|
+
"DateTime": "'2000-01-01 00:00:00'", "Date": "'2000-01-01'", "Bool": "true"}
|
|
770
|
+
PG_OF = {"String": "text", "UInt64": "bigint", "Int64": "bigint", "UInt32": "bigint", "Int32": "integer", "UInt16": "integer",
|
|
771
|
+
"Int16": "smallint", "UInt8": "smallint", "Int8": "smallint", "Float64": "double precision", "Float32": "real",
|
|
772
|
+
"Bool": "boolean", "UUID": "uuid", "Date": "date", "DateTime": "timestamp", "DateTime64(6)": "timestamp"}
|
|
773
|
+
PG_JSON_OPS = ("->>", "->", "#>>", "#>")
|
|
774
|
+
|
|
775
|
+
|
|
776
|
+
def _json_minus(obs: list[dict], i: int, pg_columns: dict[str, str]) -> bool:
|
|
777
|
+
"""`col - $3 - $4` where col is a json/jsonb column: walk back over `- <value>` to the column."""
|
|
778
|
+
j = i - 1
|
|
779
|
+
while j >= 1 and obs[j]["text"] == "-" and obs[j - 1]["kind"] in ("q", "str", "num"):
|
|
780
|
+
j -= 2
|
|
781
|
+
if j < 1 or obs[j]["text"] != "-" or obs[j - 1]["kind"] != "ident":
|
|
782
|
+
return False
|
|
783
|
+
return re.match(r"jsonb?$", (pg_columns.get(obs[j - 1]["key"].rsplit(".", 1)[-1]) or "").strip(), re.I) is not None
|
|
784
|
+
|
|
785
|
+
|
|
786
|
+
def pg_internal(pg_type: str) -> str:
|
|
787
|
+
"""A PostgreSQL column type in the vocabulary the typing rules use: uuid -> UUID, timestamptz -> DateTime64(6),
|
|
788
|
+
integer -> Int32, text[] -> Array(String). What none of them names is text (String)."""
|
|
789
|
+
s = re.sub(r"\s+", " ", (pg_type or "").strip().lower().strip('"'))
|
|
790
|
+
if s.endswith("[]"):
|
|
791
|
+
return f"Array({pg_internal(s[:-2])})"
|
|
792
|
+
base = re.sub(r"\(.*?\)", "", s).strip()
|
|
793
|
+
base = base.rsplit(".", 1)[-1]
|
|
794
|
+
if base == "uuid":
|
|
795
|
+
return "UUID"
|
|
796
|
+
if base.startswith("timestamp") or base in ("timestamptz",):
|
|
797
|
+
return "DateTime64(6)"
|
|
798
|
+
if base == "date":
|
|
799
|
+
return "Date"
|
|
800
|
+
if base in ("bigint", "int8", "bigserial", "serial8"):
|
|
801
|
+
return "Int64"
|
|
802
|
+
if base in ("integer", "int", "int4", "serial", "serial4"):
|
|
803
|
+
return "Int32"
|
|
804
|
+
if base in ("smallint", "int2", "smallserial"):
|
|
805
|
+
return "Int16"
|
|
806
|
+
if base in ("numeric", "decimal", "real", "double precision", "float4", "float8", "money"):
|
|
807
|
+
return "Float64"
|
|
808
|
+
if base in ("boolean", "bool"):
|
|
809
|
+
return "Bool"
|
|
810
|
+
return "String"
|
|
811
|
+
|
|
812
|
+
|
|
813
|
+
def pg_bind_type(type_: str, place: dict, pg_columns: dict[str, str]) -> str:
|
|
814
|
+
"""The PostgreSQL type a `$n` is bound as: the compared column's own type (a value compared with a uuid column is a
|
|
815
|
+
uuid) unless a function wraps the column or the value is a list; else the type the rules found, by its PostgreSQL name."""
|
|
816
|
+
col = place.get("column")
|
|
817
|
+
if col and col in pg_columns and not place.get("wrapper") and place.get("op") not in ("limit", "interval") \
|
|
818
|
+
and not pg_columns[col].strip().endswith("[]"):
|
|
819
|
+
return pg_one_word(pg_columns[col])
|
|
820
|
+
if place.get("cast"):
|
|
821
|
+
return pg_one_word(place["cast"])
|
|
822
|
+
return pg_one_word(PG_OF.get(type_, "text"))
|
|
823
|
+
|
|
824
|
+
|
|
825
|
+
PG_ONE_WORD = {"timestamp with time zone": "timestamptz", "timestamp without time zone": "timestamp", "time with time zone": "timetz",
|
|
826
|
+
"time without time zone": "time", "double precision": "float8", "character varying": "varchar", "character": "bpchar",
|
|
827
|
+
"bit varying": "varbit"}
|
|
828
|
+
|
|
829
|
+
|
|
830
|
+
def pg_one_word(pg_type: str) -> str:
|
|
831
|
+
"""A PostgreSQL type as one word, without a length (`character varying(255)` -> varchar, `timestamp with time zone` ->
|
|
832
|
+
timestamptz): the parameter form {name:type} must survive tools that read a type up to its first space or bracket,
|
|
833
|
+
and a cast to the bare type compares the same."""
|
|
834
|
+
bare = re.sub(r"\s+", " ", re.sub(r"\(.*?\)", "", (pg_type or "").strip())).strip()
|
|
835
|
+
low = bare.lower()
|
|
836
|
+
if low in PG_ONE_WORD:
|
|
837
|
+
return PG_ONE_WORD[low]
|
|
838
|
+
return "text" if " " in bare or not bare else bare # a user type keeps its case ("StatusKind")
|
|
839
|
+
|
|
840
|
+
|
|
841
|
+
# ---- one shape made runnable ----------------------------------------------------------------------------------------
|
|
842
|
+
|
|
843
|
+
def strip_databases(text: str, databases: set[str]) -> str:
|
|
844
|
+
"""The statement without database prefixes (`db.table` -> `table`): the sandbox has one database, and a database
|
|
845
|
+
name never leaves the machine."""
|
|
846
|
+
for d in sorted((d for d in databases if d and d.lower() not in ("system", "information_schema")), key=len, reverse=True):
|
|
847
|
+
text = re.sub(r"(?<![\w.`])`?" + re.escape(d) + r"`?\.(?=`?[A-Za-z_])", "", text)
|
|
848
|
+
return text
|
|
849
|
+
|
|
850
|
+
|
|
851
|
+
def _ident(name: str, used: set[str]) -> str:
|
|
852
|
+
base = re.sub(r"\W+", "_", name).strip("_").lower() or "p"
|
|
853
|
+
base = base if re.match(r"[a-z_]", base) else f"p_{base}"
|
|
854
|
+
out, n = base, 2
|
|
855
|
+
while out in used:
|
|
856
|
+
out, n = f"{base}_{n}", n + 1
|
|
857
|
+
used.add(out)
|
|
858
|
+
return out
|
|
859
|
+
|
|
860
|
+
|
|
861
|
+
def runnable(observed_text: str, code_sqls: list[str], columns: dict[str, str], *, neutral_values: bool = True,
|
|
862
|
+
least: int = 1, engine: str = "clickhouse", window_hours: float = 24) -> dict:
|
|
863
|
+
"""The observed statement with every `?` filled: {sql, params: {name: {type, column, op, source, clause, value?}},
|
|
864
|
+
filled: {code, catalog, neutral, open}, open: [...], fragments: [{marker, text}]}.
|
|
865
|
+
|
|
866
|
+
`code_sqls`: the call site's SQL (or, for a statement assembled from pieces, each piece's), aligned with the
|
|
867
|
+
statement to put the code's own literals and parameters back. Parameters keep the code's names where it has them.
|
|
868
|
+
|
|
869
|
+
PostgreSQL (`engine`): pg_stat_statements writes every constant and parameter as `$n`; each is a `?` here. `columns`
|
|
870
|
+
are the catalog's PostgreSQL types; a `$n::type` takes the cast's type; a value after a JSON operator (`->> $1`) is a
|
|
871
|
+
key nothing types inside a filter (open). The placeholders carry PostgreSQL types (pg_bind_type)."""
|
|
872
|
+
pg = engine == "postgres"
|
|
873
|
+
pg_columns = {**columns, **{k.lower(): v for k, v in columns.items()}} if pg else {} # a quoted "roleId" is compared as roleid
|
|
874
|
+
real_name = {k.lower(): k for k in columns} if pg else {}
|
|
875
|
+
if pg:
|
|
876
|
+
columns = {k: pg_internal(v) for k, v in pg_columns.items()}
|
|
877
|
+
obs = tokens(observed_text)
|
|
878
|
+
if pg:
|
|
879
|
+
obs = [{**t, "kind": "q"} if t["kind"] == "param" and re.fullmatch(r"\$\d+", t["text"]) else t for t in obs]
|
|
880
|
+
maps = []
|
|
881
|
+
code_tokens = [tokens(sql) for sql in code_sqls]
|
|
882
|
+
for ct in code_tokens:
|
|
883
|
+
maps.append(align(obs, ct, least))
|
|
884
|
+
used: set[str] = set()
|
|
885
|
+
out_tokens: list[str] = []
|
|
886
|
+
params: dict[str, dict] = {}
|
|
887
|
+
filled = {"code": 0, "catalog": 0, "neutral": 0, "open": 0}
|
|
888
|
+
open_: list[dict] = []
|
|
889
|
+
def code_at(i: int) -> dict | None:
|
|
890
|
+
"""The code's token at observed position i: aligned, or between two aligned neighbours (a masked identifier)."""
|
|
891
|
+
for ct, mp in zip(code_tokens, maps):
|
|
892
|
+
if i in mp:
|
|
893
|
+
return ct[mp[i]]
|
|
894
|
+
if i - 1 in mp and i + 1 in mp and mp[i + 1] - mp[i - 1] == 2:
|
|
895
|
+
return ct[mp[i - 1] + 1]
|
|
896
|
+
return None
|
|
897
|
+
|
|
898
|
+
drop_settings = False
|
|
899
|
+
aliases = aliases_of(obs)
|
|
900
|
+
epochs = epoch_units(obs, columns)
|
|
901
|
+
zones = 0
|
|
902
|
+
interval_guess = 0
|
|
903
|
+
for i, t in enumerate(obs):
|
|
904
|
+
if t["key"] == MASKED:
|
|
905
|
+
code_tok = code_at(i)
|
|
906
|
+
if code_tok is not None and code_tok["kind"] == "ident":
|
|
907
|
+
out_tokens.append(code_tok["text"])
|
|
908
|
+
filled["code"] += 1
|
|
909
|
+
elif _clause(obs, i) == "settings":
|
|
910
|
+
# a trailing SETTINGS clause whose names the server masked: left out (the matcher's shape leaves it out too)
|
|
911
|
+
drop_settings = True
|
|
912
|
+
out_tokens.append(t["text"])
|
|
913
|
+
else:
|
|
914
|
+
out_tokens.append(t["text"])
|
|
915
|
+
filled["open"] += 1
|
|
916
|
+
open_.append({"at": i, "clause": _clause(obs, i), "near": " ".join(x["text"] for x in obs[max(i - 4, 0):i + 2])[:120],
|
|
917
|
+
"identifier": True})
|
|
918
|
+
continue
|
|
919
|
+
if t["kind"] not in ("q", "qlist"):
|
|
920
|
+
out_tokens.append(t["text"])
|
|
921
|
+
continue
|
|
922
|
+
code_tok = code_at(i)
|
|
923
|
+
place = place_of(obs, i, columns, aliases)
|
|
924
|
+
if pg and i + 2 < len(obs) and obs[i + 1]["text"] == "::" and obs[i + 2]["kind"] == "ident":
|
|
925
|
+
# `$4::uuid`: the statement itself says the type
|
|
926
|
+
cast = obs[i + 2]["text"].strip('"')
|
|
927
|
+
place["cast"] = cast
|
|
928
|
+
if not place.get("column") or place.get("open"):
|
|
929
|
+
place.update(type=scalar_type(pg_internal(cast)), value_type=pg_internal(cast), op=place.get("op") or "cast", open=False)
|
|
930
|
+
elif pg and _json_minus(obs, i, pg_columns):
|
|
931
|
+
# `payload - $3 - $4`: keys removed from a JSON object, not numbers subtracted
|
|
932
|
+
place.update(type="String", op="json_key", column=None, open=bool(place.get("filter")))
|
|
933
|
+
elif pg and i and obs[i - 1]["text"] in PG_JSON_OPS:
|
|
934
|
+
# `data ->> $1`: a key of a JSON value; in a filter it decides which rows match and nothing tells which key
|
|
935
|
+
place.update(type="String", op="json_key", column=None, open=bool(place.get("filter")))
|
|
936
|
+
if place["open"] and not (code_tok is not None and code_tok["kind"] in ("str", "num")):
|
|
937
|
+
filled["open"] += 1
|
|
938
|
+
open_.append({"at": i, "clause": place["clause"], "near": " ".join(x["text"] for x in obs[max(i - 4, 0):i + 2])[:120]})
|
|
939
|
+
out_tokens.append("?")
|
|
940
|
+
continue
|
|
941
|
+
if pg and (place.get("function") in ("date_trunc", "datetrunc") or (_call(obs, i) or ("", -1))[0] in ("date_trunc", "date_part")) \
|
|
942
|
+
and (_call(obs, i) or ("", -1))[1] == 0 and not (code_tok is not None and code_tok["kind"] in ("str", "num")):
|
|
943
|
+
# `date_trunc($1, ts)`: a unit, not text; the log keeps none
|
|
944
|
+
out_tokens.append("'day'")
|
|
945
|
+
filled["neutral"] += 1
|
|
946
|
+
continue
|
|
947
|
+
if pg and place.get("op") == "interval" and not (code_tok is not None and code_tok["kind"] in ("str", "num")):
|
|
948
|
+
# `interval $1`: PostgreSQL takes a literal after INTERVAL, never a parameter; the log keeps none, so the run's
|
|
949
|
+
# window (time_window_hours) stands for it
|
|
950
|
+
out_tokens.append(f"'{window_hours:g} hours'")
|
|
951
|
+
filled["neutral"] += 1
|
|
952
|
+
interval_guess += 1
|
|
953
|
+
continue
|
|
954
|
+
if pg and place.get("cast") and re.match(r"jsonb?$", place["cast"], re.I) and not place.get("filter") \
|
|
955
|
+
and not (code_tok is not None and code_tok["kind"] in ("str", "num")):
|
|
956
|
+
out_tokens.append("'null'") # `$6::jsonb` outside the filters: a JSON value ('' is not one)
|
|
957
|
+
filled["neutral"] += 1
|
|
958
|
+
continue
|
|
959
|
+
if place.get("type") == TIMEZONE and not (code_tok is not None and code_tok["kind"] in ("str", "param")):
|
|
960
|
+
# a time function's zone: the log keeps no literal; it changes how a time is read, not which column
|
|
961
|
+
out_tokens.append("'UTC'")
|
|
962
|
+
filled["neutral"] += 1
|
|
963
|
+
zones += 1
|
|
964
|
+
continue
|
|
965
|
+
if t["kind"] == "qlist" and not place.get("list") and not t.get("cast"):
|
|
966
|
+
# `f(?..)`: normalizeQuery printed several arguments as one (`toDateTime64(?, 3)` -> `toDateTime64(?..)`). Only the
|
|
967
|
+
# code knows how many there were and what they are.
|
|
968
|
+
items = _code_values(code_tokens, maps, i)
|
|
969
|
+
call = _call(obs, i)
|
|
970
|
+
if not items and neutral_values and not place.get("filter") and call and FUNCTION_ARGS.get(call[0]) and call[0] not in TYPE_NAME_LAST:
|
|
971
|
+
# outside the filters, in a function whose arguments are known: the two values `?..` stands for at least
|
|
972
|
+
known = FUNCTION_ARGS[call[0]]
|
|
973
|
+
out_tokens.append(", ".join(neutral(known.get(call[1] + k) or known.get("*") or "String") for k in range(2)))
|
|
974
|
+
filled["neutral"] += 2
|
|
975
|
+
continue
|
|
976
|
+
precision = re.match(r"DateTime64\((\d+)", place.get("column_type") or "")
|
|
977
|
+
if not items and call and call[0] in DATETIME64_PARSERS and call[1] == 0 and place.get("bound") and precision:
|
|
978
|
+
# `ts >= toDateTime64(?..)`: a time bound of a DateTime64(p) column; the second argument is its precision
|
|
979
|
+
name = _ident(f"p_{place['column']}", used)
|
|
980
|
+
params[name] = {"type": "String", "column": place["column"], "op": f"{call[0]}()", "source": "catalog", "clause": place["clause"],
|
|
981
|
+
"filter": place.get("filter", False), "function": call[0], "bound": place["bound"], "column_type": place["column_type"]}
|
|
982
|
+
out_tokens.append("{" + f"{name}:String" + "}, " + precision.group(1))
|
|
983
|
+
filled["catalog"] += 2
|
|
984
|
+
continue
|
|
985
|
+
through = _bound_through(obs, i, columns) if not items and call and call[0] in DATETIME64_PARSERS and call[1] == 0 else None
|
|
986
|
+
if through:
|
|
987
|
+
# `ts < addDays(parseDateTime64BestEffort(?..), ?)`: a time the code passes and shifts before it bounds ts.
|
|
988
|
+
# The arguments normalizeQuery joined are the text, the precision of ts and a time zone (any count of
|
|
989
|
+
# literals prints as `?..`, so the gate still holds); the time is the window's start, shifted by the code
|
|
990
|
+
column, op_, fn_, col_type = through
|
|
991
|
+
digits = re.match(r"DateTime64\((\d+)", col_type)
|
|
992
|
+
name = _ident(f"p_{column}", used)
|
|
993
|
+
params[name] = {"type": "String", "column": column, "op": f"{call[0]}()", "source": "catalog", "clause": place["clause"],
|
|
994
|
+
"filter": place.get("filter", False), "function": call[0], "column_type": col_type,
|
|
995
|
+
**({"through": fn_} if fn_ else {"bound": op_})}
|
|
996
|
+
out_tokens.append("{" + f"{name}:String" + "}, " + (digits.group(1) if digits else "6") + ", 'UTC'")
|
|
997
|
+
filled["catalog"] += 1
|
|
998
|
+
filled["neutral"] += 2
|
|
999
|
+
continue
|
|
1000
|
+
if not items and neutral_values and not place.get("filter") and call and call[0] in ("if", "multiif"):
|
|
1001
|
+
# outside the filters, the last values of if/multiIf (`multiIf(c, 'a', 'b')` -> `multiIf(c, ?..)`): two
|
|
1002
|
+
# values of the type their sibling has, else text
|
|
1003
|
+
out_tokens.append(", ".join(neutral(place.get("type") or "String") for _ in range(2)))
|
|
1004
|
+
filled["neutral"] += 2
|
|
1005
|
+
continue
|
|
1006
|
+
if not items:
|
|
1007
|
+
filled["open"] += 1
|
|
1008
|
+
open_.append({"at": i, "clause": place["clause"], "near": " ".join(x["text"] for x in obs[max(i - 4, 0):i + 2])[:120],
|
|
1009
|
+
"collapsed": True})
|
|
1010
|
+
out_tokens.append("?")
|
|
1011
|
+
continue
|
|
1012
|
+
texts = []
|
|
1013
|
+
for k, tok in enumerate(items):
|
|
1014
|
+
if tok["kind"] in ("str", "num"):
|
|
1015
|
+
texts.append(tok["text"])
|
|
1016
|
+
filled["code"] += 1
|
|
1017
|
+
continue
|
|
1018
|
+
m = re.match(r"\{(\w+)\s*:\s*([^{}]*)\}", tok["text"])
|
|
1019
|
+
known = (FUNCTION_ARGS.get(call[0]) or {}) if call else {}
|
|
1020
|
+
type_k = m.group(2).strip() if m else (known.get(call[1] + k) or known.get("*")) if call else None
|
|
1021
|
+
if not type_k:
|
|
1022
|
+
texts.append("?")
|
|
1023
|
+
filled["open"] += 1
|
|
1024
|
+
open_.append({"at": i, "clause": place["clause"], "near": tok["text"], "collapsed": True})
|
|
1025
|
+
continue
|
|
1026
|
+
first = k == 0 and place.get("column") # `ts >= toDateTime64(?, 3)`: the first is the bound of ts
|
|
1027
|
+
stem = place["column"] if first else (call[0] if call else "value")
|
|
1028
|
+
name = m.group(1) if m and m.group(1) in params else _ident(m.group(1) if m else f"p_{stem}", used)
|
|
1029
|
+
params.setdefault(name, {"type": type_k, "column": place.get("column") if first else None, "op": f"{call[0]}()" if call else None,
|
|
1030
|
+
"source": "code", "clause": place["clause"], "filter": place.get("filter", False),
|
|
1031
|
+
**({"function": call[0]} if call else {}),
|
|
1032
|
+
**({x: place[x] for x in ("bound", "column_type") if place.get(x)} if first else {})})
|
|
1033
|
+
texts.append("{" + f"{name}:{type_k}" + "}")
|
|
1034
|
+
filled["code"] += 1
|
|
1035
|
+
out_tokens.append(", ".join(texts))
|
|
1036
|
+
continue
|
|
1037
|
+
if code_tok is not None and code_tok["kind"] in ("str", "num"):
|
|
1038
|
+
text = code_tok["text"]
|
|
1039
|
+
if t["kind"] == "qlist" and place.get("list"): # ('a', 'b') in code, (?..) in the log: keep the code's list
|
|
1040
|
+
ct, mp = next((ct, mp) for ct, mp in zip(code_tokens, maps) if i in mp)
|
|
1041
|
+
j, items = mp[i], [code_tok["text"]]
|
|
1042
|
+
while j + 2 < len(ct) and ct[j + 1]["text"] == "," and ct[j + 2]["kind"] in ("str", "num"):
|
|
1043
|
+
items.append(ct[j + 2]["text"])
|
|
1044
|
+
j += 2
|
|
1045
|
+
text = ", ".join(items)
|
|
1046
|
+
out_tokens.append(text)
|
|
1047
|
+
filled["code"] += 1
|
|
1048
|
+
continue
|
|
1049
|
+
name_hint = None
|
|
1050
|
+
type_ = place.get("type")
|
|
1051
|
+
source = "catalog"
|
|
1052
|
+
if code_tok is not None and code_tok["kind"] == "param":
|
|
1053
|
+
m = re.match(r"\{(\w+)\s*:\s*([^{}]*)\}", code_tok["text"])
|
|
1054
|
+
if m:
|
|
1055
|
+
name_hint, type_, source = m.group(1), m.group(2).strip(), "code"
|
|
1056
|
+
else:
|
|
1057
|
+
name_hint = (code_tok["text"].lstrip(":$%(").rstrip(")s") or None) if not code_tok["text"].startswith("$") else None
|
|
1058
|
+
source = "code" if type_ else "catalog"
|
|
1059
|
+
if place.get("op") == "setting":
|
|
1060
|
+
out_tokens.append("''" if place.get("setting") == "log_comment" else "0")
|
|
1061
|
+
filled["neutral"] += 1
|
|
1062
|
+
continue
|
|
1063
|
+
if type_ and (place.get("filter") or place.get("op") in ("limit", "interval") or place.get("column") or source == "code"):
|
|
1064
|
+
if name_hint and name_hint in params and params[name_hint]["type"] == type_:
|
|
1065
|
+
name = name_hint # the code binds one parameter in several places: one value
|
|
1066
|
+
else:
|
|
1067
|
+
stem = place.get("column") or place.get("alias") or place.get("function") or place.get("op") or "value"
|
|
1068
|
+
name = _ident(name_hint or f"p_{stem}", used)
|
|
1069
|
+
array = type_.startswith("Array(")
|
|
1070
|
+
bind = type_[6:-1] if place.get("list") and array and source != "code" else type_
|
|
1071
|
+
wrap = (t["kind"] == "qlist" or (t.get("list") and not (source == "code" and array))) and obs[i - 1]["text"] not in ("(", "[")
|
|
1072
|
+
shown = pg_bind_type(bind, place, pg_columns) if pg else bind
|
|
1073
|
+
out_tokens.append(("(" if wrap else "") + "{" + f"{name}:{shown}" + "}" + (")" if wrap else ""))
|
|
1074
|
+
params.setdefault(name, {"type": bind, "column": real_name.get(place.get("column") or "", place.get("column")), "op": place.get("op"), "source": source,
|
|
1075
|
+
"clause": place["clause"], "filter": place.get("filter", False),
|
|
1076
|
+
**({"pg_type": shown} if pg else {}),
|
|
1077
|
+
**{k: place[k] for k in ("bound", "column_type", "function", "wrapper", "alias", "alias_type", "value_type")
|
|
1078
|
+
if place.get(k)}})
|
|
1079
|
+
filled["code" if source == "code" else "catalog"] += 1
|
|
1080
|
+
continue
|
|
1081
|
+
if type_ and neutral_values and not place.get("filter"):
|
|
1082
|
+
out_tokens.append(neutral(type_, engine))
|
|
1083
|
+
filled["neutral"] += 1
|
|
1084
|
+
continue
|
|
1085
|
+
if neutral_values and not place.get("filter") and place.get("clause") in ("select", "group", "order"):
|
|
1086
|
+
out_tokens.append(neutral("String"))
|
|
1087
|
+
filled["neutral"] += 1
|
|
1088
|
+
continue
|
|
1089
|
+
filled["open"] += 1
|
|
1090
|
+
open_.append({"at": i, "clause": place["clause"], "near": " ".join(x["text"] for x in obs[max(i - 4, 0):i + 2])[:120]})
|
|
1091
|
+
out_tokens.append("?")
|
|
1092
|
+
fragments = []
|
|
1093
|
+
for ct, mp in zip(code_tokens, maps):
|
|
1094
|
+
back = {b: a for a, b in mp.items()}
|
|
1095
|
+
for j, tok in enumerate(ct):
|
|
1096
|
+
if tok["kind"] != "frag":
|
|
1097
|
+
continue
|
|
1098
|
+
before = max((back[k] for k in range(j) if k in back), default=-1)
|
|
1099
|
+
after = min((back[k] for k in range(j + 1, len(ct)) if k in back), default=len(obs))
|
|
1100
|
+
fragments.append({"marker": tok["text"][:80], "tokens": max(after - before - 1, 0),
|
|
1101
|
+
"text": _join([x["text"] for x in obs[before + 1:after]])[:4000]})
|
|
1102
|
+
notes = []
|
|
1103
|
+
if drop_settings:
|
|
1104
|
+
at = max((k for k, x in enumerate(out_tokens) if x.upper() == "SETTINGS"), default=None)
|
|
1105
|
+
if at is not None:
|
|
1106
|
+
out_tokens = out_tokens[:at]
|
|
1107
|
+
notes.append("the statement's trailing SETTINGS were left out: the server masked their names in the log")
|
|
1108
|
+
if interval_guess:
|
|
1109
|
+
notes.append(f"{interval_guess} interval(s) the log does not keep (PostgreSQL takes no parameter there) run as the run's window, {window_hours:g} hours")
|
|
1110
|
+
if zones:
|
|
1111
|
+
notes.append(f"{zones} time zone argument(s) the log does not keep run as 'UTC'")
|
|
1112
|
+
for p in params.values():
|
|
1113
|
+
if p.get("column") in epochs:
|
|
1114
|
+
p["epoch_unit"] = epochs[p["column"]] # a number column the statement reads as a time (epoch_units)
|
|
1115
|
+
if epochs:
|
|
1116
|
+
notes.append("number columns read as a time: " + ", ".join(f"{c} ({u} since the epoch)" for c, u in sorted(epochs.items())))
|
|
1117
|
+
sql = re.sub(r"\s+FORMAT\s+\w+\s*;?\s*$", "", _join(out_tokens), flags=re.I) # the benchmark chooses its own output format
|
|
1118
|
+
return {"sql": sql, "params": params, "filled": filled, "open": open_, "fragments": fragments, "notes": notes, "epoch_columns": epochs}
|
|
1119
|
+
|
|
1120
|
+
|
|
1121
|
+
def _code_values(code_tokens: list[list[dict]], maps: list[dict[int, int]], i: int) -> list[dict]:
|
|
1122
|
+
"""The code's run of values (`'x', 3`, `?, 3`) at the place observed token i aligns with, or [] when it aligns nowhere."""
|
|
1123
|
+
for ct, mp in zip(code_tokens, maps):
|
|
1124
|
+
if i not in mp:
|
|
1125
|
+
continue
|
|
1126
|
+
j = mp[i]
|
|
1127
|
+
if ct[j]["kind"] not in VALUE_KINDS:
|
|
1128
|
+
return []
|
|
1129
|
+
while j >= 2 and ct[j - 1]["text"] == "," and ct[j - 2]["kind"] in VALUE_KINDS: # the run starts at its first value
|
|
1130
|
+
j -= 2
|
|
1131
|
+
items = [ct[j]]
|
|
1132
|
+
while j + 2 < len(ct) and ct[j + 1]["text"] == "," and ct[j + 2]["kind"] in VALUE_KINDS:
|
|
1133
|
+
items.append(ct[j + 2])
|
|
1134
|
+
j += 2
|
|
1135
|
+
return items
|
|
1136
|
+
return []
|
|
1137
|
+
|
|
1138
|
+
|
|
1139
|
+
def _join(parts: list[str]) -> str:
|
|
1140
|
+
"""Tokens back into text: a space between two words, none around punctuation that does not need one."""
|
|
1141
|
+
out = ""
|
|
1142
|
+
for p in parts:
|
|
1143
|
+
if not out:
|
|
1144
|
+
out = p
|
|
1145
|
+
elif p in (",", ")", "]", ".", "::") or out.endswith(("(", "[", ".", "::")) or (p in ("(", "[") and re.search(r"\w$", out)):
|
|
1146
|
+
out += p
|
|
1147
|
+
else:
|
|
1148
|
+
out += " " + p
|
|
1149
|
+
return out
|
|
1150
|
+
|
|
1151
|
+
|
|
1152
|
+
def gate(baseline: str, observed_text: str, tables: list[str]) -> dict:
|
|
1153
|
+
"""The mechanical check: the baseline, normalized by the matcher, is the observed shape. {ok, reason?, detail?}."""
|
|
1154
|
+
if re.search(r"`\?`|\"\?\"", baseline):
|
|
1155
|
+
return {"ok": False, "reason": "identifier_masked", "detail": "the server masked a quoted name in the logged text and the code does not hold it"}
|
|
1156
|
+
unquoted = re.sub(r"'(?:[^'\\]|\\.|'')*'", "", baseline)
|
|
1157
|
+
if "?" in unquoted or re.search(r"(?<![\w$])\$\d+\b", unquoted):
|
|
1158
|
+
# a `?`, or a PostgreSQL `$n` no source filled: the benchmark would have no value to bind
|
|
1159
|
+
return {"ok": False, "reason": "value_type_open", "detail": "a value production sent could not be typed from the code or the catalog"}
|
|
1160
|
+
mine, theirs = match_mod.shape(baseline, tables), match_mod.shape(observed_text, tables)
|
|
1161
|
+
if mine == theirs or match_mod.loose(mine) == match_mod.loose(theirs):
|
|
1162
|
+
return {"ok": True}
|
|
1163
|
+
a, b = match_mod.loose(mine), match_mod.loose(theirs)
|
|
1164
|
+
if match_mod.IDENT in b and re.fullmatch(r"[a-z_][\w.]*".join(re.escape(p) for p in b.split(match_mod.IDENT)), a):
|
|
1165
|
+
return {"ok": True, "how": "identifier"} # the server masked a name the code holds (the matcher's `identifier`)
|
|
1166
|
+
at = next((k for k in range(min(len(a), len(b))) if a[k] != b[k]), min(len(a), len(b)))
|
|
1167
|
+
return {"ok": False, "reason": "shape_differs", "detail": f"the runnable text normalizes to another shape from character {at}"}
|
|
1168
|
+
|
|
1169
|
+
|
|
1170
|
+
# ---- values -----------------------------------------------------------------------------------------------------------
|
|
1171
|
+
|
|
1172
|
+
RANGE_OPS = ("<", ">", "<=", ">=")
|
|
1173
|
+
|
|
1174
|
+
|
|
1175
|
+
def _stem(column: str) -> str:
|
|
1176
|
+
"""Columns that hold the same thing under two names (`tenant` and `tenant_id`) take one value."""
|
|
1177
|
+
return re.sub(r"_(id|uuid|key)$", "", (column or "").lower())
|
|
1178
|
+
|
|
1179
|
+
|
|
1180
|
+
EPOCH_SCALE = {"s": 1, "ms": 1000, "us": 1_000_000, "ns": 1_000_000_000}
|
|
1181
|
+
|
|
1182
|
+
|
|
1183
|
+
def time_spec(p: dict, columns: dict[str, str]) -> dict | None:
|
|
1184
|
+
"""Where a parameter's value falls in the run's time window, and in which form: {at, form, fmt?, int?, why}, or None
|
|
1185
|
+
for a value that is not a time.
|
|
1186
|
+
|
|
1187
|
+
`at`: start (a lower bound, or a time the code shifts before it bounds: `ts < addDays(parse(?), 1)`), end (an upper
|
|
1188
|
+
bound) or mid (a time compared for equality, or `toYYYYMM(ts) = ?`). `form`: s, ms, us or ns since the epoch, text
|
|
1189
|
+
the server parses, or a strftime pattern (`fmt`; `int` when the value is a number such as 202611)."""
|
|
1190
|
+
spec = _time_spec(p, columns)
|
|
1191
|
+
t = p.get("type") or ""
|
|
1192
|
+
if spec and t.startswith("Array("):
|
|
1193
|
+
# the code binds a list of times (`toDate(ts) IN {days:Array(Date)}`): one, in the element's form
|
|
1194
|
+
inner = base_type(t[6:-1])
|
|
1195
|
+
if inner.startswith("Date") and not inner.startswith("DateTime"):
|
|
1196
|
+
spec.update(form="fmt", fmt="%Y-%m-%d", int=False)
|
|
1197
|
+
spec["list"] = True
|
|
1198
|
+
return spec
|
|
1199
|
+
|
|
1200
|
+
|
|
1201
|
+
def _time_spec(p: dict, columns: dict[str, str]) -> dict | None:
|
|
1202
|
+
col, op = p.get("column"), p.get("op") or ""
|
|
1203
|
+
fn = p.get("function") or ""
|
|
1204
|
+
bound = p.get("bound") or (op if op in RANGE_OPS else None)
|
|
1205
|
+
col_type = p.get("column_type") or base_type(columns.get(col or "", ""))
|
|
1206
|
+
t = p.get("type") or ""
|
|
1207
|
+
epoch = p.get("epoch_unit")
|
|
1208
|
+
unit = "us" if "micro" in fn else "ms" if "milli" in fn else "ns" if "nano" in fn else None
|
|
1209
|
+
if p.get("wrapper") in TIME_WRAPPERS:
|
|
1210
|
+
kind, fmt = TIME_WRAPPERS[p["wrapper"]]
|
|
1211
|
+
return {"at": "mid", "form": "fmt", "fmt": fmt, "int": kind.startswith("UInt"), "why": f"{p['wrapper']}({col}) compared with a value"}
|
|
1212
|
+
if p.get("through") and col:
|
|
1213
|
+
return {"at": "start", "form": unit or "text", "why": f"a time the code passes to {fn}() and shifts with {p['through']}() before it bounds {col}"}
|
|
1214
|
+
if bound in RANGE_OPS and (col or p.get("alias")) and (TIME_TYPE.match((col_type if col else p.get("alias_type")) or "") or epoch):
|
|
1215
|
+
form = unit or epoch or ("s" if NUMBER_TYPE.match(t) and t != "Bool" else "text")
|
|
1216
|
+
return {"at": "start" if bound in (">", ">=") else "end", "form": form,
|
|
1217
|
+
"why": f"{'an upper' if bound in ('<', '<=') else 'a lower'} bound of {col or p.get('alias')}"
|
|
1218
|
+
+ (f" ({epoch} since the epoch, as the statement reads it)" if epoch and not unit else "")}
|
|
1219
|
+
if col and TIME_TYPE.match(col_type or ""):
|
|
1220
|
+
return {"at": "mid", "form": unit or "text", "why": f"a time the code compares {col} with"}
|
|
1221
|
+
if p.get("alias_type") and TIME_TYPE.match(p["alias_type"]):
|
|
1222
|
+
date = p["alias_type"].startswith("Date") and not p["alias_type"].startswith("DateTime")
|
|
1223
|
+
return {"at": "mid", "form": "fmt", "fmt": "%Y-%m-%d" if date else "%Y-%m-%d %H:%M:%S", "int": False,
|
|
1224
|
+
"why": f"a time the code compares {p.get('alias')} ({p['alias_type']}) with"}
|
|
1225
|
+
if re.match(r"(parsedatetime|todatetime|todate|fromunixtimestamp)", fn):
|
|
1226
|
+
# a time passed to a time function, with no column bound we can see: the window's start
|
|
1227
|
+
return {"at": "start", "form": unit or ("s" if fn == "fromunixtimestamp" else "text"), "why": f"a time passed to {fn}()"}
|
|
1228
|
+
return None
|
|
1229
|
+
|
|
1230
|
+
|
|
1231
|
+
def fitting(text: str, type_: str) -> str:
|
|
1232
|
+
"""A value of `type_` made from `text`: the server parses a String value compared with a UUID, an Enum, an IP or a
|
|
1233
|
+
FixedString column, and refuses one that is not of its form ("Cannot parse UUID", "Unknown element for enum").
|
|
1234
|
+
A UUID is derived from the text (the same text gives the same UUID), an Enum takes its first name."""
|
|
1235
|
+
import uuid as uuid_mod
|
|
1236
|
+
b = base_type(type_ or "")
|
|
1237
|
+
if b == "UUID":
|
|
1238
|
+
# "qopt:": the seed from before the rename (formerly qopt), kept so the generated values stay the same
|
|
1239
|
+
return str(uuid_mod.uuid5(uuid_mod.NAMESPACE_URL, "qopt:" + text))
|
|
1240
|
+
if b.startswith("Enum"):
|
|
1241
|
+
names = re.findall(r"'((?:[^'\\]|\\.)*)'\s*=", b)
|
|
1242
|
+
return names[0] if names else text
|
|
1243
|
+
if b == "IPv4":
|
|
1244
|
+
return f"10.0.{len(text) % 256}.{sum(map(ord, text)) % 254 + 1}"
|
|
1245
|
+
if b == "IPv6":
|
|
1246
|
+
return f"::ffff:10.0.{len(text) % 256}.{sum(map(ord, text)) % 254 + 1}"
|
|
1247
|
+
m = re.match(r"FixedString\((\d+)\)", b)
|
|
1248
|
+
if m:
|
|
1249
|
+
return text[:int(m.group(1))]
|
|
1250
|
+
return text
|
|
1251
|
+
|
|
1252
|
+
|
|
1253
|
+
def time_value(spec: dict, end: datetime, window_hours: float):
|
|
1254
|
+
"""The value of a time parameter for a window of `window_hours` that ends at `end` (time_spec)."""
|
|
1255
|
+
at = {"start": end - timedelta(hours=window_hours), "end": end, "mid": end - timedelta(hours=window_hours / 2)}[spec.get("at", "mid")]
|
|
1256
|
+
form = spec.get("form")
|
|
1257
|
+
if form in EPOCH_SCALE:
|
|
1258
|
+
value = int(at.replace(tzinfo=at.tzinfo or timezone.utc).timestamp() * EPOCH_SCALE[form])
|
|
1259
|
+
elif form == "fmt":
|
|
1260
|
+
text = at.strftime(spec.get("fmt") or "%Y-%m-%d %H:%M:%S")
|
|
1261
|
+
value = int(text) if spec.get("int") else text
|
|
1262
|
+
else:
|
|
1263
|
+
value = at.strftime("%Y-%m-%d %H:%M:%S")
|
|
1264
|
+
return [value] if spec.get("list") else value
|
|
1265
|
+
|
|
1266
|
+
|
|
1267
|
+
def choose_values(params: dict[str, dict], columns: dict[str, str], finding: str, *, now: datetime, window_hours: float) -> tuple[dict, list[str]]:
|
|
1268
|
+
"""A value for every named parameter, and the assumptions they stand on.
|
|
1269
|
+
|
|
1270
|
+
Equality on a column: one value per column stem, which the candidate's own fixture puts on rows (catalog_profile.py),
|
|
1271
|
+
so the fit can move how many rows carry it. A time range: the last `window_hours`, in the unit the code passes
|
|
1272
|
+
(microseconds, milliseconds, seconds, or text the server parses). A flag the code binds: true. A count: 1000."""
|
|
1273
|
+
values, notes = {}, []
|
|
1274
|
+
by_stem: dict[str, str] = {}
|
|
1275
|
+
tag = finding.lower().replace("-", "")
|
|
1276
|
+
for name, p in params.items():
|
|
1277
|
+
col, op = p.get("column"), p.get("op") or ""
|
|
1278
|
+
t = p["type"]
|
|
1279
|
+
fn = p.get("function") or ""
|
|
1280
|
+
spec = time_spec(p, columns)
|
|
1281
|
+
if spec:
|
|
1282
|
+
# a time: kept as where it falls in the window (start, middle, end) and in which form, so the benchmark puts
|
|
1283
|
+
# the window where its data is (time_value, bench.anchor_times); the value here is the one for `now`
|
|
1284
|
+
p["time"] = spec
|
|
1285
|
+
values[name] = time_value(spec, now, window_hours)
|
|
1286
|
+
notes.append(f"{name}: {spec['why']}; the run covers the last {window_hours:g} h before the benchmark's clock")
|
|
1287
|
+
elif op == "flag" or t == "Bool":
|
|
1288
|
+
values[name] = True
|
|
1289
|
+
notes.append(f"{name}: a condition the code binds as a value; run as true (the log does not say which)")
|
|
1290
|
+
elif op == "flag_compare":
|
|
1291
|
+
values[name] = ""
|
|
1292
|
+
notes.append(f"{name}: one side of a comparison of two values the code binds; both sides run as '' (equal)")
|
|
1293
|
+
elif op == "limit":
|
|
1294
|
+
values[name] = 1000
|
|
1295
|
+
notes.append(f"{name}: a row limit the code binds; run with 1000 (the log does not say which)")
|
|
1296
|
+
elif op == "interval":
|
|
1297
|
+
values[name] = 1
|
|
1298
|
+
elif t.startswith("Array("):
|
|
1299
|
+
inner = base_type(t[6:-1])
|
|
1300
|
+
one = by_stem.setdefault(_stem(col or name), fitting(f"{_stem(col or name)}-{tag}", base_type(columns.get(col or "", "")))) \
|
|
1301
|
+
if inner.startswith("String") else 7
|
|
1302
|
+
values[name] = [one]
|
|
1303
|
+
notes.append(f"{name}: a list the code binds; run with one value")
|
|
1304
|
+
elif col and t == "String":
|
|
1305
|
+
stem = _stem(col)
|
|
1306
|
+
target = p.get("value_type") or base_type(columns.get(col, ""))
|
|
1307
|
+
values[name] = by_stem.setdefault(stem if target == base_type(columns.get(col, "")) else f"{stem}:{target}",
|
|
1308
|
+
fitting(f"{stem}-{tag}", target))
|
|
1309
|
+
if values[name] != f"{stem}-{tag}":
|
|
1310
|
+
notes.append(f"{name}: compared with a value of type {target}; run with {values[name]!r}, a value of that type")
|
|
1311
|
+
elif col and NUMBER_TYPE.match(t):
|
|
1312
|
+
values[name] = by_stem.setdefault(_stem(col), 7)
|
|
1313
|
+
else:
|
|
1314
|
+
vt = p.get("value_type") or ""
|
|
1315
|
+
if vt == "UUID": # `$1::uuid` with no column: a value of the type the statement casts to
|
|
1316
|
+
values[name] = fitting(f"{name}-{tag}", "UUID")
|
|
1317
|
+
elif TIME_TYPE.match(vt):
|
|
1318
|
+
values[name] = time_value({"at": "mid", "form": "text"}, now, window_hours)
|
|
1319
|
+
else:
|
|
1320
|
+
values[name] = "" if t == "String" else 1
|
|
1321
|
+
notes.append(f"{name}: no column to take a value from; run with {values[name]!r}")
|
|
1322
|
+
return values, notes
|
|
1323
|
+
|
|
1324
|
+
|
|
1325
|
+
# ---- building the candidates --------------------------------------------------------------------------------------
|
|
1326
|
+
|
|
1327
|
+
def _columns_of(facts, engine: str, tables: list[str]) -> dict[str, str]:
|
|
1328
|
+
out: dict[str, str] = {}
|
|
1329
|
+
for name in tables:
|
|
1330
|
+
t = facts.tables(engine).get(name)
|
|
1331
|
+
for c in (t or {}).get("columns") or []:
|
|
1332
|
+
out.setdefault(c["name"], c.get("type", ""))
|
|
1333
|
+
return out
|
|
1334
|
+
|
|
1335
|
+
|
|
1336
|
+
def _databases(catalog: dict) -> set[str]:
|
|
1337
|
+
out = set()
|
|
1338
|
+
for conn in (catalog.get("connections") or {}).values():
|
|
1339
|
+
out |= {d.get("database") for d in conn.get("databases") or [] if d.get("database")}
|
|
1340
|
+
out |= {t.get("database") for t in conn.get("tables") or [] if t.get("database")}
|
|
1341
|
+
out |= {d for d in conn.get("databases_described") or [] if d}
|
|
1342
|
+
return out
|
|
1343
|
+
|
|
1344
|
+
|
|
1345
|
+
def _scope(inventory: dict, rank: dict | None, matchdata: dict, settings: dict, sql_cut: int) -> set[str]:
|
|
1346
|
+
"""The call sites an observed statement is built for. `unresolved` (the default): the ones the agent rejected as
|
|
1347
|
+
unresolved SQL, and, of the ones it was never shown, those whose SQL it could not have read (run-time parts, or longer
|
|
1348
|
+
than the prompt shows). `all`: every matched call site that is not already a candidate."""
|
|
1349
|
+
sites = {c["id"]: c for c in inventory.get("call_sites") or [] if c.get("id")}
|
|
1350
|
+
candidates = {c["id"] for c in (rank or {}).get("candidates") or []}
|
|
1351
|
+
rejected = {r["id"]: r for r in (rank or {}).get("rejected") or [] if r.get("id")}
|
|
1352
|
+
out = set()
|
|
1353
|
+
for sid in (matchdata.get("sites") or {}):
|
|
1354
|
+
if sid in candidates or sid not in sites:
|
|
1355
|
+
continue
|
|
1356
|
+
s = sites[sid]
|
|
1357
|
+
if settings["observed_for"] == "all" and sid not in rejected:
|
|
1358
|
+
out.add(sid)
|
|
1359
|
+
elif (rejected.get(sid) or {}).get("code") == "unresolved_sql":
|
|
1360
|
+
out.add(sid)
|
|
1361
|
+
elif sid not in rejected and (has_fragment(s.get("sql") or "") or len((s.get("sql") or "").strip()) > sql_cut
|
|
1362
|
+
or not (s.get("sql") or "").strip()):
|
|
1363
|
+
out.add(sid) # run-time parts, longer than the prompt shows, or no text at all (placed by a tag)
|
|
1364
|
+
return out
|
|
1365
|
+
|
|
1366
|
+
|
|
1367
|
+
def _site_brief(s: dict) -> dict:
|
|
1368
|
+
return {"site_id": s["id"], "file": s.get("file", ""), "line": s.get("line", 0), "symbol": s.get("symbol", ""), "sql_hash": s.get("sql_hash", "")}
|
|
1369
|
+
|
|
1370
|
+
|
|
1371
|
+
def build(inventory: dict, facts, *, rank: dict | None = None, settings: dict | None = None, previous: dict | None = None,
|
|
1372
|
+
engine: str | None = None, now: datetime | None = None, sql_cut: int | None = None) -> dict:
|
|
1373
|
+
"""observed.json: candidates whose baseline is a statement production ran, the gate's rejections, the shapes below the
|
|
1374
|
+
line, and production statements with no place in code. `facts`: realdb.facts (the pulled files). `previous`: an
|
|
1375
|
+
earlier observed.json, so a shape keeps its label (O-001...) across runs."""
|
|
1376
|
+
from .realdb.ratios import classify
|
|
1377
|
+
from .rank import sql_cut_of
|
|
1378
|
+
settings = settings_of(settings) if settings is None or "shape_min_share" not in settings else settings
|
|
1379
|
+
engine = engine or (rank or {}).get("engine") or next(iter((facts.matchdata.get("engines") or {})), "")
|
|
1380
|
+
m = facts.match(engine) or {}
|
|
1381
|
+
now = now or datetime.now(timezone.utc).replace(minute=0, second=0, microsecond=0)
|
|
1382
|
+
cut = sql_cut if sql_cut is not None else sql_cut_of(rank)
|
|
1383
|
+
workload = next((w for w in (facts.workload.get("connections") or {}).values() if w.get("engine") == engine), None)
|
|
1384
|
+
if workload is None and facts.out_dir is not None:
|
|
1385
|
+
from .dbcli import load_workload
|
|
1386
|
+
try:
|
|
1387
|
+
whole = load_workload(facts.out_dir)
|
|
1388
|
+
except (OSError, ValueError):
|
|
1389
|
+
whole = {}
|
|
1390
|
+
workload = next((w for w in (whole.get("connections") or {}).values() if w.get("engine") == engine), {}) or {}
|
|
1391
|
+
texts = {q["hash"]: q for q in (workload or {}).get("queries") or []}
|
|
1392
|
+
rows = {q["hash"]: q for q in m.get("queries") or []}
|
|
1393
|
+
sites = {c["id"]: c for c in inventory.get("call_sites") or [] if c.get("id")}
|
|
1394
|
+
databases = _databases(facts.catalog)
|
|
1395
|
+
labels: dict[str, str] = dict((previous or {}).get("labels") or {})
|
|
1396
|
+
next_label = max((int(v[2:]) for v in labels.values() if re.fullmatch(r"O-\d+", v)), default=0)
|
|
1397
|
+
scope = _scope(inventory, rank, m, settings, cut)
|
|
1398
|
+
total_bytes = int((m.get("workload") or {}).get("read_bytes") or 0)
|
|
1399
|
+
candidates, rejected, below = [], [], []
|
|
1400
|
+
by_hash: dict[str, dict] = {}
|
|
1401
|
+
gates: dict[str, dict] = {}
|
|
1402
|
+
|
|
1403
|
+
def label_for(key: str) -> str:
|
|
1404
|
+
nonlocal next_label
|
|
1405
|
+
if key not in labels:
|
|
1406
|
+
next_label += 1
|
|
1407
|
+
labels[key] = f"O-{next_label:03d}"
|
|
1408
|
+
return labels[key]
|
|
1409
|
+
|
|
1410
|
+
for sid in sorted(scope, key=lambda s: (-int((m["sites"][s] or {}).get("read_bytes") or 0), s)):
|
|
1411
|
+
row, site = m["sites"][sid], sites[sid]
|
|
1412
|
+
grade = row["match"]
|
|
1413
|
+
if grade not in ("exact", "template", "tag", "part"):
|
|
1414
|
+
continue
|
|
1415
|
+
hashes = [h for h in row.get("hashes") or [] if h in rows]
|
|
1416
|
+
site_bytes = sum(int(rows[h]["read_bytes"]) for h in hashes) or 1
|
|
1417
|
+
ordered = sorted(hashes, key=lambda h: -int(rows[h]["read_bytes"]))
|
|
1418
|
+
kept = [h for h in ordered if int(rows[h]["read_bytes"]) / site_bytes >= settings["shape_min_share"]][:int(settings["max_shapes_per_site"])]
|
|
1419
|
+
if not kept and ordered:
|
|
1420
|
+
kept = ordered[:1] # the heaviest shape always: a site whose bytes are spread thin still has its main statement
|
|
1421
|
+
left = [h for h in ordered if h not in kept]
|
|
1422
|
+
if left:
|
|
1423
|
+
below.append({"site_id": sid, "shapes": len(left), "read_bytes": sum(int(rows[h]["read_bytes"]) for h in left),
|
|
1424
|
+
"share_of_site_bytes": round(sum(int(rows[h]["read_bytes"]) for h in left) / site_bytes, 4)})
|
|
1425
|
+
for h in kept:
|
|
1426
|
+
q, text_row = rows[h], texts.get(h) or {}
|
|
1427
|
+
reason = None
|
|
1428
|
+
places = [sites[x] for x in q.get("site_ids") or [] if x in sites]
|
|
1429
|
+
if grade == "template" and len({p.get("sql_hash") for p in places}) > 1:
|
|
1430
|
+
reason = ("ambiguous_template", f"{len(places)} call sites with different SQL match this statement through their templates")
|
|
1431
|
+
text = text_row.get("text") or ""
|
|
1432
|
+
# `text_truncated` of older pulls compares the raw statement's length (with its literals) with the cut; the
|
|
1433
|
+
# normalized text is cut only when it reaches it
|
|
1434
|
+
limit = int((workload or {}).get("text_max_chars") or TEXT_CUT_BEFORE_SETTING)
|
|
1435
|
+
if reason is None and not text:
|
|
1436
|
+
reason = ("no_text", "the pull kept no text for this shape")
|
|
1437
|
+
elif reason is None and not is_read(text, text_row.get("kind")):
|
|
1438
|
+
reason = ("not_a_read", f"production ran it as a {(text_row.get('kind') or 'write').lower()}: candidates are reads only "
|
|
1439
|
+
"(a write changes the rows the benchmark compares results on)")
|
|
1440
|
+
elif reason is None and (match_mod.TEMP_TABLE.search(text) or any(match_mod.TEMP_TABLE.search(str(x)) for x in text_row.get("tables") or [])):
|
|
1441
|
+
reason = ("external_data", "it reads a table of external data sent with each query (_tmp_<uuid>): not in the catalog")
|
|
1442
|
+
elif reason is None and text_row.get("text_truncated") and len(text) >= limit:
|
|
1443
|
+
reason = ("text_cut_at_limit", f"the pull cut this statement's text at {limit:,} characters (db_pull.text_max_chars)")
|
|
1444
|
+
tables = tables_of(text, q.get("tables") or text_row.get("tables") or [], engine)
|
|
1445
|
+
user_tables = [t for t in tables if not (t.startswith("system") or t in ("one", "numbers"))]
|
|
1446
|
+
if reason is None:
|
|
1447
|
+
missing = [t for t in user_tables if facts.definition(engine, t) is None]
|
|
1448
|
+
if missing:
|
|
1449
|
+
reason = ("table_not_in_catalog", f"no loadable definition for {', '.join(missing[:4])} in the pulled catalog")
|
|
1450
|
+
elif not user_tables:
|
|
1451
|
+
reason = ("table_not_in_catalog", "no table of the pulled catalog could be read from the statement's text: "
|
|
1452
|
+
"nothing for the benchmark to build")
|
|
1453
|
+
built = None
|
|
1454
|
+
if reason is None:
|
|
1455
|
+
clean = strip_databases(text, databases)
|
|
1456
|
+
columns = _columns_of(facts, engine, user_tables)
|
|
1457
|
+
code = [p["sql"] for p in places if p.get("sql")] if grade in ("part", "tag") else [site["sql"]]
|
|
1458
|
+
built = runnable(clean, code or [site["sql"]], columns, neutral_values=settings["neutral_values"], least=3 if grade in ("part", "tag") else 1,
|
|
1459
|
+
engine=engine, window_hours=float(settings["time_window_hours"]))
|
|
1460
|
+
g = gate(built["sql"], text, text_row.get("tables") or q.get("tables") or []) # the log's names, with their database
|
|
1461
|
+
if not g["ok"]:
|
|
1462
|
+
reason = (g["reason"], g["detail"])
|
|
1463
|
+
key = f"{sid}:{h}"
|
|
1464
|
+
if reason is not None:
|
|
1465
|
+
rec = {"site_id": sid, "hash": h, "located": grade, "reason": reason[0], "detail": reason[1],
|
|
1466
|
+
"read_bytes": int(q["read_bytes"]), "executions": int(q["executions"]),
|
|
1467
|
+
**({"open": built["open"][:6], "filled": built["filled"]} if built else {})}
|
|
1468
|
+
rejected.append(rec)
|
|
1469
|
+
gates.setdefault(sid, {"reason": reason[0], "detail": reason[1], "hash": h})
|
|
1470
|
+
continue
|
|
1471
|
+
if h in by_hash: # the same statement from another call site: one candidate, several places
|
|
1472
|
+
by_hash[h]["observed"]["places"] = sorted({*by_hash[h]["observed"]["places"], sid})
|
|
1473
|
+
continue
|
|
1474
|
+
finding = label_for(key)
|
|
1475
|
+
values, notes = choose_values(built["params"], value_columns(columns, engine), finding, now=now,
|
|
1476
|
+
window_hours=float(settings["time_window_hours"]))
|
|
1477
|
+
fixed = len(match_mod.loose(match_mod.shape(site["sql"]).replace(match_mod.FRAGMENT, ""))) if grade != "part" else None
|
|
1478
|
+
observed_loose = len(match_mod.loose(match_mod.shape(text, text_row.get("tables") or q.get("tables") or [])))
|
|
1479
|
+
cand = {
|
|
1480
|
+
"finding": finding, "id": sid,
|
|
1481
|
+
"title": ("Production statement that contains " if grade == "part" else "Production statement of ") + f"{site['file'].split('/')[-1]}:{site.get('line', 0)}",
|
|
1482
|
+
"severity": "medium", "confidence": "high" if grade in PLACES else "medium",
|
|
1483
|
+
"baseline_sql": built["sql"], "params": values, "tables": user_tables, "variants": [], "causes": [],
|
|
1484
|
+
"assumptions": ["the statement is the one production ran (query log); values are chosen, the log has none"] + built["notes"] + notes
|
|
1485
|
+
+ stats_notes(m, engine),
|
|
1486
|
+
"origin": {"role": site.get("role") or "unknown", "kind": ((site.get("origins") or [{}])[0]).get("kind", "unknown"),
|
|
1487
|
+
"entry_points": [{k: o.get(k) for k in ("kind", "name", "file", "line")} for o in (site.get("origins") or [])[:3]],
|
|
1488
|
+
"path": [], "frequency": {"trigger": "unknown", "every_seconds": 0, "in_loop": bool(site.get("in_loop")),
|
|
1489
|
+
"cache_seconds": 0, "note": ""}, "verified": False},
|
|
1490
|
+
"site": {**{k: site.get(k) for k in ("file", "line", "symbol", "sink", "resolution", "flags", "sql_hash")},
|
|
1491
|
+
"same_sql_sites": 1, "score": 0.0, "role": site.get("role") or "unknown", "origins": site.get("origins") or [],
|
|
1492
|
+
"origin_count": site.get("origin_count", 0)},
|
|
1493
|
+
"original_sql": site.get("sql") or "",
|
|
1494
|
+
"sql_from": "query_log", "located": grade,
|
|
1495
|
+
"observed": {
|
|
1496
|
+
"hash": h, "located": grade, "how": q.get("how") or "", "window_hours": m.get("window_hours"),
|
|
1497
|
+
"executions": int(q["executions"]), "read_bytes": int(q["read_bytes"]),
|
|
1498
|
+
"share_of_read_bytes": round(int(q["read_bytes"]) / total_bytes, 6) if total_bytes else 0.0,
|
|
1499
|
+
"share_of_site_bytes": round(int(q["read_bytes"]) / site_bytes, 4), "shapes_of_site": len(hashes),
|
|
1500
|
+
"places": [sid] if grade not in ("part", "tag") else sorted({p["id"] for p in places} | {sid}),
|
|
1501
|
+
"pieces": [_site_brief(p) for p in places] if grade == "part" else [],
|
|
1502
|
+
# located by the application's tag: the tag, and "one of n" when it names call sites with different SQL
|
|
1503
|
+
**({"tag": q.get("how") or "", "one_of": len({p.get("sql_hash") for p in places})} if grade == "tag" else {}),
|
|
1504
|
+
"joining_function": _joiner(places) if grade == "part" else None,
|
|
1505
|
+
"fixed_share": round(min(fixed / observed_loose, 1.0), 4) if fixed is not None and observed_loose else None,
|
|
1506
|
+
"fragments": [{k: f[k] for k in ("marker", "tokens")} for f in built["fragments"]],
|
|
1507
|
+
"fragments_text": built["fragments"],
|
|
1508
|
+
"filled": built["filled"],
|
|
1509
|
+
"params": {k: {x: v[x] for x in ("type", "column", "op", "source", "clause", "time", "epoch_unit", "alias", "bound")
|
|
1510
|
+
if v.get(x) is not None} for k, v in built["params"].items()},
|
|
1511
|
+
# the run's time window (time_window_hours): bench.anchor_times ends it at the benchmark's clock
|
|
1512
|
+
"time_window_hours": float(settings["time_window_hours"]),
|
|
1513
|
+
**({"epoch_columns": built["epoch_columns"]} if built.get("epoch_columns") else {}),
|
|
1514
|
+
"text_chars": len(text),
|
|
1515
|
+
# what one run of this shape reads and returns in production: the fit's target (fidelity.py)
|
|
1516
|
+
"production": {**{k: q[k] for k in ("rows_read_per_run", "bytes_read_per_run", "rows_returned_per_run", "read_bytes",
|
|
1517
|
+
"executions", "aggregate", *match_mod.SPREAD_KEYS, *match_mod.RESOURCE_KEYS) if q.get(k) is not None},
|
|
1518
|
+
**({"max_bytes_read_per_run": int(text_row["max_read_bytes"])} if text_row.get("max_read_bytes") else {}),
|
|
1519
|
+
**production_resources(q)},
|
|
1520
|
+
"normalized_text": clean[:int(settings.get("text_keep_chars", 200_000))],
|
|
1521
|
+
**{k: q[k] for k in ("rows_read_per_run", "bytes_read_per_run", "rows_returned_per_run", "rows_read_per_row_returned",
|
|
1522
|
+
"bytes_read_per_row_read", "avg_ms", "p95_ms") if q.get(k) is not None},
|
|
1523
|
+
**classify(text),
|
|
1524
|
+
**stats_basis(m, engine),
|
|
1525
|
+
},
|
|
1526
|
+
}
|
|
1527
|
+
candidates.append(cand)
|
|
1528
|
+
by_hash[h] = cand
|
|
1529
|
+
user_names = {n.rsplit(".", 1)[-1].lower() for n in facts.tables(engine)}
|
|
1530
|
+
unlocated_built = {"considered": 0, "candidates": 0, "below_share": 0, "over_max": 0, "reasons": {}}
|
|
1531
|
+
if settings.get("unlocated_candidates", "postgres") in (engine, "all"):
|
|
1532
|
+
unlocated_built = _unlocated_candidates(m, rows, texts, sites, facts, engine, settings, databases, total_bytes, user_names,
|
|
1533
|
+
workload, now, label_for, by_hash, candidates)
|
|
1534
|
+
asked = {c["finding"]: c for c in (previous or {}).get("candidates") or [] if c.get("variants_asked")}
|
|
1535
|
+
for c in candidates:
|
|
1536
|
+
if c["located"] == "part":
|
|
1537
|
+
c["observed"]["places"] = sorted(set(c["observed"]["places"]))
|
|
1538
|
+
old = asked.get(c["finding"])
|
|
1539
|
+
if old and old.get("baseline_sql") == c["baseline_sql"]: # the paid answer stays while the statement is the same
|
|
1540
|
+
c["variants"], c["variants_asked"] = old.get("variants") or [], True
|
|
1541
|
+
return {"schema_version": SCHEMA_VERSION, "generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"), "engine": engine,
|
|
1542
|
+
"window_hours": m.get("window_hours"), "settings": {k: settings[k] for k in DEFAULTS}, "labels": labels,
|
|
1543
|
+
**({"agent": previous["agent"]} if (previous or {}).get("agent") else {}),
|
|
1544
|
+
"candidates": candidates, "rejected": rejected, "gates": gates, "below_line": below,
|
|
1545
|
+
"unlocated": unlocated(inventory, m, texts, databases, settings, user_names),
|
|
1546
|
+
"unlocated_candidates": unlocated_built,
|
|
1547
|
+
"scope": {"sites": len(scope), "with_candidate": len({c["id"] for c in candidates}),
|
|
1548
|
+
"rejected_by_gate": len(gates.keys() - {c["id"] for c in candidates})}}
|
|
1549
|
+
|
|
1550
|
+
|
|
1551
|
+
def value_columns(columns: dict[str, str], engine: str) -> dict[str, str]:
|
|
1552
|
+
"""The column types choose_values reads: PostgreSQL's in the vocabulary of the typing rules (pg_internal)."""
|
|
1553
|
+
if engine != "postgres":
|
|
1554
|
+
return columns
|
|
1555
|
+
# a quoted "userId" is compared (and named in params) as userid
|
|
1556
|
+
return {**{k.lower(): pg_internal(v) for k, v in columns.items()}, **{k: pg_internal(v) for k, v in columns.items()}}
|
|
1557
|
+
|
|
1558
|
+
|
|
1559
|
+
def stats_basis(m: dict, engine: str) -> dict:
|
|
1560
|
+
"""What the server's statistics can and can not say about one statement, for the candidate's record."""
|
|
1561
|
+
if engine != "postgres":
|
|
1562
|
+
return {}
|
|
1563
|
+
return {"stats_basis": {"source": "pg_stat_statements", "since": m.get("since"), "cumulative_since_reset": True,
|
|
1564
|
+
"typical_run": "mean", "per_run_distribution": False, "p99": None}}
|
|
1565
|
+
|
|
1566
|
+
|
|
1567
|
+
def stats_notes(m: dict, engine: str) -> list[str]:
|
|
1568
|
+
if engine != "postgres":
|
|
1569
|
+
return []
|
|
1570
|
+
since = m.get("since")
|
|
1571
|
+
return [f"pg_stat_statements totals are cumulative since its last reset{f' ({since})' if since else ''}, not a window: "
|
|
1572
|
+
"runs and bytes are counted from then",
|
|
1573
|
+
"pg_stat_statements keeps no per-run distribution: the typical run is the mean run (total / calls), and there is "
|
|
1574
|
+
"no 99th-percentile run, so no heavy run is judged"]
|
|
1575
|
+
|
|
1576
|
+
|
|
1577
|
+
def _unlocated_candidates(m: dict, rows: dict, texts: dict, sites: dict, facts, engine: str, settings: dict, databases: set[str],
|
|
1578
|
+
total_bytes: int, user_names: set[str], workload: dict | None, now: datetime, label_for, by_hash: dict,
|
|
1579
|
+
candidates: list[dict]) -> dict:
|
|
1580
|
+
"""Production statements with no place in code (or only a likely one) as benchmark candidates, heaviest first: reads
|
|
1581
|
+
only, not the server's catalog (tooling), from `unlocated_candidate_min_share` of all bytes read, at most
|
|
1582
|
+
`unlocated_candidates_max`. Each passes the same steps as a located one (fill from the catalog, gate, values); it
|
|
1583
|
+
carries no file and line, and a likely match's places only as possible places. Appends to `candidates` and returns
|
|
1584
|
+
the counts: {considered, candidates, below_share, over_max, reasons, rejected[]}."""
|
|
1585
|
+
from collections import Counter
|
|
1586
|
+
floor, most = float(settings["unlocated_candidate_min_share"]), int(settings["unlocated_candidates_max"])
|
|
1587
|
+
reasons: Counter = Counter()
|
|
1588
|
+
out = {"considered": 0, "candidates": 0, "below_share": 0, "over_max": 0, "min_share": floor, "max": most, "rejected": []}
|
|
1589
|
+
limit = int((workload or {}).get("text_max_chars") or TEXT_CUT_BEFORE_SETTING)
|
|
1590
|
+
free = sorted((q for q in m.get("queries") or [] if q.get("match") in ("none", "likely")), key=lambda q: -int(q.get("read_bytes") or 0))
|
|
1591
|
+
for q in free:
|
|
1592
|
+
h = str(q.get("hash"))
|
|
1593
|
+
if h in by_hash:
|
|
1594
|
+
continue
|
|
1595
|
+
out["considered"] += 1
|
|
1596
|
+
text_row = texts.get(h) or {}
|
|
1597
|
+
text = text_row.get("text") or ""
|
|
1598
|
+
tables = tables_of(text, q.get("tables") or text_row.get("tables") or [], engine)
|
|
1599
|
+
if text and not is_read(text, text_row.get("kind")):
|
|
1600
|
+
reasons["not_a_read"] += 1
|
|
1601
|
+
continue
|
|
1602
|
+
if tooling(tables, text, user_names):
|
|
1603
|
+
reasons["tooling"] += 1
|
|
1604
|
+
continue
|
|
1605
|
+
share = int(q.get("read_bytes") or 0) / total_bytes if total_bytes else 0.0
|
|
1606
|
+
if share < floor:
|
|
1607
|
+
out["below_share"] += 1
|
|
1608
|
+
continue
|
|
1609
|
+
if out["candidates"] >= most:
|
|
1610
|
+
out["over_max"] += 1
|
|
1611
|
+
continue
|
|
1612
|
+
reason = None
|
|
1613
|
+
user_tables = [t for t in tables if not catalog_table(t, text)]
|
|
1614
|
+
if not text:
|
|
1615
|
+
reason = ("no_text", "the pull kept no text for this shape")
|
|
1616
|
+
elif match_mod.TEMP_TABLE.search(text):
|
|
1617
|
+
reason = ("external_data", "it reads a table of external data sent with each query (_tmp_<uuid>): not in the catalog")
|
|
1618
|
+
elif text_row.get("text_truncated") and len(text) >= limit:
|
|
1619
|
+
reason = ("text_cut_at_limit", f"the pull cut this statement's text at {limit:,} characters (db_pull.text_max_chars)")
|
|
1620
|
+
elif not user_tables or any(facts.definition(engine, t) is None for t in user_tables):
|
|
1621
|
+
missing = [t for t in user_tables if facts.definition(engine, t) is None]
|
|
1622
|
+
reason = ("table_not_in_catalog", f"no loadable definition for {', '.join(missing[:4])} in the pulled catalog" if missing
|
|
1623
|
+
else "no table of the pulled catalog could be read from the statement's text")
|
|
1624
|
+
built = None
|
|
1625
|
+
if reason is None:
|
|
1626
|
+
clean = strip_databases(text, databases)
|
|
1627
|
+
columns = _columns_of(facts, engine, user_tables)
|
|
1628
|
+
built = runnable(clean, [""], columns, neutral_values=settings["neutral_values"], least=3, engine=engine,
|
|
1629
|
+
window_hours=float(settings["time_window_hours"]))
|
|
1630
|
+
g = gate(built["sql"], text, text_row.get("tables") or q.get("tables") or [])
|
|
1631
|
+
if not g["ok"]:
|
|
1632
|
+
reason = (g["reason"], g["detail"])
|
|
1633
|
+
if reason is not None:
|
|
1634
|
+
reasons[reason[0]] += 1
|
|
1635
|
+
out["rejected"].append({"hash": h, "match": q.get("match"), "reason": reason[0], "detail": reason[1],
|
|
1636
|
+
"read_bytes": int(q.get("read_bytes") or 0), "executions": int(q.get("executions") or 0),
|
|
1637
|
+
"share_of_read_bytes": round(share, 6), **({"open": built["open"][:6]} if built else {})})
|
|
1638
|
+
continue
|
|
1639
|
+
finding = label_for(f"shape:{h}")
|
|
1640
|
+
values, notes = choose_values(built["params"], value_columns(columns, engine), finding, now=now,
|
|
1641
|
+
window_hours=float(settings["time_window_hours"]))
|
|
1642
|
+
possible = [{"site_id": sid, "file": sites[sid].get("file", ""), "symbol": sites[sid].get("symbol", ""),
|
|
1643
|
+
"basis": "same tables and nearly the same tokens (a likely match): not proof"}
|
|
1644
|
+
for sid in q.get("site_ids") or [] if sid in sites][:5] if q.get("match") == "likely" else []
|
|
1645
|
+
cand = {
|
|
1646
|
+
"finding": finding, "id": f"shape-{h}", "title": "Production statement with no place in code",
|
|
1647
|
+
"severity": "medium", "confidence": "medium",
|
|
1648
|
+
"baseline_sql": built["sql"], "params": values, "tables": user_tables, "variants": [], "causes": [],
|
|
1649
|
+
"assumptions": ["the statement is the one production ran (query log); values are chosen, the log has none",
|
|
1650
|
+
"no call site in the scanned code matches it" + (" for sure; a likely match is listed as a possible place" if possible else "")]
|
|
1651
|
+
+ built["notes"] + notes + stats_notes(m, engine),
|
|
1652
|
+
"origin": {"role": "unknown", "kind": "unknown", "entry_points": [], "path": [],
|
|
1653
|
+
"frequency": {"trigger": "unknown", "every_seconds": 0, "in_loop": False, "cache_seconds": 0, "note": ""}, "verified": False},
|
|
1654
|
+
"site": {"file": "", "line": 0, "symbol": "", "sink": "", "resolution": "", "flags": [], "sql_hash": "", "same_sql_sites": 0,
|
|
1655
|
+
"score": 0.0, "role": "unknown", "origins": [], "origin_count": 0},
|
|
1656
|
+
"original_sql": "", "sql_from": "query_log", "located": q.get("match") or "none",
|
|
1657
|
+
"observed": {
|
|
1658
|
+
"hash": h, "located": q.get("match") or "none", "how": q.get("how") or "", "window_hours": m.get("window_hours"),
|
|
1659
|
+
"executions": int(q.get("executions") or 0), "read_bytes": int(q.get("read_bytes") or 0),
|
|
1660
|
+
"share_of_read_bytes": round(share, 6), "share_of_site_bytes": 1.0, "shapes_of_site": 1, "places": [],
|
|
1661
|
+
"possible_places": possible, "pieces": [], "joining_function": None, "fixed_share": None,
|
|
1662
|
+
"fragments": [], "fragments_text": [], "filled": built["filled"],
|
|
1663
|
+
"params": {k: {x: v[x] for x in ("type", "column", "op", "source", "clause", "time", "epoch_unit", "alias", "bound")
|
|
1664
|
+
if v.get(x) is not None} for k, v in built["params"].items()},
|
|
1665
|
+
"time_window_hours": float(settings["time_window_hours"]),
|
|
1666
|
+
**({"epoch_columns": built["epoch_columns"]} if built.get("epoch_columns") else {}),
|
|
1667
|
+
"text_chars": len(text),
|
|
1668
|
+
"production": {**{k: q[k] for k in ("rows_read_per_run", "bytes_read_per_run", "rows_returned_per_run", "read_bytes",
|
|
1669
|
+
"executions", "aggregate", *match_mod.SPREAD_KEYS, *match_mod.RESOURCE_KEYS) if q.get(k) is not None},
|
|
1670
|
+
**({"max_bytes_read_per_run": int(text_row["max_read_bytes"])} if text_row.get("max_read_bytes") else {}),
|
|
1671
|
+
**production_resources(q)},
|
|
1672
|
+
"normalized_text": clean[:int(settings.get("text_keep_chars", 200_000))],
|
|
1673
|
+
**{k: q[k] for k in ("rows_read_per_run", "bytes_read_per_run", "rows_returned_per_run", "rows_read_per_row_returned",
|
|
1674
|
+
"bytes_read_per_row_read", "avg_ms", "p95_ms") if q.get(k) is not None},
|
|
1675
|
+
**stats_basis(m, engine),
|
|
1676
|
+
},
|
|
1677
|
+
}
|
|
1678
|
+
from .realdb.ratios import classify
|
|
1679
|
+
cand["observed"].update(classify(text))
|
|
1680
|
+
candidates.append(cand)
|
|
1681
|
+
by_hash[h] = cand
|
|
1682
|
+
out["candidates"] += 1
|
|
1683
|
+
out["reasons"] = dict(reasons.most_common())
|
|
1684
|
+
return out
|
|
1685
|
+
|
|
1686
|
+
|
|
1687
|
+
# ---- the paid step: an agent proposes variants of the statement as production ran it ----------------------------------
|
|
1688
|
+
|
|
1689
|
+
VARIANT_BATCH = 20 # statements per agent call
|
|
1690
|
+
VARIANTS_PROMPT_REV = "observed-1" # bumped when the instructions change answers: stored answers are asked again
|
|
1691
|
+
|
|
1692
|
+
|
|
1693
|
+
def variants_estimate(observed_doc: dict, only: list[str] | None = None) -> dict:
|
|
1694
|
+
"""What `codecop rank --observed-variants` would cost, at the rank stage's measured cost per query (an estimate)."""
|
|
1695
|
+
from .rank import COST_PER_QUERY_USD
|
|
1696
|
+
todo = [c for c in observed_doc.get("candidates") or [] if not c.get("variants_asked") and (not only or c["finding"] in only)]
|
|
1697
|
+
n = len(todo)
|
|
1698
|
+
return {"statements": n, "batches": -(-n // VARIANT_BATCH) if n else 0,
|
|
1699
|
+
"cost_low_usd": round(n * COST_PER_QUERY_USD[0], 2), "cost_high_usd": round(n * COST_PER_QUERY_USD[1], 2),
|
|
1700
|
+
"findings": [c["finding"] for c in todo]}
|
|
1701
|
+
|
|
1702
|
+
|
|
1703
|
+
def variants_schema() -> dict:
|
|
1704
|
+
from .rank import load_schema
|
|
1705
|
+
variant = load_schema("rank_output")["properties"]["candidates"]["items"]["properties"]["variants"]
|
|
1706
|
+
return {"type": "object", "required": ["candidates"], "additionalProperties": False, "properties": {"candidates": {"type": "array", "items": {
|
|
1707
|
+
"type": "object", "required": ["id", "variants"], "additionalProperties": False,
|
|
1708
|
+
"properties": {"id": {"type": "string"}, "variants": variant}}}}}
|
|
1709
|
+
|
|
1710
|
+
|
|
1711
|
+
def variants_prompt(cands: list[dict], definitions: list[dict], engine: str, version: str) -> str:
|
|
1712
|
+
from . import engines
|
|
1713
|
+
from .rank import _fill, load_prompt
|
|
1714
|
+
statements = "\n\n".join(
|
|
1715
|
+
f"### {c['finding']}\ncall site: {c['site']['file']}:{c['site']['line']}"
|
|
1716
|
+
+ (" (one of the places that build it)" if c.get("located") == "part" else "")
|
|
1717
|
+
+ f"\nruns in the window: {c['observed']['executions']:,}; tables: {', '.join(c['tables'])}\n```sql\n{c['baseline_sql']}\n```" for c in cands)
|
|
1718
|
+
tables = "\n\n".join(f"### {d['name']}\n```sql\n{d['create_sql'].strip()}\n```" for d in definitions) or "(none)"
|
|
1719
|
+
return _fill(load_prompt("observed_variants"), {"engine": engines.get(engine).label, "engine_version": version,
|
|
1720
|
+
"tables": tables, "statements": statements})
|
|
1721
|
+
|
|
1722
|
+
|
|
1723
|
+
def variants_answer_key(c: dict, answers, engine: str) -> str:
|
|
1724
|
+
"""The answer store's key of one statement's variants question (verdicts.Answers)."""
|
|
1725
|
+
from . import engines, verdicts
|
|
1726
|
+
full = variants_schema()
|
|
1727
|
+
full["properties"]["candidates"]["items"]["properties"]["variants"]["items"]["properties"]["kind"]["enum"] = list(engines.get(engine).variant_kinds)
|
|
1728
|
+
pv = verdicts.prompt_version(VARIANTS_PROMPT_REV, json.dumps(full, sort_keys=True))
|
|
1729
|
+
return answers.key("observed", c.get("baseline_sql") or "", c.get("tables") or [], pv)
|
|
1730
|
+
|
|
1731
|
+
|
|
1732
|
+
def ask_for_variants(observed_doc: dict, definitions: list[dict], root, runner, *, engine: str, version: str, model: str | None = None,
|
|
1733
|
+
max_budget_usd: float | None = None, only: list[str] | None = None, batch_size: int | None = None,
|
|
1734
|
+
answers=None, fresh=False) -> dict:
|
|
1735
|
+
"""Run the paid step: the agent proposes variants; the baseline stays the statement production ran. Changes
|
|
1736
|
+
`observed_doc` in place (variants, `variants_asked`, the cost ledger) and returns {asked, with_variants, cost_usd}.
|
|
1737
|
+
`answers` (verdicts.Answers): a statement answered before, with the same text on the same table definitions, takes its
|
|
1738
|
+
stored answer and is not asked; every answer is stored there."""
|
|
1739
|
+
from . import engines, verdicts
|
|
1740
|
+
todo = [c for c in observed_doc.get("candidates") or [] if not c.get("variants_asked") and (not only or c["finding"] in only)]
|
|
1741
|
+
full = variants_schema()
|
|
1742
|
+
full["properties"]["candidates"]["items"]["properties"]["variants"]["items"]["properties"]["kind"]["enum"] = list(engines.get(engine).variant_kinds)
|
|
1743
|
+
pv = verdicts.prompt_version(VARIANTS_PROMPT_REV, json.dumps(full, sort_keys=True))
|
|
1744
|
+
reused = 0
|
|
1745
|
+
if answers is not None:
|
|
1746
|
+
# answered before for the statement as production runs it now, on the same table definitions: not asked again
|
|
1747
|
+
left = []
|
|
1748
|
+
for c in todo:
|
|
1749
|
+
rec = answers.get(answers.key("observed", c.get("baseline_sql") or "", c.get("tables") or [], pv), fresh,
|
|
1750
|
+
ref=c["finding"], file=(c.get("site") or {}).get("file") or "")
|
|
1751
|
+
if rec is None:
|
|
1752
|
+
left.append(c)
|
|
1753
|
+
continue
|
|
1754
|
+
c["variants"] = list((rec.get("answer") or {}).get("variants") or [])
|
|
1755
|
+
c["variants_asked"] = True
|
|
1756
|
+
c["answered_before"] = True
|
|
1757
|
+
reused += 1
|
|
1758
|
+
todo = left
|
|
1759
|
+
spent, asked, got = 0.0, 0, 0
|
|
1760
|
+
ledger = observed_doc.setdefault("agent", {"calls": []})
|
|
1761
|
+
size = max(int(batch_size or VARIANT_BATCH), 1) # `[agent] items_per_call.observed`
|
|
1762
|
+
stopped = limited = False
|
|
1763
|
+
for i in range(0, len(todo), size):
|
|
1764
|
+
batch = todo[i:i + size]
|
|
1765
|
+
names = {t for c in batch for t in c["tables"]}
|
|
1766
|
+
prompt = variants_prompt(batch, [d for d in definitions if d["name"] in names], engine, version)
|
|
1767
|
+
left = None if max_budget_usd is None else max(max_budget_usd - spent, 0.0)
|
|
1768
|
+
if left is not None and left <= 0:
|
|
1769
|
+
stopped = True
|
|
1770
|
+
break
|
|
1771
|
+
if hasattr(runner, "tell"):
|
|
1772
|
+
runner.tell("observed", len(batch))
|
|
1773
|
+
try:
|
|
1774
|
+
result = runner.run(prompt, full, root, model=model, max_budget_usd=left)
|
|
1775
|
+
except UsageLimitError:
|
|
1776
|
+
stopped = limited = True # the agent's usage limit: what was asked so far is kept, the rest is said
|
|
1777
|
+
break
|
|
1778
|
+
except AgentError as e:
|
|
1779
|
+
if "budget" not in str(e).lower():
|
|
1780
|
+
raise
|
|
1781
|
+
stopped = True # the run budget is reached: what was asked so far is kept
|
|
1782
|
+
break
|
|
1783
|
+
spent += float(result.cost_usd or 0)
|
|
1784
|
+
ledger["calls"].append({"findings": [c["finding"] for c in batch], "cost_usd": round(float(result.cost_usd or 0), 6),
|
|
1785
|
+
"model": result.model, "at": datetime.now(timezone.utc).isoformat(timespec="seconds")})
|
|
1786
|
+
by_id = {c["finding"]: c for c in batch}
|
|
1787
|
+
for entry in (result.output or {}).get("candidates") or []:
|
|
1788
|
+
c = by_id.get(entry.get("id"))
|
|
1789
|
+
if c is None:
|
|
1790
|
+
continue # an id that was not asked about is the agent's mistake: dropped
|
|
1791
|
+
c["variants"] = [v for v in entry.get("variants") or [] if v.get("sql")][:3]
|
|
1792
|
+
got += bool(c["variants"])
|
|
1793
|
+
for c in batch:
|
|
1794
|
+
c["variants_asked"] = True
|
|
1795
|
+
asked += 1
|
|
1796
|
+
if answers is not None:
|
|
1797
|
+
answers.put(answers.key("observed", c.get("baseline_sql") or "", c.get("tables") or [], pv),
|
|
1798
|
+
{"kind": "observed", "id": c["finding"], "answer": {"variants": list(c.get("variants") or [])},
|
|
1799
|
+
"model": result.model}, save=False)
|
|
1800
|
+
if answers is not None:
|
|
1801
|
+
answers.save()
|
|
1802
|
+
ledger["cost_total_usd"] = round(sum(x["cost_usd"] for x in ledger["calls"]), 4)
|
|
1803
|
+
return {"asked": asked, "with_variants": got, "cost_usd": round(spent, 4), "stopped_by_budget": stopped and not limited,
|
|
1804
|
+
"stopped_by_limit": limited, "not_asked": len(todo) - asked, "answered_before": reused}
|
|
1805
|
+
|
|
1806
|
+
|
|
1807
|
+
WHO = ("your_tables", "system", "mixed", "other_service")
|
|
1808
|
+
|
|
1809
|
+
|
|
1810
|
+
def unlocated(inventory: dict, m: dict, texts: dict[str, dict], databases: set[str], settings: dict,
|
|
1811
|
+
user_names: set[str] | None = None) -> dict:
|
|
1812
|
+
"""Production statements with no located call site: {shapes, read_bytes, executions, share_of_read_bytes, by_who, statements}.
|
|
1813
|
+
|
|
1814
|
+
Each statement: its hash, load, tables (without database), who it most likely comes from by the tables it reads
|
|
1815
|
+
(`your_tables`: every table it reads is read or defined by the scanned code; `system`: the server's own catalog only
|
|
1816
|
+
(ClickHouse system.*, PostgreSQL pg_* and information_schema.*: tooling, not the application's load, `tooling`); `mixed`;
|
|
1817
|
+
`other_service`: no scanned code names any of them), and, for a `likely` match, the possible places with the token
|
|
1818
|
+
agreement. A possible place is never a location: no file and line is given as where the statement comes from."""
|
|
1819
|
+
sites = {c["id"]: c for c in inventory.get("call_sites") or [] if c.get("id")}
|
|
1820
|
+
known = {t.rsplit(".", 1)[-1].lower() for c in inventory.get("call_sites") or [] for t in c.get("tables") or []}
|
|
1821
|
+
known |= {t["name"].rsplit(".", 1)[-1].lower() for t in inventory.get("tables") or [] if t.get("name")}
|
|
1822
|
+
total = int((m.get("workload") or {}).get("read_bytes") or 0)
|
|
1823
|
+
total_exec = int((m.get("workload") or {}).get("executions") or 0)
|
|
1824
|
+
rows = [q for q in m.get("queries") or [] if q.get("match") in ("none", "likely")]
|
|
1825
|
+
rows.sort(key=lambda q: -int(q.get("read_bytes") or 0))
|
|
1826
|
+
out = []
|
|
1827
|
+
for q in rows:
|
|
1828
|
+
tables = [t for t in q.get("tables") or [] if not match_mod.TEMP_TABLE.search(t)]
|
|
1829
|
+
text = (texts.get(q["hash"]) or {}).get("text") or ""
|
|
1830
|
+
system = [t for t in tables if catalog_table(t, text) or (not text and t in CATALOG_NAMES)]
|
|
1831
|
+
user = [t for t in tables if t not in system]
|
|
1832
|
+
is_tooling = tooling(tables, text, user_names) if text else bool(tables) and not user
|
|
1833
|
+
who = ("system" if is_tooling or (tables and not user) else "your_tables" if user and all(t in known for t in user)
|
|
1834
|
+
else "mixed" if any(t in known for t in user) else "other_service")
|
|
1835
|
+
row = {"hash": q["hash"], "match": q["match"], "executions": int(q["executions"]), "read_bytes": int(q["read_bytes"]),
|
|
1836
|
+
"share_of_read_bytes": round(int(q["read_bytes"]) / total, 6) if total else 0.0, "tables": tables, "who": who,
|
|
1837
|
+
**({"tooling": True} if who == "system" else {}),
|
|
1838
|
+
**({"read": is_read(text, (texts.get(q["hash"]) or {}).get("kind"))} if text else {}),
|
|
1839
|
+
**{k: q[k] for k in ("avg_ms", "rows_read_per_run", "rows_returned_per_run", "aggregate", "aggregate_kind") if q.get(k) is not None}}
|
|
1840
|
+
if q["match"] == "likely":
|
|
1841
|
+
row["possible_places"] = [{"site_id": sid, "file": sites[sid].get("file", ""), "symbol": sites[sid].get("symbol", ""),
|
|
1842
|
+
"basis": "same tables and nearly the same tokens (a likely match): not proof"}
|
|
1843
|
+
for sid in q.get("site_ids") or [] if sid in sites][:5]
|
|
1844
|
+
if text:
|
|
1845
|
+
row["normalized_text"] = strip_databases(text, databases)[:20_000]
|
|
1846
|
+
out.append(row)
|
|
1847
|
+
listed = [r for r in out if r["share_of_read_bytes"] >= float(settings["unlocated_min_share"])][:int(settings["unlocated_max"])]
|
|
1848
|
+
by_who = {w: {"shapes": sum(1 for r in out if r["who"] == w), "read_bytes": sum(r["read_bytes"] for r in out if r["who"] == w),
|
|
1849
|
+
"executions": sum(r["executions"] for r in out if r["who"] == w)} for w in WHO}
|
|
1850
|
+
for v in by_who.values():
|
|
1851
|
+
v["share_of_read_bytes"] = round(v["read_bytes"] / total, 4) if total else 0.0
|
|
1852
|
+
b, n = sum(r["read_bytes"] for r in out), sum(r["executions"] for r in out)
|
|
1853
|
+
return {"shapes": len(out), "read_bytes": b, "executions": n, "share_of_read_bytes": round(b / total, 4) if total else 0.0,
|
|
1854
|
+
"share_of_executions": round(n / total_exec, 4) if total_exec else 0.0,
|
|
1855
|
+
"likely": sum(1 for r in out if r["match"] == "likely"), "by_who": by_who, "listed": len(listed), "statements": listed}
|
|
1856
|
+
|
|
1857
|
+
|
|
1858
|
+
def _joiner(pieces: list[dict]) -> dict | None:
|
|
1859
|
+
"""The function that joins the pieces, when every piece is reached from one function in the inventory's call paths:
|
|
1860
|
+
{symbol, file, line}. None when the pieces share no caller (the finding then says the joining code was not found)."""
|
|
1861
|
+
common = None
|
|
1862
|
+
for p in pieces:
|
|
1863
|
+
names = {(o.get("name"), o.get("file"), o.get("line")) for o in p.get("origins") or []}
|
|
1864
|
+
common = names if common is None else common & names
|
|
1865
|
+
if common and len(pieces) > 1:
|
|
1866
|
+
name, file, line = sorted(common, key=lambda x: (str(x[1]), x[2] or 0))[0]
|
|
1867
|
+
return {"symbol": name, "file": file, "line": line}
|
|
1868
|
+
return None
|