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
codecop/dbcli.py ADDED
@@ -0,0 +1,885 @@
1
+ """`codecop db`: read a real database, read-only, to replace guesses with facts. See realdb/__init__.py for the rules."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ from datetime import datetime, timezone
8
+ from pathlib import Path
9
+ from typing import Optional
10
+
11
+ import typer
12
+ from rich.console import Console
13
+ from rich.table import Table
14
+
15
+ from . import __version__, realdb
16
+ from .realdb import AUDIT_FILE, CATALOG_FILE, MATCH_FILE, SAMPLE_FILE, WORKLOAD_FILE, Audit, DbError, Refused
17
+
18
+ db_app = typer.Typer(add_completion=False, no_args_is_help=True,
19
+ help="Read a real database, read-only: catalog, workload, plans. Nothing is written to it, ever.")
20
+ console = Console()
21
+ err = Console(stderr=True)
22
+
23
+ ENV_HELP = "Env file with the connection variables (CH_*/CLICKHOUSE_*, PG_*/POSTGRES_*, DATABASE_URL). Read at run time; never copied."
24
+ TLS_NO_VERIFY_HELP = ("Connect over TLS without verifying the server's certificate (a self-signed one). Said on every run. Prefer "
25
+ "--tls-ca-file. Per connection: tls_no_verify = true under [db.<connection>] in codecop.toml.")
26
+ TLS_CA_HELP = ("Verify the server's certificate against this CA file (PEM), for a self-signed or private CA. Per connection: "
27
+ "tls_ca_file under [db.<connection>] in codecop.toml.")
28
+ MAP_HELP = "Name the variables yourself: name.field=VARIABLE, e.g. analytics.engine=clickhouse analytics.host=MY_CH_HOST. Repeatable."
29
+
30
+
31
+ def _human(n: float | None) -> str:
32
+ if n is None:
33
+ return "-"
34
+ for unit, size in (("T", 1e12), ("B", 1e9), ("M", 1e6), ("K", 1e3)):
35
+ if abs(n) >= size:
36
+ return f"{n / size:.1f}{unit}"
37
+ return f"{n:.0f}"
38
+
39
+
40
+ def _bytes(n: float | None) -> str:
41
+ if n is None:
42
+ return "-"
43
+ for unit, size in (("TB", 1e12), ("GB", 1e9), ("MB", 1e6), ("KB", 1e3)):
44
+ if abs(n) >= size:
45
+ return f"{n / size:.1f} {unit}"
46
+ return f"{n:.0f} B"
47
+
48
+
49
+ def connections(root: Path, env_file: Optional[Path], maps: list[str], engine: Optional[str], only: list[str], *,
50
+ tls_no_verify: bool = False, tls_ca_file: Optional[Path] = None) -> list[realdb.Connection]:
51
+ """The connections to read, each with its TLS choice: --tls-ca-file / --tls-no-verify, then tls_ca_file /
52
+ tls_no_verify under [db.<connection>] and then [db] in codecop.toml, then CODECOP_DB_TLS_NO_VERIFY=1 (realdb.apply_tls)."""
53
+ try:
54
+ config = realdb.load_toml_db(root)
55
+ found = realdb.load_connections(env_file, maps=maps, config=config)
56
+ realdb.apply_tls(found, config, root=root, no_verify=bool(tls_no_verify), ca_file=tls_ca_file)
57
+ except DbError as e:
58
+ err.print(f"[red]{e}[/red]")
59
+ raise typer.Exit(2)
60
+ if engine:
61
+ wanted = {"pg": "postgres", "postgresql": "postgres", "ch": "clickhouse"}.get(engine.lower(), engine.lower())
62
+ found = [c for c in found if c.engine == wanted]
63
+ if only:
64
+ found = [c for c in found if c.name in only]
65
+ if not found:
66
+ err.print("[red]No database connection found.[/red] Expected CH_*/CLICKHOUSE_* or PG_*/POSTGRES_*/DATABASE_URL variables "
67
+ "in the env file, or name them with --map.")
68
+ raise typer.Exit(2)
69
+ for conn in found:
70
+ warning = realdb.tls_warning(conn)
71
+ if warning:
72
+ err.print(f"[yellow]{warning}[/yellow]", highlight=False)
73
+ return found
74
+
75
+
76
+ def every_database(conns: list[realdb.Connection], databases: list[str]) -> list[realdb.Connection]:
77
+ """PostgreSQL: one connection per database named with --database (same server and sign-in, another database), each
78
+ pulled and stored as its own connection `<name>:<database>`, so a repository whose statements read tables of several
79
+ databases gets all of them (the sandbox and the matcher read every connection of the engine). The env file's own
80
+ database is kept. ClickHouse describes several databases over one connection (--database is passed to its catalog)."""
81
+ import dataclasses
82
+ out: list[realdb.Connection] = []
83
+ for c in conns:
84
+ out.append(c)
85
+ if c.engine != "postgres":
86
+ continue
87
+ for db in dict.fromkeys(databases):
88
+ if db and db != c.database:
89
+ out.append(dataclasses.replace(c, name=f"{c.name}:{db}", database=db, notes=list(c.notes)))
90
+ return out
91
+
92
+
93
+ def tls_planned(conn: realdb.Connection) -> str:
94
+ """The TLS mode a connection asks for, before connecting (a local server may still fall back, and says so)."""
95
+ kind, why = realdb.tls_request(conn)
96
+ return realdb.tls_mode_text(kind, conn, why)
97
+
98
+
99
+ def planned_statements(engine: str, tiers: set[str], settings: dict | None = None) -> list[realdb.Statement]:
100
+ """What a command would send, for --dry-run, with the limits the settings give each. Tier C and D statements depend
101
+ on what A and B return. A statement a setting switches off is not listed."""
102
+ if engine == "clickhouse":
103
+ from .realdb.clickhouse import STATEMENTS
104
+ else:
105
+ from .realdb.postgres import STATEMENTS
106
+ s = settings or {}
107
+ # the resource statements and the switch of each
108
+ switches = {"ch.workload.memory": "memory", "ch.workload.resource_totals": "cpu", "ch.workload.resources": "cpu",
109
+ "ch.workload.failures": "failures", "ch.workload.pressure": "pressure", "ch.check.capacity": "capacity",
110
+ "pg.workload.resource_totals": "cpu", "pg.workload.resources": "cpu", "pg.workload.temp": "cpu",
111
+ "pg.check.settings": "capacity", "pg.workload.kcache": "kcache"}
112
+
113
+ def switched_off(statement_id: str) -> bool:
114
+ key = next((k for k in sorted(switches, key=len, reverse=True) if statement_id.startswith(k)), None)
115
+ return key is not None and not bool(s.get(switches[key], True))
116
+
117
+ if engine != "clickhouse":
118
+ return [st for st in STATEMENTS.values() if st.tier in tiers and not switched_off(st.id)]
119
+ spread = s.get("spread", "auto")
120
+
121
+ def sent(statement_id: str) -> bool:
122
+ if switched_off(statement_id):
123
+ return False
124
+ if statement_id.startswith("ch.catalog.partition_"):
125
+ return bool(s.get("partition_detail", True))
126
+ if statement_id.startswith("ch.workload.selected"):
127
+ return bool(s.get("selected", True))
128
+ for key in ("tags", "comments", "clients", "columns", "repeats", "minutes", "inserts"):
129
+ if statement_id.startswith(f"ch.workload.{key}"):
130
+ return bool(s.get(key, True))
131
+ if statement_id.startswith("ch.workload.spread"):
132
+ approximate = statement_id.startswith("ch.workload.spread_tdigest")
133
+ return spread == "auto" or (spread == "tdigest" and approximate) or (spread == "exact" and not approximate)
134
+ return True
135
+ return [realdb.with_limits(st, s.get("limits")) for st in STATEMENTS.values() if st.tier in tiers and sent(st.id)]
136
+
137
+
138
+ def minutes_size(settings: dict, hours: int) -> tuple[int, int]:
139
+ """The most rows ch.workload.minutes can return for a window of `hours`, and about how many bytes they take in
140
+ db_workload.json: every kept shape running every minute (a minute of a dense series is about four characters)."""
141
+ rows = min(int(settings["minutes_shapes"]) * (max(int(hours), 1) * 60 + 1), int(settings["minutes_max_rows"]))
142
+ return rows, rows * 4
143
+
144
+
145
+ def print_statements(conn: realdb.Connection, tiers: set[str], *, plans: bool, sample: bool, settings: dict | None = None,
146
+ hours: int = 24) -> None:
147
+ console.print(f"\n[bold]{conn.label}[/bold]: would send these statements (not connecting)")
148
+ console.print(f" TLS: {tls_planned(conn)}", markup=False, highlight=False)
149
+ for s in planned_statements(conn.engine, tiers, settings):
150
+ lim = s.limits
151
+ console.print(f" [bold]{s.id}[/bold] (tier {s.tier}{', optional' if s.optional else ''}): {s.purpose}", markup=True, highlight=False)
152
+ console.print(f" limits: {lim.seconds}s, {lim.rows_to_read:,} rows to read, {_bytes(lim.bytes_to_read)} to read, "
153
+ f"{lim.result_rows:,} result rows, {_bytes(lim.memory_bytes)} memory, {lim.threads} threads", highlight=False)
154
+ console.print(" " + " ".join(s.sql.split()), markup=False, highlight=False, soft_wrap=True)
155
+ if conn.engine == "clickhouse":
156
+ console.print(" Every request also carries readonly=1. The `.all_replicas` workload statements are used only when the "
157
+ "server has more than one replica.", highlight=False)
158
+ p = settings or realdb.pull_settings(None)
159
+ if "A" in tiers and p["partition_detail"]:
160
+ console.print(f" Per partition (optional; a refusal is a note, not a failure): at most {p['partitions_per_table']:,} partitions per "
161
+ f"table for parts, {p['column_partitions_per_table']:,} for column sizes, the highest partition ids first, and "
162
+ f"{p['partition_rows']:,} rows in all for each; fewer per table when the partition counts say that would not fit.",
163
+ highlight=False)
164
+ if "B" in tiers and p["spread"] != "off":
165
+ console.print(f" ch.workload.spread: one form is sent, for the shapes ch.workload.top kept, 400 at a time. spread = {p['spread']}"
166
+ + (f": exact when those shapes ran at most {p['spread_exact_max_runs']:,} times in the window, else t-digest."
167
+ if p["spread"] == "auto" else "."), highlight=False)
168
+ if "B" in tiers and p["selected"]:
169
+ console.print(f" ch.workload.selected: for the {p['selected_shapes']:,} heaviest shapes, over the most recent hours that hold about "
170
+ f"{p['selected_max_log_rows']:,} finished queries. The `_arrays` form is tried only when the server has no ProfileEvents map.",
171
+ highlight=False)
172
+ if "B" in tiers and p["selected"]:
173
+ console.print(" ch.workload.selected also returns the parts and marks each run chose from (SelectedPartsTotal, SelectedMarksTotal) "
174
+ "and the ranges it selected, from the same ProfileEvents read: null, with a note, where the server does not count them.",
175
+ highlight=False)
176
+ if "B" in tiers and p["spread"] != "off":
177
+ console.print(" ch.workload.spread also sums the rows and bytes read by the runs that returned nothing and by the others "
178
+ "(no other column is read for them).", highlight=False)
179
+ if "B" in tiers and p["columns"]:
180
+ console.print(f" ch.workload.columns: for the shapes ch.workload.top kept, 400 at a time; at most {p['columns_per_shape']:,} column names "
181
+ "and as many projection names per shape (db_pull.columns_per_shape). Database prefixes are removed before anything is "
182
+ "written; `codecop push` may send the names as table.column.", highlight=False)
183
+ if "B" in tiers and p["repeats"]:
184
+ console.print(f" ch.workload.repeats: for the shapes ch.workload.top kept, 400 at a time, over the most recent hours that hold about "
185
+ f"{p['repeats_max_log_rows']:,} finished queries (db_pull.repeats_max_log_rows): it reads every run's text, and returns two "
186
+ "counts per shape. Stopped by a limit, it is tried once more over a quarter of those hours.", highlight=False)
187
+ if "B" in tiers and p["minutes"]:
188
+ rows, size = minutes_size(p, hours)
189
+ console.print(f" ch.workload.minutes: for the {p['minutes_shapes']:,} heaviest shapes by bytes read, in batches whose rows fit the "
190
+ f"statement's result rows; at most {p['minutes_max_rows']:,} rows in all (db_pull.minutes_max_rows). Over {hours} h: at most "
191
+ f"{rows:,} rows, about {_bytes(size)} in db_workload.json when every shape runs every minute (less for quieter ones). "
192
+ "Stays on this machine.", highlight=False)
193
+ if "B" in tiers and p["inserts"]:
194
+ console.print(f" ch.workload.inserts: one request over the same window, at most {p['inserts_tables']:,} tables (db_pull.inserts_tables).",
195
+ highlight=False)
196
+ if "A" in tiers and p["partition_detail"]:
197
+ console.print(" ch.catalog.partition_parts also returns when each partition's parts last changed (first and last modification "
198
+ "time). Partition ids and times stay on this machine.", highlight=False)
199
+ if "B" in tiers:
200
+ console.print(f" ch.workload.texts: each normalized text is cut at text_chars = {p['text_max_chars']:,} characters (db_pull.text_max_chars).",
201
+ highlight=False)
202
+ on = [k for k in ("tags", "comments", "clients") if p.get(k)]
203
+ if on:
204
+ console.print(" " + ", ".join(f"ch.workload.{k}" for k in on) + " (optional; a refusal is a note, not a failure): for the shapes "
205
+ "ch.workload.top kept, 400 at a time, over the same window. What leaves this machine on `codecop push`: "
206
+ + ("the tags only (text matching codecop:<tag>), as the link from a statement to its call site; " if "tags" in on else "")
207
+ + "the labels and client names never (they stay in db_workload.json).", highlight=False)
208
+ else:
209
+ console.print(" Before any statement the session is made read-only: " + "; ".join(realdb_pg_setup()), markup=False, highlight=False)
210
+ if plans:
211
+ console.print(" --plans: for each of the heaviest SELECTs in pg_stat_statements, `EXPLAIN (GENERIC_PLAN, FORMAT JSON) <its "
212
+ "normalized text>` (PostgreSQL 16+, planned and never executed).", markup=False, highlight=False)
213
+ if sample:
214
+ console.print(" --sample: per chosen table one `SELECT count(), uniqCombined(col)..., min/max of date columns` and up to six "
215
+ "`top-10 share` statements, each capped at --sample-rows rows read. Built from catalog identifiers.",
216
+ markup=False, highlight=False)
217
+
218
+
219
+ def realdb_pg_setup() -> tuple[str, ...]:
220
+ from .realdb.postgres import SESSION_SETUP
221
+ return SESSION_SETUP
222
+
223
+
224
+ def print_capabilities(rows: list[tuple[realdb.Connection, dict | None, str]]) -> None:
225
+ table = Table(title="What each connection allows", title_justify="left")
226
+ for col in ("connection", "server", "TLS", "read-only enforced", "catalog (A)", "workload (B)", "plans (C)", "account could write", "notes"):
227
+ table.add_column(col, overflow="fold")
228
+ for conn, cap, error in rows:
229
+ if cap is None:
230
+ table.add_row(conn.label, "-", f"asked for: {tls_planned(conn)}", "-", "-", "-", "-", "-", f"[red]{error}[/red]")
231
+ continue
232
+ could = cap.get("account_can_write")
233
+ tls = cap.get("tls") or "; ".join(cap.get("transport") or []) or "-"
234
+ notes = list(conn.notes) + [f"limit not accepted: {x}" for x in cap.get("limits_refused") or []]
235
+ if cap.get("is_replica"):
236
+ notes.append("a replica")
237
+ table.add_row(
238
+ conn.label, f"{cap['engine']} {cap['version']}", tls,
239
+ "[green]yes[/green]" if cap["read_only_enforced"] else "[red]NO[/red]",
240
+ "yes" if cap["catalog"] else "no", cap["workload_source"] if cap["workload"] else f"no: {cap['workload_source']}",
241
+ cap["plans"], "unknown" if could is None else ("[yellow]yes[/yellow]: " + ", ".join(cap.get("write_access_kinds") or [])) if could else "no",
242
+ "; ".join(n for n in notes if n))
243
+ console.print(table)
244
+ from .grantscript import print_hint
245
+ print_hint(rows, console)
246
+
247
+
248
+ def print_audit(audits: list[Audit], out_dir: Path | None) -> None:
249
+ table = Table(title="What was sent to the databases", title_justify="left")
250
+ for col in ("connection", "statements", "refused", "time", "rows returned", "rows read (server)", "bytes read (server)", "by tier"):
251
+ table.add_column(col, justify="right" if col not in ("connection", "by tier") else "left")
252
+ for a in audits:
253
+ s = a.summary()
254
+ reads = a.connection.engine == "clickhouse"
255
+ table.add_row(a.connection.label, str(s["statements"]), str(s["failed"]), f"{s['duration_ms'] / 1000:.1f} s", f"{s['rows_returned']:,}",
256
+ _human(s["read_rows"]) if reads else "not reported", _bytes(s["read_bytes"]) if reads else "not reported",
257
+ ", ".join(f"{t}: {n}" for t, n in s["by_tier"].items()))
258
+ console.print(table)
259
+ if out_dir is not None and any(a.summary()["statements"] for a in audits):
260
+ console.print(f"Every statement is listed in [bold]{out_dir / AUDIT_FILE}[/bold].")
261
+
262
+
263
+ ERROR_KINDS = (("tls", r"certificate|ssl|tls"), ("auth", r"auth|password|denied for user|not allowed|code: 516|code: 192"),
264
+ ("timeout", r"timed? ?out|timeout"), ("unreachable", r"refused|unreachable|resolve|name or service|no route|connect"),
265
+ ("read_only", r"read-only|readonly"))
266
+
267
+
268
+ def error_kind(text: str) -> str:
269
+ """A fixed word for why a connection failed, for machines: tls, auth, timeout, unreachable, read_only or other."""
270
+ import re
271
+ low = (text or "").lower()
272
+ return next((kind for kind, pattern in ERROR_KINDS if re.search(pattern, low)), "other")
273
+
274
+
275
+ def check_document(rows: list[tuple[realdb.Connection, dict | None, str]]) -> dict:
276
+ """`codecop db check --json`: per connection label, whether it connected, why not (a fixed word only, never the error
277
+ text), and the capability check as reader.check() returned it. No host, user, password or database name."""
278
+ out = {"schema_version": 1, "tool_version": __version__, "generated_at": _stamp(), "connections": {}}
279
+ for conn, cap, error in rows:
280
+ out["connections"][conn.name] = {"ok": cap is not None, "error_kind": error_kind(error) if cap is None else "",
281
+ "capabilities": cap}
282
+ return out
283
+
284
+
285
+ @db_app.command()
286
+ def check(
287
+ path: Path = typer.Argument(Path("."), help="Repository (for codecop.toml and the default out dir)."),
288
+ env_file: Optional[Path] = typer.Option(None, "--env-file", help=ENV_HELP),
289
+ engine: Optional[str] = typer.Option(None, "--engine", help="Only connections of this engine: clickhouse or postgres."),
290
+ connection: list[str] = typer.Option([], "--connection", help="Only this connection (as named in the table). Repeatable."),
291
+ maps: list[str] = typer.Option([], "--map", help=MAP_HELP),
292
+ out: Optional[Path] = typer.Option(None, "--out", help="Directory for the audit file. Default: <path>/.codecop"),
293
+ dry_run: bool = typer.Option(False, "--dry-run", help="Print the statements and stop, without connecting."),
294
+ tls_no_verify: bool = typer.Option(False, "--tls-no-verify", help=TLS_NO_VERIFY_HELP),
295
+ tls_ca_file: Optional[Path] = typer.Option(None, "--tls-ca-file", help=TLS_CA_HELP),
296
+ json_out: Optional[Path] = typer.Option(None, "--json", help="Also write what each connection allows as JSON to this file "
297
+ "(no host, user or database name: the connection's name and the server's answers)."),
298
+ ) -> None:
299
+ """Connect, verify that read-only is enforced by the server, and show what the account can see. The TLS column says how
300
+ the server's certificate was checked; db_audit.jsonl says it on every line (`tls`)."""
301
+ root = path.resolve()
302
+ out_dir = out or (root / ".codecop")
303
+ conns = connections(root, env_file, maps, engine, connection, tls_no_verify=tls_no_verify, tls_ca_file=tls_ca_file)
304
+ if dry_run:
305
+ for conn in conns:
306
+ print_statements(conn, {"check"}, plans=False, sample=False)
307
+ return
308
+ rows, audits = [], []
309
+ for conn in conns:
310
+ audit = Audit(out_dir, conn)
311
+ audits.append(audit)
312
+ try:
313
+ with realdb.open_reader(conn, audit) as reader:
314
+ rows.append((conn, reader.check(), ""))
315
+ except DbError as e:
316
+ rows.append((conn, None, str(e)[:160]))
317
+ print_capabilities(rows)
318
+ print_audit(audits, out_dir)
319
+ if isinstance(json_out, Path):
320
+ write_json(json_out, check_document(rows))
321
+ if any(cap is not None and not cap["read_only_enforced"] for _, cap, _ in rows):
322
+ err.print("[red]A server did not confirm read-only.[/red] Nothing else will be sent to it.")
323
+ raise typer.Exit(1)
324
+ if all(cap is None for _, cap, _ in rows):
325
+ raise typer.Exit(1)
326
+
327
+
328
+ RATIO_COLUMNS = ("rows read / run", "returned / run", "read per returned", "bytes per row read", "shape")
329
+
330
+
331
+ def ratio_cells(q: dict) -> list[str]:
332
+ """What one run reads against what it returns: the absolutes, the two ratios, and whether the shape is an aggregate."""
333
+ per = q.get("rows_read_per_row_returned")
334
+ return [_human(q.get("rows_read_per_run")), _human(q.get("rows_returned_per_run")), f"{_human(per)}x" if per is not None else "-",
335
+ _bytes(q.get("bytes_read_per_row_read")), {"group_by": "aggregate (GROUP BY)", "count": "aggregate (count)",
336
+ "aggregate": "aggregate"}.get(q.get("aggregate_kind"), "")]
337
+
338
+
339
+ def partition_cell(conn: dict) -> str:
340
+ """What the per-partition statements returned for one connection, in counts."""
341
+ d = conn.get("partition_detail") or {}
342
+ bits = []
343
+ if d.get("parts"):
344
+ bits.append(f"parts: {d['parts']['rows']:,} partitions of {d['parts']['tables']:,} tables")
345
+ if d.get("columns"):
346
+ bits.append(f"column sizes: {d['columns']['rows']:,} cells of {d['columns']['tables']:,} tables")
347
+ return "; ".join(bits) or "-"
348
+
349
+
350
+ def _stamp() -> str:
351
+ return datetime.now(timezone.utc).isoformat(timespec="seconds")
352
+
353
+
354
+ def write_json(path: Path, data: dict) -> None:
355
+ path.parent.mkdir(parents=True, exist_ok=True)
356
+ # whole or not at all: the engines of a scan side by side match the same pull (db_match.json) and read it while one writes
357
+ import os
358
+ import threading
359
+ tmp = path.with_name(f"{path.name}.{os.getpid()}.{threading.get_ident()}.tmp")
360
+ tmp.write_text(realdb.compact_json(data))
361
+ tmp.replace(path)
362
+
363
+
364
+ def load_workload(out_dir: Path) -> dict:
365
+ """db_workload.json, with query texts repaired when an older pull masked an ordinary word in them (see facts.masked_word)."""
366
+ from .realdb import facts as facts_mod
367
+
368
+ workload = json.loads((out_dir / WORKLOAD_FILE).read_text())
369
+ catalog_path = out_dir / CATALOG_FILE
370
+ catalog = json.loads(catalog_path.read_text()) if catalog_path.exists() else None
371
+ word = facts_mod.masked_word(catalog) or facts_mod.masked_word_in_workload(workload, catalog)
372
+ if word:
373
+ for w in (workload.get("connections") or {}).values():
374
+ for q in w.get("queries") or []:
375
+ q["text"] = facts_mod.unmask(q.get("text") or "", word)
376
+ return workload
377
+
378
+
379
+ def run_match(out_dir: Path, quiet: bool = False) -> dict | None:
380
+ """Match db_workload.json to inventory.json and write db_match.json. Local only."""
381
+ from .realdb import match as match_mod
382
+
383
+ inv_path, work_path = out_dir / "inventory.json", out_dir / WORKLOAD_FILE
384
+ if not inv_path.exists() or not work_path.exists():
385
+ return None
386
+ inventory, workload = json.loads(inv_path.read_text()), load_workload(out_dir)
387
+ result = {"schema_version": 1, "tool_version": __version__, "generated_at": _stamp(), "engines": {}}
388
+ for name, w in (workload.get("connections") or {}).items():
389
+ if not w.get("queries"):
390
+ continue
391
+ m = match_mod.match(inventory, w, engine=w["engine"])
392
+ m["connection"] = name
393
+ prior = result["engines"].get(w["engine"])
394
+ if prior is None or m["workload"]["read_bytes"] > prior["workload"]["read_bytes"]:
395
+ result["engines"][w["engine"]] = m
396
+ write_json(out_dir / MATCH_FILE, result)
397
+ if not quiet:
398
+ table = Table(title="Real workload matched to call sites", title_justify="left")
399
+ for col in ("engine", "window", "shapes", "exact", "template", "part", "likely", "none", "share of read bytes matched (sure)", "sites with real load"):
400
+ table.add_column(col, justify="left" if col in ("engine", "window") else "right")
401
+ for eng, m in result["engines"].items():
402
+ r = m["rates"]
403
+ n = m["workload"]["shapes_with_text"]
404
+ table.add_row(eng, f"{m['window_hours']} h" if m["window_hours"] else "since reset", str(n), str(r["exact"]["shapes"]),
405
+ str(r["template"]["shapes"]), str(r["part"]["shapes"]), str(r["likely"]["shapes"]), str(n - r["any"]["shapes"]),
406
+ f"{r['sure']['share_of_all_read_bytes']:.1%} of all, {r['sure']['share_of_top_read_bytes']:.1%} of the top shapes",
407
+ str(sum(m["sites_matched"].values())))
408
+ console.print(table)
409
+ for eng, m in result["engines"].items():
410
+ if m.get("sites_without_text"):
411
+ console.print(f" {eng}: {m['sites_without_text']:,} call sites hold no SQL text (an unresolved argument or a wrapper's "
412
+ "parameter): nothing to match them with.", highlight=False)
413
+ return result
414
+
415
+
416
+ def print_lock_statements(conn: realdb.Connection, settings: dict) -> None:
417
+ """--dry-run --watch-locks: the lock statements with their limits, and the sampling plan."""
418
+ from .realdb import locks as locks_mod
419
+ console.print(f"\n[bold]{conn.label}[/bold]: --watch-locks would also send (not connecting)")
420
+ for s in locks_mod.planned(conn.engine, settings):
421
+ lim = s.limits
422
+ console.print(f" [bold]{s.id}[/bold] (lock evidence{', optional' if s.optional else ''}): {s.purpose}", markup=True, highlight=False)
423
+ console.print(f" limits: {lim.seconds}s, {lim.rows_to_read:,} rows to read, {_bytes(lim.bytes_to_read)} to read, "
424
+ f"{lim.result_rows:,} result rows, {_bytes(lim.memory_bytes)} memory, {lim.threads} threads", highlight=False)
425
+ console.print(" " + " ".join(s.sql.split()), markup=False, highlight=False, soft_wrap=True)
426
+ if conn.engine == "clickhouse":
427
+ console.print(f" --watch-locks on ClickHouse: each statement once; mutations, the part log and refused inserts over the last "
428
+ f"{settings['watch_days']} days (db_pull.watch_days); merges are what runs at that moment. Counts and table names only.",
429
+ markup=False, highlight=False)
430
+ else:
431
+ console.print(" On PostgreSQL 13 the `_v13` forms are sent instead (no statement ids, no wait start, no session counters).",
432
+ markup=False, highlight=False)
433
+ console.print(" " + locks_mod.plan_text(settings), markup=False, highlight=False)
434
+
435
+
436
+ def print_locks(out_dir: Path, doc: dict, workload: dict | None) -> None:
437
+ from .realdb import locks as locks_mod
438
+ locks_mod.link_workload(doc, workload)
439
+ write_json(out_dir / locks_mod.LOCKS_FILE, doc)
440
+ table = Table(title="Lock evidence (--watch-locks)", title_justify="left")
441
+ for col in ("connection", "samples", "with a lock wait", "idle in transaction", "blocking pairs", "deadlocks in window",
442
+ "FK without index", "notes"):
443
+ table.add_column(col, justify="left" if col in ("connection", "notes") else "right", overflow="fold")
444
+ for name, c in doc["connections"].items():
445
+ if c.get("engine") == "clickhouse":
446
+ table.add_row(name, "once", "-", "-", "-", "-", "-",
447
+ f"most active parts in a partition: {c.get('max_active_parts_per_partition', 0):,}; "
448
+ f"running mutations: {sum(int(m.get('running') or 0) for m in c.get('mutations') or []):,}; "
449
+ + "; ".join(c.get("notes") or []))
450
+ continue
451
+ table.add_row(name, f"{c['samples']:,} over {c['window_s']:g} s", f"{c['lock_wait_samples']:,}", f"{c['idle_in_tx_samples']:,}",
452
+ f"{len(c['blocking_pairs']):,}", str((c.get("counters_delta") or {}).get("deadlocks", "-")),
453
+ f"{len(c['fk_without_index']):,}", "; ".join(c.get("notes") or []))
454
+ console.print(table)
455
+ pg = any(c.get("engine") != "clickhouse" for c in doc["connections"].values())
456
+ console.print(f"Written to [bold]{out_dir / locks_mod.LOCKS_FILE}[/bold] (stays on this machine)."
457
+ + (" pg_stat_activity is point-in-time: a wait shorter than the interval is seen only by chance; none seen does not "
458
+ "prove there is none." if pg else ""))
459
+
460
+
461
+ LOCALITY_STATUS = {"answered": "answered", "planned": "planned", "refused": "not judged (refused)", "over_budget": "not sent (budget)",
462
+ "not_counted": "not counted", "nothing_to_gain": "nothing to gain (no statement)"}
463
+
464
+
465
+ def _advisor_ch(out_dir: Path) -> dict | None:
466
+ """The ClickHouse advisor's document from advisor.json (`codecop advise` writes it), or None."""
467
+ from . import advisors
468
+ stage = advisors.load(out_dir)
469
+ return advisors.doc_of(stage, "clickhouse") if stage else None
470
+
471
+
472
+ def locality_step(reader, conn: realdb.Connection, out_dir: Path, catalog_conn: dict | None, settings: dict) -> dict | None:
473
+ """`--locality`: count the ClickHouse advisor's candidates on production (realdb/locality.py) and write db_locality.json
474
+ (local only). Needs advisor.json (`codecop advise`) and the pulled catalog. With the reader's dry_run nothing is sent:
475
+ the plan and its planned cost are printed."""
476
+ from .realdb import locality
477
+ doc = _advisor_ch(out_dir)
478
+ if conn.engine != "clickhouse":
479
+ return None
480
+ if doc is None or not doc.get("table_suggestions"):
481
+ err.print(f"[yellow]{conn.label}: no ClickHouse candidates in {out_dir / 'advisor.json'}: run `codecop advise` first; nothing counted.[/yellow]")
482
+ return None
483
+ if catalog_conn is None:
484
+ err.print(f"[yellow]{conn.label}: no pulled catalog for this connection: nothing counted.[/yellow]")
485
+ return None
486
+ err.print(f"[dim] {conn.label}: locality (counts on production)[/dim]")
487
+ result = locality.run(reader, doc, {"connections": {conn.name: catalog_conn}}, settings, log=lambda m: err.print(f"[dim] {m}[/dim]"))
488
+ result["connection"] = conn.name
489
+ print_locality(result)
490
+ if not result["dry_run"]:
491
+ write_json(out_dir / locality.FILE, result)
492
+ console.print(f"Locality: [bold]{out_dir / locality.FILE}[/bold] (counts only; part names never leave this machine). "
493
+ "`codecop advise` or `codecop report` reads it.")
494
+ return result
495
+
496
+
497
+ def print_locality(result: dict) -> None:
498
+ table = Table(title="Locality: candidates counted on production" + (" (planned, nothing sent)" if result.get("dry_run") else ""),
499
+ title_justify="left")
500
+ for col in ("suggestion", "kind", "table", "statement", "parts", "rows of parts", "planned CPU (est.)", "status", "answer", "server cost"):
501
+ table.add_column(col, overflow="fold", justify="right" if col in ("parts", "rows of parts", "planned CPU (est.)") else "left")
502
+ from .realdb import locality
503
+ small = [r for r in result["results"] if r["status"] == "nothing_to_gain"]
504
+ for r in result["results"]:
505
+ if r["status"] == "nothing_to_gain":
506
+ continue # one line below
507
+ read = locality.read(r, result["budget"].get("draws") or 3)
508
+ sp = (read or {}).get("spread") or {}
509
+ answer = (f"x{read['ratio']:g} (x{sp.get('draw_min')}–x{sp.get('draw_max')})" + (f", floor x{read['floor']:g}" if read.get("floor") is not None else "")
510
+ if read and read.get("ratio") is not None else "")
511
+ c = r.get("cost") or {}
512
+ cost = (f"{c['cpu_s_server']:.1f} CPU-s, {_human(c.get('read_rows'))} rows, {_bytes(c.get('memory_bytes'))}" if c.get("cpu_s_server") is not None
513
+ else f"≤ {c['cpu_s_upper_bound']:.1f} CPU-s (wall x threads)" if c.get("cpu_s_upper_bound") is not None else "")
514
+ p = r.get("parts") or {}
515
+ table.add_row(r["suggestion"], r["kind"], r["table"], r["statement_id"].removeprefix("ch.locality."), str(p.get("parts", "")),
516
+ _human(p.get("rows")) if p else "", f"{(r.get('planned') or {}).get('cpu_s_estimate', 0):.1f} s" if r.get("planned") else "",
517
+ LOCALITY_STATUS.get(r["status"], r["status"]) + (f": {r['reason']}" if r.get("reason") else "")
518
+ + (f" (shared with {r['shared_with']}: no statement of its own)" if r.get("shared_with") else ""), answer, cost)
519
+ console.print(table)
520
+ b, s = result["budget"], result.get("spent") or {}
521
+ planned = [r for r in result["results"] if r.get("planned") and r["status"] in ("planned", "answered") and not r.get("shared_with")]
522
+ if small:
523
+ console.print(f" nothing to gain, no statement sent: {len(small)} candidate(s) on {len({r['table'] for r in small})} table(s) under "
524
+ f"db_pull.locality_min_table_rows rows (read whole in a few granules)", highlight=False)
525
+ console.print(f" budget: {b['rows_per_statement']:,} rows of parts a statement (read 3-4x), {b['max_statements']} statements, "
526
+ f"{b['cpu_seconds_total']:g} CPU-s in all (db_pull.locality_*). Planned: {len(planned)} statements, "
527
+ f"{sum(r['planned']['rows_read'] for r in planned):,} rows read, about {sum(r['planned']['cpu_s_estimate'] for r in planned):.0f} "
528
+ "CPU-s (an estimate)." + (f" Spent: {s.get('statements')} statements, server CPU "
529
+ f"{s['cpu_s_server'] if s.get('cpu_s_server') is not None else '-'} s (upper bound {s.get('cpu_s_upper_bound')} s)."
530
+ if not result.get("dry_run") else ""), highlight=False)
531
+ aside: dict[str, int] = {}
532
+ for r in result.get("set_aside") or []:
533
+ aside[r["reason"]] = aside.get(r["reason"], 0) + 1
534
+ if aside:
535
+ console.print(" not counted: " + "; ".join(f"{n} {k.replace('_', ' ')}" for k, n in sorted(aside.items(), key=lambda x: -x[1])), highlight=False)
536
+ for n in result.get("notes") or []:
537
+ console.print(f" {n}", markup=False, highlight=False)
538
+
539
+
540
+ def print_locality_statements() -> None:
541
+ from .realdb import locality
542
+ console.print(" --locality (reads table data; counts only leave the server; values hashed and compared in the server, probes drawn "
543
+ "in the statement, part names from system.parts; 2 threads, a memory cap and a time limit per statement):", highlight=False)
544
+ for st in (locality.PARTS, locality.COST):
545
+ console.print(f" [bold]{st.id}[/bold]: {st.purpose}", highlight=False)
546
+ console.print(" " + " ".join(st.sql.split()), markup=False, highlight=False, soft_wrap=True)
547
+ for sid in locality.KINDS:
548
+ console.print(f" [bold]{sid}[/bold] (tier D, one per candidate): {locality.PURPOSE[sid]}", highlight=False)
549
+ console.print(" " + " ".join(locality.TEMPLATES[sid].split()), markup=False, highlight=False, soft_wrap=True)
550
+
551
+
552
+ def _trial_step(reader, out_dir: Path, wanted: list[str], hours: int) -> None:
553
+ """--trial-compare: each named trial (apply/trial/trials.json) compared in the query log; db_trial.json (local)."""
554
+ from .realdb import locality
555
+ path = out_dir / "apply" / "trial" / "trials.json"
556
+ trials = {t["id"].upper(): t for t in json.loads(path.read_text())} if path.exists() else {}
557
+ got = json.loads((out_dir / locality.TRIAL_FILE).read_text()) if (out_dir / locality.TRIAL_FILE).exists() else {"trials": {}}
558
+ for w in wanted:
559
+ t = trials.get(w.upper())
560
+ if t is None:
561
+ err.print(f"[yellow]{w}: no trial written for it ({path}); run `codecop apply --trial --finding {w}` first.[/yellow]")
562
+ continue
563
+ r = locality.trial_compare(reader, t, hours)
564
+ got["trials"][t["fingerprint"] or t["id"]] = {**r, "id": t["id"], "window_hours": hours, "at": _stamp()}
565
+ console.print(f" trial {t['id']}: {r['status']}" + (f", marks selected x{r['ratio']} on runs that read only the trial partition "
566
+ f"({r['runs_trial']:,} runs after the build; "
567
+ + "; ".join(f"against {x['against']}" for x in r["statements"][:1]) + ")"
568
+ if r.get("ratio") is not None else f" ({r.get('reason')})"), highlight=False)
569
+ write_json(out_dir / locality.TRIAL_FILE, got)
570
+
571
+
572
+ def _locality_only(out_dir: Path, conns: list[realdb.Connection], settings: dict, dry_run: bool, trials: list[str] | None = None,
573
+ hours: int = 24) -> None:
574
+ """`codecop db pull --locality-only`: the read-only check, then the locality step on the catalog already pulled (or, with
575
+ --trial-compare, the comparison of trials the user ran)."""
576
+ cat = json.loads((out_dir / CATALOG_FILE).read_text()) if (out_dir / CATALOG_FILE).exists() else {}
577
+ chs = [c for c in conns if c.engine == "clickhouse" and c.name in (cat.get("connections") or {})]
578
+ if not chs:
579
+ err.print(f"[red]No pulled ClickHouse catalog in {out_dir / CATALOG_FILE} for these connections.[/red] Run `codecop db pull` first.")
580
+ raise typer.Exit(2)
581
+ if dry_run:
582
+ for conn in chs:
583
+ console.print(f"\n[bold]{conn.label}[/bold]: would send these statements (not connecting)")
584
+ print_locality_statements()
585
+ with realdb.open_reader(conn, Audit(None, conn, dry_run=True), dry_run=True, settings=settings) as reader:
586
+ locality_step(reader, conn, out_dir, cat["connections"][conn.name], settings)
587
+ return
588
+ caps, audits = [], []
589
+ for conn in chs:
590
+ audit = Audit(out_dir, conn)
591
+ audits.append(audit)
592
+ try:
593
+ with realdb.open_reader(conn, audit, settings=settings) as reader:
594
+ cap = reader.check()
595
+ caps.append((conn, cap, ""))
596
+ if not cap["read_only_enforced"]:
597
+ err.print(f"[red]{conn.label}: the server did not confirm read-only; skipped.[/red]")
598
+ continue
599
+ if trials:
600
+ _trial_step(reader, out_dir, trials, hours)
601
+ continue
602
+ locality_step(reader, conn, out_dir, cat["connections"][conn.name], settings)
603
+ except DbError as e:
604
+ if not any(c is conn for c, _, _ in caps):
605
+ caps.append((conn, None, str(e)[:160]))
606
+ else:
607
+ err.print(f"[red]{conn.label}: {str(e)[:300]}[/red]")
608
+ print_capabilities(caps)
609
+ print_audit(audits, out_dir)
610
+
611
+
612
+ @db_app.command()
613
+ def pull(
614
+ path: Path = typer.Argument(Path("."), help="Repository that was (or will be) scanned."),
615
+ env_file: Optional[Path] = typer.Option(None, "--env-file", help=ENV_HELP),
616
+ out: Optional[Path] = typer.Option(None, "--out", help="Directory for db_catalog.json and db_workload.json. Default: <path>/.codecop"),
617
+ engine: Optional[str] = typer.Option(None, "--engine", help="Only connections of this engine."),
618
+ connection: list[str] = typer.Option([], "--connection", help="Only this connection. Repeatable."),
619
+ maps: list[str] = typer.Option([], "--map", help=MAP_HELP),
620
+ database: list[str] = typer.Option([], "--database", help="ClickHouse: describe this database (default: the one in the env file). PostgreSQL: also pull this "
621
+ "database of the same server, stored as connection <name>:<database>. Repeatable."),
622
+ hours: int = typer.Option(24, "--hours", help="Workload window: the last N hours of the query log (ClickHouse). At most 168."),
623
+ top: int = typer.Option(500, "--top", help="Query shapes to keep per ranking (by bytes read, by executions, by time)."),
624
+ max_log_rows: int = typer.Option(20_000_000, "--max-log-rows", help="Shrink the window until the query log holds at most this many rows."),
625
+ workload: bool = typer.Option(True, "--workload/--no-workload", help="Tier B: aggregate the query log."),
626
+ plans: bool = typer.Option(False, "--plans", help="Tier C, PostgreSQL 16+: EXPLAIN (GENERIC_PLAN) the heaviest SELECTs. Planned, never executed."),
627
+ sample: bool = typer.Option(False, "--sample", help="Tier D: read a capped sample of table data for column statistics. Off by default."),
628
+ sample_rows: int = typer.Option(1_000_000, "--sample-rows", help="Rows a sampling statement may read."),
629
+ sample_table: list[str] = typer.Option([], "--sample-table", help="Sample only this table. Repeatable. Default: the ten largest."),
630
+ partition_detail: Optional[bool] = typer.Option(None, "--partition-detail/--no-partition-detail", help="ClickHouse, tier A: parts and "
631
+ "column sizes per partition (no data values). Default: on, or partition_detail under "
632
+ "[db_pull] in codecop.toml."),
633
+ spread: Optional[str] = typer.Option(None, "--spread", help="ClickHouse, tier B: quantiles of rows and bytes read per query shape: "
634
+ "auto, exact, tdigest or off. Default: auto, or spread under [db_pull] in codecop.toml."),
635
+ dry_run: bool = typer.Option(False, "--dry-run", help="Print the statements and stop, without connecting."),
636
+ tls_no_verify: bool = typer.Option(False, "--tls-no-verify", help=TLS_NO_VERIFY_HELP),
637
+ tls_ca_file: Optional[Path] = typer.Option(None, "--tls-ca-file", help=TLS_CA_HELP),
638
+ watch_locks: bool = typer.Option(False, "--watch-locks", help="Also gather lock and contention evidence into db_locks.json: "
639
+ "PostgreSQL, a sampled watch of pg_stat_activity and pg_locks (db_pull.watch_samples x "
640
+ "db_pull.watch_interval_ms, default 60 x 2 s) plus deadlock counters, settings and foreign keys "
641
+ "without an index; ClickHouse, mutations, merges, parts and refused inserts once. Counts only."),
642
+ locality: bool = typer.Option(False, "--locality", help="ClickHouse: count the advisor's skip indexes, projections and re-keys on "
643
+ "production by aggregates (advisor.json from `codecop advise`). Reads table data inside a row and CPU "
644
+ "budget; counts only leave the server. --dry-run lists the statements with their planned cost."),
645
+ locality_only: bool = typer.Option(False, "--locality-only", help="Only the locality step, on the catalog already pulled "
646
+ "(db_catalog.json): no catalog or workload is read again."),
647
+ trial_compare: list[str] = typer.Option([], "--trial-compare", help="With --locality-only: after `codecop apply --trial` was run by "
648
+ "you, compare marks per run inside the trial partition with a neighbour, from the query log "
649
+ "(TS-003). Repeatable. Over --hours."),
650
+ ) -> None:
651
+ """Pull the real catalog (tier A) and workload (tier B) into the out dir. Read-only, limited, audited.
652
+
653
+ Settings under the db_pull table of codecop.toml (caps on what is asked for and kept; the defaults are generous):
654
+ partition_detail (true), partitions_per_table (1000), column_partitions_per_table (120), partition_rows (150000),
655
+ spread (auto), spread_exact_max_runs (10000000), selected (true), selected_shapes (400), selected_max_log_rows (500000),
656
+ text_max_chars (a normalized query text is cut at this many characters, 100000), tags (call-site tags from log_comment, true),
657
+ comments (the application's own log_comment labels, kept on this machine, true), clients (driver and tool names, kept on this
658
+ machine, true), columns (columns read and projections used per shape, true), columns_per_shape (200), repeats (runs per distinct
659
+ statement, true), repeats_max_log_rows (500000), minutes (runs per minute, kept on this machine, true), minutes_shapes (200),
660
+ minutes_max_rows (500000), inserts (inserts per table, true), inserts_tables (5000); with --watch-locks: watch_samples (60),
661
+ watch_interval_ms (2000), watch_days (ClickHouse window, 7).
662
+ What one statement may cost the server: a table db_pull.limits.<statement id or the start of one> with any of seconds,
663
+ rows_to_read, bytes_to_read, result_rows, memory_bytes, threads. --dry-run prints the limits in force.
664
+
665
+ \b
666
+ --locality (ClickHouse): locality (true: a scan given --env-file counts too; false: never), locality_rows_per_statement
667
+ (5000000), locality_max_statements (200), locality_cpu_seconds_total (120), locality_min_table_rows (32768), locality_probes (63), locality_draws (3),
668
+ locality_window_hours (168), locality_cpu_ns_per_row (1000, for the planned cost), locality_max_parts (2000),
669
+ locality_parts_per_statement (256), locality_log_wait_s (10)."""
670
+ root = path.resolve()
671
+ out_dir = out or (root / ".codecop")
672
+ conns = connections(root, env_file, maps, engine, connection, tls_no_verify=tls_no_verify, tls_ca_file=tls_ca_file)
673
+ conns = every_database(conns, database)
674
+ try:
675
+ settings = realdb.pull_settings(realdb.load_toml_db(root), partition_detail=partition_detail, spread=spread)
676
+ except DbError as e:
677
+ err.print(f"[red]{e}[/red]")
678
+ raise typer.Exit(2)
679
+ tiers = {"check", "A"} | ({"B"} if workload else set())
680
+ locality = bool(locality is True or locality_only is True)
681
+ if locality_only is True:
682
+ return _locality_only(out_dir, conns, settings, dry_run is True,
683
+ trials=[t for t in trial_compare if isinstance(t, str)] if isinstance(trial_compare, list) else [],
684
+ hours=max(1, min(hours, 168)) if isinstance(hours, int) else 24)
685
+ if dry_run:
686
+ for conn in conns:
687
+ print_statements(conn, tiers, plans=plans, sample=sample, settings=settings, hours=max(1, min(hours, 168)))
688
+ if watch_locks is True:
689
+ print_lock_statements(conn, settings)
690
+ if locality and conn.engine == "clickhouse":
691
+ print_locality_statements()
692
+ cat = json.loads((out_dir / CATALOG_FILE).read_text()) if (out_dir / CATALOG_FILE).exists() else {}
693
+ c = (cat.get("connections") or {}).get(conn.name)
694
+ if c is None:
695
+ console.print(" --locality: the planned statements per candidate need a pulled catalog (db_catalog.json) and advisor.json.",
696
+ highlight=False)
697
+ else:
698
+ with realdb.open_reader(conn, Audit(None, conn, dry_run=True), dry_run=True, settings=settings) as reader:
699
+ locality_step(reader, conn, out_dir, c, settings)
700
+ return
701
+ hours = max(1, min(hours, 168))
702
+ catalog = {"schema_version": 1, "tool_version": __version__, "generated_at": _stamp(), "connections": {}}
703
+ work = {"schema_version": 1, "tool_version": __version__, "generated_at": _stamp(), "connections": {}}
704
+ samples = {"schema_version": 1, "tool_version": __version__, "generated_at": _stamp(), "connections": {}}
705
+ caps, audits = [], []
706
+ locks_doc = {"schema_version": 1, "tool_version": __version__, "generated_at": _stamp(), "connections": {}}
707
+ for conn in conns:
708
+ audit = Audit(out_dir, conn)
709
+ audits.append(audit)
710
+ try:
711
+ with realdb.open_reader(conn, audit, settings=settings) as reader:
712
+ cap = reader.check()
713
+ caps.append((conn, cap, ""))
714
+ if not cap["read_only_enforced"]:
715
+ err.print(f"[red]{conn.label}: the server did not confirm read-only; skipped.[/red]")
716
+ continue
717
+ meta = {"engine": conn.engine, "source": conn.source, "version": cap["version"], "capabilities": cap}
718
+ if cap["catalog"]:
719
+ err.print(f"[dim] {conn.label}: catalog[/dim]")
720
+ cat = reader.catalog(databases=database or None)
721
+ catalog["connections"][conn.name] = {**meta, **cat}
722
+ if workload and cap["workload"]:
723
+ err.print(f"[dim] {conn.label}: workload[/dim]")
724
+ try:
725
+ w = reader.workload(hours=hours, top=top, max_queries=max_log_rows)
726
+ except Refused as e:
727
+ w = {"engine": conn.engine, "available": False, "reason": str(e)[:300], "queries": []}
728
+ err.print(f"[yellow]{conn.label}: the workload could not be read within the limits: {str(e)[:200]}[/yellow]")
729
+ if plans and w.get("queries"):
730
+ w["plans"] = reader.plans(w)
731
+ work["connections"][conn.name] = {"engine": conn.engine, "source": conn.source, "version": cap["version"], **w}
732
+ elif workload:
733
+ work["connections"][conn.name] = {"engine": conn.engine, "source": conn.source, "version": cap["version"],
734
+ "available": False, "reason": cap["workload_source"], "queries": []}
735
+ if locality and conn.engine == "clickhouse" and conn.name in catalog["connections"]:
736
+ write_json(out_dir / CATALOG_FILE, catalog) # the advisor may read it next; written again below
737
+ locality_step(reader, conn, out_dir, catalog["connections"][conn.name], settings)
738
+ if sample and conn.name in catalog["connections"]:
739
+ from .realdb import sample as sample_mod
740
+ err.print(f"[dim] {conn.label}: sampling (tier D)[/dim]")
741
+ samples["connections"][conn.name] = sample_mod.run(reader, catalog["connections"][conn.name],
742
+ tables=sample_table or None, rows=sample_rows)
743
+ if watch_locks is True:
744
+ from .realdb import locks as locks_mod
745
+ if conn.engine == "clickhouse":
746
+ err.print(f"[dim] {conn.label}: lock evidence (mutations, merges, parts)[/dim]")
747
+ got = locks_mod.evidence_clickhouse(reader, settings)
748
+ else:
749
+ err.print(f"[dim] {conn.label}: watching locks, {settings['watch_samples']} samples "
750
+ f"{settings['watch_interval_ms'] / 1000:g} s apart[/dim]")
751
+ got = locks_mod.watch_postgres(reader, settings, log=lambda t: err.print(f"[dim] {t}[/dim]"))
752
+ locks_doc["connections"][conn.name] = {"source": conn.source, "version": cap["version"], **got}
753
+ except DbError as e:
754
+ if not any(c is conn for c, _, _ in caps):
755
+ caps.append((conn, None, str(e)[:160]))
756
+ else:
757
+ err.print(f"[red]{conn.label}: {str(e)[:300]}[/red]")
758
+ print_capabilities(caps)
759
+ if catalog["connections"]:
760
+ write_json(out_dir / CATALOG_FILE, catalog)
761
+ table = Table(title="Catalog (tier A)", title_justify="left")
762
+ for col in ("connection", "tables", "rows", "on disk", "largest table", "per partition"):
763
+ table.add_column(col, justify="left" if col in ("connection", "largest table", "per partition") else "right", overflow="fold")
764
+ for name, c in catalog["connections"].items():
765
+ tables = c["tables"]
766
+ big = max(tables, key=lambda t: t.get("bytes_on_disk") or 0, default=None)
767
+ table.add_row(name, f"{len(tables):,}", _human(sum(t.get("rows") or 0 for t in tables)),
768
+ _bytes(sum(t.get("bytes_on_disk") or 0 for t in tables)),
769
+ f"{big['name']} ({_human(big.get('rows'))} rows, {_bytes(big.get('bytes_on_disk'))})" if big else "-",
770
+ partition_cell(c))
771
+ console.print(table)
772
+ for name, c in catalog["connections"].items():
773
+ for note in c.get("notes") or []:
774
+ console.print(f" {name}: {note}", markup=False, highlight=False)
775
+ if work["connections"]:
776
+ if (out_dir / WORKLOAD_FILE).exists():
777
+ # the previous pull is kept: a server whose log holds an hour gives a day of shapes over a day of pulls
778
+ snaps = out_dir / "db_snapshots"
779
+ snaps.mkdir(exist_ok=True)
780
+ prev = out_dir / WORKLOAD_FILE
781
+ stamp = re.sub(r"\W", "", str(json.loads(prev.read_text()).get("generated_at") or "earlier"))[:15]
782
+ prev.replace(snaps / f"db_workload-{stamp}.json")
783
+ write_json(out_dir / WORKLOAD_FILE, work)
784
+ table = Table(title="Workload (tier B)", title_justify="left")
785
+ for col in ("connection", "source", "window", "SELECT executions", "shapes", "bytes read", "shapes kept", "notes"):
786
+ table.add_column(col, justify="left" if col in ("connection", "source", "notes") else "right", overflow="fold")
787
+ for name, w in work["connections"].items():
788
+ if not w.get("queries") and w.get("available") is False:
789
+ table.add_row(name, "-", "-", "-", "-", "-", "-", f"unavailable: {w.get('reason', '')}")
790
+ continue
791
+ t = w["totals"]["select"]
792
+ table.add_row(name, w.get("source", ""), f"{w['window_hours']} h" if w.get("window_hours") else f"since {str(w.get('since', ''))[:10] or 'reset'}",
793
+ _human(t["executions"]), _human(t["shapes"]), _bytes(t["read_bytes"]), str(len(w["queries"])), "; ".join(w.get("notes") or []))
794
+ console.print(table)
795
+ if samples["connections"]:
796
+ write_json(out_dir / SAMPLE_FILE, samples)
797
+ if locks_doc["connections"]:
798
+ print_locks(out_dir, locks_doc, work if work["connections"] else (load_workload(out_dir) if (out_dir / WORKLOAD_FILE).exists() else None))
799
+ run_match(out_dir)
800
+ print_audit(audits, out_dir)
801
+ console.print("Stays on this machine: table definitions, database and account names, labels and client names, partition ids and times, "
802
+ "runs per minute. `codecop push` sends counts and sizes, the column and projection names a call site reads (table.column), the "
803
+ "call-site tags, and the normalized text of the statements (every value is `?`, database prefixes removed; "
804
+ "[push] observed_text = false keeps the text here).")
805
+
806
+
807
+ @db_app.command()
808
+ def match(
809
+ path: Path = typer.Argument(Path("."), help="Repository that was scanned."),
810
+ out: Optional[Path] = typer.Option(None, "--out", help="Directory holding inventory.json and db_workload.json. Default: <path>/.codecop"),
811
+ limit: int = typer.Option(20, "--limit", help="Heaviest real queries to list."),
812
+ inventory: list[Path] = typer.Option([], "--inventory", help="Match the same workload against another repository too: its out dir "
813
+ "(or its inventory.json). Repeatable. A database is usually shared by several repositories."),
814
+ ) -> None:
815
+ """Match the pulled workload to the repo's call sites (local: no database is contacted)."""
816
+ root = path.resolve()
817
+ out_dir = out or (root / ".codecop")
818
+ if inventory:
819
+ return match_all(out_dir, inventory, limit)
820
+ result = run_match(out_dir)
821
+ if result is None:
822
+ err.print(f"[red]Need inventory.json and {WORKLOAD_FILE} in {out_dir}.[/red] Run `codecop discover` and `codecop db pull` first.")
823
+ raise typer.Exit(2)
824
+ sites = {c["id"]: c for c in json.loads((out_dir / "inventory.json").read_text())["call_sites"]}
825
+ for eng, m in result["engines"].items():
826
+ table = Table(title=f"Heaviest real {eng} queries by bytes read", title_justify="left")
827
+ for col in ("#", "read", "share", "runs", "avg ms", *RATIO_COLUMNS, "tables", "match", "call site", "entry point"):
828
+ table.add_column(col, overflow="fold", justify="right" if col in ("#", "read", "share", "runs", "avg ms", *RATIO_COLUMNS[:4]) else "left")
829
+ total = m["workload"]["read_bytes"] or 1
830
+ for q in sorted(m["queries"], key=lambda q: -q["read_bytes"])[:limit]:
831
+ site = sites.get(q["site_ids"][0]) if q["site_ids"] else None
832
+ origin = (site.get("origins") or [{}])[0] if site else {}
833
+ more = f" +{len(q['site_ids']) - 1}" if len(q["site_ids"]) > 1 else ""
834
+ table.add_row(str(q["rank_by_bytes"]), _bytes(q["read_bytes"]), f"{q['read_bytes'] / total:.1%}", _human(q["executions"]),
835
+ f"{q['avg_ms']:.0f}", *ratio_cells(q), ", ".join(q["tables"][:3]), q["match"],
836
+ f"{site['file']}:{site['line']}{more}" if site else "no call site in this repo",
837
+ f"{origin.get('kind', '')} {origin.get('name', '')}".strip() if site else "")
838
+ console.print(table)
839
+ console.print(f"Match: [bold]{out_dir / MATCH_FILE}[/bold]")
840
+
841
+
842
+ def match_all(out_dir: Path, others: list[Path], limit: int) -> None:
843
+ """One workload, several repositories: each one's share, the union, and what no repository accounts for."""
844
+ from .realdb import match as match_mod
845
+
846
+ if not (out_dir / WORKLOAD_FILE).exists():
847
+ err.print(f"[red]No {WORKLOAD_FILE} in {out_dir}.[/red] Run `codecop db pull` first.")
848
+ raise typer.Exit(2)
849
+ paths = ([out_dir / "inventory.json"] if (out_dir / "inventory.json").exists() else []) + [
850
+ p / "inventory.json" if p.is_dir() else p for p in others]
851
+ inventories: dict[str, dict] = {}
852
+ for p in paths:
853
+ if not p.exists():
854
+ err.print(f"[red]No inventory at {p}.[/red]")
855
+ raise typer.Exit(2)
856
+ inv = json.loads(p.read_text())
857
+ name = (inv.get("repo") or {}).get("name") or p.parent.name
858
+ inventories[name if name not in inventories else f"{name} ({p.parent.name})"] = inv
859
+ workload = load_workload(out_dir)
860
+ result = {"schema_version": 1, "tool_version": __version__, "generated_at": _stamp(), "engines": {}}
861
+ for w in (workload.get("connections") or {}).values():
862
+ if w.get("queries") and w["engine"] not in result["engines"]:
863
+ result["engines"][w["engine"]] = match_mod.match_many(inventories, w, engine=w["engine"])
864
+ write_json(out_dir / "db_match_all.json", result)
865
+ for eng, m in result["engines"].items():
866
+ total = m["workload"].get("read_bytes") or 1
867
+ table = Table(title=f"{eng}: one workload, {len(inventories)} repositories", title_justify="left")
868
+ for col in ("repository", "sites matched (sure)", "bytes read matched (sure)", "part of a longer statement", "likely"):
869
+ table.add_column(col, justify="left" if col == "repository" else "right")
870
+ for name, r in m["repositories"].items():
871
+ table.add_row(name, str(r["sites_matched"]["exact"] + r["sites_matched"]["template"]), f"{r['rates']['sure']['share_of_all_read_bytes']:.1%}",
872
+ f"{r['rates']['part']['share_of_all_read_bytes']:.1%}", f"{r['rates']['likely']['share_of_all_read_bytes']:.1%}")
873
+ u = m["union"]
874
+ table.add_row("[bold]all together[/bold]", "", f"[bold]{u['sure']['share_of_all_read_bytes']:.1%}[/bold]",
875
+ f"{u['part']['share_of_all_read_bytes']:.1%}", f"{u['likely']['share_of_all_read_bytes']:.1%}")
876
+ table.add_row("no repository", "", f"{u['none']['share_of_all_read_bytes']:.1%}", "", "")
877
+ console.print(table)
878
+ rows = Table(title=f"Heaviest real {eng} queries no repository matches for sure", title_justify="left")
879
+ for col in ("#", "read", "share", "runs", "avg ms", *RATIO_COLUMNS, "tables", "nearest", "where"):
880
+ rows.add_column(col, overflow="fold", justify="right" if col in ("#", "read", "share", "runs", "avg ms", *RATIO_COLUMNS[:4]) else "left")
881
+ for q in [q for q in m["queries"] if q["match"] not in ("exact", "template", "tag")][:limit]:
882
+ rows.add_row(str(q["rank_by_bytes"]), _bytes(q["read_bytes"]), f"{q['read_bytes'] / total:.1%}", _human(q["executions"]),
883
+ f"{q['avg_ms']:.0f}", *ratio_cells(q), ", ".join(q["tables"][:3]), q["match"], "; ".join(q.get("sites") or [])[:120])
884
+ console.print(rows)
885
+ console.print(f"Match across repositories: [bold]{out_dir / 'db_match_all.json'}[/bold] (no query text in it)")