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/plangate.py
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
"""The plan gate: every statement of the baseline pass planned, not run, against the sandbox schema before any data is
|
|
2
|
+
loaded.
|
|
3
|
+
|
|
4
|
+
In the bench's sandbox, before the first load: each table the pass's statements read is created empty from its
|
|
5
|
+
definition (a table already loaded in a kept sandbox is used as it is), then each statement is planned with its
|
|
6
|
+
parameters (PostgreSQL `EXPLAIN`, ClickHouse `EXPLAIN PLAN`, SQLite `EXPLAIN QUERY PLAN`). Nothing is executed and
|
|
7
|
+
no row is read. A statement that does not plan is taken out of the run, with a typed reason (`class`):
|
|
8
|
+
|
|
9
|
+
table_not_pulled a table it reads is not in the pulled catalog nor in the repository's schema
|
|
10
|
+
table_in_other_database it names a database (or schema) the sandbox has no table of
|
|
11
|
+
table_build its table's definition could not be built
|
|
12
|
+
column a column it reads is not in the table's definition
|
|
13
|
+
function a function the sandbox server does not have
|
|
14
|
+
piece not a whole statement (a fragment of a longer one: syntax error at its start or end)
|
|
15
|
+
template_text text of a template that was never rendered (`{{`, `${`, `%(`)
|
|
16
|
+
stand_in_type a parameter's stand-in value or type does not fit where it is used
|
|
17
|
+
other anything else; the server's first line is kept
|
|
18
|
+
|
|
19
|
+
The empty tables the gate created are dropped again, so the bench builds them as it always does. Results are keyed
|
|
20
|
+
by a fingerprint of the statement and its definitions (baseline.json `gate`): a later run with the same text and
|
|
21
|
+
definitions does not plan it again to know it fails.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import re
|
|
27
|
+
import time
|
|
28
|
+
|
|
29
|
+
from .baseline import _bare, is_baseline
|
|
30
|
+
|
|
31
|
+
CLASSES = ("table_not_pulled", "table_in_other_database", "table_build", "column", "function", "piece", "template_text",
|
|
32
|
+
"stand_in_type", "other")
|
|
33
|
+
PG_PATTERNS = [
|
|
34
|
+
(re.compile(r'relation "([^"]+)" does not exist', re.I), "table"),
|
|
35
|
+
(re.compile(r'schema "([^"]+)" does not exist', re.I), "table_in_other_database"),
|
|
36
|
+
(re.compile(r"column .* does not exist|missing FROM-clause entry|column reference .* is ambiguous", re.I), "column"),
|
|
37
|
+
(re.compile(r"function .* does not exist|operator does not exist", re.I), "function_or_type"),
|
|
38
|
+
(re.compile(r"invalid input syntax|could not determine data type|is of type .* but expression is of type|cannot cast|"
|
|
39
|
+
r"malformed array literal|invalid input value|out of range|argument of .* must be type", re.I), "stand_in_type"),
|
|
40
|
+
(re.compile(r"syntax error at end of input|syntax error at or near", re.I), "syntax"),
|
|
41
|
+
]
|
|
42
|
+
CH_PATTERNS = [
|
|
43
|
+
(re.compile(r"UNKNOWN_DATABASE|Database \S+ does(?: not|n't) exist", re.I), "table_in_other_database"),
|
|
44
|
+
(re.compile(r"UNKNOWN_TABLE|Table \S+ does(?: not|n't) exist", re.I), "table"),
|
|
45
|
+
(re.compile(r"UNKNOWN_IDENTIFIER|NO_SUCH_COLUMN|THERE_IS_NO_COLUMN|Missing columns|Unknown expression identifier|"
|
|
46
|
+
r"UNKNOWN_COMPOUND_IDENTIFIER|AMBIGUOUS_", re.I), "column"),
|
|
47
|
+
(re.compile(r"UNKNOWN_FUNCTION|UNKNOWN_AGGREGATE_FUNCTION", re.I), "function"),
|
|
48
|
+
(re.compile(r"TYPE_MISMATCH|ILLEGAL_TYPE_OF_ARGUMENT|CANNOT_PARSE|CANNOT_CONVERT|NO_COMMON_TYPE|BAD_QUERY_PARAMETER|"
|
|
49
|
+
r"UNKNOWN_QUERY_PARAMETER|CANNOT_READ_ARRAY|ILLEGAL_COLUMN|BAD_ARGUMENTS|Cannot parse|Illegal type", re.I), "stand_in_type"),
|
|
50
|
+
(re.compile(r"SYNTAX_ERROR|Syntax error", re.I), "syntax"),
|
|
51
|
+
]
|
|
52
|
+
TEMPLATE = re.compile(r"\{\{|\{%|\$\{|%\(\w+\)s|«")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _first_line(error: str) -> str:
|
|
56
|
+
text = re.sub(r"^psql:<stdin>:\d+:\s*", "", str(error or "").strip(), flags=re.M)
|
|
57
|
+
m = re.search(r"DB::Exception: (.*?)(?: \(version|$)", text, re.S)
|
|
58
|
+
return re.sub(r"\s+", " ", m.group(1) if m else text.splitlines()[0] if text else "")[:300]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def classify(engine: str, error: str, sql: str, tables_built: set[str]) -> str:
|
|
62
|
+
"""One class from CLASSES for the server's error on planning `sql`."""
|
|
63
|
+
text = str(error or "")
|
|
64
|
+
if TEMPLATE.search(sql):
|
|
65
|
+
return "template_text"
|
|
66
|
+
for pat, kind in (CH_PATTERNS if engine == "clickhouse" else PG_PATTERNS):
|
|
67
|
+
m = pat.search(text)
|
|
68
|
+
if not m:
|
|
69
|
+
continue
|
|
70
|
+
if kind == "table":
|
|
71
|
+
name = (m.group(1) if m.groups() else "") or ""
|
|
72
|
+
if "." in name and _bare(name) in tables_built:
|
|
73
|
+
return "table_in_other_database"
|
|
74
|
+
return "table_not_pulled"
|
|
75
|
+
if kind == "function_or_type":
|
|
76
|
+
return "stand_in_type" if re.search(r"operator does not exist|unknown|text|character varying", text, re.I) and \
|
|
77
|
+
re.search(r"\{\w+:", sql) else "function"
|
|
78
|
+
if kind == "syntax":
|
|
79
|
+
return "piece" if _looks_like_piece(sql) else "other"
|
|
80
|
+
return kind
|
|
81
|
+
if re.search(r"no such table", text, re.I):
|
|
82
|
+
return "table_not_pulled"
|
|
83
|
+
if re.search(r"no such column", text, re.I):
|
|
84
|
+
return "column"
|
|
85
|
+
if re.search(r"no such function", text, re.I):
|
|
86
|
+
return "function"
|
|
87
|
+
if re.search(r"syntax error|incomplete input", text, re.I):
|
|
88
|
+
return "piece" if _looks_like_piece(sql) else "other"
|
|
89
|
+
return "other"
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _looks_like_piece(sql: str) -> bool:
|
|
93
|
+
"""A fragment of a longer statement: it starts or ends where no statement does (a clause, an operator, an open paren)."""
|
|
94
|
+
s = re.sub(r"--[^\n]*", "", sql or "").strip()
|
|
95
|
+
if not s:
|
|
96
|
+
return True
|
|
97
|
+
head = s.split(None, 1)[0].upper()
|
|
98
|
+
if head not in ("SELECT", "WITH", "(", "VALUES", "TABLE", "EXPLAIN", "SHOW", "DESCRIBE"):
|
|
99
|
+
return True
|
|
100
|
+
if re.search(r"(?:\bAND|\bOR|\bWHERE|\bON|,|\(|=|\bJOIN|\bFROM|\bBY)\s*$", s, re.I):
|
|
101
|
+
return True
|
|
102
|
+
return s.count("(") != s.count(")")
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _plan_sql(engine: str, sql: str) -> str:
|
|
106
|
+
sql = sql.strip().rstrip(";")
|
|
107
|
+
sql = re.sub(r"\s+FORMAT\s+\w+\s*$", "", sql, flags=re.I) if engine == "clickhouse" else sql
|
|
108
|
+
if engine == "clickhouse":
|
|
109
|
+
# the sandbox is one node: `ON CLUSTER '{cluster}'` and cluster table functions name a cluster it has not
|
|
110
|
+
sql = re.sub(r"\s+ON\s+CLUSTER\s+(?:'[^']*'|`[^`]*`|\{\w+\}|\w+)", "", sql, flags=re.I)
|
|
111
|
+
sql = re.sub(r"\bcluster(?:AllReplicas)?\(\s*'[^']*'\s*,\s*([\w`.]+)(?:\s*,\s*([\w`]+))?\s*\)",
|
|
112
|
+
lambda m: m.group(1) + ("." + m.group(2) if m.group(2) else ""), sql)
|
|
113
|
+
return "EXPLAIN PLAN " + sql
|
|
114
|
+
if engine == "sqlite":
|
|
115
|
+
return "EXPLAIN QUERY PLAN " + sql
|
|
116
|
+
return "EXPLAIN " + sql
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
ALTERNATIVES = {
|
|
120
|
+
# (type, value) a stand-in parameter is tried with, in order, when the statement does not plan with the first
|
|
121
|
+
# ("qopt": a neutral text value kept from before the rename, formerly qopt)
|
|
122
|
+
"clickhouse": [("UUID", "00000000-0000-4000-8000-000000000001"), ("Int64", 1), ("DateTime", "2026-01-01 00:00:00"),
|
|
123
|
+
("Date", "2026-01-01"), ("Array(String)", "['qopt']"), ("Float64", 1), ("String", "qopt")],
|
|
124
|
+
"postgres": [("uuid", "00000000-0000-4000-8000-000000000001"), ("bigint", 1), ("timestamptz", "2026-01-01 00:00:00"),
|
|
125
|
+
("date", "2026-01-01"), ("text[]", "{qopt}"), ("jsonb", "{}"), ("boolean", "true"), ("text", "qopt")],
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _retry(sb, engine: str, cand: dict) -> bool:
|
|
130
|
+
"""A statement refused for a parameter's type: its stand-in parameters (then every parameter that is not a LIMIT)
|
|
131
|
+
are tried with each type of ALTERNATIVES in turn. The first that plans is kept on the candidate (its text and
|
|
132
|
+
values), so the bench runs what was planned. True when one planned."""
|
|
133
|
+
ops = cand.get("param_ops") or {}
|
|
134
|
+
order = [[n for n, o in ops.items() if o == "stand_in"], [n for n, o in ops.items() if o not in ("limit", "offset", "interval")]]
|
|
135
|
+
for names in order:
|
|
136
|
+
if not names:
|
|
137
|
+
continue
|
|
138
|
+
for typ, value in ALTERNATIVES.get(engine, []):
|
|
139
|
+
sql = cand["baseline_sql"]
|
|
140
|
+
for n in names:
|
|
141
|
+
sql = re.sub(r"\{" + re.escape(n) + r"\s*:[^{}]+\}", "{" + n + ":" + typ + "}", sql)
|
|
142
|
+
params = {**(cand.get("params") or {}), **{n: value for n in names}}
|
|
143
|
+
try:
|
|
144
|
+
sb.execute(_plan_sql(engine, sql), params)
|
|
145
|
+
except Exception: # noqa: BLE001 -- not this type either
|
|
146
|
+
continue
|
|
147
|
+
cand["baseline_sql"], cand["params"] = sql, params
|
|
148
|
+
cand.setdefault("assumptions", []).append(f"parameter(s) {', '.join(names)} planned as {typ} (the plan gate's stand-in)")
|
|
149
|
+
return True
|
|
150
|
+
return False
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _drop(sb, engine: str, name: str) -> None:
|
|
154
|
+
try:
|
|
155
|
+
if engine == "clickhouse":
|
|
156
|
+
sb.release([name])
|
|
157
|
+
elif engine == "postgres":
|
|
158
|
+
sb.execute(f"DROP TABLE IF EXISTS {sb._q(name)} CASCADE")
|
|
159
|
+
else:
|
|
160
|
+
sb.execute(f'DROP TABLE IF EXISTS "{name.replace(chr(34), "").split(".")[-1]}"')
|
|
161
|
+
except Exception: # noqa: BLE001 -- an empty table left behind is rebuilt by the bench's own create_table
|
|
162
|
+
pass
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def run(sb, rank: dict, log=lambda msg: None) -> tuple[dict, dict]:
|
|
166
|
+
"""(rank without the statements that do not plan, the gate's record: {checked, planned, failed, by_class, seconds,
|
|
167
|
+
results: {finding: {ok, class, reason, error, fingerprint}}}). Only the baseline pass's statements are gated; the
|
|
168
|
+
agent's candidates and the other kinds' statements go on as before."""
|
|
169
|
+
from .engines.clickhouse import SandboxError
|
|
170
|
+
engine = rank.get("engine") or "clickhouse"
|
|
171
|
+
began = time.monotonic()
|
|
172
|
+
gated = [c for c in rank.get("candidates") or [] if is_baseline(c.get("finding")) and c.get("baseline_pass")]
|
|
173
|
+
record = {"checked": 0, "planned": 0, "failed": 0, "by_class": {}, "results": {}, "tables_created": 0, "tables_failed": 0}
|
|
174
|
+
if not gated:
|
|
175
|
+
return rank, record
|
|
176
|
+
defs = {_bare(d["name"]): d for d in rank.get("table_definitions") or []}
|
|
177
|
+
loaded = set((getattr(sb, "loaded", None) or {}).keys())
|
|
178
|
+
loaded_bare = {_bare(n) for n in loaded}
|
|
179
|
+
want = sorted({_bare(t) for c in gated for t in c.get("tables") or []})
|
|
180
|
+
created, failed_tables = [], {}
|
|
181
|
+
for t in want:
|
|
182
|
+
d = defs.get(t)
|
|
183
|
+
if d is None:
|
|
184
|
+
failed_tables[t] = "no definition"
|
|
185
|
+
continue
|
|
186
|
+
if t in loaded_bare:
|
|
187
|
+
continue # loaded by an earlier pass of this scan: planned against as it is
|
|
188
|
+
try:
|
|
189
|
+
sb.create_table(d)
|
|
190
|
+
created.append(d["name"])
|
|
191
|
+
except SandboxError as e:
|
|
192
|
+
if type(e).__name__ != "QueryError":
|
|
193
|
+
raise
|
|
194
|
+
failed_tables[t] = _first_line(str(e))
|
|
195
|
+
record["tables_created"], record["tables_failed"] = len(created), len(failed_tables)
|
|
196
|
+
built = {_bare(n) for n in created} | loaded_bare
|
|
197
|
+
keep, results = [], {}
|
|
198
|
+
by_class: dict[str, int] = {}
|
|
199
|
+
gated_ids = {id(c) for c in gated}
|
|
200
|
+
for c in rank.get("candidates") or []:
|
|
201
|
+
if id(c) not in gated_ids:
|
|
202
|
+
keep.append(c)
|
|
203
|
+
continue
|
|
204
|
+
record["checked"] += 1
|
|
205
|
+
bad = [t for t in (_bare(x) for x in c.get("tables") or []) if t in failed_tables]
|
|
206
|
+
res = {"fingerprint": c.get("gate_fingerprint") or "", "ok": True}
|
|
207
|
+
if bad:
|
|
208
|
+
res.update(ok=False, reason="does_not_plan", **{"class": "table_build"},
|
|
209
|
+
error=f"{bad[0]}: {failed_tables[bad[0]]}"[:300])
|
|
210
|
+
else:
|
|
211
|
+
try:
|
|
212
|
+
sb.execute(_plan_sql(engine, c["baseline_sql"]), c.get("params") or {})
|
|
213
|
+
except SandboxError as e:
|
|
214
|
+
if type(e).__name__ != "QueryError":
|
|
215
|
+
raise
|
|
216
|
+
cls = classify(engine, str(e), c["baseline_sql"], built)
|
|
217
|
+
if cls in ("stand_in_type", "other", "function") and _retry(sb, engine, c):
|
|
218
|
+
res["retyped"] = True
|
|
219
|
+
results[c["finding"]] = res
|
|
220
|
+
record["planned"] += 1
|
|
221
|
+
keep.append(c)
|
|
222
|
+
continue
|
|
223
|
+
res.update(ok=False, reason="table_not_pulled" if cls == "table_not_pulled" else "does_not_plan",
|
|
224
|
+
error=_first_line(str(e)), **{"class": cls})
|
|
225
|
+
results[c["finding"]] = res
|
|
226
|
+
if res["ok"]:
|
|
227
|
+
record["planned"] += 1
|
|
228
|
+
keep.append(c)
|
|
229
|
+
else:
|
|
230
|
+
record["failed"] += 1
|
|
231
|
+
by_class[res["class"]] = by_class.get(res["class"], 0) + 1
|
|
232
|
+
for name in created:
|
|
233
|
+
_drop(sb, engine, name)
|
|
234
|
+
used_after = {_bare(t) for c in keep for t in c.get("tables") or []}
|
|
235
|
+
used_gated = {_bare(t) for c in gated for t in c.get("tables") or []}
|
|
236
|
+
out = {**rank, "candidates": keep,
|
|
237
|
+
"table_definitions": [d for d in rank.get("table_definitions") or [] if _bare(d["name"]) in used_after or _bare(d["name"]) not in used_gated]}
|
|
238
|
+
record.update(by_class=dict(sorted(by_class.items(), key=lambda x: -x[1])), results=results, seconds=round(time.monotonic() - began, 1))
|
|
239
|
+
log(f"plan gate: {record['planned']} of {record['checked']} statements plan on the sandbox schema"
|
|
240
|
+
+ (f"; not planned: " + ", ".join(f"{k} {v}" for k, v in record["by_class"].items()) if by_class else "")
|
|
241
|
+
+ f" ({record['seconds']:.0f} s)")
|
|
242
|
+
return out, record
|