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,1223 @@
1
+ """A real ClickHouse, read-only, over its HTTP interface with the standard library.
2
+
3
+ Every request carries `readonly=1` and the statement's limits as URL settings, so the server
4
+ refuses anything that is not a read and stops a read that costs too much. With `readonly=1` a
5
+ statement cannot lift those settings itself. Credentials go in headers, never in the URL.
6
+
7
+ The statements below are the whole list of what this module can send for tiers A and B. Their
8
+ text is constant. Tier C does not exist for ClickHouse: a normalized query text is not runnable
9
+ (literals are `?`), and EXPLAIN evaluates scalar subqueries, so nothing derived from the workload
10
+ is sent.
11
+ Tier D (sample.py) builds its statements from catalog identifiers and needs an explicit flag.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import base64
17
+ import http.client
18
+ import json
19
+ import re
20
+ import ssl
21
+ import time
22
+ from datetime import datetime, timezone
23
+ import urllib.error
24
+ import urllib.parse
25
+ import urllib.request
26
+
27
+ from . import (CATALOG_LIMITS, COLUMN_LIMITS, FAILURE_LIMITS, INSERT_LIMITS, MINUTE_LIMITS, PARTITION_LIMITS, PULL_DEFAULTS, REPEAT_LIMITS,
28
+ RESOURCE_LIMITS, SELECTED_LIMITS, SPREAD_LIMITS, TAG_LIMITS, TEXT_LIMITS, WORKLOAD_LIMITS, Audit, Connection, DbError, Limits, Refused, Statement, check_statement,
29
+ with_limits, TLS_MODES, TLS_VERIFY_HINT, tls_attempts)
30
+
31
+ SYSTEM_DATABASES = ("system", "INFORMATION_SCHEMA", "information_schema")
32
+ # Engines whose CREATE statement holds only schema. Anything else (dictionaries, Kafka, S3, MySQL, URL...) can
33
+ # carry an address or a secret in its definition, so its definition is not fetched at all.
34
+ SCHEMA_ONLY_ENGINES = ("View", "MaterializedView", "Distributed", "Null", "Memory", "Log", "TinyLog", "StripeLog", "Buffer",
35
+ "Merge", "Set", "Join")
36
+ _ENGINES = ", ".join(f"'{e}'" for e in SCHEMA_ONLY_ENGINES)
37
+ _SCOPE = "database IN ({dbs:Array(String)})"
38
+ _LOG_LOCAL = "system.query_log"
39
+ _LOG_CLUSTER = "clusterAllReplicas('default', system.query_log)"
40
+ _WINDOW = ("event_date >= toDate(now() - toIntervalHour({from_hours:UInt32})) AND event_time >= now() - toIntervalHour({from_hours:UInt32}) "
41
+ "AND event_time < now() - toIntervalHour({to_hours:UInt32}) AND type = 'QueryFinish' AND is_initial_query")
42
+ # the same window over the runs that failed while running (ch.workload.failures): its rows are not in _WINDOW
43
+ _FAILED_WINDOW = _WINDOW.replace("type = 'QueryFinish'", "type = 'ExceptionWhileProcessing'")
44
+
45
+
46
+ def _workload(suffix: str, source: str) -> list[Statement]:
47
+ return [
48
+ Statement(f"ch.workload.volume{suffix}", "B",
49
+ f"SELECT count() AS queries, min(event_time) AS first_seen, max(event_time) AS last_seen FROM {source} WHERE {_WINDOW}",
50
+ "How many finished queries the log holds for the window, to size the window before aggregating.", WORKLOAD_LIMITS),
51
+ Statement(f"ch.workload.kinds{suffix}", "B",
52
+ "SELECT query_kind AS kind, count() AS executions, uniq(normalized_query_hash) AS shapes, sum(read_rows) AS sum_read_rows, "
53
+ "sum(read_bytes) AS sum_read_bytes, sum(query_duration_ms) AS total_ms, sum(written_rows) AS sum_written_rows "
54
+ f"FROM {source} WHERE {_WINDOW} GROUP BY kind ORDER BY sum_read_bytes DESC LIMIT 50",
55
+ "Totals per kind of statement, so each query's share of the load can be stated.", WORKLOAD_LIMITS),
56
+ Statement(f"ch.workload.top{suffix}", "B",
57
+ "SELECT * FROM (SELECT *, row_number() OVER (ORDER BY sum_read_bytes DESC) AS by_bytes, "
58
+ "row_number() OVER (ORDER BY executions DESC) AS by_executions, row_number() OVER (ORDER BY total_ms DESC) AS by_time FROM ("
59
+ "SELECT toString(normalized_query_hash) AS hash, count() AS executions, sum(query_duration_ms) AS total_ms, "
60
+ "round(avg(query_duration_ms), 1) AS avg_ms, round(quantile(0.95)(query_duration_ms), 1) AS p95_ms, "
61
+ "sum(read_rows) AS sum_read_rows, sum(read_bytes) AS sum_read_bytes, max(read_bytes) AS max_read_bytes, "
62
+ "sum(result_rows) AS sum_result_rows, sum(result_bytes) AS sum_result_bytes, max(memory_usage) AS max_memory, "
63
+ "round(avg(memory_usage)) AS avg_memory, "
64
+ "uniq(user) AS users, groupUniqArrayArray(12)(tables) AS tables, toString(min(event_time)) AS first_seen, "
65
+ "toString(max(event_time)) AS last_seen "
66
+ f"FROM {source} WHERE {_WINDOW} AND query_kind = 'Select' GROUP BY normalized_query_hash)) "
67
+ "WHERE by_bytes <= {top:UInt32} OR by_executions <= {top:UInt32} OR by_time <= {top:UInt32} ORDER BY by_bytes",
68
+ "The heaviest and the most frequent SELECT shapes, aggregated on the server by normalized query hash. No query text.",
69
+ WORKLOAD_LIMITS),
70
+ Statement(f"ch.workload.texts{suffix}", "B",
71
+ "SELECT toString(normalized_query_hash) AS hash, any(substring(normalizeQuery(query), 1, {text_chars:UInt32})) AS text, "
72
+ f"any(length(query)) AS length FROM {source} WHERE {_WINDOW} "
73
+ "AND normalized_query_hash IN ({hashes:Array(UInt64)}) GROUP BY normalized_query_hash",
74
+ "One normalized text per shape: the server replaces every literal with `?` before the text leaves it. Cut at "
75
+ "db_pull.text_max_chars characters.", TEXT_LIMITS),
76
+ # The application's own labels of a statement, read from log_comment (set by the driver per query, or SETTINGS
77
+ # log_comment = '...' in the text). Only a call-site tag (`codecop:<file>:<line>` or `codecop:<function>`) is returned by
78
+ # the first; the second returns the labels as written and stays on the machine. See docs/query-tags.md.
79
+ Statement(f"ch.workload.tags{suffix}", "B",
80
+ "SELECT toString(normalized_query_hash) AS hash, extract(log_comment, '(?:codecop|qopt):([A-Za-z0-9_.:/-]{1,80})') AS tag, "
81
+ f"count() AS executions, sum(read_bytes) AS sum_read_bytes FROM {source} WHERE {_WINDOW} AND query_kind = 'Select' "
82
+ "AND normalized_query_hash IN ({hashes:Array(UInt64)}) AND log_comment != '' GROUP BY hash, tag HAVING tag != '' LIMIT 50000",
83
+ "Call-site tags per shape: only the text that matches codecop:<tag> (or qopt:<tag>, from before the rename; letters, digits and _.:/- up to 80 characters) "
84
+ "leaves the server, never the rest of the label.", TAG_LIMITS, optional=True),
85
+ Statement(f"ch.workload.comments{suffix}", "B",
86
+ "SELECT toString(normalized_query_hash) AS hash, topK(3)(substring(log_comment, 1, 120)) AS comments, count() AS executions "
87
+ f"FROM {source} WHERE {_WINDOW} AND query_kind = 'Select' AND normalized_query_hash IN ({{hashes:Array(UInt64)}}) "
88
+ "AND log_comment != '' GROUP BY hash LIMIT 50000",
89
+ "The application's own labels per shape, as written (the three most frequent, 120 characters each). They can hold "
90
+ "a value, so they stay on this machine: never uploaded.", TAG_LIMITS, optional=True),
91
+ Statement(f"ch.workload.clients{suffix}", "B",
92
+ "SELECT toString(normalized_query_hash) AS hash, topK(3)(client_name) AS clients, topK(3)(http_user_agent) AS agents, "
93
+ f"topK(2)(toString(interface)) AS interfaces FROM {source} WHERE {_WINDOW} AND query_kind = 'Select' "
94
+ "AND normalized_query_hash IN ({hashes:Array(UInt64)}) GROUP BY hash LIMIT 50000",
95
+ "Driver and tool names per shape (clickhouse-go, clickhouse-connect, the command-line client), to tell services "
96
+ "from people. No account or address column is read. Stays on this machine.", TAG_LIMITS, optional=True),
97
+ *(Statement(f"ch.workload.spread{form}{suffix}", "B",
98
+ "SELECT toString(normalized_query_hash) AS hash, "
99
+ f"{fn}(0.5, 0.9, 0.99)(read_rows) AS read_rows_q, {fn}(0.5, 0.9, 0.99)(read_bytes) AS read_bytes_q, "
100
+ f"{fn}(0.5, 0.9, 0.99)(result_rows) AS result_rows_q, countIf(result_rows = 0) AS no_result_runs, "
101
+ "countIf(read_rows = 0) AS no_read_runs, sumIf(read_bytes, result_rows = 0) AS no_result_read_bytes, "
102
+ "sumIf(read_rows, result_rows = 0) AS no_result_read_rows, countIf(result_rows > 0) AS result_runs, "
103
+ "sumIf(read_bytes, result_rows > 0) AS result_read_bytes, sumIf(read_rows, result_rows > 0) AS result_read_rows "
104
+ f"FROM {source} WHERE {_WINDOW} AND query_kind = 'Select' "
105
+ "AND normalized_query_hash IN ({hashes:Array(UInt64)}) GROUP BY normalized_query_hash",
106
+ f"The spread per shape: median, 90th and 99th percentile of rows read, bytes read and rows returned per run, how "
107
+ f"many runs read or returned nothing, and the rows and bytes read by the runs that returned nothing and by the "
108
+ f"others. {why} Integers only.", SPREAD_LIMITS, optional=True)
109
+ for form, fn, why in (("", "quantilesExact", "Exact: holds every run's three values in memory, so it is used up to a number of runs."),
110
+ ("_tdigest", "quantilesTDigest", "Approximate (t-digest): memory does not grow with the runs; used above that number."))),
111
+ *(Statement(f"ch.workload.selected{form}{suffix}", "B",
112
+ "SELECT toString(normalized_query_hash) AS hash, count() AS runs, "
113
+ f"avg({ev('SelectedParts')}) AS selected_parts, avg({ev('SelectedMarks')}) AS selected_marks, "
114
+ f"avg({ev('SelectedPartsTotal')}) AS selected_parts_total, avg({ev('SelectedMarksTotal')}) AS selected_marks_total, "
115
+ f"avg({ev('SelectedRanges')}) AS selected_ranges, max({has('SelectedPartsTotal')}) AS counts_parts_total, "
116
+ f"max({has('SelectedMarksTotal')}) AS counts_marks_total "
117
+ f"FROM {source} WHERE {_WINDOW} AND query_kind = 'Select' "
118
+ "AND normalized_query_hash IN ({hashes:Array(UInt64)}) GROUP BY normalized_query_hash",
119
+ f"Parts, marks and ranges a run selects, and the parts and marks it chose them from, averaged per shape{note}: a "
120
+ "filtered shape that still selects nearly all of them does not use the table's key. Reads the ProfileEvents column, "
121
+ "so its window is cut to a number of log rows first.", SELECTED_LIMITS, optional=True)
122
+ for form, ev, has, note in (
123
+ ("", lambda e: f"ProfileEvents['{e}']", lambda e: f"mapContains(ProfileEvents, '{e}')", ""),
124
+ ("_arrays", lambda e: f"ProfileEvents.Values[indexOf(ProfileEvents.Names, '{e}')]", lambda e: f"has(ProfileEvents.Names, '{e}')",
125
+ " (servers that keep ProfileEvents as two arrays, not a Map)"))),
126
+ Statement(f"ch.workload.columns{suffix}", "B",
127
+ "SELECT toString(normalized_query_hash) AS hash, groupUniqArrayArray({columns_per_shape:UInt32})(columns) AS columns_read, "
128
+ "groupUniqArrayArray({columns_per_shape:UInt32})(projections) AS projections_used, countIf(notEmpty(projections)) AS projection_runs, "
129
+ f"count() AS runs FROM {source} WHERE {_WINDOW} AND query_kind = 'Select' "
130
+ "AND normalized_query_hash IN ({hashes:Array(UInt64)}) GROUP BY normalized_query_hash",
131
+ "The columns a shape reads and the projections it used (names only, at most db_pull.columns_per_shape of each), and how "
132
+ "many runs used a projection. Database prefixes are removed before anything is written.", COLUMN_LIMITS, optional=True),
133
+ Statement(f"ch.workload.repeats{suffix}", "B",
134
+ "SELECT toString(normalized_query_hash) AS hash, count() AS runs, uniq(cityHash64(query)) AS statements, "
135
+ f"uniq(toStartOfMinute(event_time)) AS minutes FROM {source} WHERE {_WINDOW} AND query_kind = 'Select' "
136
+ "AND normalized_query_hash IN ({hashes:Array(UInt64)}) GROUP BY normalized_query_hash",
137
+ "Runs per distinct full statement (values included) and the minutes a shape was active: the same statement sent again "
138
+ "and again is polling or a missing cache. Only the two counts leave the server, never a text or a hash of one. Reads "
139
+ "the query column, so its window is cut to a number of log rows first.", REPEAT_LIMITS, optional=True),
140
+ Statement(f"ch.workload.minutes{suffix}", "B",
141
+ "SELECT toString(normalized_query_hash) AS hash, toUInt32(toStartOfMinute(event_time)) AS minute, count() AS runs "
142
+ f"FROM {source} WHERE {_WINDOW} AND query_kind = 'Select' AND normalized_query_hash IN ({{hashes:Array(UInt64)}}) "
143
+ "GROUP BY normalized_query_hash, minute ORDER BY hash, minute LIMIT {max_rows:UInt32}",
144
+ "Runs per minute of the heaviest shapes, to see which statements fire together. Stays on this machine.",
145
+ MINUTE_LIMITS, optional=True),
146
+ # ---- the resource profile per shape: aggregates per normalized hash, numbers only ----
147
+ *(Statement(f"ch.workload.memory{form}{suffix}", "B",
148
+ "SELECT toString(normalized_query_hash) AS hash, count() AS runs, "
149
+ "quantilesTDigest(0.5, 0.95, 0.99)(memory_usage) AS memory_q, max(memory_usage) AS max_memory, "
150
+ "sum(toFloat64(memory_usage) * query_duration_ms) AS memory_byte_ms, "
151
+ "quantilesTDigest(0.5, 0.95)(query_duration_ms) AS duration_q, max(query_duration_ms) AS max_ms, "
152
+ f"{threads} "
153
+ f"FROM {source} WHERE {_WINDOW} AND query_kind = 'Select' "
154
+ "AND normalized_query_hash IN ({hashes:Array(UInt64)}) GROUP BY normalized_query_hash",
155
+ "Peak memory of one run per shape (median, 95th and 99th percentile, max: the memory tracker's figure), memory "
156
+ "held (peak x time, summed: an upper bound), time quantiles and max, and threads per run" + note
157
+ + ". No ProfileEvents. Numbers only.", SPREAD_LIMITS, optional=True)
158
+ for form, threads, note in (
159
+ ("_peak_threads", "avg(peak_threads_usage) AS avg_threads, max(peak_threads_usage) AS max_threads",
160
+ " (threads at once, peak_threads_usage)"),
161
+ ("", "avg(length(thread_ids)) AS avg_threads, max(length(thread_ids)) AS max_threads",
162
+ " (threads ever used, for servers without peak_threads_usage)"))),
163
+ *(Statement(f"ch.workload.resources{form}{suffix}", "B",
164
+ "SELECT toString(normalized_query_hash) AS hash, count() AS runs, "
165
+ f"sum({ev('UserTimeMicroseconds')}) AS user_us, sum({ev('SystemTimeMicroseconds')}) AS system_us, "
166
+ f"quantilesTDigest(0.5, 0.95)({ev('UserTimeMicroseconds')} + {ev('SystemTimeMicroseconds')}) AS cpu_us_q, "
167
+ f"max({ev('UserTimeMicroseconds')} + {ev('SystemTimeMicroseconds')}) AS max_cpu_us, "
168
+ f"sum({ev('OSCPUVirtualTimeMicroseconds')}) AS os_cpu_us, sum({ev('OSCPUWaitMicroseconds')}) AS cpu_wait_us, "
169
+ f"sum({ev('OSIOWaitMicroseconds')}) AS io_wait_us, sum({ev('RealTimeMicroseconds')}) AS thread_real_us, "
170
+ f"sum({ev('OSReadBytes')}) AS disk_read_bytes, sum({ev('NetworkSendBytes')}) AS network_send_bytes, "
171
+ f"countIf({ev('ExternalSortWritePart')} + {ev('ExternalAggregationWritePart')} > 0) AS spilled_runs, "
172
+ f"sum({ev('ExternalSortUncompressedBytes')} + {ev('ExternalAggregationUncompressedBytes')}) AS spilled_bytes, "
173
+ f"max({has('UserTimeMicroseconds')}) AS counts_cpu, max({has('OSCPUVirtualTimeMicroseconds')}) AS counts_os_cpu "
174
+ f"FROM {source} WHERE {_WINDOW} AND query_kind = 'Select' "
175
+ "AND normalized_query_hash IN ({hashes:Array(UInt64)}) GROUP BY normalized_query_hash",
176
+ f"CPU per shape{note}: user and system CPU time (getrusage, counted on every server) summed, its median and 95th "
177
+ "percentile per run and max; the OS counters (CPU, waiting for a core, waiting on disk; only where the kernel's "
178
+ "task statistics are on), disk and network bytes, and the runs that spilled a sort or an aggregation to disk. "
179
+ "Reads the ProfileEvents column, so its window is cut to a number of log rows first.", RESOURCE_LIMITS, optional=True)
180
+ for form, ev, has, note in (
181
+ ("", lambda e: f"ProfileEvents['{e}']", lambda e: f"mapContains(ProfileEvents, '{e}')", ""),
182
+ ("_arrays", lambda e: f"ProfileEvents.Values[indexOf(ProfileEvents.Names, '{e}')]", lambda e: f"has(ProfileEvents.Names, '{e}')",
183
+ " (servers that keep ProfileEvents as two arrays, not a Map)"))),
184
+ *(Statement(f"ch.workload.resource_totals{form}{suffix}", "B",
185
+ f"SELECT query_kind AS kind, count() AS runs, sum({ev('UserTimeMicroseconds')} + {ev('SystemTimeMicroseconds')}) AS cpu_us, "
186
+ "sum(toFloat64(memory_usage) * query_duration_ms) AS memory_byte_ms, max(memory_usage) AS max_memory "
187
+ f"FROM {source} WHERE {_WINDOW} GROUP BY kind ORDER BY cpu_us DESC LIMIT 50",
188
+ f"All query CPU and memory held per kind of statement over the same window as ch.workload.resources{note}, so a "
189
+ "shape's share of them can be stated.", RESOURCE_LIMITS, optional=True)
190
+ for form, ev, note in (("", lambda e: f"ProfileEvents['{e}']", ""),
191
+ ("_arrays", lambda e: f"ProfileEvents.Values[indexOf(ProfileEvents.Names, '{e}')]", " (ProfileEvents as two arrays)"))),
192
+ Statement(f"ch.workload.failures{suffix}", "B",
193
+ "SELECT toString(normalized_query_hash) AS hash, count() AS failed_runs, "
194
+ "countIf(exception_code = 241) AS memory_limit_runs, countIf(exception_code IN (159, 160)) AS timeout_runs, "
195
+ "max(memory_usage) AS max_memory_failed "
196
+ f"FROM {source} WHERE {_FAILED_WINDOW} AND query_kind = 'Select' "
197
+ "GROUP BY normalized_query_hash ORDER BY memory_limit_runs DESC, failed_runs DESC LIMIT {max_rows:UInt32}",
198
+ "SELECT runs that failed while running, per shape: how many, how many stopped at the memory limit (code 241), how "
199
+ "many at a time limit (159, 160), and their peak memory. Codes only: the exception text is never selected.",
200
+ FAILURE_LIMITS, optional=True),
201
+ Statement(f"ch.workload.pressure{suffix}", "B",
202
+ "SELECT count() AS minutes, quantilesTDigest(0.5, 0.95)(running) AS running_q, max(running) AS max_running, "
203
+ "quantilesTDigest(0.5, 0.95)(held) AS held_bytes_q, max(held) AS max_held_bytes "
204
+ "FROM (SELECT toStartOfMinute(event_time) AS minute, sum(query_duration_ms) / 60000 AS running, "
205
+ f"sum(toFloat64(memory_usage) * query_duration_ms) / 60000 AS held FROM {source} WHERE {_WINDOW} GROUP BY minute)",
206
+ "How much runs at once: queries running and memory held on average in each minute, as median, 95th percentile and "
207
+ "max over the window's minutes. One row, no per-shape detail.", WORKLOAD_LIMITS, optional=True),
208
+ Statement(f"ch.workload.inserts{suffix}", "B",
209
+ "SELECT arrayJoin(arrayFilter(t -> NOT startsWith(t, '_table_function.'), tables)) AS target, count() AS inserts, "
210
+ "sum(written_rows) AS sum_written_rows, sum(written_bytes) AS sum_written_bytes, "
211
+ "quantile(0.5)(written_rows) AS median_written_rows, sum(query_duration_ms) AS total_ms "
212
+ f"FROM {source} WHERE {_WINDOW} AND query_kind = 'Insert' GROUP BY target ORDER BY sum_written_bytes DESC "
213
+ "LIMIT {max_rows:UInt32}",
214
+ "Inserts per table they name: how many, rows and bytes written, the median rows of one insert and the time spent, to "
215
+ "say what a projection or a materialized view would add to each. An insert's rows are its total (its target and the "
216
+ "views it feeds) and count for every table it names.", INSERT_LIMITS, optional=True),
217
+ ]
218
+
219
+
220
+ STATEMENTS: dict[str, Statement] = {s.id: s for s in [
221
+ Statement("ch.check.server", "check", "SELECT version() AS version, timezone() AS timezone, uptime() AS uptime_s",
222
+ "Server version."),
223
+ Statement("ch.check.settings", "check",
224
+ "SELECT name, value FROM system.settings WHERE name IN ('readonly', 'max_execution_time', 'max_rows_to_read', "
225
+ "'max_bytes_to_read', 'max_result_rows', 'max_memory_usage', 'max_threads', 'priority')",
226
+ "Reads back the limits the server applied to this request, to prove read-only is enforced by the server."),
227
+ Statement("ch.check.grants", "check",
228
+ "SELECT access_type, count() AS grants, countIf(database IS NULL) AS on_all_databases FROM system.grants "
229
+ "WHERE user_name = currentUser() OR role_name IN (SELECT role_name FROM system.current_roles) "
230
+ "GROUP BY access_type ORDER BY access_type LIMIT 300",
231
+ "Which kinds of access the account holds (to report whether it could write without this tool's read-only).", optional=True),
232
+ Statement("ch.check.replicas", "check", "SELECT count() AS replicas, uniqExact(hostName()) AS hosts FROM clusterAllReplicas('default', system.one)",
233
+ "Whether the query log must be read from every replica.", optional=True),
234
+ Statement("ch.check.query_log", "check",
235
+ "SELECT count() AS rows FROM system.query_log WHERE event_date = today() AND event_time >= now() - toIntervalMinute(10)",
236
+ "Whether the query log is visible to the account.", optional=True),
237
+ Statement("ch.check.visible", "check",
238
+ "SELECT name FROM system.tables WHERE database = 'system' AND name IN ('tables', 'columns', 'parts', 'query_log', "
239
+ "'data_skipping_indices', 'projections', 'dictionaries', 'grants', 'processes', 'mutations', 'replicas')",
240
+ "Which system tables exist for the account."),
241
+ Statement("ch.check.capacity", "check",
242
+ "SELECT metric AS name, toString(value) AS value FROM system.asynchronous_metrics "
243
+ "WHERE metric IN ('OSMemoryTotal', 'CGroupMemoryTotal', 'CGroupMaxCPU') "
244
+ "UNION ALL SELECT 'OSCPUCount' AS name, toString(count()) AS value FROM system.asynchronous_metrics WHERE metric LIKE 'OSIdleTimeCPU%' "
245
+ "UNION ALL SELECT name, value FROM system.server_settings WHERE name IN ('max_server_memory_usage', 'max_server_memory_usage_to_ram_ratio', 'max_concurrent_queries')",
246
+ "The server's memory, its memory limit, its processors and how many queries it runs at once, so a shape's peak can be "
247
+ "read against the limit and its CPU against the cores. Names only, numbers back.", optional=True),
248
+ Statement("ch.catalog.databases", "A",
249
+ "SELECT database, count() AS tables, sum(total_rows) AS rows, sum(total_bytes) AS bytes FROM system.tables "
250
+ f"WHERE database NOT IN ({', '.join(repr(d) for d in SYSTEM_DATABASES)}) GROUP BY database ORDER BY bytes DESC LIMIT 2000",
251
+ "Databases with their size, to choose which ones to describe."),
252
+ Statement("ch.catalog.tables", "A",
253
+ "SELECT database, name, engine, "
254
+ f"if(engine LIKE '%MergeTree' OR engine IN ({_ENGINES}), create_table_query, '') AS create_table_query, "
255
+ "sorting_key, partition_key, primary_key, sampling_key, total_rows, total_bytes, "
256
+ "arrayMap((d, t) -> concat(d, '.', t), dependencies_database, dependencies_table) AS feeds "
257
+ f"FROM system.tables WHERE {_SCOPE} ORDER BY database, name LIMIT 20000",
258
+ "Table definitions, keys and sizes. Definitions are fetched only for engines whose definition is schema."),
259
+ Statement("ch.catalog.columns", "A",
260
+ "SELECT database, table, name, type, default_kind, is_in_partition_key, is_in_sorting_key, is_in_primary_key, "
261
+ "is_in_sampling_key, data_compressed_bytes, data_uncompressed_bytes, compression_codec, position "
262
+ f"FROM system.columns WHERE {_SCOPE} ORDER BY database, table, position LIMIT 400000",
263
+ "Columns with their types and bytes on disk."),
264
+ Statement("ch.catalog.parts", "A",
265
+ "SELECT database, table, sum(rows) AS rows, sum(bytes_on_disk) AS bytes_on_disk, "
266
+ "sum(data_uncompressed_bytes) AS uncompressed_bytes, count() AS parts, uniqExact(partition) AS partitions, "
267
+ "min(partition) AS min_partition, max(partition) AS max_partition, toString(max(modification_time)) AS last_modified "
268
+ f"FROM system.parts WHERE active AND {_SCOPE} GROUP BY database, table LIMIT 20000",
269
+ "Rows, bytes, parts and partitions per table."),
270
+ Statement("ch.catalog.partition_parts", "A",
271
+ "SELECT database, table, partition_id, count() AS parts, sum(rows) AS rows, sum(marks) AS marks, "
272
+ "toUInt32(min(modification_time)) AS first_modified, toUInt32(max(modification_time)) AS last_modified "
273
+ f"FROM system.parts WHERE active AND {_SCOPE} GROUP BY database, table, partition_id "
274
+ "ORDER BY database, table, partition_id DESC LIMIT {partitions:UInt32} BY database, table LIMIT {max_rows:UInt32}",
275
+ "Parts, rows and marks per partition, so the sandbox can reproduce the real part layout (many small parts in the newest "
276
+ "partitions) and not the table's average, and when its parts last changed (a partition nothing writes to is closed). "
277
+ "The highest partition ids of each table first.", PARTITION_LIMITS, optional=True),
278
+ Statement("ch.catalog.partition_columns", "A",
279
+ "SELECT database, table, partition_id, column, sum(rows) AS rows, sum(column_data_uncompressed_bytes) AS uncompressed_bytes, "
280
+ "sum(column_data_compressed_bytes) AS compressed_bytes "
281
+ f"FROM system.parts_columns WHERE active AND column_data_uncompressed_bytes > 0 AND {_SCOPE} "
282
+ "GROUP BY database, table, partition_id, column ORDER BY database, table, column, partition_id DESC "
283
+ "LIMIT {partitions:UInt32} BY database, table, column LIMIT {max_rows:UInt32}",
284
+ "Column sizes per partition, to see whether recent rows are heavier than the table's average. Only parts that report a "
285
+ "column's size are summed (a compact part reports zero for every column: that is not a width of zero), so `rows` is the "
286
+ "rows those sizes are for.", PARTITION_LIMITS, optional=True),
287
+ Statement("ch.catalog.skip_indices", "A",
288
+ "SELECT database, table, name, type_full AS type, expr, granularity, data_compressed_bytes "
289
+ f"FROM system.data_skipping_indices WHERE {_SCOPE} LIMIT 20000",
290
+ "Data skipping indexes.", optional=True),
291
+ Statement("ch.catalog.projections", "A",
292
+ f"SELECT database, table, name, type, sorting_key, query FROM system.projections WHERE {_SCOPE} LIMIT 20000",
293
+ "Projections.", optional=True),
294
+ Statement("ch.catalog.dictionaries", "A",
295
+ "SELECT database, name, type, key.names AS key_names, attribute.names AS attribute_names, attribute.types AS attribute_types, "
296
+ f"element_count, bytes_allocated FROM system.dictionaries WHERE {_SCOPE} LIMIT 5000",
297
+ "Dictionaries: shape and size only, never their source.", optional=True),
298
+ *_workload("", _LOG_LOCAL),
299
+ *_workload(".all_replicas", _LOG_CLUSTER),
300
+ ]}
301
+
302
+ TAG = re.compile(r"[A-Za-z0-9_.:/-]{1,80}") # what ch.workload.tags extracts after `codecop:` (docs/query-tags.md)
303
+ # the probes of CodeCop's own locality statements (realdb/locality.py), as the server's normalized text keeps them
304
+ OWN_STATEMENT = re.compile(r"cityHash64\(_part,\s*_part_offset,")
305
+ EMPTY_KEYS = ("no_result_read_bytes", "no_result_read_rows", "result_runs", "result_read_bytes", "result_read_rows")
306
+ OPTIONAL_SETTINGS = ("priority", "max_threads", "max_memory_usage", "max_result_rows", "max_bytes_to_read", "max_rows_to_read")
307
+ SETTING_IN_ERROR = re.compile(r"[Ss]etting[s]? '?(\w+)'?|'(\w+)' setting|modify '(\w+)'")
308
+ SECRET_IN_DDL = re.compile(r"(PASSWORD|SECRET|KEY|TOKEN)\s+'[^']*'", re.I)
309
+
310
+
311
+ def _settings(limits: Limits) -> dict[str, int | str]:
312
+ return {"max_execution_time": limits.seconds, "max_rows_to_read": limits.rows_to_read, "max_bytes_to_read": limits.bytes_to_read,
313
+ "max_result_rows": limits.result_rows, "max_memory_usage": limits.memory_bytes, "max_threads": limits.threads, "priority": 10}
314
+
315
+
316
+ LIMIT_HIT = re.compile(r"TOO_MANY_ROWS|TOO_MANY_BYTES|TIMEOUT_EXCEEDED|MEMORY_LIMIT_EXCEEDED|TOO_MANY_ROWS_OR_BYTES|Limit for|memory limit"
317
+ r"|TOO_BIG_AST|TOO_DEEP_AST|Max query size exceeded|max_query_size", re.I)
318
+ REFUSAL_CODE = re.compile(r"\(([A-Z][A-Z_]{3,})\)")
319
+ # which limit a refusal names, first match wins: (pattern, the setting, the Limits field it comes from or None). A server's
320
+ # own memory limit (total, for the user) is not one this request sets.
321
+ LIMIT_NAMES = (
322
+ (re.compile(r"memory limit \(total\)|\(total\) memory limit|memory limit \(for user\)", re.I), "the server's own memory limit", None),
323
+ (re.compile(r"MEMORY_LIMIT_EXCEEDED|memory limit", re.I), "max_memory_usage", "memory_bytes"),
324
+ (re.compile(r"TIMEOUT_EXCEEDED|Timeout exceeded|estimated query execution time", re.I), "max_execution_time", "seconds"),
325
+ (re.compile(r"TOO_MANY_ROWS_OR_BYTES|Limit for result", re.I), "max_result_rows", "result_rows"),
326
+ (re.compile(r"TOO_MANY_BYTES|bytes to read", re.I), "max_bytes_to_read", "bytes_to_read"),
327
+ (re.compile(r"TOO_MANY_ROWS|rows to read|Limit for rows", re.I), "max_rows_to_read", "rows_to_read"),
328
+ (re.compile(r"TOO_BIG_AST|TOO_DEEP_AST", re.I), "max_ast_elements / max_ast_depth", None),
329
+ (re.compile(r"max query size|max_query_size", re.I), "max_query_size", None),
330
+ )
331
+
332
+
333
+ def limit_hit(error: str) -> tuple[str, str | None] | None:
334
+ """(the setting that stopped a statement, the Limits field holding the value sent) or None when no limit did."""
335
+ if not LIMIT_HIT.search(error):
336
+ return None
337
+ for pattern, name, field in LIMIT_NAMES:
338
+ if pattern.search(error):
339
+ return name, field
340
+ return "a limit", None
341
+
342
+
343
+ def refusal_reason(error: str, limits=None) -> str:
344
+ """A refusal as a note may carry it: the limit that stopped it (with the value sent, given `limits`) or the server's
345
+ error code, and nothing else. The message around it can name a table, a column or an account, and a note is printed."""
346
+ hit = limit_hit(error)
347
+ if hit:
348
+ name, field = hit
349
+ if name == "a limit":
350
+ return "a limit stopped it"
351
+ value = getattr(limits, field, None) if limits is not None and field else None
352
+ return f"a limit stopped it: {name}" + (f" ({value:,})" if isinstance(value, int) else "")
353
+ codes = REFUSAL_CODE.findall(error)
354
+ return f"the server refused it ({codes[-1]})" if codes else "the server refused it"
355
+
356
+
357
+ def _quantiles(values) -> list[int] | None:
358
+ """Three whole numbers (median, 90th, 99th percentile), or None when the server returned anything else."""
359
+ try:
360
+ out = [int(round(float(v))) for v in values or []]
361
+ except (TypeError, ValueError, OverflowError):
362
+ return None
363
+ return out if len(out) == 3 and all(v >= 0 for v in out) else None
364
+
365
+
366
+ def _floats(values, n: int) -> list[float] | None:
367
+ """`n` finite numbers of zero or more (a quantiles array), or None when the server returned anything else."""
368
+ try:
369
+ out = [float(v) for v in values or []]
370
+ except (TypeError, ValueError):
371
+ return None
372
+ return out if len(out) == n and all(v >= 0 and v == v and v != float("inf") for v in out) else None
373
+
374
+
375
+ def capacity_of(rows: list[dict]) -> dict:
376
+ """ch.check.capacity's name/value rows as {memory_total_bytes, memory_limit_bytes, cores, max_concurrent_queries};
377
+ a name the server does not have is not there (unknown metric names return no row by design). A server memory limit of
378
+ 0 is the default share of the memory (max_server_memory_usage_to_ram_ratio)."""
379
+ got: dict[str, float] = {}
380
+ for r in rows:
381
+ try:
382
+ got[str(r["name"])] = float(r["value"])
383
+ except (KeyError, TypeError, ValueError):
384
+ continue
385
+ total = got.get("CGroupMemoryTotal") or got.get("OSMemoryTotal") or 0
386
+ out: dict = {}
387
+ if total > 0:
388
+ out["memory_total_bytes"] = int(total)
389
+ limit = got.get("max_server_memory_usage") or 0
390
+ ratio = got.get("max_server_memory_usage_to_ram_ratio")
391
+ if limit > 0:
392
+ out["memory_limit_bytes"] = int(limit)
393
+ elif total > 0 and ratio:
394
+ out["memory_limit_bytes"] = int(total * ratio)
395
+ out["memory_limit_from"] = "ratio of memory"
396
+ # CGroupMaxCPU where the server has it (a container's CPU quota), else its processors: one OSIdleTimeCPU<n> metric each
397
+ # (NumberOfCPUCores and NumberOfPhysicalCores are no metric on 24.8, 25.8 or 26.6)
398
+ cores = got.get("CGroupMaxCPU") or got.get("OSCPUCount") or 0
399
+ if cores > 0:
400
+ out["cores"] = round(cores, 2)
401
+ if got.get("max_concurrent_queries"):
402
+ out["max_concurrent_queries"] = int(got["max_concurrent_queries"])
403
+ return out
404
+
405
+
406
+ def _newest_first_cap(counts: list[tuple[int, int]], wanted: int, budget: int) -> int:
407
+ """The most partitions per table (at most `wanted`) for which the rows returned stay within `budget`.
408
+ `counts`: per table (its partitions, rows returned per partition)."""
409
+ def rows(n: int) -> int:
410
+ return sum(min(p, n) * per for p, per in counts)
411
+
412
+ if wanted <= 0 or rows(wanted) <= budget:
413
+ return max(wanted, 0)
414
+ lo, hi = 1, wanted
415
+ while lo < hi: # the largest n whose rows fit; 1 when even that does not (the total LIMIT then cuts)
416
+ mid = (lo + hi + 1) // 2
417
+ if rows(mid) <= budget:
418
+ lo = mid
419
+ else:
420
+ hi = mid - 1
421
+ return lo
422
+
423
+
424
+ def recent_span(hours: float, log_rows: int, budget: int) -> int:
425
+ """The most recent whole hours (at least one) that hold about `budget` of the `log_rows` finished queries of `hours`."""
426
+ return int(max(hours, 1)) if log_rows <= budget else max(int(hours * budget / max(log_rows, 1)), 1)
427
+
428
+
429
+ def short_name(name: str, databases: set[str]) -> str:
430
+ """`database.table.column` (or `database.table.projection`) without the database: what may leave this machine.
431
+ A known database prefix is removed; otherwise a name of three or more parts loses its first."""
432
+ name = str(name)
433
+ head, _, rest = name.partition(".")
434
+ if rest and (head in databases or rest.count(".") >= 1):
435
+ return rest
436
+ return name
437
+
438
+
439
+ def compact_minutes(rows: list[tuple[int, int]]) -> dict:
440
+ """Runs per minute of one shape, as few numbers as possible: `start` (UTC, the first active minute) and either `runs`
441
+ for every minute from there to the last active one (zeros included, when the shape is active at least every other
442
+ minute), or `at` (minutes after `start`) with `runs` beside it."""
443
+ rows = sorted(rows)
444
+ first = rows[0][0] // 60
445
+ offsets = [m // 60 - first for m, _ in rows]
446
+ start = datetime.fromtimestamp(first * 60, tz=timezone.utc).strftime("%Y-%m-%dT%H:%MZ")
447
+ span = offsets[-1] + 1
448
+ if 2 * len(rows) >= span:
449
+ dense = [0] * span
450
+ for off, (_, n) in zip(offsets, rows):
451
+ dense[off] += n
452
+ return {"start": start, "runs": dense}
453
+ return {"start": start, "at": offsets, "runs": [n for _, n in rows]}
454
+
455
+
456
+ def render_param(value) -> str:
457
+ """A bound value for the HTTP interface (`param_<name>`). The server parses it as the declared type."""
458
+ if isinstance(value, (list, tuple)):
459
+ return "[" + ",".join("'" + str(v).replace("\\", "\\\\").replace("'", "\\'") + "'" if isinstance(v, str) else str(v) for v in value) + "]"
460
+ return str(value)
461
+
462
+
463
+ class ClickHouseReader:
464
+ engine = "clickhouse"
465
+
466
+ def __init__(self, connection: Connection, audit: Audit, *, timeout: int = 90, dry_run: bool = False, settings: dict | None = None):
467
+ self.connection, self.audit, self.timeout, self.dry_run = connection, audit, timeout, dry_run
468
+ self.settings = {**PULL_DEFAULTS, "limits": {}, **(settings or {})} # realdb.pull_settings: caps and per-statement limits
469
+ self.last_refusal = "" # why the last optional statement was refused (scrubbed), for a note
470
+ self.dropped: list[str] = [] # limits this server would not let the request set
471
+ self.profile_readonly = False # the account is read-only by its own profile: no setting can be sent
472
+ self.extra_settings: dict = {} # set by tier D only (read_overflow_mode)
473
+ # how the server's certificate is checked (realdb.tls_attempts): one context for every request, said on every audit line
474
+ attempts = tls_attempts(connection)
475
+ self.tls_context, self.tls_mode = attempts[0] if attempts else (None, TLS_MODES["plain"])
476
+ audit.tls = self.tls_mode
477
+
478
+ def __enter__(self) -> "ClickHouseReader":
479
+ return self
480
+
481
+ def __exit__(self, *exc) -> None:
482
+ pass
483
+
484
+ # ---- one request -----------------------------------------------------
485
+ def _send(self, sql: str, params: dict, settings: dict) -> tuple[str, dict]:
486
+ c = self.connection
487
+ query = {"readonly": 1, "wait_end_of_query": 1, "default_format": "JSONEachRow", **settings}
488
+ if self.profile_readonly:
489
+ query = {"wait_end_of_query": 1, "default_format": "JSONEachRow"}
490
+ if c.database:
491
+ query["database"] = c.database
492
+ for k, v in params.items():
493
+ query[f"param_{k}"] = render_param(v)
494
+ url = f"{'https' if c.secure else 'http'}://{c.host}:{c.port}/?{urllib.parse.urlencode(query)}"
495
+ headers = {"User-Agent": "codecop-db/1"}
496
+ if c.user:
497
+ headers["Authorization"] = "Basic " + base64.b64encode(f"{c.user}:{c.password.reveal()}".encode()).decode()
498
+ req = urllib.request.Request(url, data=sql.encode("utf-8"), method="POST", headers=headers)
499
+ try:
500
+ with urllib.request.urlopen(req, timeout=self.timeout, context=self.tls_context) as resp:
501
+ body = resp.read().decode("utf-8", "replace")
502
+ summary = json.loads(resp.headers.get("X-ClickHouse-Summary") or "{}")
503
+ return body, summary
504
+ except urllib.error.HTTPError as e:
505
+ raise Refused(c.scrub(e.read().decode("utf-8", "replace").strip()[:600])) from None
506
+ except (urllib.error.URLError, http.client.HTTPException, OSError) as e:
507
+ reason = getattr(e, "reason", e)
508
+ hint = TLS_VERIFY_HINT if isinstance(reason, ssl.SSLCertVerificationError) else ""
509
+ raise DbError(c.scrub(f"Could not reach the database: {type(reason).__name__ if not isinstance(reason, str) else reason}") + hint) from None
510
+
511
+ def run(self, statement_id: str, **params) -> list[dict]:
512
+ """Send one statement from the allowlist. Returns its rows. Raises Refused or DbError; both are in the audit file."""
513
+ stmt = with_limits(STATEMENTS[statement_id], self.settings.get("limits"))
514
+ return self.run_statement(stmt, params)
515
+
516
+ def run_statement(self, stmt: Statement, params: dict) -> list[dict]:
517
+ check_statement(stmt)
518
+ started = time.monotonic()
519
+ if self.dry_run:
520
+ self.audit.record(stmt, params, started=started, sent=False)
521
+ return []
522
+ settings = {k: v for k, v in {**_settings(stmt.limits), **self.extra_settings}.items() if k not in self.dropped}
523
+ while True:
524
+ try:
525
+ body, summary = self._send(stmt.sql, params, settings)
526
+ break
527
+ except Refused as e:
528
+ # A managed service may forbid changing one of the limits. Drop that one limit and try again;
529
+ # `readonly` is never dropped, and without a time limit nothing is sent.
530
+ named = next((g for m in SETTING_IN_ERROR.finditer(str(e)) for g in m.groups() if g), "")
531
+ if not self.profile_readonly and "Cannot modify" in str(e) and re.search(r"readonly mode|\(READONLY\)", str(e)):
532
+ # The account's own profile is read-only: the server refuses every setting a request tries to set,
533
+ # and names whichever it looks at first (max_execution_time, not necessarily readonly). It already
534
+ # enforces read-only and accepts no settings; that is confirmed from system.settings before going on.
535
+ self.profile_readonly = True
536
+ self.dropped = ["every limit (the account's profile is read-only and accepts no settings)"]
537
+ settings = {}
538
+ try: # believe the server's own setting, not the wording of an error
539
+ body, _ = self._send("SELECT value FROM system.settings WHERE name = 'readonly'", {}, {})
540
+ confirmed = str(json.loads(body.splitlines()[0]).get("value")) in ("1", "2")
541
+ except (DbError, ValueError, IndexError):
542
+ confirmed = False
543
+ if not confirmed:
544
+ self.profile_readonly = False
545
+ self.audit.record(stmt, params, started=started, error="read-only could not be confirmed")
546
+ raise DbError("The server did not confirm a read-only session; nothing was sent.") from None
547
+ continue
548
+ if named in OPTIONAL_SETTINGS and named in settings and re.search(r"READONLY|SETTING_CONSTRAINT|should not be changed|Cannot modify", str(e)):
549
+ settings.pop(named)
550
+ self.dropped.append(named)
551
+ continue
552
+ self.audit.record(stmt, params, started=started, error=str(e))
553
+ raise
554
+ except DbError as e:
555
+ self.audit.record(stmt, params, started=started, error=str(e))
556
+ raise
557
+ rows = [json.loads(line) for line in body.splitlines() if line.strip()]
558
+ self.audit.record(stmt, params, started=started, rows=len(rows), read_rows=int(summary.get("read_rows") or 0),
559
+ read_bytes=int(summary.get("read_bytes") or 0))
560
+ return rows
561
+
562
+ def try_run(self, statement_id: str, **params) -> list[dict] | None:
563
+ """For optional statements: None when the server refuses (a table the account cannot see, an older version)."""
564
+ try:
565
+ return self.run(statement_id, **params)
566
+ except Refused as e:
567
+ self.last_refusal = refusal_reason(str(e))
568
+ return None
569
+
570
+ # ---- check -----------------------------------------------------------
571
+ def check(self) -> dict:
572
+ """Connect, prove read-only is enforced by the server, and say what the account can see."""
573
+ server = self.run("ch.check.server")[0]
574
+ applied = {r["name"]: r["value"] for r in self.run("ch.check.settings")}
575
+ visible = {r["name"] for r in self.run("ch.check.visible")}
576
+ grants = self.try_run("ch.check.grants")
577
+ replicas = self.try_run("ch.check.replicas")
578
+ self.cluster_readable = replicas is not None
579
+ if replicas:
580
+ # count() alone can be answered by one replica; the distinct host names cannot
581
+ replicas = [{"replicas": max(int(replicas[0].get("replicas") or 0), int(replicas[0].get("hosts") or 0))}]
582
+ self.uptime_s = int(float(server.get("uptime_s") or 0)) or None
583
+ log = self.try_run("ch.check.query_log") if "query_log" in visible else None
584
+ writes = None
585
+ if grants is not None:
586
+ kinds = {g["access_type"] for g in grants}
587
+ first = ("ALL", "INSERT", "ALTER", "ALTER TABLE", "ALTER UPDATE", "ALTER DELETE", "CREATE", "CREATE DATABASE", "CREATE TABLE",
588
+ "DROP", "DROP DATABASE", "DROP TABLE", "TRUNCATE", "OPTIMIZE") # the ones that change data, before the long tail
589
+ writes = sorted((k for k in kinds if re.match(r"INSERT|ALTER|CREATE|DROP|TRUNCATE|OPTIMIZE|ALL$|SYSTEM|KILL|GRANT|ACCESS MANAGEMENT", k)),
590
+ key=lambda k: (first.index(k) if k in first else len(first), k))
591
+ return {
592
+ "engine": "clickhouse", "version": server["version"],
593
+ "read_only_enforced": applied.get("readonly") in ("1", "2"),
594
+ "read_only_how": f"readonly={applied.get('readonly')} on every request, applied by the server",
595
+ "limits_applied": {k: applied.get(k) for k in ("max_execution_time", "max_rows_to_read", "max_bytes_to_read",
596
+ "max_result_rows", "max_memory_usage", "max_threads", "priority")},
597
+ "limits_refused": list(self.dropped), "transport": [self.tls_mode], "tls": self.tls_mode,
598
+ "system_tables": sorted(visible),
599
+ "catalog": {"tables", "columns", "parts"} <= visible,
600
+ "workload": log is not None,
601
+ "workload_source": "query_log on every replica" if replicas and int(replicas[0]["replicas"]) > 1 and log is not None
602
+ else "query_log" if log is not None else "not visible",
603
+ "replicas": int(replicas[0]["replicas"]) if replicas else None,
604
+ "uptime_s": self.uptime_s,
605
+ "plans": "not offered: a normalized text is not runnable and EXPLAIN can evaluate subqueries",
606
+ "account_can_write": bool(writes) if writes is not None else None,
607
+ "write_access_kinds": writes[:12] if writes else [],
608
+ }
609
+
610
+ # ---- tier A ----------------------------------------------------------
611
+ def catalog(self, databases: list[str] | None = None, max_databases: int = 20) -> dict:
612
+ overview = self.run("ch.catalog.databases")
613
+ wanted = [d for d in (databases or []) if d]
614
+ if not wanted:
615
+ wanted = [self.connection.database] if self.connection.database else [d["database"] for d in overview[:max_databases]]
616
+ tables = self.run("ch.catalog.tables", dbs=wanted)
617
+ columns = self.run("ch.catalog.columns", dbs=wanted)
618
+ parts = {(p["database"], p["table"]): p for p in self.run("ch.catalog.parts", dbs=wanted)}
619
+ indices = self.try_run("ch.catalog.skip_indices", dbs=wanted) or []
620
+ projections = self.try_run("ch.catalog.projections", dbs=wanted) or []
621
+ dictionaries = self.try_run("ch.catalog.dictionaries", dbs=wanted) or []
622
+ by_table: dict[tuple, list[dict]] = {}
623
+ for col in columns:
624
+ by_table.setdefault((col["database"], col["table"]), []).append({
625
+ "name": col["name"], "type": col["type"], "default_kind": col.get("default_kind", ""),
626
+ "in_partition_key": bool(col.get("is_in_partition_key")), "in_sorting_key": bool(col.get("is_in_sorting_key")),
627
+ "in_primary_key": bool(col.get("is_in_primary_key")),
628
+ "compressed_bytes": int(col.get("data_compressed_bytes") or 0), "uncompressed_bytes": int(col.get("data_uncompressed_bytes") or 0),
629
+ "codec": col.get("compression_codec", "")})
630
+ out = []
631
+ for t in tables:
632
+ key = (t["database"], t["name"])
633
+ p = parts.get(key) or {}
634
+ out.append({
635
+ "database": t["database"], "name": t["name"], "engine": t["engine"],
636
+ "create_sql": SECRET_IN_DDL.sub(r"\1 '[HIDDEN]'", self.connection.mask_secret(t.get("create_table_query") or "")),
637
+ "sorting_key": t.get("sorting_key", ""), "partition_key": t.get("partition_key", ""), "primary_key": t.get("primary_key", ""),
638
+ "sampling_key": t.get("sampling_key", ""),
639
+ "rows": int(p.get("rows") or t.get("total_rows") or 0), "bytes_on_disk": int(p.get("bytes_on_disk") or t.get("total_bytes") or 0),
640
+ "uncompressed_bytes": int(p.get("uncompressed_bytes") or 0), "parts": int(p.get("parts") or 0),
641
+ "partitions": int(p.get("partitions") or 0), "min_partition": p.get("min_partition", ""), "max_partition": p.get("max_partition", ""),
642
+ "last_modified": p.get("last_modified", ""), "feeds": t.get("feeds") or [],
643
+ "columns": by_table.get(key, []),
644
+ "skip_indexes": [{k: i[k] for k in ("name", "type", "expr", "granularity")} for i in indices
645
+ if (i["database"], i["table"]) == key],
646
+ "projections": [{k: x.get(k, "") for k in ("name", "type", "sorting_key", "query")} for x in projections
647
+ if (x["database"], x["table"]) == key],
648
+ })
649
+ detail = self.partition_detail(wanted, out)
650
+ return {
651
+ "engine": "clickhouse", "databases_described": wanted, "partition_detail": detail, "notes": list(detail["notes"]),
652
+ "databases": [{"database": d["database"], "tables": int(d["tables"]), "rows": int(d["rows"] or 0), "bytes": int(d["bytes"] or 0)}
653
+ for d in overview],
654
+ "tables": out,
655
+ "dictionaries": [{"database": d["database"], "name": d["name"], "type": d["type"], "keys": d.get("key_names") or [],
656
+ "attributes": [{"name": n, "type": ty} for n, ty in zip(d.get("attribute_names") or [], d.get("attribute_types") or [])],
657
+ "elements": int(d.get("element_count") or 0), "bytes": int(d.get("bytes_allocated") or 0)} for d in dictionaries],
658
+ }
659
+
660
+ def partition_detail(self, wanted: list[str], tables: list[dict]) -> dict:
661
+ """Tier A, optional: parts per partition and column sizes per partition, added to each table's entry.
662
+
663
+ `partition_parts` {ids, parts, rows, marks} and `partition_columns` {columns, ids, cells}: parallel lists, the
664
+ highest partition id first. A cell is [rows, uncompressed bytes, compressed bytes] over the parts that report
665
+ the column's size, or null where none does (compact parts): not reported, never a width of zero.
666
+ How many partitions per table are asked for is worked out first from the partition counts the catalog already
667
+ holds, so that the rows returned stay within `partition_rows`; what that left out is counted and said."""
668
+ s = self.settings
669
+ info: dict = {"available": False, "notes": []}
670
+ if not s["partition_detail"]:
671
+ info["notes"].append("per-partition detail is switched off (db_pull.partition_detail)")
672
+ return info
673
+ by_key = {(t["database"], t["name"]): t for t in tables}
674
+ known = [t for t in tables if t.get("partitions")]
675
+
676
+ def ask(statement_id: str, setting: str, per_partition) -> tuple[list[dict] | None, dict]:
677
+ allowed = with_limits(STATEMENTS[statement_id], s["limits"]).limits.result_rows
678
+ max_rows = max(min(int(s["partition_rows"]), allowed), 1)
679
+ n = _newest_first_cap([(t["partitions"], per_partition(t)) for t in known], int(s[setting]), max_rows)
680
+ said = {"partitions_per_table": n, "asked": int(s[setting]), "max_rows": max_rows}
681
+ if n <= 0:
682
+ info["notes"].append(f"{statement_id} was not sent (db_pull.{setting} is 0)")
683
+ return None, said
684
+ rows = self.try_run(statement_id, dbs=wanted, partitions=n, max_rows=max_rows)
685
+ if rows is None:
686
+ info["notes"].append(f"{statement_id} is not available: {self.last_refusal}")
687
+ elif len(rows) >= max_rows:
688
+ info["notes"].append(f"{statement_id} stopped at {max_rows:,} rows (db_pull.partition_rows): tables late in the "
689
+ "alphabet have no per-partition detail")
690
+ return rows, said
691
+
692
+ rows, said = ask("ch.catalog.partition_parts", "partitions_per_table", lambda t: 1)
693
+ if rows is not None:
694
+ for r in rows:
695
+ t = by_key.get((r["database"], r["table"]))
696
+ if t is None:
697
+ continue
698
+ d = t.setdefault("partition_parts", {"ids": [], "parts": [], "rows": [], "marks": []})
699
+ d["ids"].append(str(r["partition_id"]))
700
+ for k in ("parts", "rows", "marks"):
701
+ d[k].append(int(r[k] or 0))
702
+ # when the partition's parts last changed (unix seconds): a partition nothing writes to or merges any more is
703
+ # closed. Absent in files pulled before these were asked for.
704
+ for k in ("first_modified", "last_modified"):
705
+ if k in r:
706
+ d.setdefault(k, []).append(int(r[k]) if r[k] is not None else None)
707
+ cut = [(t, t["partitions"] - len(t["partition_parts"]["ids"])) for t in known
708
+ if "partition_parts" in t and t["partitions"] > len(t["partition_parts"]["ids"])]
709
+ info["parts"] = {**said, "rows": len(rows), "tables": sum(1 for t in tables if "partition_parts" in t),
710
+ "tables_cut": len(cut), "partitions_cut": sum(n for _, n in cut)}
711
+ if cut:
712
+ info["notes"].append(f"parts per partition: the {said['partitions_per_table']:,} highest partition ids of each table were kept; "
713
+ f"{sum(n for _, n in cut):,} older partitions of {len(cut)} tables were left out")
714
+ rows, said = ask("ch.catalog.partition_columns", "column_partitions_per_table", lambda t: max(len(t.get("columns") or []), 1))
715
+ if rows is not None:
716
+ found: dict[tuple, dict[str, dict[str, list[int]]]] = {}
717
+ for r in rows:
718
+ found.setdefault((r["database"], r["table"]), {}).setdefault(str(r["partition_id"]), {})[r["column"]] = [
719
+ int(r["rows"] or 0), int(r["uncompressed_bytes"] or 0), int(r["compressed_bytes"] or 0)]
720
+ cut = []
721
+ for key, partitions in found.items():
722
+ t = by_key.get(key)
723
+ if t is None:
724
+ continue
725
+ seen = {c for cells in partitions.values() for c in cells}
726
+ columns = [c["name"] for c in t.get("columns") or [] if c["name"] in seen] or sorted(seen)
727
+ ids = sorted(partitions, reverse=True)
728
+ t["partition_columns"] = {"columns": columns, "ids": ids, "cells": [[partitions[i].get(c) for c in columns] for i in ids]}
729
+ if t.get("partitions", 0) > len(ids) and len(ids) >= said["partitions_per_table"]:
730
+ cut.append(t["partitions"] - len(ids))
731
+ unreported = sum(1 for t in known if "partition_columns" not in t and t.get("rows"))
732
+ info["columns"] = {**said, "rows": len(rows), "tables": len(found), "tables_cut": len(cut), "partitions_cut": sum(cut),
733
+ "tables_not_reported": unreported}
734
+ if cut:
735
+ info["notes"].append(f"column sizes per partition: the {said['partitions_per_table']:,} highest partition ids of each table "
736
+ f"were kept; {sum(cut):,} older partitions of {len(cut)} tables were left out")
737
+ if unreported:
738
+ info["notes"].append(f"{unreported} tables report no column sizes per partition (all their parts are compact, or the "
739
+ "engine keeps no parts): their widths stay the table's average")
740
+ info["available"] = "parts" in info or "columns" in info
741
+ return info
742
+
743
+ # ---- tier B ----------------------------------------------------------
744
+ def spread(self, suffix: str, window: int, top_rows: list[dict], notes: list[str]) -> tuple[dict[str, dict], str]:
745
+ """hash -> the spread of its runs, and the form used ("exact", "tdigest" or "").
746
+
747
+ The exact form keeps every run's three values in memory until the group is finished: about 24 bytes a run,
748
+ some 100 with the arrays' growth and the merge of the two threads. The runs of the kept shapes are already
749
+ known from the aggregation that chose them, so the form is decided before anything is sent: exact up to
750
+ `spread_exact_max_runs` runs (a gigabyte at the default, half the statement's memory limit), t-digest above."""
751
+ s = self.settings
752
+ if s["spread"] == "off" or not top_rows:
753
+ return {}, ""
754
+ runs = sum(int(r["executions"]) for r in top_rows)
755
+ form = s["spread"]
756
+ if form == "auto":
757
+ form = "exact" if runs <= int(s["spread_exact_max_runs"]) else "tdigest"
758
+ if form == "tdigest":
759
+ notes.append(f"the spread per shape is approximate (t-digest): the kept shapes ran {runs:,} times, above the "
760
+ f"{int(s['spread_exact_max_runs']):,} runs the exact form is used for")
761
+ out: dict[str, dict] = {}
762
+ hashes = [r["hash"] for r in top_rows]
763
+ for i in range(0, len(hashes), 400):
764
+ chunk = [int(h) for h in hashes[i:i + 400]]
765
+ rows = self.try_run(f"ch.workload.spread{'' if form == 'exact' else '_tdigest'}{suffix}", from_hours=window, to_hours=0, hashes=chunk)
766
+ if rows is None and form == "exact" and s["spread"] == "auto" and "limit" in self.last_refusal:
767
+ notes.append("the exact spread per shape was stopped by a limit; the approximate form (t-digest) was used")
768
+ form = "tdigest"
769
+ rows = self.try_run(f"ch.workload.spread_tdigest{suffix}", from_hours=window, to_hours=0, hashes=chunk)
770
+ if rows is None:
771
+ notes.append(f"the spread per shape is not available ({self.last_refusal}): runs are described by their mean only"
772
+ if not out else f"the spread per shape is missing for {len(hashes) - len(out)} shapes ({self.last_refusal})")
773
+ break
774
+ for r in rows:
775
+ q = {k: _quantiles(r.get(f"{k}_q")) for k in ("read_rows", "read_bytes", "result_rows")}
776
+ if all(q.values()):
777
+ out[r["hash"]] = {"method": form, **q, "no_result_runs": int(r["no_result_runs"] or 0), "no_read_runs": int(r["no_read_runs"] or 0),
778
+ # what the runs that returned nothing read, measured (and the others), not estimated from the median
779
+ **{k: int(r[k] or 0) for k in EMPTY_KEYS if k in r}}
780
+ return out, (form if out else "")
781
+
782
+ def selected(self, suffix: str, hours: float, log_rows: int, top_rows: list[dict], notes: list[str]) -> tuple[dict[str, dict], int]:
783
+ """hash -> parts and marks a run selects on average, for the heaviest shapes, and the hours it was read over.
784
+
785
+ ProfileEvents is a map of about a hundred counters a row, and a filter on the shape does not keep the server from
786
+ reading it for every granule that holds one matching row. What bounds the read is the window: the most recent
787
+ hours in which about `selected_max_log_rows` queries finished (the server reads about twice as many log rows: each query
788
+ also has its start row). An average over fewer hours is still an average."""
789
+ s = self.settings
790
+ if not s["selected"] or not top_rows or not s["selected_shapes"] or hours <= 0:
791
+ return {}, 0
792
+ budget = int(s["selected_max_log_rows"])
793
+ span = recent_span(hours, log_rows, budget)
794
+ chosen = [int(r["hash"]) for r in sorted(top_rows, key=lambda r: int(r["by_bytes"]))[:int(s["selected_shapes"])]]
795
+ rows = self.try_run(f"ch.workload.selected{suffix}", from_hours=span, to_hours=0, hashes=chosen)
796
+ if rows is None and "limit" not in self.last_refusal:
797
+ rows = self.try_run(f"ch.workload.selected_arrays{suffix}", from_hours=span, to_hours=0, hashes=chosen)
798
+ if rows is None:
799
+ notes.append(f"parts and marks selected per run are not available ({self.last_refusal})")
800
+ return {}, 0
801
+ # SelectedPartsTotal and SelectedMarksTotal are newer counters (on 24.8 and later): a server that never counts one
802
+ # has it in no run of any shape. Then it is null (not known), never 0, and that is said once.
803
+ known = {k: any(int(r.get(f"counts_{k}") or 0) for r in rows) for k in ("parts_total", "marks_total")}
804
+ for k, event in (("parts_total", "SelectedPartsTotal"), ("marks_total", "SelectedMarksTotal")):
805
+ if rows and not known[k] and any(f"counts_{k}" in r for r in rows):
806
+ notes.append(f"the server's query log does not count {event}: parts and marks chosen from are not known")
807
+
808
+ def avg(r: dict, key: str, k: str = "") -> float | None:
809
+ if r.get(key) is None or (k and not known[k]):
810
+ return None
811
+ return round(float(r[key]), 2)
812
+
813
+ out = {}
814
+ for r in rows:
815
+ if r.get("selected_parts") is None or r.get("selected_marks") is None:
816
+ continue
817
+ out[r["hash"]] = {"parts_per_run": round(float(r["selected_parts"]), 2), "marks_per_run": round(float(r["selected_marks"]), 2)}
818
+ if "selected_ranges" in r: # an older file or answer has the first two only
819
+ out[r["hash"]].update({"parts_total_per_run": avg(r, "selected_parts_total", "parts_total"),
820
+ "marks_total_per_run": avg(r, "selected_marks_total", "marks_total"),
821
+ "ranges_per_run": avg(r, "selected_ranges"), "runs": int(r.get("runs") or 0)})
822
+ if out and not any(v["parts_per_run"] or v["marks_per_run"] for v in out.values()):
823
+ notes.append("the server's query log counts no selected parts or marks: not compared")
824
+ return {}, 0
825
+ if span < hours:
826
+ notes.append(f"parts and marks selected per run are averaged over the last {span} h (about {budget:,} finished queries), for the "
827
+ f"{len(chosen)} heaviest shapes")
828
+ return out, span
829
+
830
+ def labels(self, suffix: str, window: int, top_rows: list[dict], notes: list[str]) -> dict[str, dict[str, object]]:
831
+ """Per shape kept: `tags` [{tag, executions, read_bytes}] (call-site tags in log_comment), `comments` [label, ...] (the
832
+ application's labels as written; local only) and `clients` {clients, agents, interfaces} (local only). Each of the
833
+ three statements is optional and switched by a setting (db_pull.tags, .comments, .clients): a refusal is a note."""
834
+ out: dict[str, dict[str, object]] = {}
835
+ hashes = [r["hash"] for r in top_rows]
836
+ for key, statement in (("tags", "ch.workload.tags"), ("comments", "ch.workload.comments"), ("clients", "ch.workload.clients")):
837
+ if not self.settings.get(key) or not hashes:
838
+ continue
839
+ found: dict[str, object] = {}
840
+ for i in range(0, len(hashes), 400):
841
+ rows = self.try_run(f"{statement}{suffix}", from_hours=window, to_hours=0, hashes=[int(h) for h in hashes[i:i + 400]])
842
+ if rows is None:
843
+ notes.append(f"{statement} is not available ({self.last_refusal}): no {key} per shape")
844
+ break
845
+ for r in rows:
846
+ if key == "tags":
847
+ tag = str(r.get("tag") or "")
848
+ if TAG.fullmatch(tag): # the server already extracted it; checked again before it is kept
849
+ found.setdefault(r["hash"], []).append({"tag": tag, "executions": int(r["executions"] or 0),
850
+ "read_bytes": int(r["sum_read_bytes"] or 0)})
851
+ elif key == "comments":
852
+ found[r["hash"]] = [self.connection.mask_secret(str(c))[:120] for c in r.get("comments") or [] if c]
853
+ else:
854
+ found[r["hash"]] = {k: [str(x)[:80] for x in r.get(k) or [] if x] for k in ("clients", "agents", "interfaces")}
855
+ if found:
856
+ out[key] = found
857
+ return out
858
+
859
+ def _batched(self, statement_id: str, hashes: list, chunk: int, notes: list[str], what: str, **params) -> list[dict] | None:
860
+ """One optional per-shape statement, `chunk` shapes a request. None when the first request is refused (a note says so);
861
+ what came back before a later refusal is kept, and the note says how many shapes are missing."""
862
+ rows: list[dict] = []
863
+ for i in range(0, len(hashes), max(chunk, 1)):
864
+ got = self.try_run(statement_id, hashes=[int(h) for h in hashes[i:i + chunk]], **params)
865
+ if got is None:
866
+ notes.append(f"{what} is not available ({self.last_refusal})" if not rows else
867
+ f"{what} is missing for {len(hashes) - i} shapes ({self.last_refusal})")
868
+ return rows or None
869
+ rows.extend(got)
870
+ return rows
871
+
872
+ def _databases(self, top_rows: list[dict]) -> set[str]:
873
+ """The database names this pull has seen: the connection's and the prefixes of the tables the kept shapes read."""
874
+ return {d for d in [self.connection.database, *(str(t).split(".", 1)[0] for r in top_rows for t in r.get("tables") or [] if "." in str(t))] if d}
875
+
876
+ def shape_columns(self, suffix: str, window: int, top_rows: list[dict], notes: list[str]) -> dict[str, dict]:
877
+ """hash -> {columns, projections, projection_runs, runs, cut}: the column names read (`table.column`) and the projections
878
+ used (`table.projection`), without their database, at most `columns_per_shape` of each; `cut` when that many came back."""
879
+ s = self.settings
880
+ n = int(s["columns_per_shape"])
881
+ if not s["columns"] or not top_rows or n <= 0:
882
+ return {}
883
+ rows = self._batched(f"ch.workload.columns{suffix}", [r["hash"] for r in top_rows], 400, notes, "columns read per shape",
884
+ from_hours=window, to_hours=0, columns_per_shape=n)
885
+ dbs = self._databases(top_rows)
886
+ out = {}
887
+ for r in rows or []:
888
+ cols = sorted({short_name(c, dbs) for c in r.get("columns_read") or [] if c})
889
+ projections = sorted({short_name(p, dbs) for p in r.get("projections_used") or [] if p})
890
+ out[r["hash"]] = {"columns": cols, "projections": projections, "projection_runs": int(r.get("projection_runs") or 0),
891
+ "runs": int(r.get("runs") or 0), **({"cut": True} if len(r.get("columns_read") or []) >= n else {})}
892
+ cut = sum(1 for v in out.values() if v.get("cut"))
893
+ if cut:
894
+ notes.append(f"{cut} shapes read more than {n} distinct columns: {n} of them were kept (db_pull.columns_per_shape)")
895
+ return out
896
+
897
+ def repeats(self, suffix: str, hours: float, log_rows: int, top_rows: list[dict], notes: list[str]) -> tuple[dict[str, dict], int]:
898
+ """hash -> {runs, statements, minutes}: runs, distinct full statements (values included; only their number leaves the
899
+ server) and minutes with at least one run, over the most recent hours that hold about `repeats_max_log_rows` finished
900
+ queries (the statement reads every run's text). A limit stops it: tried once more over a quarter of those hours."""
901
+ s = self.settings
902
+ if not s["repeats"] or not top_rows or hours <= 0:
903
+ return {}, 0
904
+ span = recent_span(hours, log_rows, int(s["repeats_max_log_rows"]))
905
+ hashes = [r["hash"] for r in top_rows]
906
+ quiet: list[str] = []
907
+ rows = self._batched(f"ch.workload.repeats{suffix}", hashes, 400, quiet, "runs per distinct statement", from_hours=span, to_hours=0)
908
+ if rows is None and "limit" in self.last_refusal and span > 1:
909
+ span, quiet = max(span // 4, 1), []
910
+ rows = self._batched(f"ch.workload.repeats{suffix}", hashes, 400, quiet, "runs per distinct statement", from_hours=span, to_hours=0)
911
+ notes.extend(quiet)
912
+ if rows is None:
913
+ return {}, 0
914
+ if span < hours:
915
+ notes.append(f"runs per distinct statement are counted over the last {span} h (about {int(s['repeats_max_log_rows']):,} finished "
916
+ "queries, db_pull.repeats_max_log_rows)")
917
+ return {r["hash"]: {"runs": int(r["runs"] or 0), "statements": int(r["statements"] or 0), "minutes": int(r["minutes"] or 0)}
918
+ for r in rows}, span
919
+
920
+ def minutes(self, suffix: str, window: int, top_rows: list[dict], notes: list[str]) -> tuple[dict[str, dict], dict]:
921
+ """hash -> its runs per minute (compact_minutes), for the `minutes_shapes` heaviest shapes, and what was asked.
922
+
923
+ A shape has at most one row a minute, so a request of k shapes returns at most k x the window's minutes rows: the
924
+ shapes go out in batches that fit the statement's result rows, and all of them stop at `minutes_max_rows`."""
925
+ s = self.settings
926
+ if not s["minutes"] or not top_rows or not s["minutes_shapes"] or not s["minutes_max_rows"]:
927
+ return {}, {}
928
+ chosen = [r["hash"] for r in sorted(top_rows, key=lambda r: int(r["by_bytes"]))[:int(s["minutes_shapes"])]]
929
+ per_request = with_limits(STATEMENTS[f"ch.workload.minutes{suffix}"], s["limits"]).limits.result_rows
930
+ span_minutes = max(int(window), 1) * 60 + 1 # a window of h hours touches h x 60 + 1 minutes
931
+ chunk = max(1, min(400, per_request // span_minutes))
932
+ left = int(s["minutes_max_rows"])
933
+ found: dict[str, list[tuple[int, int]]] = {}
934
+ sent = 0
935
+ for i in range(0, len(chosen), chunk):
936
+ if left <= 0:
937
+ break
938
+ ask = min(left, per_request)
939
+ rows = self.try_run(f"ch.workload.minutes{suffix}", from_hours=window, to_hours=0, hashes=[int(h) for h in chosen[i:i + chunk]],
940
+ max_rows=ask)
941
+ if rows is None:
942
+ notes.append(f"runs per minute are not available ({self.last_refusal})" if not found else
943
+ f"runs per minute are missing for {len(chosen) - i} shapes ({self.last_refusal})")
944
+ break
945
+ sent += 1
946
+ for r in rows:
947
+ found.setdefault(r["hash"], []).append((int(r["minute"]), int(r["runs"] or 0)))
948
+ left -= len(rows)
949
+ if len(rows) >= ask:
950
+ notes.append(f"runs per minute stopped at {int(s['minutes_max_rows']) - left:,} rows (db_pull.minutes_max_rows): the last shape "
951
+ "of that request is cut, the lighter ones are left out")
952
+ break
953
+ info = {"shapes": len(found), "asked": len(chosen), "rows": int(s["minutes_max_rows"]) - left, "requests": sent, "window_hours": window}
954
+ return {h: compact_minutes(v) for h, v in found.items()}, info
955
+
956
+ def inserts(self, suffix: str, window: int, top_rows: list[dict], notes: list[str]) -> list[dict] | None:
957
+ """Per table INSERT statements name: {table, database (local only), inserts, written_rows, written_bytes,
958
+ median_written_rows, total_ms}, the most bytes written first, at most `inserts_tables`."""
959
+ s = self.settings
960
+ if not s["inserts"] or not s["inserts_tables"]:
961
+ return None
962
+ rows = self.try_run(f"ch.workload.inserts{suffix}", from_hours=window, to_hours=0, max_rows=int(s["inserts_tables"]))
963
+ if rows is None:
964
+ notes.append(f"inserts per table are not available ({self.last_refusal})")
965
+ return None
966
+ if len(rows) >= int(s["inserts_tables"]):
967
+ notes.append(f"inserts per table stopped at {len(rows):,} tables (db_pull.inserts_tables): the lightest are left out")
968
+ out = []
969
+ for r in rows:
970
+ database, _, table = str(r["target"]).partition(".")
971
+ database, table = (database, table) if table else ("", database)
972
+ out.append({"table": table, "database": database, "inserts": int(r["inserts"] or 0), "written_rows": int(r["sum_written_rows"] or 0),
973
+ "written_bytes": int(r["sum_written_bytes"] or 0), "median_written_rows": int(round(float(r["median_written_rows"] or 0))),
974
+ "total_ms": int(r["total_ms"] or 0)})
975
+ return out
976
+
977
+ # ---- the resource profile per shape ----------------------------------------------------------
978
+ def resources(self, suffix: str, window: int, hours: float, log_rows: int, top_rows: list[dict], notes: list[str]) -> tuple[dict, dict]:
979
+ """(hash -> {cpu, memory, duration, threads, spill, disk_read_bytes, network_send_bytes, failures}, top-level facts
980
+ {resources, memory, failures, pressure, capacity, facts}). Each statement is optional and switched by a setting
981
+ (db_pull.memory, .cpu, .failures, .pressure, .capacity); a refusal is a note and its facts are absent ("not in this
982
+ pull"), never zero."""
983
+ s = self.settings
984
+ per: dict[str, dict] = {}
985
+ top: dict = {}
986
+ hashes = [r["hash"] for r in top_rows]
987
+ if s.get("memory") and hashes:
988
+ rows = self._batched(f"ch.workload.memory_peak_threads{suffix}", hashes, 400, [], "peak memory per shape", from_hours=window, to_hours=0)
989
+ kind = "peak"
990
+ if rows is None and "limit" not in self.last_refusal:
991
+ kind = "ever"
992
+ rows = self._batched(f"ch.workload.memory{suffix}", hashes, 400, notes, "peak memory per shape", from_hours=window, to_hours=0)
993
+ for r in rows or []:
994
+ q, d = _floats(r.get("memory_q"), 3), _floats(r.get("duration_q"), 2)
995
+ if q is None or d is None:
996
+ continue
997
+ per.setdefault(r["hash"], {}).update({
998
+ "memory": {"q50": int(q[0]), "q95": int(q[1]), "q99": int(q[2]), "max": int(r.get("max_memory") or 0),
999
+ "byte_ms": float(r.get("memory_byte_ms") or 0), "runs": int(r.get("runs") or 0)},
1000
+ "duration": {"q50": round(d[0], 1), "q95": round(d[1], 1), "max": int(r.get("max_ms") or 0)},
1001
+ "threads": {"avg": round(float(r.get("avg_threads") or 0), 2), "max": int(r.get("max_threads") or 0), "kind": kind}})
1002
+ if rows is not None:
1003
+ top["memory"] = {"shapes": sum(1 for v in per.values() if "memory" in v), "window_hours": hours, "threads_kind": kind}
1004
+ if s.get("cpu") and hashes and hours > 0:
1005
+ span = recent_span(hours, log_rows, int(s["resources_max_log_rows"]))
1006
+ chosen = [int(r["hash"]) for r in sorted(top_rows, key=lambda r: int(r["by_bytes"]))[:int(s["selected_shapes"])]]
1007
+ rows = self.try_run(f"ch.workload.resources{suffix}", from_hours=span, to_hours=0, hashes=chosen)
1008
+ form = ""
1009
+ if rows is None and "limit" not in self.last_refusal:
1010
+ form = "_arrays"
1011
+ rows = self.try_run(f"ch.workload.resources_arrays{suffix}", from_hours=span, to_hours=0, hashes=chosen)
1012
+ if rows is None:
1013
+ notes.append(f"CPU per shape is not available ({self.last_refusal}): not in this pull")
1014
+ else:
1015
+ counted = any(int(r.get("counts_cpu") or 0) for r in rows)
1016
+ os_counted = any(int(r.get("counts_os_cpu") or 0) for r in rows)
1017
+ for r in rows:
1018
+ q = _floats(r.get("cpu_us_q"), 2)
1019
+ if q is None:
1020
+ continue
1021
+ per.setdefault(r["hash"], {}).update({
1022
+ "cpu": {"user_us": int(r.get("user_us") or 0), "system_us": int(r.get("system_us") or 0), "q50_us": int(q[0]),
1023
+ "q95_us": int(q[1]), "max_us": int(r.get("max_cpu_us") or 0), "runs": int(r.get("runs") or 0),
1024
+ # a counter the server does not know reads 0 in a Map: `counted` tells 0 from absent
1025
+ "os_cpu_us": int(r.get("os_cpu_us") or 0) if os_counted else None,
1026
+ "cpu_wait_us": int(r.get("cpu_wait_us") or 0) if os_counted else None,
1027
+ "io_wait_us": int(r.get("io_wait_us") or 0) if os_counted else None,
1028
+ "counted": counted, "os_counted": os_counted},
1029
+ "spill": {"runs": int(r.get("spilled_runs") or 0), "bytes": int(r.get("spilled_bytes") or 0)},
1030
+ "disk_read_bytes": int(r.get("disk_read_bytes") or 0) if os_counted else None,
1031
+ "network_send_bytes": int(r.get("network_send_bytes") or 0)})
1032
+ totals = self.try_run(f"ch.workload.resource_totals{form}{suffix}", from_hours=span, to_hours=0)
1033
+ if totals is None:
1034
+ notes.append(f"the CPU of all queries is not available ({self.last_refusal}): shares of CPU are not stated")
1035
+ top["resources"] = {"window_hours": span, "shapes": sum(1 for r in rows if r["hash"] in per and "cpu" in per[r["hash"]]),
1036
+ "counted": counted, "os_counted": os_counted,
1037
+ **({"totals": {"by_kind": [{"kind": str(t["kind"]), "runs": int(t["runs"] or 0), "cpu_us": int(t["cpu_us"] or 0),
1038
+ "memory_byte_ms": float(t["memory_byte_ms"] or 0),
1039
+ "max_memory": int(t["max_memory"] or 0)} for t in totals]}}
1040
+ if totals is not None else {})}
1041
+ if not counted and rows:
1042
+ notes.append("the server's query log counts no CPU time (UserTimeMicroseconds): CPU is not in this pull")
1043
+ if span < hours:
1044
+ notes.append(f"CPU per shape is summed over the last {span} h (about {int(s['resources_max_log_rows']):,} finished queries, "
1045
+ "db_pull.resources_max_log_rows); per-day figures are scaled from it")
1046
+ if s.get("failures"):
1047
+ rows = self.try_run(f"ch.workload.failures{suffix}", from_hours=window, to_hours=0, max_rows=int(s["failures_shapes"]))
1048
+ if rows is None:
1049
+ notes.append(f"failed runs per shape are not available ({self.last_refusal}): not in this pull")
1050
+ else:
1051
+ known = set(hashes)
1052
+ other = {"shapes": 0, "runs": 0, "memory_limit": 0, "timeout": 0}
1053
+ for r in rows:
1054
+ got = {"runs": int(r["failed_runs"] or 0), "memory_limit": int(r["memory_limit_runs"] or 0),
1055
+ "timeout": int(r["timeout_runs"] or 0), "max_memory": int(r["max_memory_failed"] or 0)}
1056
+ if r["hash"] in known:
1057
+ per.setdefault(r["hash"], {})["failures"] = got
1058
+ else: # a shape not kept: counted, never fetched or matched
1059
+ other["shapes"] += 1
1060
+ for k in ("runs", "memory_limit", "timeout"):
1061
+ other[k] += got[k]
1062
+ top["failures"] = {"window_hours": hours, "shapes": sum(1 for v in per.values() if "failures" in v), "other_shapes": other,
1063
+ **({"cut": True} if len(rows) >= int(s["failures_shapes"]) else {})}
1064
+ if s.get("pressure"):
1065
+ rows = self.try_run(f"ch.workload.pressure{suffix}", from_hours=window, to_hours=0)
1066
+ r = rows[0] if rows else None
1067
+ running, held = (_floats(r.get("running_q"), 2), _floats(r.get("held_bytes_q"), 2)) if r else (None, None)
1068
+ if rows is None:
1069
+ notes.append(f"how much runs at once is not available ({self.last_refusal})")
1070
+ elif r is not None and running is not None and held is not None and int(r.get("minutes") or 0):
1071
+ top["pressure"] = {"minutes": int(r.get("minutes") or 0), "running_q50": round(running[0], 2), "running_q95": round(running[1], 2),
1072
+ "running_max": round(float(r.get("max_running") or 0), 2), "held_bytes_q50": int(held[0]),
1073
+ "held_bytes_q95": int(held[1]), "held_bytes_max": int(float(r.get("max_held_bytes") or 0)),
1074
+ "window_hours": hours}
1075
+ if s.get("capacity"):
1076
+ rows = self.try_run("ch.check.capacity")
1077
+ if rows is None:
1078
+ notes.append(f"the server's memory limit and cores are not available ({self.last_refusal}): the limit is not compared")
1079
+ else:
1080
+ top["capacity"] = capacity_of(rows)
1081
+ top["facts"] = {"cpu": "profile_events" if (top.get("resources") or {}).get("counted") else "none",
1082
+ "memory": "query_log" if "memory" in top else "none",
1083
+ "io_wait": bool((top.get("resources") or {}).get("os_counted"))}
1084
+ return per, top
1085
+
1086
+ def workload(self, *, hours: int = 24, top: int = 500, max_queries: int = 20_000_000, all_replicas: bool | None = None) -> dict:
1087
+ """The query log aggregated by normalized query hash over a bounded window, heaviest first.
1088
+
1089
+ The window shrinks until it holds at most `max_queries` finished queries, so the aggregation's cost is
1090
+ bounded before it runs. Text comes back only as the server's own normalized form, one per shape."""
1091
+ if all_replicas is None:
1092
+ replicas = self.try_run("ch.check.replicas")
1093
+ self.cluster_readable = replicas is not None
1094
+ all_replicas = bool(replicas and int(replicas[0]["replicas"]) > 1)
1095
+ suffix = ".all_replicas" if all_replicas else ""
1096
+ window, volume = hours, None
1097
+ notes: list[str] = []
1098
+ while True:
1099
+ try:
1100
+ volume = self.run(f"ch.workload.volume{suffix}", from_hours=window, to_hours=0)[0]
1101
+ except Refused as e:
1102
+ if suffix and re.search(r"ACCESS_DENIED|Not enough privileges|UNKNOWN|CLUSTER", str(e)):
1103
+ notes.append("the query log could be read from one replica only")
1104
+ suffix = ""
1105
+ continue
1106
+ if window > 1 and re.search(r"TOO_MANY_ROWS|TOO_MANY_BYTES|TIMEOUT_EXCEEDED|Limit for", str(e)):
1107
+ window = max(window // 4, 1)
1108
+ continue
1109
+ raise
1110
+ if int(volume["queries"]) <= max_queries or window <= 1:
1111
+ break
1112
+ # shrink in proportion, with a margin
1113
+ window = max(int(window * max_queries / int(volume["queries"]) * 0.8), 1)
1114
+ if window != hours:
1115
+ notes.append(f"window reduced from {hours} h to {window} h to stay within {max_queries:,} log rows")
1116
+ from .match import covered_hours
1117
+ span = covered_hours({"window_hours": window, "first_seen": str(volume["first_seen"]), "last_seen": str(volume["last_seen"])})
1118
+ if not suffix and span and span < window * 0.95 and getattr(self, "cluster_readable", True):
1119
+ # The log of the replica this connection reached holds less than the window (24 h asked, 1 h back on a ClickHouse
1120
+ # Cloud service): each replica keeps its own query_log, and a replica started recently holds only what it ran
1121
+ # since. The replica check can see one replica where several serve; the log of every replica is asked as well and
1122
+ # kept when it holds more.
1123
+ wide = self.try_run("ch.workload.volume.all_replicas", from_hours=window, to_hours=0)
1124
+ if wide and int(wide[0]["queries"]) > int(volume["queries"]) and str(wide[0]["first_seen"]) < str(volume["first_seen"]):
1125
+ notes.append(f"this replica's query log held {span} h of the {window} h; the log of every replica holds more and was read")
1126
+ suffix, volume = ".all_replicas", wide[0]
1127
+ else:
1128
+ started = getattr(self, "uptime_s", None)
1129
+ if started is not None and started < window * 3600:
1130
+ notes.append(f"the server started {started / 3600:.1f} h ago and its query log begins then: {span} h of the "
1131
+ f"{window} h asked; earlier pulls are kept in db_snapshots/ so shapes accumulate across pulls")
1132
+ else:
1133
+ notes.append(f"the query log begins at {volume['first_seen']}: {span} h of the {window} h asked (the server keeps "
1134
+ "its log shorter, or it was cleared); earlier pulls are kept in db_snapshots/ so shapes accumulate")
1135
+ kinds = self.run(f"ch.workload.kinds{suffix}", from_hours=window, to_hours=0)
1136
+ top_rows = self.run(f"ch.workload.top{suffix}", from_hours=window, to_hours=0, top=top)
1137
+ texts: dict[str, dict] = {}
1138
+ missing = [r["hash"] for r in top_rows]
1139
+ for span in sorted({min(1, window), min(6, window), min(24, window), window}):
1140
+ if not missing:
1141
+ break
1142
+ for i in range(0, len(missing), 400):
1143
+ try:
1144
+ for row in self.run(f"ch.workload.texts{suffix}", from_hours=span, to_hours=0, hashes=[int(h) for h in missing[i:i + 400]],
1145
+ text_chars=int(self.settings["text_max_chars"])):
1146
+ texts[row["hash"]] = row
1147
+ except Refused as e:
1148
+ notes.append(f"query texts for a {span} h window were refused by a limit")
1149
+ if not re.search(r"TOO_MANY|TIMEOUT|Limit for|MEMORY", str(e)):
1150
+ raise
1151
+ missing = [h for h in missing if h not in texts]
1152
+ if missing:
1153
+ notes.append(f"{len(missing)} shapes have no text (not found within the limits)")
1154
+ select = next((k for k in kinds if k["kind"] == "Select"), None) or {}
1155
+ covered = covered_hours({"window_hours": window, "first_seen": str(volume["first_seen"]), "last_seen": str(volume["last_seen"])})
1156
+ spreads, spread_form = self.spread(suffix, window, top_rows, notes)
1157
+ selections, selected_hours = self.selected(suffix, min(float(covered or window), window), int(volume["queries"]), top_rows, notes)
1158
+ labels = self.labels(suffix, window, top_rows, notes)
1159
+ columns = self.shape_columns(suffix, window, top_rows, notes)
1160
+ repeats, repeats_hours = self.repeats(suffix, min(float(covered or window), window), int(volume["queries"]), top_rows, notes)
1161
+ per_minute, minutes_info = self.minutes(suffix, window, top_rows, notes)
1162
+ inserts = self.inserts(suffix, window, top_rows, notes)
1163
+ resources, resource_facts = self.resources(suffix, window, min(float(covered or window), window), int(volume["queries"]), top_rows, notes)
1164
+ limit = int(self.settings["text_max_chars"])
1165
+ queries = []
1166
+ own = [r["hash"] for r in top_rows if OWN_STATEMENT.search((texts.get(r["hash"]) or {}).get("text") or "")]
1167
+ if own:
1168
+ # CodeCop's own locality statements (an earlier `codecop db pull --locality`) read the user's tables: not workload
1169
+ notes.append(f"{len(own)} shapes of CodeCop's own locality statements were left out")
1170
+ top_rows = [r for r in top_rows if r["hash"] not in set(own)]
1171
+ for r in top_rows:
1172
+ t = texts.get(r["hash"]) or {}
1173
+ queries.append({
1174
+ **({"spread": spreads[r["hash"]]} if r["hash"] in spreads else {}),
1175
+ **({"selected": selections[r["hash"]]} if r["hash"] in selections else {}),
1176
+ **({"columns": columns[r["hash"]]} if r["hash"] in columns else {}),
1177
+ **({"repeats": repeats[r["hash"]]} if r["hash"] in repeats else {}),
1178
+ **({"minutes": per_minute[r["hash"]]} if r["hash"] in per_minute else {}),
1179
+ **{k: v[r["hash"]] for k, v in labels.items() if r["hash"] in v},
1180
+ # cpu, memory, duration, threads, spill, failures, disk_read_bytes, network_send_bytes (resources); absent when not pulled
1181
+ **resources.get(r["hash"], {}),
1182
+ "hash": r["hash"], "kind": "select", "executions": int(r["executions"]), "total_ms": int(r["total_ms"]),
1183
+ "avg_ms": float(r["avg_ms"]), "p95_ms": float(r["p95_ms"]), "read_rows": int(r["sum_read_rows"]), "read_bytes": int(r["sum_read_bytes"]),
1184
+ "max_read_bytes": int(r["max_read_bytes"]), "result_rows": int(r["sum_result_rows"]),
1185
+ "result_bytes": int(r["sum_result_bytes"]) if r.get("sum_result_bytes") is not None else None, "max_memory": int(r["max_memory"]),
1186
+ "avg_memory": int(float(r["avg_memory"])), "users": int(r["users"]), "tables": r.get("tables") or [],
1187
+ "first_seen": r["first_seen"], "last_seen": r["last_seen"],
1188
+ "rank_by_bytes": int(r["by_bytes"]), "rank_by_executions": int(r["by_executions"]), "rank_by_time": int(r["by_time"]),
1189
+ # cut when the normalized text reached the limit (the raw length counts literals the normalized text has not)
1190
+ "text": self.connection.mask_secret(t.get("text", "")), "text_truncated": len(t.get("text") or "") >= limit,
1191
+ "raw_length": int(t.get("length") or 0),
1192
+ # the text carries `SETTINGS log_comment = ?`: the code labels this statement (the value is masked by the server)
1193
+ **({"labelled_in_text": True} if re.search(r"log_comment\s*=", t.get("text") or "", re.I) else {}),
1194
+ })
1195
+ if covered != window:
1196
+ notes.append(f"the log holds {covered} h of the {window} h asked for; per-day figures are scaled from {covered} h")
1197
+ return {
1198
+ "engine": "clickhouse", "source": "system.query_log" + (" on every replica" if suffix else ""),
1199
+ "window_hours": covered, "window_requested_hours": hours, "first_seen": str(volume["first_seen"]), "last_seen": str(volume["last_seen"]),
1200
+ "log_rows": int(volume["queries"]), "top": top, "notes": notes, "text_max_chars": limit,
1201
+ "labels": {k: len(v) for k, v in labels.items()},
1202
+ # which of the optional per-shape statements answered: the quantile form, and the hours parts and marks were averaged over
1203
+ "spread": {"method": spread_form, "shapes": len(spreads)}, "selected": {"window_hours": selected_hours, "shapes": len(selections)},
1204
+ # the optional per-shape statements added later: absent from files pulled before them
1205
+ "columns": {"shapes": len(columns), "per_shape": int(self.settings["columns_per_shape"])},
1206
+ "repeats": {"window_hours": repeats_hours, "shapes": len(repeats)},
1207
+ "minutes": minutes_info,
1208
+ **({"inserts": inserts} if inserts is not None else {}),
1209
+ # resources {window_hours, shapes, totals}, memory, failures, pressure, capacity, facts
1210
+ **resource_facts,
1211
+ "totals": {"select": {"executions": int(select.get("executions") or 0), "shapes": int(select.get("shapes") or 0),
1212
+ "read_rows": int(select.get("sum_read_rows") or 0), "read_bytes": int(select.get("sum_read_bytes") or 0),
1213
+ "total_ms": int(select.get("total_ms") or 0)},
1214
+ "by_kind": [{"kind": k["kind"], "executions": int(k["executions"]), "shapes": int(k["shapes"]),
1215
+ "read_rows": int(k["sum_read_rows"]), "read_bytes": int(k["sum_read_bytes"]), "total_ms": int(k["total_ms"]),
1216
+ "written_rows": int(k["sum_written_rows"])} for k in kinds]},
1217
+ "queries": queries,
1218
+ }
1219
+
1220
+ def plans(self, workload: dict, limit: int = 0) -> dict:
1221
+ return {"engine": "clickhouse", "available": False, "plans": [],
1222
+ "reason": "No statement derived from the workload is sent to ClickHouse: a normalized text is not runnable, and EXPLAIN "
1223
+ "can evaluate scalar subqueries."}