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,964 @@
1
+ """ClickHouse locality: what a skip index, a projection or a re-key would read on production, counted by the server from
2
+ aggregates over the table's own granules. Nothing is built on production.
3
+
4
+ Why: a skip index, a projection and a re-key are only as good as where values sit inside production's parts. The sandbox
5
+ does not know that (its generator places a column's values without regard to the tenant or the time), so its read of a
6
+ skip index on such a column is not evidence either way. Here the server is asked, per granule of a few recent parts:
7
+ which granules the present key selects for a value, which of those hold the value (what an index keeps), how many
8
+ distinct values each holds (what a set(N) index can keep), and, for a new sort order, how many rows the new key prefix
9
+ matches per part (what it would read).
10
+
11
+ Four statements, one per candidate (`ch.locality.skip_eq`, `.skip_eq_ranked`, `.skip_range`, `.key_order`), plus two
12
+ catalog reads (`ch.locality.parts`: the table's active parts, to choose parts inside a row budget; `ch.locality.cost`: the
13
+ server's own CPU, memory and rows for each statement sent, from its query log). All are single read-only SELECTs.
14
+
15
+ What leaves the server: counters per probe (granules, rows), the shares and ranks of the most frequent values, and
16
+ quantiles of distinct values per granule. Values are hashed and compared inside the server (cityHash64); the probes are
17
+ drawn from the table's own rows inside the statement (no literal is sent) and no value or hash is returned. Identifiers
18
+ come from the catalog only, each checked against a plain-identifier pattern and backquoted; everything else is a typed
19
+ parameter or a part name system.parts returned. Part names stay on this machine.
20
+
21
+ Cost control: a statement is planned only for a candidate the advisor proposed whose statement shape can be counted
22
+ (equality, IN, a range on a number, date, time or decimal; a new key prefix), most valuable first (the measured load of
23
+ the statements it serves x the table's rows); a candidate on a table under `locality_min_table_rows` is nothing to gain
24
+ without a statement, and candidates that need the identical count share one statement. A statement reads only named
25
+ parts whose rows sum to at most `locality_rows_per_statement`, at most `locality_parts_per_statement` of them (its memory
26
+ and time grow with the parts it opens), with max_rows_to_read set to what its passes over them can read (SCANS); the pull stops at `locality_max_statements` statements or when the CPU spent (wall time x threads, an
27
+ upper bound) reaches `locality_cpu_seconds_total`. Every request carries the pull's read-only flag and per-statement
28
+ limits (2 threads, a memory cap, a time limit); a refusal or a missing privilege is "not judged" with the reason, never a
29
+ failure of the pull.
30
+
31
+ Versions: 25.8 and later number a part's granules themselves (`_part_granule_offset`): exact for any row width. Before,
32
+ the granule is `_part_offset / rows per mark`: exact when the table's rows per mark is its index granularity (narrow rows),
33
+ an estimate (labelled) otherwise.
34
+ """
35
+
36
+ from __future__ import annotations
37
+
38
+ import json
39
+ import re
40
+ import time
41
+ import uuid
42
+ from datetime import datetime, timezone
43
+
44
+ from . import PULL_DEFAULTS, DbError, Limits, Refused, Statement
45
+
46
+ SCHEMA_VERSION = 1
47
+ FILE = "db_locality.json"
48
+ IDENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]*\Z")
49
+ TIME_TYPE = re.compile(r"^(?:Nullable\()?(?:LowCardinality\()?(Date|Date32|DateTime|DateTime64)\b")
50
+ # a column a range is simulated on (skip_range compares it as Float64): numbers, Decimal, Date, Date32, DateTime, DateTime64,
51
+ # under Nullable and LowCardinality in either order
52
+ NUMERIC = re.compile(r"^(?:(?:Nullable|LowCardinality)\()*(?:U?Int\d+|Float\d+|Decimal\d*|Date|Date32|DateTime|DateTime64)\b", re.I)
53
+ GRANULE_OFFSET_VERSION = "25.8"
54
+ # the statements' own limits; db_pull.limits."ch.locality" changes them like any other statement's
55
+ LOCALITY_LIMITS = Limits(seconds=60, rows_to_read=30_000_000, bytes_to_read=8_000_000_000, result_rows=1_000,
56
+ memory_bytes=1_000_000_000, threads=2)
57
+ # What each statement reads of its chosen parts (measured on 24.8, 25.8 and 26.6): one pass per scan of the table in it.
58
+ # (name, bounded by the window, the parameter naming how many rows it draws or None.) `hi` (the newest time) is answered
59
+ # from the parts' min-max (the implicit projection) when the time column is in the partition key, else it is a full pass.
60
+ # A scan that draws rows (ORDER BY ... LIMIT n) is read a second time for the n rows it keeps on servers that materialize
61
+ # lazily (26.x: query_plan_max_limit_for_lazy_materialization = 10000; 25.8: 10): up to n granules more. Each one-row
62
+ # scalar subquery (no FROM) reads a row of system.one: a few rows more. The old cap (rows x 3 x 1.2) missed all three:
63
+ # skip_eq_ranked and skip_range make four passes, 26.6 re-reads the draws, a table of 6 rows adds 5 rows of system.one.
64
+ SCANS = {
65
+ "ch.locality.skip_eq": (("hi", False, None), ("probes", True, "probes"), ("main", False, None)),
66
+ "ch.locality.skip_eq_ranked": (("hi", False, None), ("keys", True, "keys"), ("values", True, None), ("main", False, None)),
67
+ "ch.locality.skip_range": (("hi", False, None), ("thresholds", False, None), ("probes", True, "probes"), ("main", False, None)),
68
+ "ch.locality.key_order": (("hi", False, None), ("probes", True, "probes"), ("main", False, None)),
69
+ }
70
+ PASSES = max(len(v) for v in SCANS.values()) # the most passes any statement makes (divides the row budget)
71
+ LAZY_VERSION = "25.10" # from here a draw of up to 10000 rows is materialized lazily (the estimate; the cap always allows it)
72
+ ROWS_SLACK = 1_000 # rows of system.one and rounding: the cap's constant
73
+ # [db_pull] in codecop.toml: the locality_* keys of realdb.PULL_DEFAULTS
74
+ DEFAULTS = {k: v for k, v in PULL_DEFAULTS.items() if k.startswith("locality")}
75
+
76
+ PARTS = Statement(
77
+ "ch.locality.parts", "A",
78
+ "SELECT name AS part, partition_id, rows, marks, toUInt32(min_time) AS min_t, toUInt32(max_time) AS max_t, "
79
+ "toUInt32(modification_time) AS modified FROM system.parts WHERE active AND database = {db:String} AND table = {table:String} "
80
+ "ORDER BY modification_time DESC, name DESC LIMIT {max_parts:UInt32}",
81
+ "The table's active parts (name, rows, marks, time range), to choose recent parts whose rows fit the statement's row "
82
+ "budget. Part names stay on this machine.", Limits(seconds=30, rows_to_read=5_000_000, result_rows=20_000), optional=True)
83
+ COST = Statement(
84
+ "ch.locality.cost", "check",
85
+ "SELECT query_id, query_duration_ms AS ms, read_rows, read_bytes, memory_usage AS memory, "
86
+ "ProfileEvents['UserTimeMicroseconds'] + ProfileEvents['SystemTimeMicroseconds'] AS cpu_us FROM system.query_log "
87
+ "WHERE event_date >= yesterday() AND event_time >= now() - toIntervalMinute({minutes:UInt32}) "
88
+ "AND type IN ('QueryFinish', 'ExceptionWhileProcessing') AND query_id IN {ids:Array(String)}",
89
+ "The server's own CPU, memory and rows for each locality statement this pull sent (by its query id), for the audit.",
90
+ Limits(seconds=30, rows_to_read=20_000_000, result_rows=1_000), optional=True)
91
+
92
+ TRIAL_FILE = "db_trial.json"
93
+ TRIAL_COMPARE = Statement(
94
+ "ch.locality.trial_compare", "B",
95
+ "WITH (SELECT toUInt32(max(create_time)) FROM system.mutations WHERE database = {db:String} AND table = {table:String} AND is_done "
96
+ "AND position(command, {name:String}) > 0) AS since "
97
+ "SELECT toString(normalized_query_hash) AS hash, multiIf(partitions = [{trial:String}], if(toUInt32(event_time) >= since, 'trial_after', "
98
+ "'trial_before'), partitions = [{neighbour:String}], 'neighbour', 'other') AS side, count() AS runs, avg(ProfileEvents['SelectedMarks']) AS marks, "
99
+ "avg(ProfileEvents['SelectedMarksTotal']) AS marks_total, any(since) AS built_at FROM system.query_log "
100
+ "WHERE event_date >= toDate(now() - toIntervalHour({from_hours:UInt32})) AND event_time >= now() - toIntervalHour({from_hours:UInt32}) "
101
+ "AND type = 'QueryFinish' AND is_initial_query AND query_kind = 'Select' AND normalized_query_hash IN {hashes:Array(UInt64)} "
102
+ "GROUP BY hash, side",
103
+ "After `codecop apply --trial` (run by the user): marks selected per run of the statements a trial index or projection serves, "
104
+ "on runs that read only the trial partition, before and after its MATERIALIZE finished (system.mutations), and on runs that read "
105
+ "only a neighbouring partition (the query log's `partitions`). Counts only.",
106
+ Limits(seconds=60, rows_to_read=5_000_000, bytes_to_read=3_000_000_000, result_rows=5_000, memory_bytes=1_000_000_000, threads=2),
107
+ optional=True)
108
+ TRIAL_MIN_RUNS = 10 # runs on each side below which a trial says nothing (db_pull.locality_trial_min_runs is not a setting yet)
109
+
110
+
111
+ def trial_compare(reader, trial: dict, hours: int) -> dict:
112
+ """One trial's comparison, per statement it serves: marks selected per run as a share of the marks the run chose from,
113
+ on runs that read only the trial partition after the build against before it (else against runs that read only the
114
+ neighbour), and the load-weighted ratio. Statements with no time bound read every partition and are never compared.
115
+ {status, ratio, basis, statements: [...], runs_trial, runs_neighbour}."""
116
+ from .clickhouse import refusal_reason
117
+ db = trial.get("database") or ""
118
+ name = f"{db}.{trial['table']}" if db else trial["table"]
119
+ if not trial.get("partition") or not trial.get("hashes") or not trial.get("name"):
120
+ return {"status": "not_compared", "reason": "the trial names no partition, change or statement from the query log"}
121
+ try:
122
+ rows = reader.run_statement(TRIAL_COMPARE, {"trial": f"{name}.{trial['partition']}", "neighbour": f"{name}.{trial.get('neighbour') or ''}",
123
+ "db": db, "table": trial["table"], "name": trial["name"],
124
+ "hashes": [int(h) for h in trial["hashes"]], "from_hours": int(hours)})
125
+ except Refused as e:
126
+ return {"status": "refused", "reason": refusal_reason(str(e))}
127
+ if rows and not int(rows[0].get("built_at") or 0):
128
+ return {"status": "not_built", "reason": "no finished MATERIALIZE of it in the server's mutations"}
129
+ by: dict[str, dict] = {}
130
+ for r in rows:
131
+ if r["side"] in ("trial_after", "trial_before", "neighbour"):
132
+ by.setdefault(r["hash"], {})[r["side"]] = {"runs": int(r["runs"]), "marks": float(r["marks"] or 0), "marks_total": float(r["marks_total"] or 0)}
133
+
134
+ def share(x: dict | None) -> float | None:
135
+ return x["marks"] / x["marks_total"] if x and x["runs"] >= TRIAL_MIN_RUNS and x["marks_total"] and x["marks"] else None
136
+ stmts, num, den = [], 0.0, 0.0
137
+ for h, sides in by.items():
138
+ after = share(sides.get("trial_after"))
139
+ before, basis = share(sides.get("trial_before")), "the trial partition before its build"
140
+ if before is None:
141
+ before, basis = share(sides.get("neighbour")), "the neighbouring partition"
142
+ if after is None or before is None:
143
+ continue
144
+ w = sides["trial_after"]["runs"]
145
+ stmts.append({"hash": h, "runs_after": w, "share_after": round(after, 4), "share_before": round(before, 4), "against": basis,
146
+ "ratio": round(after / before, 4)})
147
+ num += w * after
148
+ den += w * before
149
+ if not stmts:
150
+ return {"status": "too_few_runs", "reason": f"fewer than {TRIAL_MIN_RUNS} runs that read only the trial partition after the build, "
151
+ "or nothing to compare them with"}
152
+ return {"status": "answered", "ratio": round(num / den, 4) if den else None, "statements": stmts,
153
+ "runs_trial": sum(x["runs_after"] for x in stmts), "runs_neighbour": None}
154
+
155
+
156
+ _W = "({window_s:UInt32} = 0 OR @TIME@ >= hi - toIntervalSecond({window_s:UInt32}))"
157
+ _HI = "(SELECT max(@TIME@) FROM @T@ WHERE _part IN {parts:Array(String)}) AS hi"
158
+ _TAIL_EQ = """
159
+ SELECT count() AS granules, sum(n) AS rows_scanned, length(pk) AS probes@EXTRA@,
160
+ sumForEach(arrayMap(a -> toUInt32(bitTest(km, a)), ik)) AS key_granules,
161
+ sumForEach(arrayMap((a, c) -> toUInt32(bitTest(km, a) AND bitTest(cmg, c)), ik, ic)) AS index_granules,
162
+ sumForEach(arrayMap((a, c) -> toUInt32(bitTest(km, a) AND (bitTest(cmg, c) OR ug > {set_values:UInt32})), ik, ic)) AS set_granules,
163
+ sumForEach(arrayMap(p -> toUInt32(bitTest(bm, p)), ip)) AS needed_granules,
164
+ quantiles(0.5, 0.9)(u) AS distinct_per_granule
165
+ FROM (
166
+ SELECT *, groupBitOr(cm) OVER (PARTITION BY _part, gg) AS cmg,
167
+ sum(u) OVER (PARTITION BY _part, gg) AS ug
168
+ FROM (
169
+ SELECT _part, @GRANULE@ AS g, intDiv(g, {index_granularity:UInt32}) AS gg, count() AS n, uniq(@COL@) AS u,
170
+ groupBitOr(bitShiftRight(bitShiftLeft(toUInt64(1), indexOf(dk, @KEY@) * @W@), 1)) AS km,
171
+ groupBitOr(bitShiftRight(bitShiftLeft(toUInt64(1), indexOf(dc, cityHash64(@COL@))), 1)) AS cm,
172
+ groupBitOr(bitShiftRight(bitShiftLeft(toUInt64(1), indexOf(dp, cityHash64(@KEY@, cityHash64(@COL@))) * @W@), 1)) AS bm
173
+ FROM @T@ WHERE _part IN {parts:Array(String)}
174
+ GROUP BY _part, g))"""
175
+ _ARRAYS = """
176
+ pr.1 AS pk, pr.2 AS pc, arrayDistinct(pk) AS dk, arrayDistinct(pc) AS dc,
177
+ (SELECT arrayDistinct(arrayMap((a, b) -> cityHash64(a, b), pr.1, pr.2))) AS dp,
178
+ (SELECT arrayMap(x -> indexOf(arrayDistinct(pr.1), x) - 1, pr.1)) AS ik,
179
+ (SELECT arrayMap(x -> indexOf(arrayDistinct(pr.2), x) - 1, pr.2)) AS ic,
180
+ (SELECT arrayMap((a, b) -> indexOf(arrayDistinct(arrayMap((a, b) -> cityHash64(a, b), pr.1, pr.2)), cityHash64(a, b)) - 1, pr.1, pr.2)) AS ip"""
181
+
182
+ TEMPLATES = {
183
+ # equality / IN on a column: set, bloom_filter, any GRANULARITY. One probe = one row drawn at random from the window.
184
+ "ch.locality.skip_eq": "WITH\n " + _HI + """,
185
+ (SELECT (groupArray(hk), groupArray(hc)) FROM (
186
+ SELECT @KEY@ AS hk, cityHash64(@COL@) AS hc FROM @T@
187
+ WHERE _part IN {parts:Array(String)} AND @W@
188
+ ORDER BY cityHash64(_part, _part_offset, {seed:UInt32}) LIMIT {probes:UInt32})) AS pr,""" + _ARRAYS + _TAIL_EQ.replace("@EXTRA@", ""),
189
+ # the same for a column of few values: its most frequent values by rank, each with every key drawn
190
+ "ch.locality.skip_eq_ranked": "WITH\n " + _HI + """,
191
+ (SELECT (groupArray(hk), groupArray(hc), groupArray(share), groupArray(rnk)) FROM (
192
+ SELECT hk, hc, share, rnk FROM
193
+ (SELECT @KEY@ AS hk FROM @T@ WHERE _part IN {parts:Array(String)} AND @W@
194
+ ORDER BY cityHash64(_part, _part_offset, {seed:UInt32}) LIMIT {keys:UInt32}) AS a
195
+ CROSS JOIN
196
+ (SELECT cityHash64(@COL@) AS hc, count() / sum(count()) OVER () AS share, row_number() OVER (ORDER BY count() DESC) AS rnk
197
+ FROM @T@ WHERE _part IN {parts:Array(String)} AND @W@ GROUP BY hc ORDER BY count() DESC LIMIT {values:UInt32}) AS b
198
+ ORDER BY rnk, hk)) AS pr,""" + _ARRAYS + _TAIL_EQ.replace("@EXTRA@", ", pr.3 AS value_share, pr.4 AS value_rank"),
199
+ # a range filter (column >= threshold) for minmax: the column's 99.9th, 99th and 90th percentile as thresholds. The
200
+ # column is compared as Float64 (@NUM@): quantilesTDigest refuses DateTime64 and Decimal, and Date, DateTime, their
201
+ # Nullable / LowCardinality wrappers and every number convert to it in order (NULL stays NULL: neither kept nor needed)
202
+ "ch.locality.skip_range": "WITH\n " + _HI + """,
203
+ (SELECT quantilesTDigest(0.999, 0.99, 0.9)(@NUM@) FROM @T@ WHERE _part IN {parts:Array(String)}) AS thr,
204
+ (SELECT groupArray(hk) FROM (SELECT @KEY@ AS hk FROM @T@ WHERE _part IN {parts:Array(String)} AND @W@
205
+ ORDER BY cityHash64(_part, _part_offset, {seed:UInt32}) LIMIT {probes:UInt32})) AS pk,
206
+ arrayDistinct(pk) AS dk, (SELECT arrayMap(x -> indexOf(arrayDistinct(pk), x) - 1, pk)) AS ik
207
+ SELECT count() AS granules, sum(n) AS rows_scanned, length(pk) AS probes, length(thr) AS thresholds,
208
+ sumForEach(arrayMap(a -> toUInt32(bitTest(km, a)), ik)) AS key_granules,
209
+ sumForEach(arrayFlatten(arrayMap(t -> arrayMap(a -> toUInt32(bitTest(km, a) AND cmax >= t), ik), thr))) AS index_granules,
210
+ sumForEach(arrayFlatten(arrayMap(m -> arrayMap(a -> toUInt32(bitTest(m, a)), ik), nm))) AS needed_granules
211
+ FROM (
212
+ SELECT _part, @GRANULE@ AS g, count() AS n, max(@NUM@) AS cmax,
213
+ groupBitOr(bitShiftRight(bitShiftLeft(toUInt64(1), indexOf(dk, @KEY@) * @W@), 1)) AS km,
214
+ [groupBitOr(bitShiftRight(bitShiftLeft(toUInt64(1), indexOf(dk, @KEY@) * (@W@ AND @NUM@ >= thr[1])), 1)),
215
+ groupBitOr(bitShiftRight(bitShiftLeft(toUInt64(1), indexOf(dk, @KEY@) * (@W@ AND @NUM@ >= thr[2])), 1)),
216
+ groupBitOr(bitShiftRight(bitShiftLeft(toUInt64(1), indexOf(dk, @KEY@) * (@W@ AND @NUM@ >= thr[3])), 1))] AS nm
217
+ FROM @T@ WHERE _part IN {parts:Array(String)}
218
+ GROUP BY _part, g)""",
219
+ # a re-key or a projection: granules the present key selects per probe, rows the new key prefix matches per part
220
+ "ch.locality.key_order": "WITH\n " + _HI + """,
221
+ (SELECT (groupArray(ho), groupArray(hn)) FROM (
222
+ SELECT @OLD@ AS ho, @NEW@ AS hn FROM @T@ WHERE _part IN {parts:Array(String)} AND @W@
223
+ ORDER BY cityHash64(_part, _part_offset, {seed:UInt32}) LIMIT {probes:UInt32})) AS pr,
224
+ pr.1 AS po, pr.2 AS pn, arrayDistinct(po) AS d_old, arrayDistinct(pn) AS d_new,
225
+ (SELECT arrayMap(x -> indexOf(arrayDistinct(pr.1), x) - 1, pr.1)) AS io,
226
+ (SELECT arrayMap(x -> indexOf(arrayDistinct(pr.2), x), pr.2)) AS jn
227
+ SELECT sum(granules) AS granules, sum(part_rows) AS rows_scanned, length(po) AS probes, count() AS parts, sum(in_scope) AS parts_in_scope,
228
+ sumForEach(old_g) AS present_granules,
229
+ sumForEach(arrayMap(r -> if(in_scope, 1 + r / {new_granule_rows:UInt32}, 0), new_rows)) AS new_granules,
230
+ sumForEach(arrayMap(r -> toUInt32(r > 0), new_rows)) AS new_parts,
231
+ sumForEach(new_rows) AS matching_rows
232
+ FROM (
233
+ SELECT _part, count() AS granules, sum(n) AS part_rows,
234
+ ({window_s:UInt32} = 0 OR max(tmax) >= hi - toIntervalSecond({window_s:UInt32})) AS in_scope,
235
+ sumForEach(arrayMap(a -> toUInt32(bitTest(km, a)), io)) AS old_g,
236
+ sumMap(nr.1, nr.2) AS nrm,
237
+ arrayMap(j -> if(indexOf(nrm.1, j) > 0, nrm.2[indexOf(nrm.1, j)], 0), jn) AS new_rows
238
+ FROM (
239
+ SELECT _part, @GRANULE@ AS g, count() AS n, max(@TIME@) AS tmax,
240
+ groupBitOr(bitShiftRight(bitShiftLeft(toUInt64(1), indexOf(d_old, @OLD@) * @W@), 1)) AS km,
241
+ sumMapIf([indexOf(d_new, @NEW@)], [toUInt64(1)], indexOf(d_new, @NEW@) > 0 AND @W@) AS nr
242
+ FROM @T@ WHERE _part IN {parts:Array(String)}
243
+ GROUP BY _part, g)
244
+ GROUP BY _part)""",
245
+ }
246
+ PURPOSE = {
247
+ "ch.locality.skip_eq": "Equality / IN on a column (set, bloom_filter, any GRANULARITY), simulated without building the index: per probe "
248
+ "drawn from rows, granules the key selects, granules an index keeps, granules a set(N) keeps, granules that hold "
249
+ "a matching row. Counts only.",
250
+ "ch.locality.skip_eq_ranked": "The same for a column of few values, per value by frequency rank (its share of rows and rank only, never "
251
+ "the value). Counts only.",
252
+ "ch.locality.skip_range": "A range filter (minmax): per probe and threshold (the column's 99.9th, 99th, 90th percentile), granules the "
253
+ "key selects, granules a minmax index keeps, granules that hold a matching row. Counts only.",
254
+ "ch.locality.key_order": "A re-key or a projection: per probe, granules the present key selects and rows the new key prefix matches "
255
+ "per part, parts in the window. Counts only.",
256
+ }
257
+ KINDS = tuple(TEMPLATES)
258
+
259
+
260
+ def check_ident(*names: str) -> None:
261
+ for name in names:
262
+ if not IDENT.match(name or ""):
263
+ raise DbError(f"`{name}` is not a plain identifier: not counted.")
264
+
265
+
266
+ def q(name: str) -> str:
267
+ check_ident(name)
268
+ return f"`{name}`"
269
+
270
+
271
+ def hash_of(columns: list[str]) -> str:
272
+ """cityHash64 of the columns (the probe's key), or a constant when the statement pins no key column."""
273
+ return f"cityHash64({', '.join(q(c) for c in columns)})" if columns else "toUInt64(0)"
274
+
275
+
276
+ def granule_form(version: str) -> str:
277
+ """`exact` (the server numbers granules: _part_granule_offset) or `offset` (_part_offset / rows per mark)."""
278
+ def parts(v: str) -> list[int]:
279
+ return [int(x) for x in re.findall(r"\d+", str(v or ""))[:3]] or [0]
280
+ return "exact" if version and parts(version) >= parts(GRANULE_OFFSET_VERSION) else "offset"
281
+
282
+
283
+ def build(statement_id: str, *, database: str, table: str, time_column: str | None, key: list[str] | None = None,
284
+ column: str | None = None, old: list[str] | None = None, new: list[str] | None = None, form: str = "exact",
285
+ limits: Limits = LOCALITY_LIMITS) -> Statement:
286
+ """One locality statement with the catalog's identifiers in place. Raises DbError for a name that is not a plain
287
+ identifier (nothing is sent then)."""
288
+ sql = TEMPLATES[statement_id]
289
+ time_expr = q(time_column) if time_column else "toDateTime(0)"
290
+ subs = {"@T@": f"{q(database)}.{q(table)}", "@TIME@": time_expr, "@KEY@": hash_of(key or []), "@OLD@": hash_of(old or []),
291
+ "@NEW@": hash_of(new or []), "@GRANULE@": "_part_granule_offset" if form == "exact" else "intDiv(_part_offset, {rows_per_mark:UInt32})"}
292
+ if column is not None:
293
+ subs["@COL@"] = q(column)
294
+ subs["@NUM@"] = f"toFloat64({q(column)})"
295
+ sql = sql.replace("@W@", _W)
296
+ for k, v in subs.items():
297
+ sql = sql.replace(k, v)
298
+ if "@" in re.sub(r"'[^']*'", "", sql):
299
+ raise DbError(f"{statement_id}: an identifier is missing.")
300
+ return Statement(statement_id, "D", sql, PURPOSE[statement_id], limits)
301
+
302
+
303
+ # ---- what is asked: requests from the advisor's candidates ---------------------------------------------------------
304
+
305
+ def _table_of(catalog: dict, name: str) -> dict | None:
306
+ short = name.split(".")[-1].strip("`\"")
307
+ for conn in (catalog.get("connections") or {}).values():
308
+ if conn.get("engine") != "clickhouse":
309
+ continue
310
+ for t in conn.get("tables") or []:
311
+ if t.get("name") == short or f"{t.get('database')}.{t.get('name')}" == name:
312
+ return t
313
+ return None
314
+
315
+
316
+ def _version(catalog: dict) -> str:
317
+ return next((str(c.get("version") or "") for c in (catalog.get("connections") or {}).values() if c.get("engine") == "clickhouse"), "")
318
+
319
+
320
+ def index_granularity(create_sql: str) -> int:
321
+ m = re.search(r"\bindex_granularity\s*=\s*(\d+)", create_sql or "", re.I)
322
+ return int(m.group(1)) if m else 8192
323
+
324
+
325
+ def rows_per_mark(t: dict) -> float | None:
326
+ d = t.get("partition_parts") or {}
327
+ rows, marks = sum(d.get("rows") or []), sum(d.get("marks") or [])
328
+ return rows / marks if rows and marks else None
329
+
330
+
331
+ def time_column_of(t: dict) -> str | None:
332
+ """The time column parts are cut by: the first Date/DateTime column of the partition key, else of the sorting key."""
333
+ from ..parts import time_column
334
+ types = {c["name"]: c.get("type") or "" for c in t.get("columns") or []}
335
+ found = time_column(t.get("partition_key") or "", t.get("sorting_key") or "", types)
336
+ return found[0] if found else None
337
+
338
+
339
+ def _sorting_key(t: dict) -> list[str]:
340
+ return [k.strip().strip("`") for k in re.split(r",(?![^(]*\))", t.get("sorting_key") or "") if k.strip()]
341
+
342
+
343
+ def _plain_cols(t: dict) -> set[str]:
344
+ return {c["name"] for c in t.get("columns") or [] if IDENT.match(c["name"])}
345
+
346
+
347
+ def _shape_of(plan: dict | None, refs: list[str]) -> dict | None:
348
+ """The heaviest served statement of the plan (its filters, weight, measured marks)."""
349
+ stmts = [s for s in (plan or {}).get("statements") or [] if s["ref"] in refs]
350
+ return max(stmts, key=lambda s: (s.get("weight") or 0, -refs.index(s["ref"]))) if stmts else None
351
+
352
+
353
+ def statement_for(s: dict) -> str | None:
354
+ """Which of the four statements counts this suggestion, or None when its shape can not be counted."""
355
+ kind, ed = s["kind"], s.get("engine_detail") or {}
356
+ if kind in ("projection", "ordering_key"):
357
+ return "ch.locality.key_order"
358
+ if kind == "aggregating_projection":
359
+ return "ch.locality.key_order" if ed.get("usable", True) else None
360
+ if kind != "skip_index":
361
+ return None
362
+ ops = set(ed.get("operators") or [])
363
+ typ = str(ed.get("type") or "")
364
+ if ops & {"eq", "in"} and typ.startswith(("set", "bloom_filter", "minmax")):
365
+ return "ch.locality.skip_eq_ranked" if typ.startswith("set") else "ch.locality.skip_eq"
366
+ if ops == {"range"} and typ.startswith("minmax"):
367
+ return "ch.locality.skip_range"
368
+ return None
369
+
370
+
371
+ NOT_COUNTED = {
372
+ "like": "LIKE, token and array or map lookups are not counted (an n-gram or token index needs the text itself)",
373
+ "expression": "the index is on an expression, not a column: not counted",
374
+ "not_simulated_kind": "this kind of change is not counted on production",
375
+ }
376
+
377
+
378
+ def requests(advisor_doc: dict, catalog: dict, settings: dict) -> tuple[list[dict], list[dict]]:
379
+ """(requests, set aside): one request per suggestion whose read side the sandbox can not judge (a skip index on a
380
+ column whose placement production alone knows) or whose key order it checks (projections, re-keys), heaviest load
381
+ first, with everything the statement needs but the parts. Set aside: why a suggestion gets no statement."""
382
+ doc = (advisor_doc.get("engines") or {}).get("clickhouse") if "engines" in advisor_doc else advisor_doc
383
+ doc = doc or {}
384
+ plans = {p["table"]: p for p in doc.get("tables") or []}
385
+ version = _version(catalog)
386
+ form = granule_form(version)
387
+ out, aside = [], []
388
+ for s in doc.get("table_suggestions") or []:
389
+ ed = s.get("engine_detail") or {}
390
+ sid = statement_for(s)
391
+ refs = [sv["statement"] for sv in s.get("serves") or []]
392
+ weight = sum(int(sv.get("weight") or 0) for sv in s.get("serves") or [])
393
+ base = {"suggestion": s["id"], "fingerprint": s["fingerprint"], "kind": s["kind"], "table": s["table"], "weight": weight,
394
+ "load_share": (s.get("read_gain") or {}).get("load_share")}
395
+ if s["kind"] == "skip_index" and ed.get("measurable"):
396
+ continue # the sandbox's own verdict counts (the column is in the key, is the time column, ...)
397
+ if sid is None:
398
+ if s["kind"] == "skip_index":
399
+ aside.append({**base, "reason": "like" if set(ed.get("operators") or []) - {"eq", "in", "range"} else "not_simulated_kind"})
400
+ continue
401
+ t = _table_of(catalog, s["table"])
402
+ if t is None or "MergeTree" not in str(t.get("engine") or ""):
403
+ aside.append({**base, "reason": "no_catalog_table"})
404
+ continue
405
+ cols = _plain_cols(t)
406
+ types = {c["name"]: c.get("type") or "" for c in t.get("columns") or []}
407
+ shape = _shape_of(plans.get(s["table"]), refs)
408
+ if shape is None:
409
+ aside.append({**base, "reason": "no_statement_shape"})
410
+ continue
411
+ filters = shape.get("filters") or []
412
+ timecol = time_column_of(t)
413
+ timed = bool(timecol) and any(f["column"] == timecol and f["op"] == "range" for f in filters)
414
+ window_h = shape.get("time_window_hours") or (int(settings["locality_window_hours"]) if timed else 0)
415
+ skey = _sorting_key(t)
416
+ pinned = [f["column"] for f in filters if f["op"] in ("eq", "in")]
417
+ # the present key's prefix the statement pins (a range ends it, as key_service says)
418
+ present = []
419
+ for k in skey:
420
+ if k in pinned and k in cols:
421
+ present.append(k)
422
+ continue
423
+ break
424
+ req = {**base, "statement_id": sid, "database": t["database"], "table_name": t["name"], "time_column": timecol,
425
+ "window_hours": window_h, "window_basis": ("the statement's bound" if shape.get("time_window_hours") else
426
+ "assumed (db_pull.locality_window_hours)" if timed else "none"),
427
+ "statement": shape["ref"], "form": form, "version": version, "rows_per_mark": rows_per_mark(t),
428
+ "time_in_partition": bool(timecol and re.search(rf"\b{re.escape(timecol)}\b", t.get("partition_key") or "")),
429
+ "index_granularity_table": index_granularity(t.get("create_sql") or ""),
430
+ "marks_per_run": (shape.get("measured") or {}).get("selected_marks_per_run"),
431
+ "parts_per_run": (shape.get("measured") or {}).get("selected_parts_per_run")}
432
+ if sid.startswith("ch.locality.skip"):
433
+ col = ed.get("column")
434
+ if not col or col not in cols or ed.get("expr", col) != col:
435
+ aside.append({**base, "reason": "expression"})
436
+ continue
437
+ req.update(column=col, key=[k for k in present if k != col], index_type=ed.get("type"),
438
+ index_granularity=int((ed.get("granularities") or [1])[0]),
439
+ set_values=int(re.search(r"\d+", ed.get("type") or "set(100)").group(0)) if str(ed.get("type")).startswith("set") else 0)
440
+ if sid == "ch.locality.skip_range" and not NUMERIC.match(types.get(col, "")):
441
+ aside.append({**base, "reason": "not_simulated_kind"})
442
+ continue
443
+ else:
444
+ if s["kind"] == "ordering_key":
445
+ new_key = list(ed.get("new_key") or [])
446
+ elif s["kind"] == "projection":
447
+ new_key = list(ed.get("order_by") or [])
448
+ else:
449
+ new_key = list(ed.get("group_by") or [])
450
+ new = []
451
+ for k in new_key:
452
+ if k in pinned and k in cols:
453
+ new.append(k)
454
+ continue
455
+ break
456
+ if s["kind"] == "aggregating_projection":
457
+ new = [k for k in new_key if k in pinned and k in cols]
458
+ if not new and s["kind"] != "aggregating_projection":
459
+ aside.append({**base, "reason": "no_pinned_prefix"})
460
+ continue
461
+ ranged = {f["column"] for f in filters if f["op"] in ("range", "like_prefix")}
462
+ after = new_key[len(new)] if len(new) < len(new_key) and s["kind"] != "aggregating_projection" else None
463
+ if after in ranged and after != timecol:
464
+ # the new key also prunes by a range after its pinned prefix (tenant, latency > ?): rows per prefix do
465
+ # not count that, and the answer would miss the gain. Not counted: the sandbox's marks judge it alone
466
+ aside.append({**base, "reason": "range_in_new_key"})
467
+ continue
468
+ req.update(old=present, new=new, aggregating=s["kind"] == "aggregating_projection",
469
+ new_granule_rows=int(round(rows_per_mark(t) or index_granularity(t.get("create_sql") or "")))
470
+ if s["kind"] == "ordering_key" else index_granularity(t.get("create_sql") or ""))
471
+ req.update(value_of(req, t))
472
+ out.append(req)
473
+ out.sort(key=lambda r: (-r["value"], -(r["weight"] or 0), -(r.get("load_share") or 0), r["fingerprint"]))
474
+ return out, aside
475
+
476
+
477
+ def value_of(req: dict, t: dict) -> dict:
478
+ """What counting this candidate is worth, to spend the statements on the best first: the measured production load
479
+ of the statements it serves (bytes they read in the pulled window: bytes per run x runs) times the table's rows.
480
+ The load alone is not enough: a statement's load is the whole statement's, so a join's small side carried the large
481
+ side's load and was counted first. A statement with no measured load counts as one byte (the table's size orders)."""
482
+ rows = int(t["rows"]) if t.get("rows") is not None else None
483
+ return {"table_rows": rows, "value": float(max(int(req.get("weight") or 0), 1)) * max(rows or 0, 1)}
484
+
485
+
486
+ def too_small(req: dict, settings: dict) -> str | None:
487
+ """Why a candidate is nothing to gain without a statement: its table holds fewer rows than
488
+ db_pull.locality_min_table_rows (default: a few granules). Such a table is read whole in a few granules by any
489
+ statement; no index, projection or key reads meaningfully less."""
490
+ rows = req.get("table_rows")
491
+ floor = int(settings.get("locality_min_table_rows") or 0)
492
+ if rows is None or rows >= floor:
493
+ return None
494
+ granule = max(int(req.get("index_granularity_table") or 8192), 1)
495
+ return (f"the table holds {rows:,} rows ({max(1, -(-rows // granule))} granule(s) of {granule:,}), under "
496
+ f"db_pull.locality_min_table_rows ({floor:,}): any statement reads it whole in a few granules, nothing to gain")
497
+
498
+
499
+ # ---- choosing parts inside the row budget -------------------------------------------------------------------------
500
+
501
+ def choose_parts(parts: list[dict], budget_rows: int, window_hours: float, max_parts: int | None = None) -> tuple[list[str], dict]:
502
+ """Recent parts whose rows sum to at most `budget_rows`, at most `max_parts` of them. With a time window: the newest
503
+ parts that reach into it, newest first. Without one: the newest part of each partition first (newest partition
504
+ first), then the next newest of each, so the parts spread over the range a statement with no time bound reads.
505
+ Returns (names, what was chosen).
506
+
507
+ Why a count of parts as well as rows: a statement's memory and time grow with the parts it opens, not only with their
508
+ rows (every pass opens every part. Measured locally on 25.8 and 26.6, 200-row parts, key_order over 400 k rows: 2,000 parts 505 MiB
509
+ and 34 s cold; 256 parts 166 MiB; the same rows merged into 46 parts 15 MiB). Statements over a few hundred k rows
510
+ in thousands of small parts can be refused far inside the row cap."""
511
+ rows_of = {p["part"]: int(p.get("rows") or 0) for p in parts}
512
+ ordered = sorted(parts, key=lambda p: (-int(p.get("max_t") or 0), -int(p.get("modified") or 0), p["part"]))
513
+ newest = max((int(p.get("max_t") or 0) for p in parts), default=0)
514
+ if window_hours and newest:
515
+ lo = newest - int(window_hours * 3600)
516
+ pool = [p for p in ordered if int(p.get("max_t") or 0) >= lo] or ordered[:1]
517
+ why = "the newest parts that reach into the window"
518
+ else:
519
+ by_part: dict[str, list[dict]] = {}
520
+ for p in ordered:
521
+ by_part.setdefault(str(p.get("partition_id")), []).append(p)
522
+ pool, i = [], 0
523
+ while any(i < len(v) for v in by_part.values()):
524
+ pool += [v[i] for v in by_part.values() if i < len(v)]
525
+ i += 1
526
+ why = "the newest part of each partition first"
527
+ chosen, total = [], 0
528
+ for p in pool:
529
+ if max_parts and len(chosen) >= max_parts:
530
+ break
531
+ r = rows_of[p["part"]]
532
+ if r <= 0 or total + r > budget_rows:
533
+ continue
534
+ chosen.append(p["part"])
535
+ total += r
536
+ in_scope = sum(rows_of[p["part"]] for p in pool)
537
+ out = {"parts": len(chosen), "rows": total, "parts_listed": len(parts), "rows_listed": sum(rows_of.values()),
538
+ "parts_in_scope": len(pool), "rows_in_scope": in_scope, "basis": why, "cut": total < in_scope}
539
+ if max_parts and len(chosen) >= max_parts and total < in_scope:
540
+ out["cut_by"] = f"db_pull.locality_parts_per_statement ({max_parts:,})"
541
+ return chosen, out
542
+
543
+
544
+ # ---- running ---------------------------------------------------------------------------------------------------------
545
+
546
+ def planned_cost(rows: int, settings: dict, req: dict | None = None, params: dict | None = None) -> dict:
547
+ """What one statement over `rows` rows of parts is planned to read and cost (SCANS). `rows_read`: the estimate, what
548
+ the server is expected to report; `rows_limit`: the cap sent as max_rows_to_read, every pass at full size plus each
549
+ draw's lazy re-read, so a refusal means the statement read more than it can legitimately read. CPU: an estimate from
550
+ db_pull.locality_cpu_ns_per_row per row of parts."""
551
+ req, params = req or {}, params or {}
552
+ sid = req.get("statement_id") or "ch.locality.skip_eq"
553
+ windowed = bool(params["window_s"]) if "window_s" in params else bool(req.get("window_hours")) and bool(req.get("time_column"))
554
+ granule = max(int(round(req.get("rows_per_mark") or req.get("index_granularity_table") or 8192)), 1)
555
+ lazy_on = _ver(req.get("version") or "") >= _ver(LAZY_VERSION)
556
+ upper = estimate = 0.0
557
+ for name, bounded, limit in SCANS[sid]:
558
+ upper += rows
559
+ if name == "hi":
560
+ estimate += 0 if req.get("time_in_partition") else rows
561
+ else: # a pass bounded by the window reads what the key keeps of it: half, as an estimate
562
+ estimate += rows * (0.5 if bounded and windowed else 1.0)
563
+ if limit:
564
+ again = min(rows, int(params.get(limit) or settings.get("locality_probes") or 63) * granule)
565
+ upper += again
566
+ estimate += again if lazy_on else 0
567
+ return {"rows_of_parts": rows, "rows_read": int(round(estimate)), "rows_limit": int(upper * 1.1) + ROWS_SLACK,
568
+ "passes": len(SCANS[sid]), "cpu_s_estimate": round(rows * int(settings["locality_cpu_ns_per_row"]) / 1e9, 2)}
569
+
570
+
571
+ def _ver(v: str) -> list[int]:
572
+ return [int(x) for x in re.findall(r"\d+", str(v or ""))[:3]] or [0]
573
+
574
+
575
+ def params_of(req: dict, parts: list[str], settings: dict, seed: int) -> dict:
576
+ p = {"parts": parts, "window_s": int(round(float(req.get("window_hours") or 0) * 3600)), "seed": seed}
577
+ if req.get("time_column") is None:
578
+ p["window_s"] = 0
579
+ if req["form"] != "exact":
580
+ p["rows_per_mark"] = max(int(round(req.get("rows_per_mark") or req.get("index_granularity_table") or 8192)), 1)
581
+ sid = req["statement_id"]
582
+ probes = max(1, min(int(settings["locality_probes"]), 63))
583
+ if sid == "ch.locality.skip_eq_ranked":
584
+ values = 4
585
+ p.update(keys=max(1, min(probes // values, 15)), values=values, index_granularity=req["index_granularity"],
586
+ set_values=req["set_values"] or 100)
587
+ elif sid == "ch.locality.skip_eq":
588
+ p.update(probes=probes, index_granularity=req["index_granularity"], set_values=req["set_values"] or 100)
589
+ elif sid == "ch.locality.skip_range":
590
+ p.update(probes=min(probes, 21))
591
+ else:
592
+ p.update(probes=probes, new_granule_rows=sent_granule_rows(req))
593
+ return p
594
+
595
+
596
+ def sent_granule_rows(req: dict) -> int:
597
+ """The rows per new granule key_order is sent with: the table's index granularity, for every candidate of the table,
598
+ so a re-key (whose granules follow the real rows per mark) and a projection on the same prefix need one statement.
599
+ The answer is linear in it (new granules per probe = parts in scope + matching rows / rows per granule): read()
600
+ rescales it to the candidate's own `new_granule_rows`."""
601
+ return max(int(req.get("index_granularity_table") or req.get("new_granule_rows") or 8192), 1)
602
+
603
+
604
+ def statement_of(req: dict) -> Statement:
605
+ return build(req["statement_id"], database=req["database"], table=req["table_name"], time_column=req.get("time_column"),
606
+ key=req.get("key"), column=req.get("column"), old=req.get("old"), new=req.get("new"), form=req["form"])
607
+
608
+
609
+ def run(reader, advisor_doc: dict, catalog: dict, settings: dict, log=lambda msg: None) -> dict:
610
+ """Send the planned statements (or, with the reader's dry_run, list them). Returns the db_locality.json document."""
611
+ from . import with_limits
612
+ from .clickhouse import refusal_reason
613
+ s = {**DEFAULTS, **{k: v for k, v in settings.items() if k in DEFAULTS}}
614
+ reqs, aside = requests(advisor_doc, catalog, s)
615
+ per_stmt = int(s["locality_rows_per_statement"])
616
+ stmt_limits = with_limits(Statement("ch.locality.skip_eq", "D", "", "", LOCALITY_LIMITS), settings.get("limits")).limits
617
+ if per_stmt * PASSES * 1.2 > stmt_limits.rows_to_read: # every pass, the draws' re-reads and the cap's margin fit
618
+ per_stmt = int(stmt_limits.rows_to_read / (PASSES * 1.2))
619
+ doc = {"schema_version": SCHEMA_VERSION, "generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
620
+ "version": _version(catalog), "granule_form": granule_form(_version(catalog)),
621
+ "budget": {"rows_per_statement": per_stmt, "max_statements": int(s["locality_max_statements"]),
622
+ "cpu_seconds_total": float(s["locality_cpu_seconds_total"]), "probes": int(s["locality_probes"]),
623
+ "draws": int(s["locality_draws"])},
624
+ "settings": {k: s[k] for k in ("locality_window_hours", "locality_min_table_rows")},
625
+ "candidates": len(reqs) + len(aside), "requests": len(reqs), "results": [], "set_aside": aside,
626
+ "dry_run": bool(getattr(reader, "dry_run", False)), "notes": []}
627
+ parts_of: dict[tuple, list[dict] | None] = {}
628
+ shared: dict[tuple, dict] = {}
629
+ spent_cpu, sent, ids = 0.0, 0, {}
630
+ for req in reqs:
631
+ res = {k: req[k] for k in ("suggestion", "fingerprint", "kind", "table", "statement_id", "statement", "window_hours",
632
+ "window_basis", "form", "weight")}
633
+ res.update({k: req[k] for k in ("column", "index_type", "index_granularity", "key", "old", "new", "aggregating", "new_granule_rows")
634
+ if k in req})
635
+ if req["statement_id"] == "ch.locality.key_order":
636
+ res["sent_granule_rows"] = sent_granule_rows(req)
637
+ res["count_key"] = count_key(req)
638
+ res["granule_basis"] = "exact (the server's own granule numbers)" if req["form"] == "exact" else (
639
+ "exact (narrow rows: rows per mark is the index granularity)"
640
+ if req.get("rows_per_mark") and req["rows_per_mark"] >= 0.95 * req["index_granularity_table"] else
641
+ "estimate (the part's average rows per mark; the server is older than 25.8)")
642
+ if req["form"] != "exact" and res["granule_basis"].startswith("estimate"):
643
+ res["estimate"] = True
644
+ res["table_rows"] = req.get("table_rows")
645
+ small = too_small(req, s)
646
+ if small:
647
+ doc["results"].append({**res, "status": "nothing_to_gain", "reason": small})
648
+ continue
649
+ try:
650
+ stmt = with_limits(statement_of(req), settings.get("limits"))
651
+ except DbError as e:
652
+ doc["results"].append({**res, "status": "not_counted", "reason": str(e)[:200]})
653
+ continue
654
+ # candidates that need the identical count (same table, statement, columns, parameters, window) share one
655
+ # statement: a re-key and a projection on the same new key prefix, a bloom filter and a minmax on one column
656
+ same = (stmt.sql, json.dumps({k: v for k, v in params_of(req, [], s, seed=1).items() if k != "parts"}, sort_keys=True),
657
+ req.get("window_hours"))
658
+ if same in shared:
659
+ first = shared[same]
660
+ res.update({k: first[k] for k in ("status", "reason", "answer", "parts", "planned", "sent_granule_rows") if k in first})
661
+ res["shared_with"] = first["suggestion"]
662
+ doc["results"].append(res)
663
+ continue
664
+ shared[same] = res # filled in below, before the next candidate reads it
665
+ if sent >= int(s["locality_max_statements"]):
666
+ doc["results"].append(_settle(res, "over_budget", f"db_pull.locality_max_statements ({sent}) reached"))
667
+ continue
668
+ if spent_cpu >= float(s["locality_cpu_seconds_total"]):
669
+ doc["results"].append(_settle(res, "over_budget", f"db_pull.locality_cpu_seconds_total ({spent_cpu:.1f} s) reached"))
670
+ continue
671
+ key = (req["database"], req["table_name"])
672
+ if key not in parts_of:
673
+ if getattr(reader, "dry_run", False):
674
+ parts_of[key] = _parts_from_catalog(catalog, req)
675
+ reader.run_statement(PARTS, {"db": req["database"], "table": req["table_name"], "max_parts": int(s["locality_max_parts"])})
676
+ else:
677
+ try:
678
+ parts_of[key] = reader.run_statement(PARTS, {"db": req["database"], "table": req["table_name"],
679
+ "max_parts": int(s["locality_max_parts"])})
680
+ except Refused as e:
681
+ parts_of[key] = None
682
+ doc["notes"].append(f"{req['table']}: the table's parts could not be listed ({refusal_reason(str(e))})")
683
+ parts = parts_of[key]
684
+ if parts is None:
685
+ doc["results"].append(_settle(res, "refused", "the table's parts could not be listed"))
686
+ continue
687
+ chosen, how = choose_parts(parts, per_stmt, float(req.get("window_hours") or 0),
688
+ int(s["locality_parts_per_statement"])) if parts else ([], {"parts": 0, "rows": 0})
689
+ res["parts"] = {k: v for k, v in how.items()}
690
+ params = params_of(req, chosen or ["<parts chosen at run time>"], s, seed=1)
691
+ planned = planned_cost(how.get("rows") or 0, s, req, params)
692
+ res["planned"] = planned
693
+ if not chosen:
694
+ doc["results"].append(_settle(res, "over_budget", "every part in scope holds more rows than "
695
+ f"db_pull.locality_rows_per_statement ({per_stmt:,})"))
696
+ continue
697
+ from dataclasses import replace
698
+ stmt = replace(stmt, limits=replace(stmt.limits, rows_to_read=min(stmt.limits.rows_to_read, planned["rows_limit"])))
699
+ qid = f"codecop-locality-{uuid.uuid4().hex[:16]}"
700
+ started = time.monotonic()
701
+ try:
702
+ reader.extra_settings = {"query_id": qid}
703
+ rows = reader.run_statement(stmt, params)
704
+ except Refused as e:
705
+ res.update(status="refused", reason=refusal_reason(str(e), stmt.limits))
706
+ if res["reason"].startswith("a limit stopped it"):
707
+ res["reason"] += f", over {how.get('parts')} part(s) of {how.get('rows', 0):,} rows"
708
+ if req["form"] == "exact" and "UNKNOWN_IDENTIFIER" in str(e):
709
+ res["reason"] += ": the server has no _part_granule_offset"
710
+ doc["results"].append(res)
711
+ sent += 1
712
+ spent_cpu += (time.monotonic() - started) * stmt.limits.threads
713
+ continue
714
+ except DbError as e:
715
+ res.update(status="refused", reason=str(e)[:200])
716
+ doc["results"].append(res)
717
+ continue
718
+ finally:
719
+ reader.extra_settings = {}
720
+ wall = time.monotonic() - started
721
+ if getattr(reader, "dry_run", False):
722
+ res["status"] = "planned"
723
+ doc["results"].append(res)
724
+ sent += 1
725
+ spent_cpu += planned["cpu_s_estimate"] # the plan stops where the estimate reaches the CPU budget
726
+ continue
727
+ sent += 1
728
+ ids[qid] = res
729
+ res["cost"] = {"wall_s": round(wall, 2), "cpu_s_upper_bound": round(wall * stmt.limits.threads, 2), "query_id_local": qid}
730
+ spent_cpu += wall * stmt.limits.threads
731
+ if not rows:
732
+ res.update(status="refused", reason="the server returned no row")
733
+ else:
734
+ res.update(status="answered", answer=_clean(rows[0]))
735
+ doc["results"].append(res)
736
+ log(f"{req['statement_id']} for {req['suggestion']} ({req['kind']} on {req['table']}): {res['status']}, "
737
+ f"{how.get('parts')} part(s), {how.get('rows', 0):,} rows, {wall:.1f} s")
738
+ if ids and not getattr(reader, "dry_run", False):
739
+ _server_costs(reader, ids, s, doc)
740
+ doc["spent"] = {"statements": sent, "cpu_s_upper_bound": round(spent_cpu, 2),
741
+ "cpu_s_server": round(sum((r.get("cost") or {}).get("cpu_s_server") or 0 for r in doc["results"]), 2)
742
+ if any((r.get("cost") or {}).get("cpu_s_server") is not None for r in doc["results"]) else None,
743
+ "rows_read_server": sum((r.get("cost") or {}).get("read_rows") or 0 for r in doc["results"]) or None}
744
+ for r in doc["results"]:
745
+ (r.get("cost") or {}).pop("query_id_local", None)
746
+ return doc
747
+
748
+
749
+ def _settle(res: dict, status: str, reason: str) -> dict:
750
+ """The result itself with its status (in place: a candidate sharing its count reads it)."""
751
+ res.update(status=status, reason=reason)
752
+ return res
753
+
754
+
755
+ def _parts_from_catalog(catalog: dict, req: dict) -> list[dict]:
756
+ """For --dry-run (nothing is sent): one stand-in part per partition the pulled catalog knows, newest first."""
757
+ t = _table_of(catalog, req["table"]) or {}
758
+ d = t.get("partition_parts") or {}
759
+ out = []
760
+ from ..sizes import partition_day
761
+ ids = list(d.get("ids") or [])
762
+ days = [partition_day(p) for p in ids]
763
+ for i, (pid, n, rows) in enumerate(zip(ids, d.get("parts") or [], d.get("rows") or [])):
764
+ n = max(int(n or 1), 1)
765
+ # a part's newest row: the start of the next newer period (the partition's last change, else a month per step)
766
+ newer = days[i - 1] if i and days[i - 1] else None
767
+ last = (d.get("last_modified") or [None] * len(ids))[i]
768
+ end = int(datetime.combine(newer, datetime.min.time(), timezone.utc).timestamp()) if newer else int(last or 0) or 10 ** 9 - i * 86400 * 30
769
+ for j in range(n):
770
+ out.append({"part": f"{pid}#{j}", "partition_id": pid, "rows": int(rows or 0) // n, "max_t": end - j, "modified": end - j})
771
+ if not out and t.get("rows"): # no parts per partition pulled: the table's parts, of equal size
772
+ n = max(int(t.get("parts") or 1), 1)
773
+ out = [{"part": f"part#{j}", "partition_id": str(j % max(int(t.get("partitions") or 1), 1)), "rows": int(t["rows"]) // n,
774
+ "max_t": 0, "modified": 10 ** 9 - j} for j in range(n)]
775
+ return out
776
+
777
+
778
+ def _clean(row: dict) -> dict:
779
+ """The answer kept: numbers and arrays of numbers only (what the statement returns); anything else is dropped."""
780
+ def num(v):
781
+ return isinstance(v, (int, float)) and not isinstance(v, bool)
782
+
783
+ out = {}
784
+ for k, v in row.items():
785
+ if num(v):
786
+ out[k] = v
787
+ elif isinstance(v, str) and re.fullmatch(r"-?\d+(?:\.\d+)?(?:e[-+]?\d+)?", v):
788
+ out[k] = float(v) if re.search(r"[.e]", v) else int(v)
789
+ elif isinstance(v, list) and all(num(x) or (isinstance(x, str) and re.fullmatch(r"-?\d+(?:\.\d+)?(?:e[-+]?\d+)?", x)) for x in v):
790
+ out[k] = [float(x) if isinstance(x, str) and re.search(r"[.e]", x) else int(x) if isinstance(x, str) else x for x in v]
791
+ return out
792
+
793
+
794
+ def _server_costs(reader, ids: dict, s: dict, doc: dict) -> None:
795
+ """The server's own CPU, memory and rows read for each statement sent, from its query log (it writes it within
796
+ seconds; a few tries)."""
797
+ from .clickhouse import refusal_reason
798
+ wait = float(s["locality_log_wait_s"])
799
+ got: dict[str, dict] = {}
800
+ for attempt in range(3):
801
+ time.sleep(wait if attempt else min(wait, 8.0))
802
+ try:
803
+ rows = reader.run_statement(COST, {"minutes": 180, "ids": list(ids)})
804
+ except Refused as e:
805
+ doc["notes"].append(f"the server's own cost of each statement is not available ({refusal_reason(str(e))}): wall time x threads "
806
+ "is the upper bound kept")
807
+ return
808
+ got.update({r["query_id"]: r for r in rows})
809
+ if len(got) >= len(ids):
810
+ break
811
+ for qid, res in ids.items():
812
+ r = got.get(qid)
813
+ if r is None:
814
+ continue
815
+ res["cost"].update(cpu_s_server=round(int(r.get("cpu_us") or 0) / 1e6, 2), memory_bytes=int(r.get("memory") or 0),
816
+ read_rows=int(r.get("read_rows") or 0), read_bytes=int(r.get("read_bytes") or 0), ms=int(r.get("ms") or 0))
817
+ if len(got) < len(ids):
818
+ doc["notes"].append(f"{len(ids) - len(got)} statement(s) not yet in the server's query log: wall time x threads is their cost")
819
+
820
+
821
+ # ---- reading an answer ------------------------------------------------------------------------------------------------
822
+
823
+ def _ints(v) -> list[float]:
824
+ return [float(x) for x in (v or [])]
825
+
826
+
827
+ def _spread(pairs: list[tuple[float, float]], draws: int) -> dict:
828
+ """Ratios over draws of the probes (the probes are in random order: consecutive groups are independent draws), and
829
+ over single probes (p10 / p90)."""
830
+ def ratio(ps):
831
+ b = sum(x for x, _ in ps)
832
+ return round(sum(y for _, y in ps) / b, 4) if b else None
833
+ n = len(pairs)
834
+ k = max(1, min(int(draws), n)) if n else 1
835
+ groups = [pairs[i * n // k:(i + 1) * n // k] for i in range(k)] if n else []
836
+ by_draw = [r for r in (ratio(g) for g in groups) if r is not None]
837
+ single = sorted(y / x for x, y in pairs if x > 0)
838
+
839
+ def pct(p):
840
+ return round(single[min(int(p * len(single)), len(single) - 1)], 4) if single else None
841
+ return {"ratio": ratio(pairs), "draws": by_draw, "draw_min": min(by_draw) if by_draw else None,
842
+ "draw_max": max(by_draw) if by_draw else None, "probe_p10": pct(0.1), "probe_p90": pct(0.9)}
843
+
844
+
845
+ def read(res: dict, draws: int = 3, bloom_fpr: float = 0.01) -> dict | None:
846
+ """An answered request as the advisor reads it: {ratio, spread, floor, before, after, probes, basis}. `ratio` is marks
847
+ after / marks before (the present key's), over every probe; `floor` is granules that hold a matching row / granules the
848
+ key selects (no index of any type reads less). None when there is no answer."""
849
+ a = res.get("answer")
850
+ if res.get("status") != "answered" or not a:
851
+ return None
852
+ sid = res["statement_id"]
853
+ out: dict = {"statement_id": sid, "probes": int(a.get("probes") or 0), "granules_scanned": int(a.get("granules") or 0),
854
+ "rows_scanned": int(a.get("rows_scanned") or 0)}
855
+ if sid == "ch.locality.key_order":
856
+ key, new = _ints(a.get("present_granules")), _ints(a.get("new_granules"))
857
+ sent_g, own_g = res.get("sent_granule_rows"), res.get("new_granule_rows")
858
+ if sent_g and own_g and int(sent_g) != int(own_g):
859
+ # counted with the table's granularity: new granules = parts in scope + matching rows / rows per granule
860
+ pis = float(a.get("parts_in_scope") or 0)
861
+ new = [pis + max(x - pis, 0.0) * float(sent_g) / float(own_g) for x in new]
862
+ if res.get("aggregating"):
863
+ new = [float(a.get("parts_in_scope") or 0)] * len(key)
864
+ pairs = list(zip(key, new))
865
+ out.update(before=round(sum(key), 1), after=round(sum(new), 1), parts=int(a.get("parts") or 0),
866
+ parts_in_scope=int(a.get("parts_in_scope") or 0), floor=None, basis="key_order")
867
+ elif sid == "ch.locality.skip_range":
868
+ n = out["probes"]
869
+ key, idx, need = _ints(a.get("key_granules")), _ints(a.get("index_granules")), _ints(a.get("needed_granules"))
870
+ thresholds = []
871
+ for j, name in enumerate(("p99.9", "p99", "p90")):
872
+ after, needed = idx[j * n:(j + 1) * n], need[j * n:(j + 1) * n]
873
+ b = sum(key)
874
+ thresholds.append({"threshold": name, "ratio": round(sum(after) / b, 4) if b else None,
875
+ "floor": round(sum(needed) / b, 4) if b else None})
876
+ ok = [t for t in thresholds if t["ratio"] is not None]
877
+ mid = ok[len(ok) // 2] if ok else None
878
+ out.update(before=round(sum(key), 1), after=round(sum(idx[n:2 * n]), 1) if mid else None, thresholds=thresholds,
879
+ floor=mid["floor"] if mid else None, basis="range thresholds: the column's 99.9th, 99th, 90th percentile")
880
+ out["spread"] = {"ratio": mid["ratio"] if mid else None, "draws": [t["ratio"] for t in ok],
881
+ "draw_min": min(t["ratio"] for t in ok) if ok else None, "draw_max": max(t["ratio"] for t in ok) if ok else None,
882
+ "over": "thresholds"}
883
+ out["ratio"] = out["spread"]["ratio"]
884
+ return out
885
+ else:
886
+ key, hit, st, need = (_ints(a.get(k)) for k in ("key_granules", "index_granules", "set_granules", "needed_granules"))
887
+ typ = str(res.get("index_type") or "")
888
+ if not typ.startswith(("set", "bloom")):
889
+ # minmax on equality keeps every granule whose range holds the value: the statement keeps no order of values,
890
+ # so only the floor (granules that hold a matching row: no index type reads less) is known
891
+ out.update(before=round(sum(key), 1), after=None, floor=round(sum(need) / sum(key), 4) if sum(key) else None, ratio=None,
892
+ spread=None, basis="minmax on equality: not simulated, the floor only")
893
+ return out
894
+ after = st if typ.startswith("set") else [h + bloom_fpr * (k - h) for k, h in zip(key, hit)]
895
+ pairs = list(zip(key, after))
896
+ out.update(before=round(sum(key), 1), after=round(sum(after), 1), floor=round(sum(need) / sum(key), 4) if sum(key) else None,
897
+ distinct_per_granule=_ints(a.get("distinct_per_granule")),
898
+ basis="set(N): granules with more than N distinct values keep no set" if typ.startswith("set") else
899
+ f"bloom filter: ideal plus its nominal false-positive rate ({bloom_fpr})" if typ.startswith("bloom") else "minmax per granule")
900
+ if sid == "ch.locality.skip_eq_ranked":
901
+ ranks = [int(x) for x in a.get("value_rank") or []]
902
+ shares = _ints(a.get("value_share"))
903
+ by: dict[int, dict] = {}
904
+ for i, rk in enumerate(ranks):
905
+ o = by.setdefault(rk, {"rank": rk, "share": round(shares[i], 4) if i < len(shares) else None, "before": 0.0, "after": 0.0, "needed": 0.0})
906
+ o["before"] += key[i] if i < len(key) else 0
907
+ o["after"] += after[i] if i < len(after) else 0
908
+ o["needed"] += need[i] if i < len(need) else 0
909
+ ranked = []
910
+ for o in sorted(by.values(), key=lambda x: x["rank"]):
911
+ ranked.append({"rank": o["rank"], "share": o["share"], "ratio": round(o["after"] / o["before"], 4) if o["before"] else None,
912
+ "floor": round(o["needed"] / o["before"], 4) if o["before"] else None})
913
+ ok = sorted(r["ratio"] for r in ranked if r["ratio"] is not None)
914
+ out["by_rank"] = ranked
915
+ out["spread"] = {"ratio": ok[len(ok) // 2] if ok else None, "draws": [r["ratio"] for r in ranked],
916
+ "draw_min": ok[0] if ok else None, "draw_max": ok[-1] if ok else None, "over": "value ranks"}
917
+ out["ratio"] = out["spread"]["ratio"]
918
+ return out
919
+ out["spread"] = {**_spread(pairs, draws), "over": "draws of the probes"}
920
+ out["ratio"] = out["spread"]["ratio"]
921
+ return out
922
+
923
+
924
+ def load(out_dir) -> dict | None:
925
+ from pathlib import Path
926
+ import json
927
+ p = Path(out_dir) / FILE
928
+ try:
929
+ return json.loads(p.read_text()) if p.exists() else None
930
+ except (OSError, ValueError):
931
+ return None
932
+
933
+
934
+ COUNT_KEY_FIELDS = ("kind", "statement_id", "database", "table_name", "time_column", "window_hours", "column", "key", "index_type",
935
+ "index_granularity", "set_values", "old", "new", "aggregating", "new_granule_rows")
936
+
937
+
938
+ def count_key(req: dict) -> str:
939
+ """What a request counts, as text: two requests with the same key get the same answer from the server and read it
940
+ the same way. Results carry it, so a suggestion whose fingerprint changed (its DDL moved where the count does not
941
+ look) still finds its count."""
942
+ return json.dumps([req.get(k) for k in COUNT_KEY_FIELDS], default=str)
943
+
944
+
945
+ def by_count_key(doc: dict | None) -> dict[str, dict]:
946
+ """count key -> the result (an answered one wins over a refusal)."""
947
+ out: dict[str, dict] = {}
948
+ for r in (doc or {}).get("results") or []:
949
+ k = r.get("count_key")
950
+ if k and (k not in out or (out[k].get("status") != "answered" and r.get("status") == "answered")):
951
+ out[k] = r
952
+ return out
953
+
954
+
955
+ def by_fingerprint(doc: dict | None) -> dict[str, dict]:
956
+ """fingerprint -> the result (the newest answered one wins over a refusal)."""
957
+ out: dict[str, dict] = {}
958
+ for r in (doc or {}).get("results") or []:
959
+ prev = out.get(r["fingerprint"])
960
+ if prev is None or (prev.get("status") != "answered" and r.get("status") == "answered"):
961
+ out[r["fingerprint"]] = r
962
+ for r in (doc or {}).get("set_aside") or []:
963
+ out.setdefault(r["fingerprint"], {**r, "status": "not_counted"})
964
+ return out