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.
Files changed (222) hide show
  1. codecop/__init__.py +7 -0
  2. codecop/access.py +140 -0
  3. codecop/access_postgres.py +284 -0
  4. codecop/advisor.py +1512 -0
  5. codecop/advisor_bench.py +493 -0
  6. codecop/advisor_ch.py +2080 -0
  7. codecop/advisor_view.py +381 -0
  8. codecop/advisors.py +184 -0
  9. codecop/agent.py +221 -0
  10. codecop/agentfacts.py +745 -0
  11. codecop/apply/__init__.py +327 -0
  12. codecop/apply/check.py +344 -0
  13. codecop/apply/cli.py +162 -0
  14. codecop/apply/clickhouse.py +379 -0
  15. codecop/apply/common.py +238 -0
  16. codecop/apply/html.py +264 -0
  17. codecop/apply/patch.py +213 -0
  18. codecop/apply/postgres.py +102 -0
  19. codecop/apply/trial.py +166 -0
  20. codecop/assemble.py +104 -0
  21. codecop/baseline.py +1043 -0
  22. codecop/bench.py +2464 -0
  23. codecop/blockers.py +935 -0
  24. codecop/budget.py +980 -0
  25. codecop/catalog_profile.py +525 -0
  26. codecop/changed.py +261 -0
  27. codecop/cicmd.py +1002 -0
  28. codecop/cli.py +5421 -0
  29. codecop/client.py +729 -0
  30. codecop/coverage.py +1067 -0
  31. codecop/coverage_reasons.py +116 -0
  32. codecop/crashlog.py +70 -0
  33. codecop/datagen.py +766 -0
  34. codecop/datagen_postgres.py +630 -0
  35. codecop/datagen_sqlite.py +323 -0
  36. codecop/dbcli.py +885 -0
  37. codecop/definitions.py +457 -0
  38. codecop/discover/__init__.py +702 -0
  39. codecop/discover/arms.py +160 -0
  40. codecop/discover/base.py +234 -0
  41. codecop/discover/dialect.py +296 -0
  42. codecop/discover/elixir.py +64 -0
  43. codecop/discover/engine_go.py +320 -0
  44. codecop/discover/go.py +1947 -0
  45. codecop/discover/java.py +1528 -0
  46. codecop/discover/loops.py +1671 -0
  47. codecop/discover/named_go.py +258 -0
  48. codecop/discover/origins.py +4565 -0
  49. codecop/discover/origins_ts.py +1584 -0
  50. codecop/discover/orm_django.py +2772 -0
  51. codecop/discover/orm_django_models.py +814 -0
  52. codecop/discover/orm_django_sql.py +662 -0
  53. codecop/discover/orm_ent.py +565 -0
  54. codecop/discover/orm_ex_ecto.py +2138 -0
  55. codecop/discover/orm_go.py +2134 -0
  56. codecop/discover/orm_go_bun.py +602 -0
  57. codecop/discover/orm_go_run.py +636 -0
  58. codecop/discover/orm_go_types.py +1082 -0
  59. codecop/discover/orm_java.py +1450 -0
  60. codecop/discover/orm_jdbi.py +743 -0
  61. codecop/discover/orm_jooq.py +806 -0
  62. codecop/discover/orm_jpa.py +1307 -0
  63. codecop/discover/orm_mybatis.py +730 -0
  64. codecop/discover/orm_py.py +557 -0
  65. codecop/discover/orm_py_peewee.py +1266 -0
  66. codecop/discover/orm_py_prisma.py +298 -0
  67. codecop/discover/orm_rb_activerecord.py +1906 -0
  68. codecop/discover/orm_rust.py +1248 -0
  69. codecop/discover/orm_rust_seaorm.py +734 -0
  70. codecop/discover/orm_sqlalchemy.py +2475 -0
  71. codecop/discover/orm_stats.py +307 -0
  72. codecop/discover/orm_tables.py +29 -0
  73. codecop/discover/orm_ts.py +503 -0
  74. codecop/discover/orm_ts_drizzle.py +697 -0
  75. codecop/discover/orm_ts_knex.py +1117 -0
  76. codecop/discover/orm_ts_kysely.py +861 -0
  77. codecop/discover/orm_ts_prisma.py +1045 -0
  78. codecop/discover/orm_ts_schema.py +169 -0
  79. codecop/discover/orm_ts_sequelize.py +1401 -0
  80. codecop/discover/orm_ts_typeorm.py +1067 -0
  81. codecop/discover/probes.py +323 -0
  82. codecop/discover/python.py +595 -0
  83. codecop/discover/ruby.py +793 -0
  84. codecop/discover/rust.py +2378 -0
  85. codecop/discover/schema.py +520 -0
  86. codecop/discover/schema_ent.py +145 -0
  87. codecop/discover/schema_ts.py +420 -0
  88. codecop/discover/tsresolve.py +257 -0
  89. codecop/discover/typescript.py +1728 -0
  90. codecop/discover/xml_mapper.py +526 -0
  91. codecop/engines/__init__.py +515 -0
  92. codecop/engines/base.py +498 -0
  93. codecop/engines/clickhouse.py +1558 -0
  94. codecop/engines/pg_ddl.py +444 -0
  95. codecop/engines/pg_hints.py +137 -0
  96. codecop/engines/postgres.py +1060 -0
  97. codecop/engines/sqlite.py +742 -0
  98. codecop/families/__init__.py +3 -0
  99. codecop/families/build.py +280 -0
  100. codecop/families/cli.py +177 -0
  101. codecop/families/coverage_hook.py +62 -0
  102. codecop/families/driver.py +221 -0
  103. codecop/families/goslice.py +229 -0
  104. codecop/families/goslice_tool/go.mod +3 -0
  105. codecop/families/goslice_tool/main.go +403 -0
  106. codecop/families/holes.py +451 -0
  107. codecop/families/images/Dockerfile.go +5 -0
  108. codecop/families/images/Dockerfile.python +4 -0
  109. codecop/families/images/Dockerfile.rust +4 -0
  110. codecop/families/isolate.py +171 -0
  111. codecop/families/locate.py +270 -0
  112. codecop/families/model.py +301 -0
  113. codecop/families/plangate.py +271 -0
  114. codecop/families/tagpatch.py +174 -0
  115. codecop/fidelity.py +671 -0
  116. codecop/fixgroups.py +130 -0
  117. codecop/formerly.py +91 -0
  118. codecop/grantscript.py +254 -0
  119. codecop/groupbench.py +1375 -0
  120. codecop/groups.py +594 -0
  121. codecop/groups_view.py +186 -0
  122. codecop/heat.py +1405 -0
  123. codecop/heatcli.py +219 -0
  124. codecop/joins.py +1749 -0
  125. codecop/joins_view.py +127 -0
  126. codecop/kinds/__init__.py +507 -0
  127. codecop/kinds/calls/__init__.py +501 -0
  128. codecop/kinds/calls/extract.py +1097 -0
  129. codecop/kinds/calls/harness.py +408 -0
  130. codecop/kinds/calls/measure.py +342 -0
  131. codecop/kinds/calls/rules.py +139 -0
  132. codecop/kinds/calls/runners/RunCalls.java +167 -0
  133. codecop/kinds/calls/runners/run_go.go +141 -0
  134. codecop/kinds/calls/runners/run_node.js +186 -0
  135. codecop/kinds/calls/runners/run_python.py +319 -0
  136. codecop/kinds/calls/runners/run_rust.rs +200 -0
  137. codecop/kinds/calls/standin.py +340 -0
  138. codecop/kinds/pipeline.py +288 -0
  139. codecop/kinds/regex/__init__.py +1167 -0
  140. codecop/kinds/regex/engines/RegexHarness.java +129 -0
  141. codecop/kinds/regex/engines/run_go.go +294 -0
  142. codecop/kinds/regex/engines/run_node.js +99 -0
  143. codecop/kinds/regex/engines/run_python.py +295 -0
  144. codecop/kinds/regex/engines/run_rust.rs +149 -0
  145. codecop/kinds/regex/extract.py +1438 -0
  146. codecop/kinds/regex/harness.py +235 -0
  147. codecop/kinds/regex/measure.py +270 -0
  148. codecop/kinds/regex/shapes.py +418 -0
  149. codecop/kinds/regex/syntax.py +1721 -0
  150. codecop/kinds/testkind.py +107 -0
  151. codecop/kinds/transaction/__init__.py +228 -0
  152. codecop/kinds/transaction/bind.py +355 -0
  153. codecop/kinds/transaction/measure.py +264 -0
  154. codecop/kinds/transaction/plan.py +462 -0
  155. codecop/kinds/transaction/rules.py +540 -0
  156. codecop/kinds/transaction/sandbox.py +94 -0
  157. codecop/kinds/transaction/scenarios.py +520 -0
  158. codecop/kinds/transaction/schedule.py +483 -0
  159. codecop/kinds/transaction/shapes.py +418 -0
  160. codecop/kinds/transaction/verify.py +293 -0
  161. codecop/live.py +237 -0
  162. codecop/loopbench.py +2071 -0
  163. codecop/loopschema.py +591 -0
  164. codecop/mcpserver.py +120 -0
  165. codecop/mechanism.py +214 -0
  166. codecop/members.py +200 -0
  167. codecop/multi.py +443 -0
  168. codecop/observed.py +1868 -0
  169. codecop/parts.py +102 -0
  170. codecop/patterns.py +830 -0
  171. codecop/patterns_view.py +559 -0
  172. codecop/plangate.py +242 -0
  173. codecop/profile.py +439 -0
  174. codecop/prompts/areas.md +19 -0
  175. codecop/prompts/observed_variants.md +20 -0
  176. codecop/prompts/profile.md +60 -0
  177. codecop/prompts/profile_postgres.md +68 -0
  178. codecop/prompts/profile_sizes.md +26 -0
  179. codecop/prompts/profile_sqlite.md +69 -0
  180. codecop/prompts/rank.md +84 -0
  181. codecop/prompts/rank_postgres.md +96 -0
  182. codecop/prompts/rank_sqlite.md +94 -0
  183. codecop/prompts/scenario_variants.md +20 -0
  184. codecop/rank.py +1473 -0
  185. codecop/realdb/__init__.py +688 -0
  186. codecop/realdb/clickhouse.py +1223 -0
  187. codecop/realdb/facts.py +815 -0
  188. codecop/realdb/locality.py +964 -0
  189. codecop/realdb/locks.py +355 -0
  190. codecop/realdb/match.py +531 -0
  191. codecop/realdb/postgres.py +643 -0
  192. codecop/realdb/ratios.py +77 -0
  193. codecop/realdb/sample.py +126 -0
  194. codecop/relations.py +227 -0
  195. codecop/report.py +1854 -0
  196. codecop/resources.py +332 -0
  197. codecop/resources_view.py +266 -0
  198. codecop/rules/entry_points.toml +1013 -0
  199. codecop/rules/sinks.toml +362 -0
  200. codecop/runsonce.py +8 -0
  201. codecop/sandboxschema.py +555 -0
  202. codecop/scenario_agent.py +172 -0
  203. codecop/scenario_bind.py +507 -0
  204. codecop/scenario_sql.py +971 -0
  205. codecop/scenarios.py +675 -0
  206. codecop/scenarios_view.py +274 -0
  207. codecop/schemacli.py +67 -0
  208. codecop/schemas/areas_output.schema.json +21 -0
  209. codecop/schemas/profile_output.schema.json +362 -0
  210. codecop/schemas/rank_output.schema.json +385 -0
  211. codecop/sizes.py +200 -0
  212. codecop/sqlinfo.py +558 -0
  213. codecop/typedparams.py +576 -0
  214. codecop/verdicts.py +212 -0
  215. codecop/writebench.py +720 -0
  216. codecop/writecost.py +440 -0
  217. codecop/writes.py +1208 -0
  218. codecop-0.1.0.dist-info/METADATA +42 -0
  219. codecop-0.1.0.dist-info/RECORD +222 -0
  220. codecop-0.1.0.dist-info/WHEEL +4 -0
  221. codecop-0.1.0.dist-info/entry_points.txt +2 -0
  222. codecop-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,815 @@
1
+ """What the pulled db files say, in the form rank, profile, report and coverage use.
2
+
3
+ Reads db_catalog.json, db_match.json and db_sample.json from an out dir. Nothing here
4
+ connects to anything. Every fact carries where it came from (`real catalog`, `real workload`,
5
+ `real sample`), so a number that was measured is never confused with one that was inferred.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import re
12
+ from datetime import datetime
13
+ from pathlib import Path
14
+
15
+ from . import CATALOG_FILE, MATCH_FILE, SAMPLE_FILE, WORKLOAD_FILE
16
+ from .. import sizes
17
+ from .match import SPREAD_KEYS
18
+
19
+ REAL_CATALOG = "real catalog"
20
+ REAL_WORKLOAD = "real workload"
21
+ REAL_SAMPLE = "real sample"
22
+ INFERRED = "inferred"
23
+ TIER_SCHEMA_AND_WORKLOAD = "real schema + real workload, synthetic data"
24
+ TIER_SCHEMA = "real schema, synthetic data"
25
+ # A measured query below this share of all bytes read is known to be cheap: it ranks below queries nothing is known about.
26
+ NEGLIGIBLE_SHARE = 0.0001
27
+ LOADABLE = re.compile(r"MergeTree$")
28
+ TTL_CLAUSE = re.compile(r"\sTTL\s.+?(?=\sSETTINGS\s|\Z)", re.I | re.S)
29
+ SETTINGS_CLAUSE = re.compile(r"\sSETTINGS\s+(.+)\Z", re.I | re.S)
30
+ KEEP_SETTINGS = ("index_granularity", "allow_nullable_key")
31
+
32
+
33
+ def _read(out_dir: Path, name: str) -> dict | None:
34
+ path = out_dir / name
35
+ try:
36
+ return json.loads(path.read_text()) if path.exists() else None
37
+ except ValueError:
38
+ return None
39
+
40
+
41
+ USER_MARK = "<user>"
42
+
43
+
44
+ def masked_word(catalog: dict | None) -> str:
45
+ """The word an earlier pull masked as `<user>` inside definitions and query texts, when the files prove what it was.
46
+
47
+ Pulls before the fix scrubbed the account name out of statement text too. When the account name is an ordinary SQL
48
+ word, that replaced the word everywhere. The catalog keeps each column's default kind separately (never scrubbed),
49
+ so a column whose kind is DEFAULT and whose definition reads `<type> <user> <expression>` proves the word was
50
+ `default`. Returns "" when nothing was masked or nothing proves it."""
51
+ for conn in ((catalog or {}).get("connections") or {}).values():
52
+ for t in conn.get("tables") or []:
53
+ sql = t.get("create_sql") or ""
54
+ if USER_MARK not in sql:
55
+ continue
56
+ for c in t.get("columns") or []:
57
+ if c.get("default_kind") == "DEFAULT" and re.search(rf"`{re.escape(c['name'])}`\s+[^,]*?\s{re.escape(USER_MARK)}\s", sql):
58
+ return "default"
59
+ return ""
60
+
61
+
62
+ def masked_word_in_workload(workload: dict | None, catalog: dict | None) -> str:
63
+ """The same question for a workload file whose catalog was pulled again later and no longer holds the proof.
64
+
65
+ Two things in the texts prove the word was `default`: a function name that only exists with it (`...Or<user>(`,
66
+ as in dictGetOrDefault), or the marker used as a database prefix of a table the catalog lists in the database
67
+ `default`."""
68
+ in_default = {t["name"] for conn in ((catalog or {}).get("connections") or {}).values() for t in conn.get("tables") or []
69
+ if t.get("database") == "default"}
70
+ for w in ((workload or {}).get("connections") or {}).values():
71
+ for q in w.get("queries") or []:
72
+ text = q.get("text") or ""
73
+ if USER_MARK not in text:
74
+ continue
75
+ if re.search(rf"[a-z]Or{re.escape(USER_MARK)}\(", text):
76
+ return "default"
77
+ if any(m in in_default for m in re.findall(rf"{re.escape(USER_MARK)}\.`?(\w+)", text)):
78
+ return "default"
79
+ return ""
80
+
81
+
82
+ def unmask(text: str, word: str) -> str:
83
+ """Put a masked word back: as a keyword after whitespace, capitalised inside a camel-case name (dictGetOrDefault),
84
+ lower case before a dot (a database prefix)."""
85
+ if not word or USER_MARK not in text:
86
+ return text
87
+ text = re.sub(rf"(?<=[a-z0-9]){re.escape(USER_MARK)}", word.capitalize(), text)
88
+ text = re.sub(rf"{re.escape(USER_MARK)}(?=\.)", word, text)
89
+ return text.replace(USER_MARK, word.upper())
90
+
91
+
92
+ def sandbox_ddl(create_sql: str, database: str, name: str) -> str:
93
+ """A real ClickHouse definition as the sandbox can build it: no database prefix, no TTL, no storage settings."""
94
+ sql = create_sql.strip()
95
+ sql = re.sub(rf"(CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?)`?{re.escape(database)}`?\.`?{re.escape(name)}`?", rf"\1{name}", sql, count=1, flags=re.I)
96
+ sql = re.sub(r"\s+UUID\s+'[0-9a-f-]+'", "", sql, count=1, flags=re.I)
97
+ sql = TTL_CLAUSE.sub("", sql)
98
+ sql = strip_constraints(sql)
99
+ m = SETTINGS_CLAUSE.search(sql)
100
+ if m:
101
+ kept = [s.strip() for s in re.split(r",\s*(?=\w+\s*=)", m.group(1)) if s.strip().split("=")[0].strip() in KEEP_SETTINGS]
102
+ sql = sql[:m.start()] + (" SETTINGS " + ", ".join(kept) if kept else "")
103
+ return sql
104
+
105
+
106
+ def strip_constraints(sql: str) -> str:
107
+ """A ClickHouse definition without its CONSTRAINT ... CHECK / ASSUME entries: generated rows are not made to satisfy
108
+ a production check (a document size bound refused the whole load), and a statement's plan does not depend on it."""
109
+ out, i, depth = [], 0, 0
110
+ while i < len(sql):
111
+ ch = sql[i]
112
+ if ch == "'":
113
+ j = i + 1
114
+ while j < len(sql) and not (sql[j] == "'" and sql[j - 1] != "\\"):
115
+ j += 1
116
+ out.append(sql[i:j + 1]); i = j + 1
117
+ continue
118
+ if ch == "(":
119
+ depth += 1
120
+ elif ch == ")":
121
+ depth -= 1
122
+ if depth == 1 and ch == "," and re.match(r",\s*CONSTRAINT\s", sql[i:], re.I):
123
+ j, d = i + 1, 1
124
+ while j < len(sql):
125
+ if sql[j] == "'":
126
+ k = j + 1
127
+ while k < len(sql) and sql[k] != "'":
128
+ k += 1
129
+ j = k + 1
130
+ continue
131
+ if sql[j] == "(":
132
+ d += 1
133
+ elif sql[j] == ")":
134
+ d -= 1
135
+ if d == 0:
136
+ break
137
+ elif sql[j] == "," and d == 1:
138
+ break
139
+ j += 1
140
+ i = j
141
+ continue
142
+ out.append(ch)
143
+ i += 1
144
+ return "".join(out)
145
+
146
+
147
+ def production_resources(row: dict) -> dict:
148
+ """A call site's production figures per run from the resource pull (match.resource_fields): `memory_per_run`
149
+ {q50, q95, q99, max}, `cpu_ms_per_run` {q50, q95, max} (user + system), `threads_avg`. Empty for an older pull."""
150
+ res = row.get("resources") or {}
151
+ out: dict = {}
152
+ mem = res.get("memory") or {}
153
+ if all(mem.get(k) is not None for k in ("q50", "q99")):
154
+ out["memory_per_run"] = {k: mem.get(k) for k in ("q50", "q95", "q99", "max")}
155
+ cpu = res.get("cpu") or {}
156
+ if cpu.get("counted") and cpu.get("q50_us") is not None:
157
+ out["cpu_ms_per_run"] = {k: round(cpu[f"{k}_us"] / 1000, 3) for k in ("q50", "q95", "max") if cpu.get(f"{k}_us") is not None}
158
+ if (res.get("threads") or {}).get("avg"):
159
+ out["threads_avg"] = res["threads"]["avg"]
160
+ return out
161
+
162
+
163
+ class Facts:
164
+ negligible_share = NEGLIGIBLE_SHARE
165
+
166
+ def __init__(self, catalog: dict | None, matchdata: dict | None, samples: dict | None, workload: dict | None = None):
167
+ self.catalog, self.matchdata, self.samples, self.workload = catalog or {}, matchdata or {}, samples or {}, workload or {}
168
+ self.out_dir: Path | None = None # set by load(): where the workload file is, read only when a fact needs it
169
+ self.masked = masked_word(self.catalog)
170
+
171
+ def __bool__(self) -> bool:
172
+ return bool(self.catalog.get("connections") or self.matchdata.get("engines"))
173
+
174
+ # ---- catalog ---------------------------------------------------------
175
+ def _read_by(self, engine: str) -> dict[str, int]:
176
+ """`database.table` -> bytes the real workload read from it, from the matched query log."""
177
+ out: dict[str, int] = {}
178
+ for q in (self.match(engine) or {}).get("queries") or []:
179
+ for name in q.get("tables") or []:
180
+ out[name] = out.get(name, 0) + int(q.get("read_bytes") or 0)
181
+ return out
182
+
183
+ def tables(self, engine: str) -> dict[str, dict]:
184
+ """short table name -> its catalog entry.
185
+
186
+ A name in several databases resolves to the one the real workload reads (the most bytes read from it), and
187
+ without a workload to the one with the most rows."""
188
+ out: dict[str, dict] = {}
189
+ read_by = self._read_by(engine)
190
+
191
+ def weight(t: dict) -> tuple:
192
+ return (read_by.get(f"{t.get('database', '')}.{t['name']}", 0), t.get("rows") or 0)
193
+
194
+ for conn in (self.catalog.get("connections") or {}).values():
195
+ if conn.get("engine") != engine:
196
+ continue
197
+ for t in conn.get("tables") or []:
198
+ key = t["name"] if engine == "clickhouse" or t.get("schema", "public") == "public" else f"{t['schema']}.{t['name']}"
199
+ seen = out.get(key)
200
+ if seen is None or weight(t) > weight(seen):
201
+ out[key] = {**t, "ambiguous": seen is not None}
202
+ else:
203
+ seen["ambiguous"] = True
204
+ return out
205
+
206
+ def column_sizes(self, engine: str, name: str) -> dict[str, dict]:
207
+ """column -> {mean_bytes, compress_ratio, type, default_kind}: the real mean uncompressed size of a value and how
208
+ well the column compresses. Empty when the server reports no per-column sizes (ClickHouse reports zero for every
209
+ column of a table whose parts are all compact, and PostgreSQL has none here: its widths come from pg_stats)."""
210
+ t = self.tables(engine).get(name.split(".")[-1] if engine == "clickhouse" else name)
211
+ rows = int((t or {}).get("rows") or 0)
212
+ if not t or rows <= 0:
213
+ return {}
214
+ out = {}
215
+ for c in t.get("columns") or []:
216
+ if engine == "postgres":
217
+ if c.get("avg_width"):
218
+ out[c["name"]] = {"mean_bytes": float(c["avg_width"]), "compress_ratio": None, "type": c.get("type", ""),
219
+ "default_kind": "MATERIALIZED" if c.get("generated") or c.get("identity") else ""}
220
+ continue
221
+ unc, comp = int(c.get("uncompressed_bytes") or 0), int(c.get("compressed_bytes") or 0)
222
+ if unc <= 0:
223
+ continue
224
+ out[c["name"]] = {"mean_bytes": round(unc / rows, 1), "compress_ratio": round(unc / comp, 2) if comp else None,
225
+ "type": c.get("type", ""), "default_kind": c.get("default_kind", "")}
226
+ return out
227
+
228
+ def planner_stats(self, name: str) -> dict[str, dict]:
229
+ """PostgreSQL: column -> {n_distinct, null_frac, correlation} as pg_stats has them (no data values).
230
+ `n_distinct` is a count when positive and minus a share of the rows when negative, as the server stores it."""
231
+ t = self.tables("postgres").get(name)
232
+ return {c["name"]: {k: c.get(k) for k in ("n_distinct", "null_frac", "correlation")}
233
+ for c in (t or {}).get("columns") or [] if c.get("n_distinct") is not None or c.get("null_frac") is not None}
234
+
235
+ def table_shape(self, engine: str, name: str) -> dict | None:
236
+ """The real table's sizes, for the sandbox table's fidelity grade, and its part layout when the pull has it."""
237
+ t = self.tables(engine).get(name.split(".")[-1] if engine == "clickhouse" else name)
238
+ if not t or not t.get("rows"):
239
+ return None
240
+ out = {k: int(t.get(k) or 0) for k in ("rows", "uncompressed_bytes", "bytes_on_disk", "parts", "partitions")}
241
+ layout = self.part_layout(engine, name)
242
+ if layout:
243
+ out["layout"] = layout
244
+ d = t.get("partition_parts") or {}
245
+ rows, marks = sum(d.get("rows") or []), sum(d.get("marks") or [])
246
+ if rows and marks: # also for partitions that are not periods of time (no layout): the sandbox's granules follow it
247
+ out["rows_per_mark"] = round(rows / marks, 1)
248
+ return out
249
+
250
+ def _table(self, engine: str, name: str) -> dict | None:
251
+ return self.tables(engine).get(name.split(".")[-1] if engine == "clickhouse" else name)
252
+
253
+ def partition_time(self, engine: str, name: str) -> dict | None:
254
+ """How a table's partitions are periods of time: {unit, column, newest}. None when they are not, or when the pull
255
+ has no per-partition detail (an older file, a server that refused the statement).
256
+
257
+ `unit`: day, week, month or year, from the partition ids. `column`: the date or time column of the partition key
258
+ (the first one). `newest`: the first day of the newest period."""
259
+ t = self._table(engine, name) or {}
260
+ ids = list((t.get("partition_parts") or {}).get("ids") or []) or list((t.get("partition_columns") or {}).get("ids") or [])
261
+ unit = sizes.partition_unit(ids)
262
+ if not unit:
263
+ return None
264
+ column = next((c["name"] for c in t.get("columns") or [] if c.get("in_partition_key") and "Date" in (c.get("type") or "")), None) \
265
+ or next((c["name"] for c in t.get("columns") or [] if c.get("in_partition_key")), None)
266
+ return {"unit": unit, "column": column, "newest": max(sizes.partition_day(p) for p in ids)}
267
+
268
+ def part_layout(self, engine: str, name: str, keep: int = 400) -> dict | None:
269
+ """The real parts per partition by age, newest first: {unit, parts: [n, ...], older, rows_per_mark, partitions}.
270
+
271
+ `parts[i]` is the part count of the partition `i` periods before the newest (None where the real table has no
272
+ such partition), for the `keep` newest periods; `older` is the average of the rest. None when the partitions
273
+ are not periods of time: the table's average stays the only thing known."""
274
+ t = self._table(engine, name) or {}
275
+ d = t.get("partition_parts") or {}
276
+ when = self.partition_time(engine, name)
277
+ if not when or not d.get("ids"):
278
+ return None
279
+ by_back: dict[int, dict] = {}
280
+ for pid, parts, rows, marks in zip(d["ids"], d.get("parts") or [], d.get("rows") or [], d.get("marks") or []):
281
+ back = sizes.periods_back(when["unit"], when["newest"], sizes.partition_day(pid))
282
+ seen = by_back.setdefault(back, {"partitions": 0, "parts": 0, "rows": 0, "marks": 0})
283
+ seen["partitions"] += 1 # a tuple key gives several partitions per period: their part counts are averaged
284
+ seen["parts"] += int(parts)
285
+ seen["rows"] += int(rows)
286
+ seen["marks"] += int(marks)
287
+ per_period = {back: v["parts"] / v["partitions"] for back, v in by_back.items()}
288
+ newest = [round(per_period[i], 1) if i in per_period else None for i in range(min(max(per_period) + 1, keep))]
289
+ rest = [v for back, v in per_period.items() if back >= keep]
290
+ rows, marks = sum(v["rows"] for v in by_back.values()), sum(v["marks"] for v in by_back.values())
291
+ return {"unit": when["unit"], "parts": newest, "older": round(sum(rest) / len(rest), 1) if rest else None,
292
+ "rows_per_mark": round(rows / marks, 1) if marks else None, "partitions": len(d["ids"])}
293
+
294
+ def width_by_age(self, engine: str, name: str, max_bands: int = sizes.WIDTH_BANDS, tolerance: float = sizes.BAND_TOLERANCE) -> dict[str, dict]:
295
+ """column -> {unit, column, bands, rows_reported, rows}: its mean size by the age of the row, from the real
296
+ per-partition column sizes. Only columns whose bands differ from one another are returned.
297
+
298
+ A partition whose parts report no size for a column (compact parts) is not counted: `rows_reported` over `rows`
299
+ says how much of the table the bands were measured on."""
300
+ t = self._table(engine, name) or {}
301
+ d = t.get("partition_columns") or {}
302
+ when = self.partition_time(engine, name)
303
+ if not when or not when.get("column") or not d.get("ids"):
304
+ return {}
305
+ backs = [sizes.periods_back(when["unit"], when["newest"], sizes.partition_day(p)) for p in d["ids"]]
306
+ out = {}
307
+ for j, column in enumerate(d.get("columns") or []):
308
+ points = [(back, int(cells[j][0]), int(cells[j][1])) for back, cells in zip(backs, d.get("cells") or [])
309
+ if j < len(cells) and cells[j]]
310
+ rows, size = sum(p[1] for p in points), sum(p[2] for p in points)
311
+ bands = sizes.age_bands(points, max_bands, tolerance)
312
+ if rows and sizes.bands_matter(bands, size / rows):
313
+ out[column] = {"unit": when["unit"], "column": when["column"], "bands": bands, "rows_reported": rows,
314
+ "rows": int(t.get("rows") or 0)}
315
+ return out
316
+
317
+ def production(self, engine: str, candidates: list[dict]) -> dict[str, dict]:
318
+ """finding -> the per-run read profile the real query log measured, for candidates matched for sure."""
319
+ load = self.site_load(engine)
320
+ heaviest = self._heaviest_run(engine)
321
+ out = {}
322
+ for c in candidates:
323
+ row = load.get(c.get("id"))
324
+ if row and row.get("rows_read_per_run") is not None and row.get("executions"):
325
+ out[c["finding"]] = {k: row.get(k) for k in ("rows_read_per_run", "bytes_read_per_run", "rows_returned_per_run",
326
+ "read_bytes", "executions", "aggregate")}
327
+ # the spread of the runs, when the pull asked for it: fidelity.py then grades against the median run
328
+ out[c["finding"]].update({k: row[k] for k in SPREAD_KEYS if row.get(k) is not None})
329
+ top = max((heaviest.get(h, 0) for h in row.get("hashes") or []), default=0)
330
+ if top:
331
+ out[c["finding"]]["max_bytes_read_per_run"] = top
332
+ # what one run used in production (the resource pull): the CPU and memory grades, and the threads the
333
+ # sandbox gives the shape's runs (fidelity.resource_check, bench.bench_candidate)
334
+ out[c["finding"]].update(production_resources(row))
335
+ return out
336
+
337
+ def pg_settings(self) -> dict:
338
+ """PostgreSQL's pulled settings (pg.check.settings) as the sandbox takes them: {work_mem_kb, hash_mem_multiplier}."""
339
+ if not self.workload and self.out_dir is not None:
340
+ self.workload = _read(self.out_dir, WORKLOAD_FILE) or {}
341
+ for w in (self.workload.get("connections") or {}).values():
342
+ st = w.get("settings") if w.get("engine") == "postgres" else None
343
+ if isinstance(st, dict) and st.get("work_mem_bytes"):
344
+ return {"work_mem_kb": int(st["work_mem_bytes"]) // 1024, "hash_mem_multiplier": st.get("hash_mem_multiplier")}
345
+ return {}
346
+
347
+ def _heaviest_run(self, engine: str) -> dict[str, int]:
348
+ """query hash -> the most bytes one run of it read, from the workload file (the match file keeps sums only)."""
349
+ if not self.workload and self.out_dir is not None:
350
+ self.workload = _read(self.out_dir, WORKLOAD_FILE) or {}
351
+ out: dict[str, int] = {}
352
+ for w in (self.workload.get("connections") or {}).values():
353
+ if w.get("engine", engine) != engine:
354
+ continue
355
+ for q in w.get("queries") or []:
356
+ if q.get("max_read_bytes"):
357
+ out[q["hash"]] = int(q["max_read_bytes"])
358
+ return out
359
+
360
+ def definition(self, engine: str, name: str) -> dict | None:
361
+ """A table definition the sandbox can build, from the real catalog. None for a table that is not a plain table."""
362
+ t = self.tables(engine).get(name.split(".")[-1] if engine == "clickhouse" else name)
363
+ if t is None or not t.get("create_sql"):
364
+ return None
365
+ if USER_MARK in t["create_sql"] and not self.masked:
366
+ return None # an older pull masked a word in it and nothing proves which: the agent assembles this one
367
+ if engine == "clickhouse":
368
+ if not LOADABLE.search(t.get("engine", "")):
369
+ return None
370
+ sql = sandbox_ddl(unmask(t["create_sql"], self.masked), t.get("database", ""), t["name"])
371
+ else:
372
+ from .postgres import quote_created_table
373
+ sql = quote_created_table(t["create_sql"]) # a table named `user`: quoted, as PostgreSQL needs it
374
+ return {"name": name.split(".")[-1] if engine == "clickhouse" else name, "create_sql": sql, "inferred": False,
375
+ "basis": "The real table, read from the database catalog.", "source": REAL_CATALOG,
376
+ "rows": int(t.get("rows") or 0), "bytes_on_disk": int(t.get("bytes_on_disk") or 0)}
377
+
378
+ def definitions(self, engine: str, names: set[str]) -> list[dict]:
379
+ found = [self.definition(engine, n) for n in sorted(names)]
380
+ return [d for d in found if d]
381
+
382
+ def table_note(self, engine: str, name: str, sizes: bool = True) -> str:
383
+ """One line of real size facts for a prompt. `sizes=False` leaves out everything that tells how wide rows are."""
384
+ t = self.tables(engine).get(name.split(".")[-1] if engine == "clickhouse" else name)
385
+ if t is None:
386
+ return ""
387
+ bits = [f"{int(t.get('rows') or 0):,} rows"] + ([f"{(t.get('bytes_on_disk') or 0) / 1e9:.2f} GB on disk"] if sizes else [])
388
+ if t.get("partitions"):
389
+ bits.append(f"{t['partitions']} partitions" + (f" ({t['min_partition']} to {t['max_partition']})" if t.get("min_partition") else ""))
390
+ heavy = sorted((c for c in t.get("columns") or [] if c.get("compressed_bytes")), key=lambda c: -c["compressed_bytes"])[:4]
391
+ if heavy and sizes:
392
+ bits.append("largest columns: " + ", ".join(f"{c['name']} {c['compressed_bytes'] / 1e9:.2f} GB" for c in heavy))
393
+ if engine == "postgres" and (t.get("seq_scans") or t.get("index_scans")):
394
+ bits.append(f"{t.get('seq_scans', 0):,} sequential scans, {t.get('index_scans', 0):,} index scans since statistics reset")
395
+ return "real: " + "; ".join(bits)
396
+
397
+ def rows(self, engine: str, name: str) -> int | None:
398
+ t = self.tables(engine).get(name.split(".")[-1] if engine == "clickhouse" else name)
399
+ return int(t["rows"]) if t is not None and t.get("rows") is not None else None
400
+
401
+ def sampled(self, engine: str, name: str) -> dict | None:
402
+ for conn in (self.samples.get("connections") or {}).values():
403
+ if conn.get("engine") == engine:
404
+ for t in conn.get("tables") or []:
405
+ if t.get("ok") and t["table"] == name.split(".")[-1]:
406
+ return t
407
+ return None
408
+
409
+ # ---- workload --------------------------------------------------------
410
+ def match(self, engine: str) -> dict | None:
411
+ return (self.matchdata.get("engines") or {}).get(engine)
412
+
413
+ def site_load(self, engine: str, located: bool = False) -> dict[str, dict]:
414
+ """site id -> measured load, for matches that are sure (exact or template).
415
+
416
+ `located=True` adds call sites whose SQL is one piece of longer real statements (`part`). Their row is marked
417
+ `located` and carries the load of the whole statements, with each statement's bytes given to one piece only
418
+ (the heaviest first), so five pieces of one statement do not each claim all of it. `read_bytes` on such a row
419
+ is that share; `statement_read_bytes` is what the statements read in total. The piece's own cost is not known."""
420
+ m = self.match(engine) or {}
421
+ out = {sid: row for sid, row in (m.get("sites") or {}).items() if row["match"] in ("exact", "template", "tag")}
422
+ if not located:
423
+ return out
424
+ per_hash = {q["hash"]: q["read_bytes"] for q in m.get("queries") or []}
425
+ claimed: set[str] = set()
426
+ parts = sorted(((sid, row) for sid, row in (m.get("sites") or {}).items() if row["match"] == "part"),
427
+ key=lambda kv: (-kv[1]["read_bytes"], kv[0]))
428
+ total = (m.get("workload") or {}).get("read_bytes") or 0
429
+ for sid, row in parts:
430
+ own = sum(per_hash.get(h, 0) for h in row.get("hashes") or [] if h not in claimed)
431
+ claimed.update(row.get("hashes") or [])
432
+ out[sid] = {**row, "located": True, "statement_read_bytes": row["read_bytes"], "read_bytes": own,
433
+ "share_of_read_bytes": round(own / total, 6) if total else 0.0,
434
+ "statement_share_of_read_bytes": row["share_of_read_bytes"]}
435
+ return out
436
+
437
+ def window(self, engine: str) -> str:
438
+ m = self.match(engine) or {}
439
+ if m.get("window_hours"):
440
+ return f"last {m['window_hours']} h"
441
+ return f"since {str(m.get('since') or '')[:10] or 'the last statistics reset'}"
442
+
443
+ def load_text(self, engine: str, row: dict) -> str:
444
+ if row.get("located"):
445
+ return (f"located ({self.window(engine)}): this SQL is one piece of {row['shapes']} longer statement(s) that code assembles at run time. "
446
+ f"Together they ran {row['executions']:,} times and read {row['statement_read_bytes'] / 1e9:.2f} GB "
447
+ f"({row['statement_share_of_read_bytes']:.2%} of all bytes read by queries). How much of that this piece causes is not "
448
+ "known: read the function that joins the pieces to build the whole statement before judging it.")
449
+ per_day = f", {row['executions_per_day']:,.0f} a day" if row.get("executions_per_day") else ""
450
+ shape = ""
451
+ if row.get("rows_read_per_run") is not None:
452
+ per_returned = f"{row['rows_read_per_row_returned']:,.0f} rows read per row returned" if row.get("rows_read_per_row_returned") else "returns no rows"
453
+ shape = (f"; per run {row['rows_read_per_run']:,.0f} rows and {row['bytes_read_per_run'] / 1e6:,.1f} MB read, "
454
+ f"{row.get('rows_returned_per_run') or 0:,.0f} rows returned ({per_returned}"
455
+ + (", an aggregate by its shape, where that is expected" if row.get("aggregate") else "")
456
+ + (f"; {row['bytes_read_per_row_read']:,.0f} bytes per row read)" if row.get("bytes_read_per_row_read") else ")"))
457
+ return (f"measured ({self.window(engine)}): {row['executions']:,} executions{per_day}, {row['read_bytes'] / 1e9:.2f} GB read in total, "
458
+ f"avg {row['avg_ms']:.0f} ms, p95 {row.get('p95_ms') or 0:.0f} ms, {row['share_of_read_bytes']:.2%} of all bytes read by queries"
459
+ + shape + ("" if row["match"] == "exact" else " (matched through a query template)"))
460
+
461
+ def evidence_tier(self, engine: str, table_definitions: list[dict], fallback: str) -> str:
462
+ """The run's evidence tier: what was real and what was generated."""
463
+ if not table_definitions or not all(d.get("source") == REAL_CATALOG for d in table_definitions):
464
+ return fallback
465
+ return TIER_SCHEMA_AND_WORKLOAD if self.match(engine) else TIER_SCHEMA
466
+
467
+
468
+ def load(out_dir: Path) -> Facts:
469
+ facts = Facts(_read(out_dir, CATALOG_FILE), _read(out_dir, MATCH_FILE), _read(out_dir, SAMPLE_FILE), None)
470
+ facts.out_dir = out_dir
471
+ return facts
472
+
473
+
474
+ # What the capability check may say in an upload. Everything is chosen from these fixed words: nothing the server
475
+ # returned is passed through, so an object name, an address or an account can not ride along.
476
+ WRITE_KINDS = ("ALL", "INSERT", "ALTER", "ALTER TABLE", "ALTER UPDATE", "ALTER DELETE", "ALTER COLUMN", "ALTER INDEX", "ALTER VIEW",
477
+ "ALTER DATABASE", "ALTER USER", "ALTER ROLE", "CREATE", "CREATE DATABASE", "CREATE TABLE", "CREATE VIEW", "CREATE DICTIONARY",
478
+ "CREATE TEMPORARY TABLE", "CREATE FUNCTION", "CREATE USER", "CREATE ROLE", "DROP", "DROP DATABASE", "DROP TABLE", "DROP VIEW",
479
+ "DROP DICTIONARY", "DROP USER", "DROP ROLE", "TRUNCATE", "OPTIMIZE", "SYSTEM", "KILL QUERY", "ACCESS MANAGEMENT", "GRANT",
480
+ "superuser", "create role", "create database", "create schema", "write to tables")
481
+ _WRITE_FAMILIES = ("ALTER", "CREATE", "DROP", "INSERT", "TRUNCATE", "OPTIMIZE", "SYSTEM", "KILL QUERY", "ACCESS MANAGEMENT", "GRANT", "ALL")
482
+ READ_ONLY_HOW = {"clickhouse": "readonly setting on every request, enforced by the server",
483
+ "postgres": "read-only session (default_transaction_read_only), confirmed by the server"}
484
+ WORKLOAD_SOURCES = ("query_log on every replica", "query_log", "pg_stat_statements")
485
+
486
+
487
+ def write_kind(text) -> str:
488
+ """One privilege word from the fixed list, or "" for anything else. `INSERT ON db.t` is INSERT; a name is never kept."""
489
+ if not isinstance(text, str):
490
+ return ""
491
+ word = " ".join(text.split())
492
+ if word in WRITE_KINDS:
493
+ return word
494
+ if re.match(r"write to \d+ of \d+ tables$", word):
495
+ return "write to tables"
496
+ upper = word.upper()
497
+ return next((f for f in sorted(_WRITE_FAMILIES, key=len, reverse=True) if upper == f or upper.startswith(f + " ")), "")
498
+
499
+
500
+ def capability_fields(conn: dict, pulled_at, sampled: bool) -> dict:
501
+ """The capability check of one connection as an upload may carry it: booleans, a date and fixed words."""
502
+ cap = conn.get("capabilities") or {}
503
+ engine = conn.get("engine", "")
504
+ out: dict = {}
505
+ if isinstance(cap.get("account_can_write"), bool):
506
+ out["account_can_write"] = cap["account_can_write"]
507
+ out["write_access_kinds"] = list(dict.fromkeys(k for k in (write_kind(x) for x in cap.get("write_access_kinds") or []) if k))[:40]
508
+ if cap.get("read_only_enforced") is True and engine in READ_ONLY_HOW:
509
+ out["read_only_how"] = READ_ONLY_HOW[engine]
510
+ source = cap.get("workload_source")
511
+ if cap.get("workload") is True and isinstance(source, str):
512
+ out["workload_source"] = next((w for w in WORKLOAD_SOURCES if source.startswith(w)), "query log")
513
+ # tier C: PostgreSQL 16+ can plan without executing; never for ClickHouse. Tier D: reported only when it was used.
514
+ out["plans"] = engine == "postgres" and isinstance(cap.get("plans"), str) and cap["plans"].startswith("EXPLAIN (GENERIC_PLAN)")
515
+ if sampled:
516
+ out["sample"] = True
517
+ if isinstance(pulled_at, str):
518
+ try:
519
+ out["pulled_at"] = datetime.fromisoformat(pulled_at.strip().replace("Z", "+00:00")).isoformat()
520
+ except ValueError:
521
+ pass
522
+ return out
523
+
524
+
525
+ SPREAD_METHODS = ("exact", "tdigest")
526
+
527
+
528
+ def _amount(value, most: float | None = None) -> float | int | None:
529
+ """A finite number of zero or more (at most `most`), or None for anything else: text, a list, NaN, a boolean."""
530
+ if isinstance(value, bool) or not isinstance(value, (int, float)) or value != value or value in (float("inf"), float("-inf")):
531
+ return None
532
+ return value if value >= 0 and (most is None or value <= most) else None
533
+
534
+
535
+ NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_$]{0,126}(?:\.[A-Za-z0-9_$]{1,127}){1,3}") # table.column, table.projection, table.nested.field
536
+
537
+
538
+ def names_upload(values, databases: set[str] | frozenset = frozenset(), tables: set[str] | frozenset = frozenset(),
539
+ most: int = 200) -> list[str] | None:
540
+ """Column or projection names as an upload may carry them: `table.column`, plain identifiers only, never one that starts
541
+ with a database name, and (when the catalog's table names are given) only names of those tables. None when the value is
542
+ not a list; a name that does not fit is left out, not passed through."""
543
+ if not isinstance(values, list):
544
+ return None
545
+ lower = {d.lower() for d in databases}
546
+ out = [v for v in values if isinstance(v, str) and NAME.fullmatch(v) and v.split(".", 1)[0].lower() not in lower
547
+ and (not tables or v.split(".", 1)[0] in tables)]
548
+ return list(dict.fromkeys(out))[:most]
549
+
550
+
551
+ def spread_upload(row: dict, databases: set[str] | frozenset = frozenset(), tables: set[str] | frozenset = frozenset()) -> dict:
552
+ """The spread of a call site's runs as an upload may carry it: numbers, and the method as one of two fixed words.
553
+
554
+ Rebuilt field by field from the match file, never passed through: whatever else a file holds under these keys
555
+ (text, a name, a nested object) is dropped. Per-partition detail is not here at all: it stays in db_catalog.json.
556
+ The column and projection names a site read are names only (`names_upload`), never with a database."""
557
+ out: dict = {}
558
+ sp = row.get("spread")
559
+ if isinstance(sp, dict):
560
+ triples = {k: [_amount(v) for v in sp[k]] if isinstance(sp.get(k), list) and len(sp[k]) == 3 else None
561
+ for k in ("rows_read", "bytes_read", "rows_returned")}
562
+ if all(t is not None and None not in t for t in triples.values()):
563
+ out["spread"] = {**triples, "method": sp.get("method") if sp.get("method") in SPREAD_METHODS else ""}
564
+ for key, most in (("shapes", None), ("of_executions", 1.0)):
565
+ if _amount(sp.get(key), most) is not None:
566
+ out["spread"][key] = sp[key]
567
+ for key, most in (("no_result_share", 1.0), ("no_read_share", 1.0), ("selected_parts_per_run", None), ("selected_marks_per_run", None),
568
+ ("selected_parts_total_per_run", None), ("selected_marks_total_per_run", None), ("selected_ranges_per_run", None),
569
+ ("empty_run_bytes", None), ("empty_run_rows", None), ("result_run_bytes", None), ("runs_per_statement", None),
570
+ ("active_minutes", None), ("repeats_window_hours", None), ("projection_run_share", 1.0)):
571
+ if _amount(row.get(key), most) is not None:
572
+ out[key] = row[key]
573
+ for key in ("columns_read", "projections_used"):
574
+ names = names_upload(row.get(key), databases, tables)
575
+ if names is not None:
576
+ out[key] = names
577
+ return out
578
+
579
+
580
+ def _n(value, most: float | None = None):
581
+ got = _amount(value, most)
582
+ return None if got is None else (round(got, 4) if isinstance(got, float) else got)
583
+
584
+
585
+ def _drop_none(d: dict) -> dict:
586
+ return {k: v for k, v in d.items() if v is not None}
587
+
588
+
589
+ def resources_measured(row: dict, ctx: dict | None, source_key: str = "source") -> dict:
590
+ """What production measured of a call site's CPU, memory, time, spill and threads, as
591
+ an upload may carry it: rebuilt number by number from the match file (resource_fields) and the pull's context (`ctx`:
592
+ the engine's db_match entry: window_hours, resources {window_hours, totals}, memory, failures, capacity, facts).
593
+
594
+ cpu {typical_ms, p95_ms, max_ms, mean_ms, seconds_per_day, share, cores, source}: user + system. Shares and days are
595
+ over the window CPU was summed over (resources.window_hours, cut to a number of log rows). PostgreSQL:
596
+ only with pg_stat_kcache (mean per run since the statistics reset; no quantiles)
597
+ memory {typical_bytes, p95_bytes, p99_bytes, max_bytes, mean_bytes, held_gb_hours_per_day, held_share, limit_stops,
598
+ source}: the memory tracker's peak of one run (ClickHouse only). A peak is not additive: no share of peaks.
599
+ Memory held is peak x time summed (an upper bound). `mean_bytes` is the log's mean per run (every pull).
600
+ time {total_ms, typical_ms, p95_ms, max_ms}
601
+ io {wait_share, disk_read_bytes_per_day}: the share of a run's CPU and disk-wait time spent waiting on disk
602
+ spill {runs_share, bytes_per_day} (ClickHouse); PostgreSQL `temp_bytes_per_run`
603
+ threads_avg, and PostgreSQL busy_ms_per_run (run time minus disk waits: an upper bound of CPU), max_ms
604
+ Every figure the pull did not have is absent, never zero."""
605
+ ctx = ctx or {}
606
+ res = row.get("resources") or {}
607
+ executions = int(row.get("executions") or 0)
608
+ out: dict = {}
609
+ hours = ctx.get("window_hours")
610
+ days = float(hours) / 24 if isinstance(hours, (int, float)) and hours > 0 else None
611
+ cpu_window = (ctx.get("resources") or {}).get("window_hours")
612
+ cpu_days = float(cpu_window) / 24 if isinstance(cpu_window, (int, float)) and cpu_window > 0 else None
613
+ by_kind = ((ctx.get("resources") or {}).get("totals") or {}).get("by_kind") or []
614
+ cpu = res.get("cpu") or {}
615
+ if cpu.get("counted"):
616
+ total_us = int(cpu.get("user_us") or 0) + int(cpu.get("system_us") or 0)
617
+ runs = int(cpu.get("runs") or 0) or (executions if cpu.get("source") == "pg_stat_kcache" else 0)
618
+ all_us = sum(int(k.get("cpu_us") or 0) for k in by_kind if isinstance(k, dict))
619
+ per_day = total_us / 1e6 / cpu_days if cpu_days and cpu.get("source") != "pg_stat_kcache" else None
620
+ source = cpu.get("source") if cpu.get("source") in ("profile_events", "pg_stat_kcache") else "profile_events"
621
+ out["cpu"] = _drop_none({
622
+ "typical_ms": _n(cpu["q50_us"] / 1000) if cpu.get("q50_us") is not None else None,
623
+ "p95_ms": _n(cpu["q95_us"] / 1000) if cpu.get("q95_us") is not None else None,
624
+ "max_ms": _n(cpu["max_us"] / 1000) if cpu.get("max_us") is not None else None,
625
+ "mean_ms": _n(total_us / runs / 1000) if runs else None,
626
+ "seconds_per_day": _n(per_day) if per_day is not None else None,
627
+ "share": _n(min(total_us / all_us, 1.0)) if all_us and source == "profile_events" else None,
628
+ "cores": _n(per_day / 86400) if per_day is not None else None,
629
+ source_key: source})
630
+ mem = res.get("memory") or {}
631
+ if row.get("max_memory") is not None or mem:
632
+ held = None
633
+ if mem.get("byte_ms") is not None and days:
634
+ held = float(mem["byte_ms"]) / (1e9 * 3.6e6) / days # byte-milliseconds to GB-hours, a day
635
+ all_held = sum(float(k.get("memory_byte_ms") or 0) for k in by_kind if isinstance(k, dict))
636
+ share = None
637
+ if mem.get("byte_ms") and all_held and hours and cpu_window:
638
+ # both as rates: the shape's over the whole window, the total over the window CPU was summed over
639
+ share = min((float(mem["byte_ms"]) / float(hours)) / (all_held / float(cpu_window)), 1.0)
640
+ stops = (res.get("failures") or {}).get("memory_limit")
641
+ if stops is None and isinstance(ctx.get("failures"), dict):
642
+ stops = 0 # the pull counted failures and this shape had none
643
+ out["memory"] = _drop_none({
644
+ "typical_bytes": _n(mem.get("q50")), "p95_bytes": _n(mem.get("q95")), "p99_bytes": _n(mem.get("q99")),
645
+ "max_bytes": _n(mem.get("max") if mem.get("max") is not None else row.get("max_memory")),
646
+ "mean_bytes": _n(row.get("avg_memory")),
647
+ "held_gb_hours_per_day": _n(held) if held is not None else None, "held_share": _n(share) if share is not None else None,
648
+ "limit_stops": _n(stops), source_key: "query_log"})
649
+ dur = res.get("duration") or {}
650
+ time_ = _drop_none({"total_ms": _n(row.get("total_ms")), "typical_ms": _n(dur.get("q50")), "p95_ms": _n(dur.get("q95")),
651
+ "max_ms": _n(dur.get("max") if dur.get("max") is not None else row.get("max_ms"))})
652
+ if time_:
653
+ out["time"] = time_
654
+ io_wait = cpu.get("io_wait_us")
655
+ if io_wait is not None and cpu.get("counted"):
656
+ busy = int(cpu.get("user_us") or 0) + int(cpu.get("system_us") or 0) + int(io_wait)
657
+ out["io"] = _drop_none({"wait_share": _n(int(io_wait) / busy) if busy else None,
658
+ "disk_read_bytes_per_day": _n(res["disk_read_bytes"] / cpu_days) if res.get("disk_read_bytes") is not None and cpu_days else None})
659
+ elif res.get("read_wait_ms") is not None and row.get("total_ms"):
660
+ out["io"] = {"wait_share": _n(min((float(res["read_wait_ms"]) + float(res.get("write_wait_ms") or 0)) / float(row["total_ms"]), 1.0))}
661
+ spill = res.get("spill") or {}
662
+ if spill and cpu.get("runs"):
663
+ out["spill"] = _drop_none({"runs_share": _n(min(int(spill.get("runs") or 0) / int(cpu["runs"]), 1.0)),
664
+ "bytes_per_day": _n(int(spill.get("bytes") or 0) / cpu_days) if cpu_days else None})
665
+ if (res.get("threads") or {}).get("avg") is not None:
666
+ out["threads_avg"] = _n(float(res["threads"]["avg"]))
667
+ if executions and res.get("busy_ms") is not None:
668
+ out["busy_ms_per_run"] = _n(float(res["busy_ms"]) / executions)
669
+ slowest = dur.get("max") if dur.get("max") is not None else row.get("max_ms")
670
+ if slowest is not None: # the slowest run: PostgreSQL's max_exec_time (every pull), ClickHouse's from ch.workload.memory
671
+ out["max_ms"] = _n(float(slowest))
672
+ if row.get("result_bytes") is not None and executions:
673
+ # ClickHouse result_bytes: what one run sends back, and a day of it
674
+ out["result"] = _drop_none({"bytes_per_run": _n(int(row["result_bytes"]) / executions),
675
+ "bytes_per_day": _n(int(row["result_bytes"]) / days) if days else None})
676
+ temp = res.get("temp_bytes") if res.get("temp_bytes") is not None else (int(row["temp_blocks"]) * 8192 if row.get("temp_blocks") is not None else None)
677
+ if temp is not None and executions:
678
+ out["temp_bytes_per_run"] = _n(temp / executions)
679
+ return out
680
+
681
+
682
+ def resources_context_upload(m: dict | None) -> dict:
683
+ """The pull's resource context of one engine as an upload may carry it (`database.workload[]`): resources {window_hours,
684
+ shapes, totals}, pressure, capacity, facts. Numbers and fixed words only."""
685
+ m = m or {}
686
+ out: dict = {}
687
+ r = m.get("resources")
688
+ if isinstance(r, dict):
689
+ out["resources"] = _drop_none({"window_hours": _n(r.get("window_hours")), "shapes": _n(r.get("shapes")),
690
+ "since_reset": True if r.get("since_reset") else None})
691
+ by_kind = ((r.get("totals") or {}).get("by_kind")) if isinstance(r.get("totals"), dict) else None
692
+ if isinstance(by_kind, list):
693
+ out["resources"]["totals"] = {"by_kind": [_drop_none({"kind": k["kind"] if isinstance(k.get("kind"), str) and re.fullmatch(r"[A-Za-z]{1,40}", k["kind"]) else "",
694
+ "runs": _n(k.get("runs")), "cpu_us": _n(k.get("cpu_us")),
695
+ "memory_byte_ms": _n(k.get("memory_byte_ms")), "max_memory": _n(k.get("max_memory"))})
696
+ for k in by_kind if isinstance(k, dict)][:50]}
697
+ elif isinstance(r.get("totals"), dict):
698
+ out["resources"]["totals"] = _drop_none({k: _n(r["totals"].get(k)) for k in ("executions", "total_ms", "read_wait_ms", "write_wait_ms",
699
+ "temp_bytes", "wal_bytes")})
700
+ p = m.get("pressure")
701
+ if isinstance(p, dict):
702
+ out["pressure"] = _drop_none({k: _n(p.get(k)) for k in ("minutes", "running_q50", "running_q95", "running_max", "held_bytes_q50",
703
+ "held_bytes_q95", "held_bytes_max", "window_hours")})
704
+ c = m.get("capacity")
705
+ if isinstance(c, dict):
706
+ out["capacity"] = _drop_none({k: _n(c.get(k)) for k in ("memory_total_bytes", "memory_limit_bytes", "cores", "max_concurrent_queries")})
707
+ st = m.get("settings")
708
+ if isinstance(st, dict): # PostgreSQL pg.check.settings: numbers and on/off only
709
+ out["capacity"] = {**out.get("capacity", {}), **_drop_none({
710
+ k: (st.get(k) if isinstance(st.get(k), bool) else _n(st.get(k))) for k in (
711
+ "work_mem_bytes", "hash_mem_multiplier", "shared_buffers_bytes", "max_connections", "max_parallel_workers_per_gather",
712
+ "track_io_timing", "track_planning", "jit", "block_size")})}
713
+ f = m.get("facts")
714
+ if isinstance(f, dict):
715
+ out["facts"] = {"cpu": f.get("cpu") if f.get("cpu") in ("profile_events", "pg_stat_kcache", "none") else "none",
716
+ "memory": f.get("memory") if f.get("memory") in ("query_log", "none") else "none",
717
+ "io_wait": bool(f.get("io_wait"))}
718
+ fl = m.get("failures")
719
+ if isinstance(fl, dict):
720
+ other = fl.get("other_shapes") or {}
721
+ out["failures"] = _drop_none({"window_hours": _n(fl.get("window_hours")), "shapes": _n(fl.get("shapes")),
722
+ "other_shapes": _drop_none({k: _n(other.get(k)) for k in ("shapes", "runs", "memory_limit", "timeout")})})
723
+ return out
724
+
725
+
726
+ INSERT_FIELDS = ("inserts", "written_rows", "written_bytes", "median_written_rows", "total_ms")
727
+
728
+
729
+ def inserts_by_table(workload: dict | None) -> dict[str, dict]:
730
+ """table name (no database) -> what INSERT statements wrote to it in the pulled window, summed over databases; the
731
+ median of one insert is the largest of the databases'. Numbers only. Empty for a pull without ch.workload.inserts."""
732
+ out: dict[str, dict] = {}
733
+ for w in ((workload or {}).get("connections") or {}).values():
734
+ for r in w.get("inserts") or []:
735
+ name = r.get("table")
736
+ if not isinstance(name, str) or not name or not all(_amount(r.get(k)) is not None for k in INSERT_FIELDS):
737
+ continue
738
+ seen = out.setdefault(name, {k: 0 for k in INSERT_FIELDS})
739
+ for k in INSERT_FIELDS:
740
+ seen[k] = max(seen[k], r[k]) if k == "median_written_rows" else seen[k] + r[k]
741
+ return out
742
+
743
+
744
+ TAG_TEXT = re.compile(r"[A-Za-z0-9_.:/-]{1,80}")
745
+
746
+
747
+ def upload_summary(out_dir: Path, include_unmatched_text: bool = False, observed_text: bool = True, text_max_chars: int = 20_000) -> dict | None:
748
+ """What of the real-database files a push may carry: counts and sizes, the call-site tags, and (unless `observed_text` is
749
+ off, `[push] observed_text`) the normalized text of each pulled statement. Never a definition, a host, an account or a
750
+ database name: the server already replaced every literal with `?`, and database prefixes are removed here.
751
+
752
+ `include_unmatched_text` adds the normalized text of real queries that match no call site under its older name
753
+ (`unmatched_queries`), for consoles that read it."""
754
+ catalog, matchdata = _read(out_dir, CATALOG_FILE), _read(out_dir, MATCH_FILE)
755
+ if not catalog and not matchdata:
756
+ return None
757
+ out: dict = {"schema_version": 1, "connections": [], "tables": [], "workload": {}}
758
+ sampled = {name for name, c in ((_read(out_dir, SAMPLE_FILE) or {}).get("connections") or {}).items() if c.get("tables")}
759
+ from ..observed import _databases, strip_databases
760
+ databases = _databases(catalog or {})
761
+ workload = _read(out_dir, WORKLOAD_FILE)
762
+ inserts = inserts_by_table(workload)
763
+ known_tables = {t["name"] for conn in ((catalog or {}).get("connections") or {}).values() for t in conn.get("tables") or [] if t.get("name")}
764
+ for name, conn in ((catalog or {}).get("connections") or {}).items():
765
+ cap = conn.get("capabilities") or {}
766
+ version = conn.get("version", "")
767
+ out["connections"].append({"engine": conn.get("engine", "") if conn.get("engine") in ("clickhouse", "postgres") else "",
768
+ # the leading number only: a server's version string can name a build host or a distribution
769
+ "version": (re.match(r"\d+(?:\.\d+){0,4}", version) or [""])[0] if isinstance(version, str) else "",
770
+ "read_only_enforced": bool(cap.get("read_only_enforced")), "catalog": bool(cap.get("catalog")),
771
+ "workload": bool(cap.get("workload")),
772
+ **capability_fields(conn, (catalog or {}).get("generated_at"), name in sampled)})
773
+ for t in conn.get("tables") or []:
774
+ out["tables"].append({"name": t["name"], "engine": conn.get("engine", ""), "table_engine": t.get("engine", ""),
775
+ "rows": int(t.get("rows") or 0), "bytes_on_disk": int(t.get("bytes_on_disk") or 0),
776
+ "parts": int(t.get("parts") or 0), "partitions": int(t.get("partitions") or 0),
777
+ "columns": len(t.get("columns") or []),
778
+ # what INSERT statements wrote to it in the pulled window (ch.workload.inserts): numbers only
779
+ **({"inserts": inserts[t["name"]]} if t["name"] in inserts else {})})
780
+ texts: dict[str, str] = {}
781
+ if include_unmatched_text or observed_text:
782
+ for w in ((workload or {}).get("connections") or {}).values():
783
+ texts.update({q["hash"]: strip_databases(q.get("text", ""), databases) for q in w.get("queries") or []})
784
+ for engine, m in ((matchdata or {}).get("engines") or {}).items():
785
+ unmatched = [q for q in m.get("queries") or [] if q["match"] == "none"]
786
+ entry = {
787
+ "window_hours": m.get("window_hours"), "since": m.get("since", ""), "workload": m.get("workload"), "rates": m.get("rates"),
788
+ "sites_matched": m.get("sites_matched"),
789
+ # a site's CPU, memory, time and spill under the names findings[].measured uses (resources_measured), rebuilt, never passed
790
+ "sites": {sid: {**{k: v for k, v in row.items() if k != "hashes" and k not in SPREAD_KEYS and k != "resources"},
791
+ **spread_upload(row, databases, known_tables),
792
+ **resources_measured(row, m)}
793
+ for sid, row in (m.get("sites") or {}).items()},
794
+ **resources_context_upload(m),
795
+ "unmatched": {"shapes": len(unmatched), "executions": sum(q["executions"] for q in unmatched),
796
+ "read_bytes": sum(q["read_bytes"] for q in unmatched)},
797
+ }
798
+ if include_unmatched_text:
799
+ entry["unmatched_queries"] = [{"hash": q["hash"], "executions": q["executions"], "read_bytes": q["read_bytes"],
800
+ "avg_ms": q["avg_ms"], "tables": q["tables"], "normalized_text": texts.get(q["hash"], "")[:4000]}
801
+ for q in sorted(unmatched, key=lambda q: -q["read_bytes"])[:200]]
802
+ # the tag -> call site link: only tags the pattern allows, with the call sites they placed the statement at
803
+ tagged = [q for q in m.get("queries") or [] if q.get("tags")]
804
+ if tagged:
805
+ entry["tags"] = [{"hash": q["hash"], "tags": [t for t in q["tags"] if isinstance(t, str) and TAG_TEXT.fullmatch(t)][:10],
806
+ "match": q["match"], "site_ids": list(q.get("site_ids") or [])[:20] if q["match"] == "tag" else [],
807
+ "executions": int(q["executions"]), "read_bytes": int(q["read_bytes"])} for q in tagged]
808
+ if observed_text:
809
+ # [push] observed_text (default on): every pulled statement as the server normalized it, so the console can show it
810
+ entry["observed_queries"] = [{"hash": q["hash"], "match": q["match"], "executions": q["executions"], "read_bytes": q["read_bytes"],
811
+ "avg_ms": q.get("avg_ms"), "tables": q.get("tables") or [],
812
+ "normalized_text": texts.get(q["hash"], "")[:max(int(text_max_chars), 0)]}
813
+ for q in sorted(m.get("queries") or [], key=lambda q: -q["read_bytes"]) if texts.get(q["hash"])]
814
+ out["workload"][engine] = entry
815
+ return out