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/rank.py ADDED
@@ -0,0 +1,1473 @@
1
+ """Stage 2, rank: the developer's coding agent picks the candidates worth benchmarking.
2
+
3
+ Cheap heuristics build a shortlist first, so the agent spends tokens on judging
4
+ and on making queries runnable, not on reading every call site.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import json
11
+ import math
12
+ import re
13
+ import threading
14
+ import time
15
+ from collections import Counter
16
+ from concurrent.futures import ThreadPoolExecutor
17
+ from dataclasses import dataclass, field
18
+ from datetime import datetime, timezone
19
+ from importlib import resources
20
+ from pathlib import Path
21
+
22
+ from . import __version__, engines
23
+ from .agent import AgentError, AgentRunner, billing
24
+ from .discover.schema import _split_top
25
+
26
+ FLAG_WEIGHT = {"in_loop": 3.0, "no_filter": 3.0, "final": 2.0, "select_star": 2.0, "offset_paging": 2.0, "leading_wildcard_like": 2.0}
27
+ LARGE_TABLE_HINT = re.compile(r"(log|event|request|call|history|audit|activity|metric|trace|message|finding)s?(_|$|\b)", re.I)
28
+ ONE_OFF_PATH = re.compile(r"(^|/)(scripts?|helper_scripts|tools?|migrations?|bench(marks?)?|examples?|legacy\w*|ci|deploy)/", re.I)
29
+ TEST_PATH = re.compile(r"(^|/)(tests?|testdata|fixtures)/|(^|/)test_|_test\.")
30
+ from .runsonce import RUNS_ONCE_PATH # noqa: E402,F401 (code that runs once: migrations, seeds, backfills)
31
+ SYSTEM_TABLE = re.compile(r"^(system|information_schema)\.", re.I)
32
+
33
+
34
+ def load_prompt(name: str) -> str:
35
+ return resources.files("codecop.prompts").joinpath(f"{name}.md").read_text()
36
+
37
+
38
+ def load_schema(name: str) -> dict:
39
+ return json.loads(resources.files("codecop.schemas").joinpath(f"{name}.schema.json").read_text())
40
+
41
+
42
+ ROLE_WEIGHT = {"app": 1.0, "job": 0.5, "unknown": 0.0, "tooling": -3.0, "script": -3.0, "migration": -4.0}
43
+ ORIGIN_WEIGHT = {"http": 2.5, "workflow": 2.0, "activity": 2.0, "job": 2.0, "consumer": 2.0, "main": 0.0, "cli": -1.0}
44
+ RECURRING = ("workflow", "activity", "job", "consumer")
45
+ PATH_KINDS = ("http",) + RECURRING # entry points that make a query part of a request path or of recurring work
46
+ # app: every query of app and job code (request paths and recurring work first; scripts, tooling, migrations and tests
47
+ # stay out): the default of `codecop scan`. paths: only queries on a request path. all: scripts and tooling too. top: the best
48
+ # --shortlist in one call (kept for debugging).
49
+ DEPTHS = ("top", "paths", "app", "all")
50
+ APP_ROLES = ("app", "job", "unknown")
51
+ # The first-run priors of the one run budget (budget.py, `[agent]` in codecop.toml: items_per_call.rank, concurrency,
52
+ # cost_per_item_usd_low/high, seconds_per_call_low/high, min_call_usd). The settings decide; these are their defaults.
53
+ BATCH_SIZE = 40 # queries per agent call
54
+ CONCURRENCY = 6 # agent calls at a time
55
+ COST_PER_QUERY_USD = (0.03, 0.06) # a rough prior per query
56
+ SECONDS_PER_BATCH = (45, 320)
57
+ MIN_BATCH_BUDGET_USD = 0.5 # below this a batch is not started: it could not finish
58
+ # the rejection codes that say why (prompts/rank.md); `other` says only that the agent gave prose
59
+ REJECTION_CODES = ("small_table", "already_cheap", "duplicate", "one_off", "unresolved_sql", "other_engine", "cached")
60
+ # The prompt shows each query's SQL up to this many characters (`[rank] max_sql_chars` in codecop.toml). Before it was a
61
+ # setting the cut was LEGACY_MAX_SQL_CHARS: a rank.json that does not record its cut was made with that one.
62
+ MAX_SQL_CHARS = 60_000
63
+ LEGACY_MAX_SQL_CHARS = 1800
64
+ RANK_DEFAULTS = {"max_sql_chars": MAX_SQL_CHARS}
65
+ # Skipped by rule before the agent is paid, with a real catalog and a real workload matched to the call site (skip_rules).
66
+ # A statement is skipped only when its measured total load is negligible: a cheap statement or one on tiny tables that
67
+ # runs so often it is a large share of all bytes read is never skipped (it goes to the agent; `heavy_by_count`).
68
+ SKIP_DEFAULTS = {
69
+ "skip_by_rule": True, # false: every query goes to the agent, as before
70
+ "cheap_max_bytes_per_run": 1_048_576, # already_cheap: a mean run reads at most this many bytes ...
71
+ "cheap_max_share": 0.01, # ... and the statement is under this share of all bytes read
72
+ "small_table_max_rows": 10_000, # small_table: every table it reads has at most this many rows (catalog) ...
73
+ "small_table_max_bytes": 67_108_864, # ... and at most this many bytes on disk ...
74
+ "small_table_max_share": 0.01, # ... and the statement is under this share of all bytes read
75
+ }
76
+
77
+
78
+ def rank_settings(config: dict | None) -> dict:
79
+ """The `[rank]` table of codecop.toml over the defaults. max_sql_chars must be a whole number above zero; the skip floors
80
+ numbers of zero or more (zero turns that rule off), skip_by_rule true or false."""
81
+ out = {**RANK_DEFAULTS, **SKIP_DEFAULTS}
82
+ for key in RANK_DEFAULTS:
83
+ value = (config or {}).get(key)
84
+ if value is None:
85
+ continue
86
+ if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
87
+ raise ValueError(f"rank.{key} must be a whole number above zero.")
88
+ out[key] = int(value)
89
+ for key, default in SKIP_DEFAULTS.items():
90
+ value = (config or {}).get(key)
91
+ if value is None:
92
+ continue
93
+ if isinstance(default, bool):
94
+ if not isinstance(value, bool):
95
+ raise ValueError(f"rank.{key} must be true or false.")
96
+ elif isinstance(value, bool) or not isinstance(value, (int, float)) or value < 0:
97
+ raise ValueError(f"rank.{key} must be a number of zero or more.")
98
+ out[key] = value
99
+ return out
100
+
101
+
102
+ def _catalog_table(real: dict[str, dict], name: str, engine: str) -> dict | None:
103
+ """The catalog entry of a table a call site names (`events`, `db.events`, `public.users`, `audit.log`)."""
104
+ clean = str(name or "").replace('"', "").replace("`", "")
105
+ short = clean.split(".")[-1]
106
+ if engine == "clickhouse":
107
+ return real.get(short)
108
+ return real.get(clean) or (real.get(short) if clean.count(".") == 0 or clean.lower().startswith("public.") else None)
109
+
110
+
111
+ def skip_rule(item: dict, real: dict[str, dict], engine: str, settings: dict) -> dict | None:
112
+ """The rejection a query gets by rule, or None when it goes to the agent. Needs the call site's measured load (a sure
113
+ match: exact, template or tag; never a piece of a longer statement, whose own cost is not known)."""
114
+ m = item.get("measured")
115
+ if not settings.get("skip_by_rule", True) or not m or m.get("located") or m.get("match") not in ("exact", "template", "tag"):
116
+ return None
117
+ if re.search(r"«[^»]*»|…|\{\{.*?\}\}|\{%.*?%\}", item.get("sql") or "", re.S) or item.get("resolution") in ("template", "unresolved", "parameter"):
118
+ return None # SQL assembled at run time: its statement as production ran it is `codecop observe`'s (observed._scope)
119
+ share = float(m.get("share_of_read_bytes") or 0)
120
+ per_run = m.get("bytes_read_per_run")
121
+ load = {"share_of_read_bytes": round(share, 6), "read_bytes": int(m.get("read_bytes") or 0), "executions": int(m.get("executions") or 0),
122
+ **({"bytes_read_per_run": round(float(per_run))} if per_run is not None else {})}
123
+ tables = [(t, _catalog_table(real, t, engine)) for t in item.get("tables") or []]
124
+ known = [(t, e) for t, e in tables if e is not None and e.get("rows") is not None]
125
+ small_rows, small_bytes, small_share = (float(settings[k]) for k in ("small_table_max_rows", "small_table_max_bytes", "small_table_max_share"))
126
+ if tables and len(known) == len(tables) and small_share > 0 and share < small_share \
127
+ and all(int(e.get("rows") or 0) <= small_rows and int(e.get("bytes_on_disk") or 0) <= small_bytes for _, e in known):
128
+ biggest = max(int(e.get("rows") or 0) for _, e in known)
129
+ return {"id": item["id"], "code": "small_table", "by_rule": True,
130
+ "detail": f"skipped by rule before the agent: every table it reads has at most {biggest:,} rows (catalog), and it is "
131
+ f"{share:.3%} of all bytes read (floors: rank.small_table_max_rows {small_rows:,.0f}, rank.small_table_max_share {small_share:g})",
132
+ "evidence": {**load, "table_rows": {t: int(e.get("rows") or 0) for t, e in known},
133
+ "table_bytes": {t: int(e.get("bytes_on_disk") or 0) for t, e in known},
134
+ "floors": {k: settings[k] for k in ("small_table_max_rows", "small_table_max_bytes", "small_table_max_share")}},
135
+ "file": item.get("file", ""), "line": item.get("line", 0)}
136
+ cheap_bytes, cheap_share = float(settings["cheap_max_bytes_per_run"]), float(settings["cheap_max_share"])
137
+ if per_run is not None and cheap_share > 0 and cheap_bytes > 0 and share < cheap_share and float(per_run) <= cheap_bytes:
138
+ return {"id": item["id"], "code": "already_cheap", "by_rule": True,
139
+ "detail": f"skipped by rule before the agent: a mean run reads {float(per_run):,.0f} bytes and it is {share:.3%} of all bytes "
140
+ f"read (floors: rank.cheap_max_bytes_per_run {cheap_bytes:,.0f}, rank.cheap_max_share {cheap_share:g})",
141
+ "evidence": {**load, "floors": {k: settings[k] for k in ("cheap_max_bytes_per_run", "cheap_max_share")}},
142
+ "file": item.get("file", ""), "line": item.get("line", 0)}
143
+ return None
144
+
145
+
146
+ def skip_rules(items: list[dict], facts, engine: str, settings: dict | None) -> tuple[list[dict], list[dict]]:
147
+ """(the queries that go to the agent, the rejections by rule). Nothing is skipped without a real catalog and workload."""
148
+ if not facts or not items:
149
+ return items, []
150
+ cfg = {**SKIP_DEFAULTS, **(settings or {})}
151
+ real = facts.tables(engine)
152
+ kept, skipped = [], []
153
+ for item in items:
154
+ got = skip_rule(item, real, engine, cfg)
155
+ (skipped.append(got) if got else kept.append(item))
156
+ return kept, skipped
157
+
158
+
159
+ def sql_cut_of(rank: dict | None) -> int:
160
+ """The length at which the prompt of a stored rank.json cut each query's SQL."""
161
+ return int((rank or {}).get("max_sql_chars") or LEGACY_MAX_SQL_CHARS)
162
+
163
+
164
+ def site_role(site: dict) -> str:
165
+ """The role discover (or the agent) gave the site; a path guess for inventories that predate roles. A migration, seed
166
+ or backfill file is "migration" whatever an area verdict said: it runs once."""
167
+ if site.get("role") != "test" and not site.get("is_test") and RUNS_ONCE_PATH.search(site.get("file") or ""):
168
+ return "migration"
169
+ if site.get("role"):
170
+ return site["role"]
171
+ if site.get("is_test"):
172
+ return "test"
173
+ return "script" if ONE_OFF_PATH.search(site["file"]) else "unknown"
174
+
175
+
176
+ def value_score(site: dict) -> float:
177
+ """What a fix here is worth: request paths first, recurring work next, one-off code last."""
178
+ kinds = {o.get("kind") for o in site.get("origins") or []}
179
+ best = max((ORIGIN_WEIGHT.get(k, 0.0) for k in kinds), default=0.0)
180
+ return ROLE_WEIGHT.get(site_role(site), 0.0) + best
181
+
182
+
183
+ def score(site: dict, same_sql: int, table_refs: Counter) -> float:
184
+ s = sum(FLAG_WEIGHT.get(f, 0.0) for f in site["flags"]) + value_score(site)
185
+ sql = site["sql"] or ""
186
+ if re.search(r"\bJOIN\b", sql, re.I):
187
+ s += 1.0
188
+ if re.search(r"\bGROUP\s+BY\b", sql, re.I):
189
+ s += 0.5
190
+ if any(LARGE_TABLE_HINT.search(t.split(".")[-1]) for t in site["tables"]):
191
+ s += 2.0
192
+ # tables many call sites read are more likely to be central and large
193
+ s += min(max((table_refs[t] for t in site["tables"]), default=0) / 40.0, 2.0)
194
+ s += min(same_sql - 1, 3) * 0.5
195
+ if site["known_sink"]:
196
+ s += 0.5
197
+ s += engines.get(site["engine"]).score_bonus(site)
198
+ return round(s, 2)
199
+
200
+
201
+ def in_paths(site: dict, paths: list[str] | None) -> bool:
202
+ return not paths or any(site["file"].startswith(p.rstrip("/") + "/") or site["file"] == p for p in paths)
203
+
204
+
205
+ def eligible(site: dict, engine: str, paths: list[str] | None = None) -> bool:
206
+ """A read of a real table on the ranked engine, outside test code: what the shortlist is drawn from.
207
+
208
+ The engine has a say: SQL plainly written for another database, or a read it does not benchmark, is not eligible."""
209
+ return bool(
210
+ site["engine"] == engine and site["statement"] == "select" and site["sql"] and not site["is_test"]
211
+ and site_role(site) != "test" and site["tables"] and not all(SYSTEM_TABLE.match(t) for t in site["tables"])
212
+ and not engines.get(engine).skip_reason(site["sql"]) and not engines.get(engine).site_skip_reason(site)
213
+ and in_paths(site, paths))
214
+
215
+
216
+ def on_request_path(site: dict) -> bool:
217
+ """App or job code that an HTTP route, workflow, activity, scheduled job or consumer reaches.
218
+
219
+ Read from the origins discover kept (the nearest few per site), so a site whose only route is further
220
+ away than its five nearest entry points is missed."""
221
+ return site_role(site) in ("app", "job") and any(o.get("kind") in PATH_KINDS for o in site.get("origins") or [])
222
+
223
+
224
+ def queries(inventory: dict, engine: str, paths: list[str] | None = None, depth: str = "top",
225
+ facts=None) -> tuple[list[dict], int]:
226
+ """Every distinct SELECT of one engine, best first, one item per distinct SQL, and the number of call sites.
227
+
228
+ depth `paths` keeps the queries with a call site on a request path; `app` the queries with a call site in app or job
229
+ code (or code of no known role); `top` and `all` keep every one.
230
+ An item is its best call site plus `locations`, the other call sites that send the same SQL.
231
+
232
+ With `facts` (the real workload matched to call sites) the order is measured, not guessed: queries with
233
+ real load first, by total bytes read; then queries nothing was measured for, those on a request path or recurring
234
+ work first, each by the static score; last the queries that were measured and found negligible."""
235
+ selects = [c for c in inventory["call_sites"] if eligible(c, engine, paths)]
236
+ by_id = {c["id"]: c for c in selects}
237
+ by_sql: dict[str, list[dict]] = {}
238
+ for c in selects:
239
+ by_sql.setdefault(c["sql_hash"], []).append(c)
240
+ table_refs = Counter(t for c in selects for t in c["tables"])
241
+ load = facts.site_load(engine, located=True) if facts else {}
242
+ negligible = getattr(facts, "negligible_share", 0.0001)
243
+ ranked = []
244
+ for group in by_sql.values():
245
+ pool = ([c for c in group if on_request_path(c)] if depth == "paths" else
246
+ [c for c in group if site_role(c) in APP_ROLES] if depth == "app" else group)
247
+ if not pool:
248
+ continue
249
+ best = max(pool, key=lambda c: (c["known_sink"], c["kind"] == "call", len(c["flags"])))
250
+ others = [{"id": c["id"], "file": c["file"], "line": c["line"], "symbol": c.get("symbol", ""), "role": site_role(c),
251
+ "origins": c.get("origins") or [], "origin_count": c.get("origin_count", 0)} for c in group if c is not best]
252
+ item = {**best, "score": score(best, len(group), table_refs), "same_sql_sites": len(group), "locations": others,
253
+ "on_path": any(on_request_path(c) for c in group)}
254
+ measured = [load[c["id"]] for c in group if c["id"] in load]
255
+ if measured:
256
+ # the sites of one group send the same SQL, so they matched the same real statements: take the row once
257
+ item["measured"] = max(measured, key=lambda r: r["read_bytes"])
258
+ item["measured_text"] = facts.load_text(engine, item["measured"])
259
+ ranked.append(item)
260
+
261
+ for item in ranked:
262
+ # the free baseline pass measured it (no production heat): rows read beyond what it returns, its cost over the floor
263
+ ex = [c.get("measured_excess") for c in [item] + [by_id.get(o["id"], {}) for o in item["locations"]] if c.get("measured_excess") is not None]
264
+ item["measured_excess"] = max(ex) if ex else None
265
+
266
+ def band(c: dict) -> tuple:
267
+ m = c.get("measured")
268
+ if m is None:
269
+ ex = c.get("measured_excess")
270
+ # request paths first; within them the measured cost over the floor, then hand-written SQL before ORM calls
271
+ return (1, 0 if c.get("on_path") else 1, -(ex or 0), 1 if c.get("resolution") == "orm" else 0)
272
+ return (2, 0, 0, 0) if m["share_of_read_bytes"] < negligible else (0, -m["read_bytes"], 0, 0)
273
+
274
+ ranked.sort(key=lambda c: (*band(c), -c["score"], c["file"], c["line"]))
275
+ return ranked, len(selects)
276
+
277
+
278
+ def shortlist(inventory: dict, engine: str, size: int, paths: list[str] | None = None) -> tuple[list[dict], int]:
279
+ """The `size` best SELECT call sites for one engine, one per distinct SQL."""
280
+ ranked, total = queries(inventory, engine, paths, "top")
281
+ return ranked[:size], total
282
+
283
+
284
+ def make_batches(items: list[dict], size: int = BATCH_SIZE) -> list[list[dict]]:
285
+ """Split into batches of about `size`, queries on the same tables together, so the agent reads each
286
+ table's definition and callers once. The busiest tables come first."""
287
+ if not items:
288
+ return []
289
+ refs = Counter(t for c in items for t in set(c["tables"]))
290
+
291
+ def anchor(c: dict) -> str:
292
+ return max(c["tables"], key=lambda t: (refs[t], t))
293
+
294
+ ordered = sorted(items, key=lambda c: (-refs[anchor(c)], anchor(c), -c["score"], c["file"], c["line"]))
295
+ count = math.ceil(len(ordered) / max(size, 1))
296
+ per = math.ceil(len(ordered) / count)
297
+ return [ordered[i:i + per] for i in range(0, len(ordered), per)]
298
+
299
+
300
+ @dataclass
301
+ class Plan:
302
+ depth: str
303
+ engine: str
304
+ paths: list[str]
305
+ batches: list[list[dict]]
306
+ select_sites: int # eligible SELECT call sites of the engine
307
+ unique_queries: int # distinct SQL among them
308
+ max_sql_chars: int = MAX_SQL_CHARS # the prompt shows each query's SQL up to this length
309
+ focus: str = "" # `join`: only the join statements CodeCop flagged, their facts in the prompt
310
+ skipped: list = field(default_factory=list) # rejections by rule (skip_rules): not shown to the agent
311
+ skipped_in_scope: int = 0 # how many of them the plan would have sent without the rule
312
+ refilled: bool = False # depth top: their places in the shortlist went to the next queries
313
+ batch_size: int = BATCH_SIZE
314
+ cached: list = field(default_factory=list) # (query, stored verdict): answered before, not asked again (verdicts.py)
315
+ unasked: list = field(default_factory=list) # queries left out to stay within the run budget: not asked yet
316
+ keys: dict = field(default_factory=dict) # query id -> its verdict key
317
+ cache_ready: bool = False
318
+ pool: tuple | None = None # (batches, unasked) as planned, before the stored verdicts were taken out
319
+ per_query_usd: tuple = COST_PER_QUERY_USD # the estimate per query: the ledger's learned cost, else the prior
320
+
321
+ def cut_items(self) -> list[dict]:
322
+ """The queries whose SQL is longer than the prompt shows: the agent sees only the start of them."""
323
+ return [c for c in self.items if len((c.get("sql") or "").strip()) > self.max_sql_chars]
324
+
325
+ @property
326
+ def items(self) -> list[dict]:
327
+ return [c for batch in self.batches for c in batch]
328
+
329
+ def estimate(self, concurrency: int = CONCURRENCY) -> dict:
330
+ """A cost and time range from a rough prior per query, or the
331
+ repository's own cost per query once its ledger has one (`per_query_usd`). Queries answered before cost nothing."""
332
+ n = len(self.items)
333
+ waves = math.ceil(len(self.batches) / max(concurrency, 1))
334
+ lo, hi = self.per_query_usd
335
+ return {"queries": n, "sites": sum(c["same_sql_sites"] for c in self.items), "batches": len(self.batches),
336
+ "cost_low_usd": round(n * lo, 2), "cost_high_usd": round(n * hi, 2),
337
+ "seconds_low": waves * SECONDS_PER_BATCH[0], "seconds_high": waves * SECONDS_PER_BATCH[1],
338
+ "answered_before": len(self.cached), "not_asked": len(self.unasked),
339
+ **self.skip_estimate()}
340
+
341
+ def skip_estimate(self) -> dict:
342
+ """The queries the rule kept from the agent and what they would have cost at the per-query estimate. With depth
343
+ top the shortlist keeps its size (the next queries take their places), so nothing is saved, only spent better."""
344
+ saved = 0 if self.refilled else self.skipped_in_scope
345
+ return {"skipped_by_rule": self.skipped_in_scope, "skipped_codes": dict(Counter(r["code"] for r in self.skipped)),
346
+ "refilled": self.refilled,
347
+ "skipped_cost_low_usd": round(self.skipped_in_scope * COST_PER_QUERY_USD[0], 2),
348
+ "skipped_cost_high_usd": round(self.skipped_in_scope * COST_PER_QUERY_USD[1], 2),
349
+ "saved_low_usd": round(saved * COST_PER_QUERY_USD[0], 2), "saved_high_usd": round(saved * COST_PER_QUERY_USD[1], 2)}
350
+
351
+
352
+ def plan(inventory: dict, engine: str, *, depth: str = "paths", shortlist_size: int = BATCH_SIZE,
353
+ paths: list[str] | None = None, batch_size: int = BATCH_SIZE, facts=None, max_sql_chars: int = MAX_SQL_CHARS,
354
+ skip_settings: dict | None = None) -> Plan:
355
+ """What the rank stage will show the agent. `top`: the best `shortlist_size` queries in one call (the
356
+ behaviour before depths existed). `paths`: every query on a request path. `all`: every query.
357
+
358
+ With `facts`, queries the real workload shows to be negligible are rejected by rule first (skip_rules; `skip_settings`
359
+ are the `[rank]` floors) and never shown to the agent. With `top` their places go to the next queries."""
360
+ if depth not in DEPTHS:
361
+ raise ValueError(f"depth must be one of {', '.join(DEPTHS)}")
362
+ everything, select_count = queries(inventory, engine, paths, "all", facts)
363
+ if depth == "top":
364
+ in_scope = everything[:shortlist_size]
365
+ kept, skipped = skip_rules(everything, facts, engine, skip_settings)
366
+ batches = [kept[:shortlist_size]] if kept else []
367
+ # the rejections recorded are those among the queries up to the last one sent: the rest were never in reach
368
+ sent = {c["id"] for c in batches[0]} if batches else set()
369
+ last = max((i for i, c in enumerate(everything) if c["id"] in sent), default=len(in_scope) - 1)
370
+ reach = {c["id"] for c in everything[:max(last + 1, len(in_scope))]}
371
+ skipped = [r for r in skipped if r["id"] in reach]
372
+ else:
373
+ in_scope = everything if depth == "all" else queries(inventory, engine, paths, depth, facts)[0]
374
+ kept, skipped = skip_rules(in_scope, facts, engine, skip_settings)
375
+ batches = value_batches(kept, batch_size)
376
+ gone = {r["id"] for r in skipped}
377
+ within = sum(1 for c in in_scope if c["id"] in gone)
378
+ return Plan(depth, engine, list(paths or []), batches, select_count, len(everything), max(int(max_sql_chars), 1),
379
+ skipped=skipped, skipped_in_scope=within, refilled=depth == "top" and within > 0, batch_size=batch_size)
380
+
381
+
382
+ def value_batches(items: list[dict], size: int = BATCH_SIZE) -> list[list[dict]]:
383
+ """make_batches, with the batches in the order of their most valuable query (`items` come best first): a run stopped
384
+ by its budget leaves the least valuable batches unasked."""
385
+ pos = {c["id"]: i for i, c in enumerate(items)}
386
+ return sorted(make_batches(items, size), key=lambda b: min(pos[c["id"]] for c in b))
387
+
388
+
389
+ def restrict(plan: Plan, keep: set[str]) -> Plan:
390
+ """The plan with only the queries `keep` names asked; the others are listed as not asked yet (`unasked`)."""
391
+ items = [c for c in plan.items if c["id"] in keep]
392
+ plan.unasked = plan.unasked + [c for c in plan.items if c["id"] not in keep]
393
+ plan.batches = value_batches(items, plan.batch_size) if plan.depth != "top" else ([items] if items else [])
394
+ return plan
395
+
396
+
397
+ # ---- per-statement verdicts (verdicts.py) ---------------------------------------------------------------------------
398
+
399
+ def rank_prompt_version(engine: str, focus: str = "") -> str:
400
+ """The prompt version of a rank question: the engine's template and output schema (and the join focus text)."""
401
+ from . import verdicts
402
+ eng = engines.get(engine)
403
+ parts = [load_prompt(eng.rank_prompt), json.dumps(eng.rank_schema(load_schema("rank_output")), sort_keys=True)]
404
+ if focus == "join":
405
+ from .joins import FOCUS_TEXT
406
+ parts.append(FOCUS_TEXT)
407
+ elif focus == "assembled":
408
+ from .assemble import FOCUS_TEXT
409
+ parts.append(FOCUS_TEXT)
410
+ return verdicts.prompt_version(*parts)
411
+
412
+
413
+ def item_key(c: dict, engine: str, version: str, fps: dict, prompt_version: str, max_sql_chars: int = MAX_SQL_CHARS) -> str:
414
+ from . import verdicts
415
+ extra = []
416
+ if c.get("join_note"):
417
+ extra.append("join:" + hashlib.sha256(c["join_note"].encode()).hexdigest()[:12])
418
+ if len((c.get("sql") or "").strip()) > max_sql_chars:
419
+ extra.append(f"sql<={max_sql_chars}")
420
+ return verdicts.key("rank", c.get("sql_hash") or c["id"], c.get("tables") or [], fps, engine, version, prompt_version, ";".join(extra))
421
+
422
+
423
+ def _defs_for(cand: dict, definitions: list[dict], engine: str) -> list[dict]:
424
+ want = {canonical_table(t, engine) for t in cand.get("tables") or []}
425
+ return [d for d in definitions if canonical_table(d.get("name", ""), engine) in want and d.get("source") != "real catalog"]
426
+
427
+
428
+ def migrate_batches(store, out_dir: Path | None, items: list[dict], keys: dict[str, str], engine: str, focus: str = "") -> int:
429
+ """Read the per-batch answers an older out dir kept (rank_batches/batch-*.json) into per-statement verdicts, once per
430
+ statement: a candidate or a rejection the batch gave for a query whose SQL is unchanged, to the same question (a
431
+ focused batch only for a focused plan). Batch files written since verdicts exist are not read: their answers are in
432
+ the store already. Batch files are kept."""
433
+ store_dir = (out_dir / "rank_batches") if out_dir else None
434
+ if not store_dir or not store_dir.is_dir():
435
+ return 0
436
+ by_id = {c["id"]: c for c in items}
437
+ by_hash: dict[str, dict] = {}
438
+ for c in items:
439
+ by_hash.setdefault(c.get("sql_hash") or "", c)
440
+ files = [d for d in (_read_json(p, None) for p in sorted(store_dir.glob("batch-*.json"))) if isinstance(d, dict) and d.get("status") == "done"]
441
+ moved = 0
442
+ for data in sorted(files, key=lambda d: d.get("finished_at", "")):
443
+ flavor = str((data.get("question") or {}).get("flavor") or "")
444
+ if data.get("verdicts") or (("focus=" in flavor) != bool(focus)) or (focus and f"focus={focus}" not in flavor):
445
+ continue
446
+ out = data.get("output") or {}
447
+ hashes = data.get("sql_hashes") or {}
448
+ cands = {c.get("id"): c for c in out.get("candidates") or [] if c.get("id")}
449
+ rejs = {r.get("id"): r for r in out.get("rejected") or [] if r.get("id")}
450
+ defs = list(out.get("table_definitions") or [])
451
+ for sid in data.get("ids") or []:
452
+ h = hashes.get(sid)
453
+ c = by_hash.get(h) if h else by_id.get(sid)
454
+ if c is None:
455
+ continue
456
+ k = keys.get(c["id"])
457
+ if not k or store.get(k):
458
+ continue
459
+ if sid in cands:
460
+ rec = {"answer": "candidate", "candidate": cands[sid], "definitions": _defs_for(cands[sid], defs, engine)}
461
+ elif sid in rejs:
462
+ rec = {"answer": "rejected", "rejection": rejs[sid]}
463
+ else:
464
+ continue # the batch said nothing about it (it was capped at --top): asked again
465
+ store.put(k, {"kind": "rank", "id": sid, "sql_hash": c.get("sql_hash", ""), "tables": c.get("tables") or [], **rec,
466
+ "migrated_from": data.get("key", ""), "at": data.get("finished_at", ""),
467
+ "engine_version": data.get("engine_version", "")}, save=False)
468
+ moved += 1
469
+ if moved:
470
+ store.save()
471
+ return moved
472
+
473
+
474
+ def prepare_cache(plan: Plan, inventory: dict, out_dir: Path | None, *, engine_version: str, facts=None, fresh=False,
475
+ store=None, full_inventory: dict | None = None):
476
+ """Take the queries answered before out of the plan (`plan.cached`) and batch only the rest. `fresh`: True asks again
477
+ about every query, a set about the queries it names (finding label, call-site id or path prefix). Returns the store."""
478
+ from . import verdicts
479
+ if store is None:
480
+ store = verdicts.Store(out_dir)
481
+ if plan.cache_ready:
482
+ return store
483
+ plan.pool = ([list(b) for b in plan.batches], list(plan.unasked)) # run_plan puts the plan back as it was planned
484
+ engine = plan.engine
485
+ fps = verdicts.table_fingerprints(full_inventory or inventory, facts, engine)
486
+ pv = rank_prompt_version(engine, plan.focus)
487
+ items = plan.items + plan.unasked
488
+ plan.keys = {c["id"]: item_key(c, engine, engine_version, fps, pv, plan.max_sql_chars) for c in items}
489
+ migrate_batches(store, out_dir, items, plan.keys, engine, plan.focus)
490
+ labels = {}
491
+ if out_dir:
492
+ labels.update({k: v for k, v in _read_json(out_dir / "rank_batches" / "labels.json", {}).items() if isinstance(v, str)})
493
+ earlier = _read_json(out_dir / "rank.json", {}) or {}
494
+ labels.update({c["id"]: c["finding"] for c in earlier.get("candidates") or [] if c.get("id") and c.get("finding")})
495
+ hits, misses = [], []
496
+ for c in plan.items:
497
+ v = store.get(plan.keys[c["id"]])
498
+ if v and v.get("answer") in ("candidate", "rejected") and not verdicts.wants_fresh(
499
+ fresh, ref=c["id"], label=labels.get(c["id"], ""), file=c.get("file", "")):
500
+ hits.append((c, v))
501
+ else:
502
+ misses.append(c)
503
+ plan.cached = hits
504
+ plan.batches = value_batches(misses, plan.batch_size) if plan.depth != "top" else ([misses] if misses else [])
505
+ plan.cache_ready = True
506
+ return store
507
+
508
+
509
+ def _format_tables(inventory: dict, engine: str, names: set[str]) -> str:
510
+ lines = []
511
+ for t in inventory["tables"]:
512
+ unnamed = t["name"].startswith("?")
513
+ if not unnamed and t["name"].split(".")[-1] not in names:
514
+ continue
515
+ # a definition with a run-time name may be one of the tables the shortlist reads: show the
516
+ # ones from application code so the agent can match them, skip test scaffolding
517
+ if unnamed and (TEST_PATH.search(t["defined_at"][0]) or t["engine"] in ("Memory", "Null") or len(t["columns"]) < 4):
518
+ continue
519
+ if (engine == "clickhouse") != bool(t["engine"]):
520
+ continue # MergeTree-family definitions for ClickHouse, plain SQL tables for every other engine
521
+ cols = ", ".join(f"{c['name']} {c['type']}" for c in t["columns"][:60])
522
+ if len(t["columns"]) > 60:
523
+ cols += f", … ({len(t['columns']) - 60} more)"
524
+ name = t["name"] if not t["name"].startswith("?") else "(name built at run time)"
525
+ parts = [f"- {name} [{t['defined_at'][0]}]"] + ([f"ENGINE {t['engine']}({t['engine_args']})"] if t["engine"] else [])
526
+ if t["partition_by"]:
527
+ parts.append(f"PARTITION BY {t['partition_by']}")
528
+ if t["order_by"]:
529
+ parts.append(f"ORDER BY {t['order_by']}")
530
+ lines.append(" ".join(parts) + f"\n columns: {cols}")
531
+ return "\n".join(lines) or "(none found)"
532
+
533
+
534
+ def _origins_text(site: dict, limit: int = 3) -> str:
535
+ origins = site.get("origins") or []
536
+ if not origins:
537
+ return "(no entry point found statically)"
538
+ text = "; ".join(f"{o['kind']} {o['name']} ({o.get('hops', '?')} hops)" for o in origins[:limit])
539
+ more = (site.get("origin_count") or len(origins)) - min(len(origins), limit)
540
+ return text + (f"; +{more} more" if more > 0 else "")
541
+
542
+
543
+ def _locations_text(item: dict, limit: int = 4) -> str:
544
+ """The other call sites that send the same SQL: the agent sees the query once, with every place it runs from."""
545
+ others = item.get("locations") or []
546
+ if not others:
547
+ return ""
548
+ lines = [f" - {o['file']}:{o['line']} ({o['role']}) reached from: {_origins_text(o, 2)}" for o in others[:limit]]
549
+ if len(others) > limit:
550
+ lines.append(f" - and {len(others) - limit} more")
551
+ return "also sent from:\n" + "\n".join(lines) + "\n"
552
+
553
+
554
+ def _format_known(definitions: list[dict]) -> str:
555
+ if not definitions:
556
+ return "(none yet)"
557
+
558
+ def head(d: dict) -> str:
559
+ if d.get("source") != "real catalog":
560
+ return f"### {d['name']}"
561
+ note = f"\n{d['note']}" if d.get("note") else ""
562
+ return f"### {d['name']} (real: read from the database catalog; exact, never return or change it){note}"
563
+ return "\n\n".join(f"{head(d)}\n```sql\n{d['create_sql'].strip()}\n```" for d in definitions)
564
+
565
+
566
+ def _format_shortlist(items: list[dict], max_sql: int = MAX_SQL_CHARS) -> str:
567
+ out = []
568
+ for c in items:
569
+ sql = c["sql"].strip()
570
+ if len(sql) > max_sql:
571
+ sql = sql[:max_sql] + f"\n… ({len(sql) - max_sql:,} more characters, cut at {max_sql:,} by CodeCop (rank.max_sql_chars): read the file)"
572
+ out.append(
573
+ f"### {c['id']}\n"
574
+ f"location: {c['file']}:{c['line']} function: {c['symbol'] or '(module level)'} via: {c['sink'] or '(string)'}\n"
575
+ f"role: {site_role(c)} reached from: {_origins_text(c)}\n{_locations_text(c)}"
576
+ f"resolved: {c['resolution']} flags: {', '.join(c['flags']) or 'none'} same SQL at {c['same_sql_sites'] - 1} other site(s)\n"
577
+ + (f"{c['measured_text']}\n" if c.get("measured_text") else "")
578
+ + (f"{c['join_note']}\n" if c.get("join_note") else "") +
579
+ f"tables: {', '.join(c['tables'])}\n```sql\n{sql}\n```"
580
+ )
581
+ return "\n\n".join(out)
582
+
583
+
584
+ def _fill(template: str, values: dict) -> str:
585
+ """Replace {key} tokens. Not str.format: prompts contain literal braces such as {name:Type}."""
586
+ for key, value in values.items():
587
+ template = template.replace("{" + key + "}", str(value))
588
+ return template
589
+
590
+
591
+ def build_prompt(inventory: dict, items: list[dict], select_count: int, engine: str, engine_version: str, top: int,
592
+ known: list[dict] | None = None, batch: tuple[int, int] | None = None, max_sql_chars: int = MAX_SQL_CHARS,
593
+ focus: str = "") -> str:
594
+ """`known`: table definitions earlier batches returned. `batch`: (number, of) when the run has several.
595
+ `max_sql_chars`: each query's SQL is shown up to this length (`[rank] max_sql_chars`)."""
596
+ names = {t.split(".")[-1] for c in items for t in c["tables"]}
597
+ note = f"{len(items)} of {select_count} SELECT call sites, pre-filtered by static heuristics"
598
+ if batch and batch[1] > 1:
599
+ note = (f"batch {batch[0]} of {batch[1]}: {len(items)} distinct queries of {select_count} SELECT call sites, "
600
+ "grouped so that queries on the same tables are together")
601
+ eng = engines.get(engine)
602
+ prompt = _fill(load_prompt(eng.rank_prompt), {
603
+ "engine": eng.label,
604
+ "context": eng.prompt_context(inventory, names),
605
+ "engine_version": engine_version,
606
+ "top": top,
607
+ "tables": _format_tables(inventory, engine, names),
608
+ "known_definitions": _format_known(known or []),
609
+ "shortlist_note": note,
610
+ "shortlist": _format_shortlist(items, max_sql_chars),
611
+ })
612
+ if focus == "join" or any(c.get("join_note") for c in items):
613
+ from .joins import FOCUS_TEXT
614
+ prompt += "\n" + FOCUS_TEXT
615
+ if focus == "assembled":
616
+ from .assemble import FOCUS_TEXT as ASSEMBLE_TEXT
617
+ prompt += "\n" + ASSEMBLE_TEXT
618
+ return prompt
619
+
620
+
621
+ def canonical_table(name: str, engine: str = "clickhouse") -> str:
622
+ """One spelling per table: the sandbox has a single database, so `default.t` and `t` (ClickHouse), or
623
+ `public.t` and `t` (Postgres), are the same table."""
624
+ return engines.get(engine).canonical_table(name)
625
+
626
+
627
+ CREATE_COLUMNS = re.compile(r"CREATE\s+(?:(?:GLOBAL\s+|LOCAL\s+)?(?:TEMP|TEMPORARY)\s+|UNLOGGED\s+|OR\s+REPLACE\s+)?TABLE\s+"
628
+ r"(?:IF\s+NOT\s+EXISTS\s+)?([`\"\w.]+)\s*(?:ON\s+CLUSTER\s+\S+\s*)?\(", re.I)
629
+ NOT_A_COLUMN = re.compile(r"^(INDEX|PROJECTION|CONSTRAINT|PRIMARY\s+KEY|UNIQUE|FOREIGN\s+KEY|CHECK|EXCLUDE|LIKE)\b", re.I)
630
+
631
+
632
+ def _columns(create_sql: str, name: str = "") -> tuple[int, dict[str, str]] | None:
633
+ """Where the column list of a CREATE TABLE ends, and its columns as {name: 'name type ...'}. With `name`, the
634
+ CREATE TABLE of that table: a script can create other tables before it (the agent's `orders` that began with a
635
+ two-column `customers` was read as `customers`, and the merge dropped its columns)."""
636
+ found = list(CREATE_COLUMNS.finditer(create_sql))
637
+ if name:
638
+ want = name.replace('"', "").replace("`", "").split(".")[-1].lower()
639
+ found = [m for m in found if m.group(1).replace('"', "").replace("`", "").split(".")[-1].lower() == want] or found[:1]
640
+ m = found[0] if found else None
641
+ if not m:
642
+ return None
643
+ depth, quote, end = 1, "", -1
644
+ for i in range(m.end(), len(create_sql)):
645
+ c = create_sql[i]
646
+ if quote:
647
+ quote = "" if c == quote else quote
648
+ elif c == "'":
649
+ quote = c
650
+ elif c == "(":
651
+ depth += 1
652
+ elif c == ")":
653
+ depth -= 1
654
+ if depth == 0:
655
+ end = i
656
+ break
657
+ if end < 0:
658
+ return None
659
+ columns = {}
660
+ for part in _split_top(create_sql[m.end():end]):
661
+ text = " ".join(part.split())
662
+ if text and not NOT_A_COLUMN.match(text):
663
+ columns[text.split(" ", 1)[0].strip("`\"")] = text
664
+ return end, columns
665
+
666
+
667
+ def merge_definitions(definitions: list[dict], engine: str = "clickhouse") -> list[dict]:
668
+ """One definition per table from what several agent calls returned.
669
+
670
+ Calls that ran at the same time each assemble a table from the queries they saw, so the same table
671
+ comes back with different column sets. The definition copied from code wins, else the one with the
672
+ most columns; columns only the others have are added to it. A column both have keeps the winner's type."""
673
+ from .definitions import split
674
+ groups: dict[str, list[dict]] = {}
675
+ for d in split(definitions, engine)[0]: # one CREATE TABLE per definition
676
+ groups.setdefault(canonical_table(d["name"], engine), []).append(d)
677
+ merged = []
678
+ for name, group in groups.items():
679
+ # a definition split out of another table's script is used only when that table has none of its own
680
+ own = [d for d in group if not d.get("basis", "").startswith("split from")]
681
+ group = own or group
682
+ parsed = [(_columns(d["create_sql"], name), d) for d in group]
683
+ best = max(parsed, key=lambda pd: (not pd[1].get("inferred"), len(pd[0][1]) if pd[0] else 0))
684
+ out = {**best[1], "name": name}
685
+ if best[0] is not None:
686
+ end, have = best[0]
687
+ added = {}
688
+ for cols, d in parsed:
689
+ if d is best[1] or cols is None:
690
+ continue
691
+ for col, text in cols[1].items():
692
+ if col not in have and col not in added:
693
+ added[col] = text
694
+ if added:
695
+ sql = out["create_sql"]
696
+ out["create_sql"] = sql[:end].rstrip() + "".join(f",\n {text}" for text in added.values()) + "\n" + sql[end:]
697
+ out["inferred"] = True
698
+ out["basis"] = (out.get("basis", "") + f" Merged: {len(added)} columns added from other batches.").strip()
699
+ # what a definition carries besides its column list (Postgres: the CREATE INDEX and CREATE TYPE statements of its script)
700
+ sql, notes = engines.get(engine).merge_scripts(out["create_sql"], [d["create_sql"] for d in group if d is not best[1]])
701
+ if notes:
702
+ out["create_sql"], out["inferred"] = sql, True
703
+ out["basis"] = (out.get("basis", "") + " Merged: " + ", ".join(notes) + " from other batches.").strip()
704
+ merged.append(out)
705
+ return merged
706
+
707
+
708
+ CONSTANT_OPS = ("eq", "in", "range", "like", "contains", "fts") # a filter against a parameter or a literal
709
+
710
+
711
+ def unconfirmed_reasons(sql: str, tables: list[str], definitions: dict[str, dict], engine: str) -> tuple[list[str], list[str]]:
712
+ """Why the computed access analysis does not support calling this query cheap: (reasons, tables that were checked).
713
+
714
+ For each table of the query whose definition is known, from the definition and the SQL alone:
715
+ - the table is partitioned and the query gives its partition key only through a join, or not at all: no
716
+ partition can be ruled out when the query is planned, so every probe may visit every partition;
717
+ - the table is reached by joins only and more than one index could serve them: which one runs depends on the
718
+ planner's statistics, so "a primary-key lookup" is one of several plans, not a fact;
719
+ - no index serves any of its filters or joins.
720
+ An empty list means nothing here contradicts the rejection, not that the query is cheap."""
721
+ eng = engines.get(engine)
722
+ reasons, checked = [], []
723
+ for name in tables:
724
+ d = definitions.get(canonical_table(name, engine))
725
+ if not d:
726
+ continue
727
+ try:
728
+ a = eng.table_access(d["create_sql"], d["name"], sql, None)
729
+ except Exception: # a definition the access analysis cannot read is not evidence either way
730
+ continue
731
+ checked.append(d["name"])
732
+ filters = a.get("filters") or []
733
+ key = a.get("partition_by") or ""
734
+ if key:
735
+ columns = set(re.findall(r"[A-Za-z_]\w*", key))
736
+ on_key = [f for f in filters if f["column"] in columns]
737
+ if not any(f["op"] in CONSTANT_OPS for f in on_key):
738
+ how = "only through a join" if any(f["op"] == "join" for f in on_key) else "not at all"
739
+ reasons.append(f"{d['name']} is partitioned by {key} and the query gives the partition key {how}: "
740
+ "no partition can be ruled out when the query is planned")
741
+ indexes = a.get("indexes")
742
+ if indexes is not None and filters:
743
+ usable = [ix for ix in indexes if ix.get("used_columns")]
744
+ joins_only = not any(f["op"] in CONSTANT_OPS for f in filters)
745
+ if not usable:
746
+ reasons.append(f"no index of {d['name']} serves this query's filters or joins")
747
+ elif joins_only and len({_leading(ix) for ix in usable}) > 1: # a primary key and a unique index on it are one way in
748
+ reasons.append(f"{d['name']} is reached by joins only and {len(usable)} indexes can serve them "
749
+ f"({', '.join(ix['name'] for ix in usable[:4])}): which one runs depends on the planner's statistics")
750
+ return reasons, checked
751
+
752
+
753
+ def _leading(index: dict) -> str:
754
+ """The first column of an index as a bare name: `"id" ASC` and `id` are the same way into the table."""
755
+ return re.sub(r"\s+(?:ASC|DESC)\b.*$", "", str(index["columns"][0]), flags=re.I).strip().strip('"').lower()
756
+
757
+
758
+ def audit_rejections(rank: dict, inventory: dict | None) -> dict[str, dict]:
759
+ """For every query the agent rejected as `already_cheap`: what the computed access analysis says against that.
760
+
761
+ id -> {reasons, checked}. Only queries with at least one table whose definition is known are listed. Free and
762
+ recomputed by the report, so it also covers a rank.json written before this check existed."""
763
+ sites = {c["id"]: c for c in (inventory or {}).get("call_sites") or [] if c.get("id")}
764
+ engine = rank["engine"]
765
+ definitions = {canonical_table(d["name"], engine): d for d in rank.get("table_definitions") or []}
766
+ out = {}
767
+ for r in rank.get("rejected") or []:
768
+ site = sites.get(r.get("id"))
769
+ if r.get("code") != "already_cheap" or not site or not site.get("sql"):
770
+ continue
771
+ reasons, checked = unconfirmed_reasons(site["sql"], site.get("tables") or [], definitions, engine)
772
+ if checked:
773
+ out[r["id"]] = {"reasons": reasons, "checked": checked}
774
+ return out
775
+
776
+
777
+ def cut_flavor(items: list[dict], max_sql_chars: int) -> str:
778
+ """What the SQL cut adds to a batch's question. Nothing while every query fits under the cut used before it was a
779
+ setting (a stored batch of short queries asked the same question); else the cut, so a batch whose agent saw only
780
+ the start of a statement is not reused as if it had read all of it."""
781
+ if max_sql_chars == LEGACY_MAX_SQL_CHARS or all(len((c.get("sql") or "").strip()) <= LEGACY_MAX_SQL_CHARS for c in items):
782
+ return ""
783
+ return f"sql<={max_sql_chars}"
784
+
785
+
786
+ def batch_key(items: list[dict], engine: str, engine_version: str, top: int, flavor: str = "") -> str:
787
+ """Names a batch by what it asks, so --resume reuses a stored result only for the same question.
788
+
789
+ The server version is not part of the question: it decides what the benchmark runs on, not which queries are
790
+ worth benchmarking. `engine_version` is accepted and ignored, so changing it reuses every stored batch."""
791
+ text = "\n".join([engine, str(top)] + ([flavor] if flavor else []) + sorted(c["id"] for c in items))
792
+ return hashlib.sha256(text.encode()).hexdigest()[:16]
793
+
794
+
795
+ def legacy_batch_key(items: list[dict], engine: str, engine_version: str, top: int, flavor: str = "") -> str:
796
+ """The key batches were stored under while the version was part of it. Read only: a batch found under it is
797
+ stored again under `batch_key`."""
798
+ text = "\n".join([engine, engine_version, str(top)] + ([flavor] if flavor else []) + sorted(c["id"] for c in items))
799
+ return hashlib.sha256(text.encode()).hexdigest()[:16]
800
+
801
+
802
+ # ---- what an out dir remembers between rank invocations -----------------------------------------------------------
803
+ # rank_batches/ledger.json every agent call that was paid for, by invocation: a resume adds to it, so the cost of an
804
+ # out dir is the sum over all of them, not the cost of the batches the last result is made of
805
+ # rank_batches/labels.json call-site id -> finding label: a query keeps its Q-number across resumes and re-runs
806
+
807
+ def _read_json(path: Path, default):
808
+ try:
809
+ return json.loads(path.read_text()) if path.exists() else default
810
+ except ValueError:
811
+ return default
812
+
813
+
814
+ def load_ledger(store: Path | None, batch_files: list[dict]) -> dict:
815
+ """The ledger, or one rebuilt from the batch files of an out dir that predates it (every stored batch was paid for once)."""
816
+ ledger = _read_json(store / "ledger.json", None) if store else None
817
+ if isinstance(ledger, dict) and isinstance(ledger.get("invocations"), list):
818
+ return ledger
819
+ calls = [{"kind": "batch", "key": d.get("key", ""), "cost_usd": float((d.get("agent") or {}).get("cost_usd") or 0),
820
+ "at": d.get("finished_at", "")} for d in sorted(batch_files, key=lambda d: d.get("finished_at", ""))]
821
+ return {"schema_version": 1, "invocations": ([{"at": calls[0]["at"], "note": "rebuilt from the stored batches: earlier invocations kept no ledger",
822
+ "calls": calls}] if calls else [])}
823
+
824
+
825
+ def ledger_total(ledger: dict) -> float:
826
+ return round(sum(float(c.get("cost_usd") or 0) for inv in ledger.get("invocations") or [] for c in inv.get("calls") or []), 4)
827
+
828
+
829
+ def merge_earlier(candidates: list[dict], rejected: list[dict], definitions: list[dict], earlier: dict | None, inventory: dict,
830
+ engine: str, asked: set[str] | None = None) -> dict:
831
+ """Keep what an earlier rank of the same queries found and this one did not. Changes the three lists in place.
832
+
833
+ Two runs of an agent over the same commit do not return the same candidates or the same variants (one run proposed
834
+ a useful rewrite, the next did not; one query was a candidate once and "already cheap" the next
835
+ time). The benchmark decides what a variant is worth, so a variant proposed once is worth measuring:
836
+ - an earlier candidate this run did not return is kept, with `carried_from` saying when it was found and what
837
+ this run said about the query instead; a rejection of it is taken off the rejected list;
838
+ - an earlier variant of a candidate both runs returned is added to it, marked `from_earlier_run`.
839
+ Only for a query that is still the same: its call site is in the inventory with the same SQL. Returns counts.
840
+
841
+ `asked`: the call-site ids this run asked about, when the run was scoped (`--focus join`). An earlier candidate
842
+ outside them was not asked about, so nothing this run said applies to it: it is kept as it was (`unasked` counts
843
+ them), and `inventory` must be the whole inventory, not the scoped one, for its call site to be found."""
844
+ out = {"candidates": 0, "variants": 0, "unasked": 0, "from": (earlier or {}).get("generated_at", "")}
845
+ if not earlier or earlier.get("engine") != engine:
846
+ return out
847
+ sites = {c["id"]: c for c in inventory.get("call_sites") or [] if c.get("id")}
848
+ mine = {c["id"]: c for c in candidates}
849
+ said = {r["id"]: r for r in rejected if r.get("id")}
850
+ have = {canonical_table(d["name"], engine) for d in definitions}
851
+ old_defs = {canonical_table(d["name"], engine): d for d in earlier.get("table_definitions") or []}
852
+
853
+ def shape(v: dict) -> tuple:
854
+ return (v.get("kind"), " ".join((v.get("sql") or "").split()), tuple(" ".join(s.split()) for s in v.get("setup_sql") or []))
855
+
856
+ for old in earlier.get("candidates") or []:
857
+ site = sites.get(old.get("id"))
858
+ if not site or site.get("sql_hash") != (old.get("site") or {}).get("sql_hash"):
859
+ continue # the query changed or is gone: what was said about it no longer applies
860
+ now = mine.get(old["id"])
861
+ if now is None and asked is not None and old["id"] not in asked:
862
+ candidates.append(dict(old))
863
+ mine[old["id"]] = candidates[-1]
864
+ out["unasked"] += 1
865
+ for t in old.get("tables") or []:
866
+ if canonical_table(t, engine) not in have and canonical_table(t, engine) in old_defs:
867
+ definitions.append(old_defs[canonical_table(t, engine)])
868
+ have.add(canonical_table(t, engine))
869
+ elif now is None:
870
+ verdict = said.pop(old["id"], None)
871
+ reason = (f"the latest run rejected this query as {verdict.get('code') or 'other'}: {(verdict.get('detail') or verdict.get('reason') or '')[:200]}"
872
+ if verdict else "the latest run did not return this query as a candidate")
873
+ kept = {**old, "carried_from": (old.get("carried_from") or {"generated_at": earlier.get("generated_at", "")}) | {"reason": reason}}
874
+ candidates.append(kept)
875
+ mine[old["id"]] = kept
876
+ out["candidates"] += 1
877
+ for t in old.get("tables") or []:
878
+ if canonical_table(t, engine) not in have and canonical_table(t, engine) in old_defs:
879
+ definitions.append(old_defs[canonical_table(t, engine)])
880
+ have.add(canonical_table(t, engine))
881
+ else:
882
+ seen = {shape(v) for v in now.get("variants") or []}
883
+ for v in old.get("variants") or []:
884
+ if shape(v) not in seen:
885
+ seen.add(shape(v))
886
+ now.setdefault("variants", []).append({**v, "from_earlier_run": v.get("from_earlier_run") or earlier.get("generated_at", "")})
887
+ out["variants"] += 1
888
+ rejected[:] = [r for r in rejected if r.get("id") in said or not r.get("id")]
889
+ return out
890
+
891
+
892
+ SQL_START = re.compile(r"\s*(?:--[^\n]*\n\s*)*(?:select|with|\(|values|table|explain)\b", re.I)
893
+ SCHEMA_KINDS = ("index", "skip_index", "projection", "ordering_key", "partitioning")
894
+
895
+
896
+ def _variants_runnable(cand: dict) -> list[dict]:
897
+ """The variants, with the `sql` of a schema change that is a placeholder (`SAME_AS_BASELINE`, "unchanged", empty)
898
+ put back to the baseline it stands for: the prompt asks for the unchanged baseline there, and a token in its place
899
+ failed on the server as a syntax error (`sql_from_baseline` says it was put back)."""
900
+ out = []
901
+ for v in cand.get("variants") or []:
902
+ if v.get("kind") in SCHEMA_KINDS and not SQL_START.match(v.get("sql") or "") and cand.get("baseline_sql"):
903
+ v = {**v, "sql": cand["baseline_sql"], "sql_from_baseline": True}
904
+ out.append(v)
905
+ return out
906
+
907
+
908
+ def _candidate(cand: dict, site: dict, label: str, engine: str = "clickhouse") -> dict:
909
+ return {
910
+ "finding": label,
911
+ **cand,
912
+ "variants": _variants_runnable(cand),
913
+ "tables": list(dict.fromkeys(canonical_table(t, engine) for t in cand.get("tables") or [])),
914
+ "params": {p["name"]: p["value"] for p in cand.get("params", [])},
915
+ "origin": {**(cand.get("origin") or {"role": site_role(site), "kind": "unknown", "entry_points": [], "path": [],
916
+ "frequency": {"trigger": "unknown", "every_seconds": 0, "in_loop": False, "cache_seconds": 0, "note": ""}}),
917
+ "verified": bool(cand.get("origin"))},
918
+ "site": {**{k: site[k] for k in ("file", "line", "symbol", "sink", "resolution", "flags", "sql_hash", "same_sql_sites", "score")},
919
+ "role": site_role(site), "origins": site.get("origins") or [], "origin_count": site.get("origin_count", 0)},
920
+ "original_sql": site["sql"],
921
+ }
922
+
923
+
924
+ def _label_number(label: str) -> int:
925
+ m = re.fullmatch(r"Q-(\d+)", label or "")
926
+ return int(m.group(1)) if m else 0
927
+
928
+
929
+ def run_plan(inventory: dict, root: Path, runner: AgentRunner, plan: Plan, *, engine_version: str, top: int = 10,
930
+ model: str | None = None, max_budget_usd: float | None = None, out_dir: Path | None = None,
931
+ resume: bool = False, concurrency: int = CONCURRENCY, on_event=lambda name, label, counts: None,
932
+ facts=None, prompt_version: str | None = None, other_costs: dict | None = None, keep_earlier: bool = True,
933
+ full_inventory: dict | None = None, fresh=False, store=None, tell=None) -> dict:
934
+ """Run the plan's batches, a few at a time, and merge what the agent returned.
935
+
936
+ With `facts` (a pulled database catalog) every batch is given the real definition of each table it reads,
937
+ so no batch assembles its own; the agent returns definitions only for tables the catalog does not have.
938
+
939
+ Every answer is stored per statement as it lands (verdicts.py, `<out_dir>/agent_verdicts.json`): a query answered
940
+ before, with the same SQL, the same table definitions, engine, version and prompt, is not asked again (`plan.cached`);
941
+ `fresh` asks again (True: every query; a set: the findings, ids or paths it names). Older per-batch answers
942
+ (`rank_batches/batch-*.json`) are migrated once and kept. `resume` is accepted and changes nothing: reuse is the default.
943
+ `max_budget_usd` is a total: a batch is given a share of what is left and is not started when the share is too
944
+ small to finish. A batch that runs out of time is asked again in two halves, once.
945
+ A candidate's finding label is given when its batch finishes and is kept in `rank_batches/labels.json` by
946
+ call-site id, so a query keeps its label across re-runs. Raises AgentError when no batch finished and none could
947
+ start for a reason other than the budget (a run that the budget stopped returns what it has).
948
+
949
+ `engine_version` is recorded and is part of a verdict's key (`prompt_version` is the text the prompt shows for it).
950
+ Every agent call that was paid for is added to `rank_batches/ledger.json`, `other_costs` (the area classification)
951
+ included, so the result's `agent.cost_total_usd` is what this out dir has cost over all invocations; the ledger is
952
+ never reset. `keep_earlier`: candidates and variants of the rank.json already in the out dir are kept when this run
953
+ does not return them (merge_earlier); with it off, the labels start again.
954
+
955
+ A focused plan (`plan.focus`, `codecop rank --focus join`) asks about a part of the queries: it adds to the ranking
956
+ already in the out dir and updates the candidates it asked about; every other candidate, rejection, shortlist entry
957
+ and batch record is kept as it was (merge_focused). `full_inventory`: the inventory before it was scoped to the
958
+ focus, where the kept candidates' call sites are looked up. `tell(step, items, estimate)`: said before each agent
959
+ call, so the run's ledger (budget.Run) knows what the call asks about."""
960
+ engine = plan.engine
961
+ store_dir = (out_dir / "rank_batches") if out_dir else None
962
+ start_over = not keep_earlier and not plan.focus
963
+ earlier = _read_json(out_dir / "rank.json", None) if out_dir and not start_over else None
964
+ earlier = earlier if isinstance(earlier, dict) and earlier.get("engine") == engine else None
965
+ verdict_store = prepare_cache(plan, inventory, out_dir, engine_version=engine_version, facts=facts,
966
+ fresh=True if (start_over and fresh is False) else fresh, store=store, full_inventory=full_inventory)
967
+ asked_ids = ({c["id"] for c in plan.items} | {c["id"] for c, _ in plan.cached}) if plan.focus else None
968
+ on_disk: list[dict] = []
969
+ if store_dir and store_dir.is_dir():
970
+ for path in sorted(store_dir.glob("batch-*.json")):
971
+ data = _read_json(path, None)
972
+ if isinstance(data, dict):
973
+ on_disk.append(data)
974
+ ledger = load_ledger(store_dir, on_disk)
975
+ if start_over and store_dir:
976
+ (store_dir / "labels.json").unlink(missing_ok=True)
977
+ invocation = {"at": datetime.now(timezone.utc).isoformat(timespec="seconds"), "engine_version": engine_version, "resume": resume,
978
+ "calls": [{"kind": k, "cost_usd": round(float(v or 0), 6)} for k, v in (other_costs or {}).items() if v]}
979
+ ledger["invocations"].append(invocation)
980
+ # call-site id -> label. The rank.json in the out dir is what the user last saw; then the registry; then the stored batches.
981
+ registry: dict[str, str] = {}
982
+ if not start_over:
983
+ for d in sorted(on_disk, key=lambda d: d.get("finished_at", "")):
984
+ for site_id, lb in (d.get("labels") or {}).items():
985
+ registry.setdefault(site_id, lb)
986
+ registry.update({k: v for k, v in (_read_json(store_dir / "labels.json", {}) if store_dir else {}).items() if isinstance(v, str)})
987
+ registry.update({c["id"]: c["finding"] for c in (earlier or {}).get("candidates") or [] if c.get("id") and c.get("finding")})
988
+ lock = threading.Condition() # also wakes batches that wait for budget held by running ones
989
+ state = {"spent": 0.0, "reserved": 0.0, "running": 0, "costliest": 0.0,
990
+ "label": max((_label_number(lb) for lb in registry.values()), default=0)}
991
+
992
+ def save_memory() -> None:
993
+ if store_dir:
994
+ store_dir.mkdir(parents=True, exist_ok=True)
995
+ (store_dir / "ledger.json").write_text(json.dumps(ledger, indent=1))
996
+ (store_dir / "labels.json").write_text(json.dumps(registry, indent=1, sort_keys=True))
997
+
998
+ def label_of(site_id: str) -> str:
999
+ """Under the lock: the finding label of a query, a new one the first time it is a candidate."""
1000
+ if site_id not in registry:
1001
+ state["label"] += 1
1002
+ registry[site_id] = f"Q-{state['label']:03d}"
1003
+ return registry[site_id]
1004
+
1005
+ total = len(plan.batches)
1006
+ defs_by_batch: list[list[dict]] = [[] for _ in plan.batches] # table definitions, as each batch returned them
1007
+ records: list[dict | None] = [None] * total
1008
+ outputs: list[dict | None] = [None] * total
1009
+ started = time.monotonic()
1010
+
1011
+ # the queries answered before: one record that cost nothing, their stored answers as its output
1012
+ cached_ids = {c["id"] for c, _ in plan.cached}
1013
+ cached_output = {"candidates": [], "rejected": [], "table_definitions": []}
1014
+ with lock:
1015
+ for c, v in plan.cached:
1016
+ if v.get("answer") == "candidate":
1017
+ cand = {**v["candidate"], "id": c["id"]}
1018
+ cached_output["candidates"].append(cand)
1019
+ label_of(c["id"])
1020
+ cached_output["table_definitions"] += list(v.get("definitions") or [])
1021
+ else:
1022
+ cached_output["rejected"].append({**(v.get("rejection") or {}), "id": c["id"]})
1023
+ cached_defs = merge_definitions(cached_output["table_definitions"], engine) if cached_output["table_definitions"] else []
1024
+
1025
+ def finish(index: int, items: list[dict], data: dict, reused: bool) -> None:
1026
+ """Under the lock: keep the batch's output and merge its table definitions (the first definition of a name wins)."""
1027
+ output = data["output"]
1028
+ defs_by_batch[index] = list(output.get("table_definitions") or [])
1029
+ outputs[index] = data
1030
+ a = data.get("agent") or {}
1031
+ ids = {c["id"] for c in items}
1032
+ records[index] = {"index": index, "key": data["key"], "queries": len(items), "status": "done", "reason": "", "reused": reused,
1033
+ "cost_usd": a.get("cost_usd", 0.0), "turns": a.get("turns", 0), "duration_s": a.get("duration_s", 0.0),
1034
+ "candidates": sum(1 for c in output.get("candidates") or [] if c.get("id") in ids),
1035
+ "rejected": sum(1 for r in output.get("rejected") or [] if r.get("id") in ids),
1036
+ **({"split": True} if data.get("split") else {})}
1037
+
1038
+ def progress(index: int) -> dict:
1039
+ done = [r for r in records if r]
1040
+ return {"batch": index + 1, "batches": total, "done": sum(1 for r in done if r["status"] == "done"),
1041
+ "failed": sum(1 for r in done if r["status"] != "done"),
1042
+ "candidates_total": sum(r.get("candidates", 0) for r in done),
1043
+ "cost_total_usd": round(sum(r.get("cost_usd", 0.0) for r in done), 4),
1044
+ "answered_before": len(plan.cached)}
1045
+
1046
+ def real_for(names: set[str]) -> list[dict]:
1047
+ """The real definitions of the tables named, each with a line of real size facts for the prompt."""
1048
+ if not facts:
1049
+ return []
1050
+ return [{**d, "note": facts.table_note(engine, d["name"])} for d in facts.definitions(engine, {canonical_table(n, engine) for n in names})]
1051
+
1052
+ flavor = "real catalog" if facts and facts.tables(engine) else ""
1053
+ schema = engines.get(engine).rank_schema(load_schema("rank_output"))
1054
+
1055
+ def ask(items: list[dict], cap, known: list[dict], index: int):
1056
+ """One agent call about `items`: (result, error)."""
1057
+ prompt = build_prompt(inventory, items, plan.select_sites, engine, prompt_version or engine_version, top, known, (index + 1, total),
1058
+ plan.max_sql_chars, focus=plan.focus)
1059
+ if tell:
1060
+ lo, hi = plan.per_query_usd
1061
+ tell("assemble" if plan.focus == "assembled" else "rank", len(items), (round(lo * len(items), 2), round(hi * len(items), 2)))
1062
+ try:
1063
+ return runner.run(prompt, schema, root, model=model, max_budget_usd=cap), ""
1064
+ except AgentError as e:
1065
+ return None, str(e)
1066
+ except Exception as e: # anything else from a runner is a failed batch too, not a hung pool
1067
+ return None, f"{type(e).__name__}: {e}"
1068
+
1069
+ def store_verdicts(items: list[dict], output: dict, known: list[dict], cost: float, key: str) -> None:
1070
+ ids = {c["id"] for c in items}
1071
+ cands = {c.get("id"): c for c in output.get("candidates") or [] if c.get("id") in ids}
1072
+ rejs = {r.get("id"): r for r in output.get("rejected") or [] if r.get("id") in ids and r.get("id") not in cands}
1073
+ defs = list(output.get("table_definitions") or []) + [d for d in known if d.get("source") != "real catalog"]
1074
+ share = round(cost / max(len(items), 1), 6)
1075
+ for c in items:
1076
+ k = plan.keys.get(c["id"])
1077
+ if not k:
1078
+ continue
1079
+ base = {"kind": "rank" + (f":{plan.focus}" if plan.focus else ""), "id": c["id"], "sql_hash": c.get("sql_hash", ""),
1080
+ "tables": c.get("tables") or [], "engine": engine, "engine_version": engine_version, "batch_key": key,
1081
+ "cost_share_usd": share, "file": c.get("file", ""), "line": c.get("line", 0)}
1082
+ if c["id"] in cands:
1083
+ verdict_store.put(k, {**base, "answer": "candidate", "candidate": cands[c["id"]],
1084
+ "definitions": _defs_for(cands[c["id"]], defs, engine)}, save=False)
1085
+ elif c["id"] in rejs:
1086
+ verdict_store.put(k, {**base, "answer": "rejected", "rejection": rejs[c["id"]]}, save=False)
1087
+ # a query the agent said nothing about is not stored: it is asked again next time
1088
+ verdict_store.save()
1089
+
1090
+ def work(index: int, items: list[dict]) -> None:
1091
+ asked = flavor + ("+workload" if any(c.get("measured") for c in items) else "")
1092
+ cut = cut_flavor(items, plan.max_sql_chars)
1093
+ asked = f"{asked}+{cut}" if cut else asked
1094
+ asked = f"{asked}+focus={plan.focus}" if plan.focus else asked # a focused question is not the plain one
1095
+ key = batch_key(items, engine, engine_version, top, asked)
1096
+ with lock:
1097
+ cap = None
1098
+ while max_budget_usd:
1099
+ # An even share of what is left for each free slot, but never less than a batch is known to need:
1100
+ # a call that runs into its limit costs the limit and returns nothing.
1101
+ left = max_budget_usd - state["spent"] - state["reserved"]
1102
+ need = max(state["costliest"], len(items) * plan.per_query_usd[1])
1103
+ cap = min(left, max(left / max(concurrency - state["running"], 1), need, MIN_BATCH_BUDGET_USD))
1104
+ if cap >= max(MIN_BATCH_BUDGET_USD, 0.75 * state["costliest"]):
1105
+ break
1106
+ if state["running"]: # running batches hold more than they will spend: wait for one to finish
1107
+ lock.wait()
1108
+ continue
1109
+ records[index] = {"index": index, "key": key, "queries": len(items), "status": "skipped", "reason": "budget",
1110
+ "reused": False, "cost_usd": 0.0, "turns": 0, "duration_s": 0.0, "candidates": 0, "rejected": 0}
1111
+ on_event("batch_skipped", f"Batch {index + 1} of {total}: budget reached", {**progress(index), "queries": len(items)})
1112
+ return
1113
+ if cap is not None:
1114
+ state["reserved"] += cap
1115
+ state["running"] += 1
1116
+ real = real_for({t for c in items for t in c["tables"]})
1117
+ real_names = {d["name"] for d in real}
1118
+ # What a batch is told must not depend on which batches happened to finish before it started: the first
1119
+ # batch's definitions (it runs alone) and the stored answers' definitions, nothing that ran beside it.
1120
+ settled = [d for i, batch in enumerate(defs_by_batch) if i == 0 for d in batch] + cached_defs
1121
+ known = real + [d for d in merge_definitions(settled, engine) if d["name"] not in real_names]
1122
+ on_event("batch_started", f"Batch {index + 1} of {total}: {len(items)} queries",
1123
+ {"batch": index + 1, "batches": total, "queries": len(items), "known_tables": len(known)})
1124
+ result, error = ask(items, cap, known, index)
1125
+ split = False
1126
+ if result is None and "did not finish within" in error and len(items) > 1:
1127
+ # out of time: asked again in two halves, once, so the batch is not lost
1128
+ half = len(items) // 2
1129
+ parts = [ask(part, (cap / 2) if cap else None, known, index) for part in (items[:half], items[half:])]
1130
+ if all(r is not None for r, _ in parts):
1131
+ split = True
1132
+ from .agent import AgentResult
1133
+ outs = [r.output for r, _ in parts]
1134
+ result = AgentResult(output={"candidates": [c for o in outs for c in o.get("candidates") or []],
1135
+ "rejected": [x for o in outs for x in o.get("rejected") or []],
1136
+ "table_definitions": [d for o in outs for d in o.get("table_definitions") or []]},
1137
+ model=parts[0][0].model, cost_usd=sum(float(r.cost_usd or 0) for r, _ in parts),
1138
+ duration_s=sum(float(r.duration_s or 0) for r, _ in parts), turns=sum(int(r.turns or 0) for r, _ in parts),
1139
+ usage={k: sum(int((r.usage or {}).get(k) or 0) for r, _ in parts) for k in (parts[0][0].usage or {})})
1140
+ else:
1141
+ error = next((e for r, e in parts if r is None), error)
1142
+ with lock:
1143
+ state["running"] -= 1
1144
+ state["reserved"] -= cap or 0.0
1145
+ lock.notify_all()
1146
+ if result is None:
1147
+ over = "budget" in error.lower()
1148
+ # a failed call does not say what it spent: count its whole share, so the total stays under the limit
1149
+ state["spent"] += (cap or 0.0) if over else 0.0
1150
+ invocation["calls"].append({"kind": "batch", "key": key, "status": "failed", "cost_usd": 0.0,
1151
+ "note": "a failed call does not report what it spent"})
1152
+ save_memory()
1153
+ records[index] = {"index": index, "key": key, "queries": len(items), "status": "failed" if not over else "skipped",
1154
+ "reason": "budget" if over else "agent_error", "error": error[:300], "reused": False,
1155
+ "cost_usd": 0.0, "turns": 0, "duration_s": 0.0, "candidates": 0, "rejected": 0}
1156
+ on_event("batch_failed", f"Batch {index + 1} of {total}: " + ("budget reached" if over else "failed"),
1157
+ {**progress(index), "queries": len(items), "reason": records[index]["reason"]})
1158
+ return
1159
+ state["spent"] += result.cost_usd
1160
+ state["costliest"] = max(state["costliest"], result.cost_usd)
1161
+ ids = {c["id"] for c in items}
1162
+ labels = {}
1163
+ for cand in result.output.get("candidates") or []:
1164
+ if cand.get("id") in ids and cand["id"] not in labels:
1165
+ labels[cand["id"]] = label_of(cand["id"]) # a query that was labelled before keeps its label
1166
+ invocation["calls"].append({"kind": "batch", "key": key, "status": "done", "cost_usd": round(result.cost_usd, 6)})
1167
+ save_memory()
1168
+ data = {"schema_version": 1, "key": key, "status": "done", "ids": sorted(ids), "labels": labels,
1169
+ "question": {"engine": engine, "top": top, "flavor": asked}, "engine_version": engine_version,
1170
+ "sql_hashes": {c["id"]: c.get("sql_hash", "") for c in items}, # which SQL each answer is about
1171
+ "finished_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
1172
+ "agent": {"runner": runner.name, "model": result.model, "cost_usd": result.cost_usd,
1173
+ "duration_s": result.duration_s, "turns": result.turns, "usage": result.usage},
1174
+ "output": result.output, "verdicts": True, **({"split": True} if split else {})}
1175
+ if store_dir:
1176
+ store_dir.mkdir(parents=True, exist_ok=True)
1177
+ (store_dir / f"batch-{key}.json").write_text(json.dumps(data, indent=1, ensure_ascii=False))
1178
+ store_verdicts(items, result.output, known, float(result.cost_usd or 0), key)
1179
+ finish(index, items, data, False)
1180
+ rec = records[index]
1181
+ on_event("batch_finished", f"Batch {index + 1} of {total}: {rec['candidates']} candidates",
1182
+ {**progress(index), "queries": len(items), "candidates": rec["candidates"], "rejected": rec["rejected"],
1183
+ "cost_usd": round(result.cost_usd, 4), "turns": result.turns, "duration_s": round(result.duration_s, 1),
1184
+ "reused": False})
1185
+
1186
+ if plan.cached:
1187
+ on_event("batch_finished", f"{len(plan.cached)} queries answered before: not asked again",
1188
+ {"batch": 0, "batches": total, "done": 0, "failed": 0, "queries": len(plan.cached),
1189
+ "candidates": len(cached_output["candidates"]), "rejected": len(cached_output["rejected"]),
1190
+ "cost_usd": 0.0, "reused": True, "answered_before": len(plan.cached), "candidates_total": len(cached_output["candidates"]),
1191
+ "cost_total_usd": 0.0})
1192
+ if total:
1193
+ # The first batch (the most valuable) runs alone: the batches that then run side by side all start from its
1194
+ # table definitions instead of each assembling their own.
1195
+ work(0, plan.batches[0])
1196
+ with ThreadPoolExecutor(max_workers=max(concurrency, 1), thread_name_prefix="codecop-rank") as pool:
1197
+ for future in [pool.submit(work, i, items) for i, items in enumerate(plan.batches) if i and records[i] is None]:
1198
+ future.result()
1199
+ if not any(r and r["status"] == "done" for r in records) and not plan.cached:
1200
+ first = next((r for r in records if r and r.get("error") and r.get("reason") != "budget"), None)
1201
+ if first or all(r and r.get("reason") != "budget" for r in records):
1202
+ raise AgentError(first["error"] if first else "The budget is too small to run one batch.")
1203
+
1204
+ every = plan.items + [c for c, _ in plan.cached]
1205
+ by_id = {c["id"]: c for c in plan.unasked + every}
1206
+ candidates, rejected, usage = [], [], Counter()
1207
+ models = []
1208
+ sources_out = [(plan.batches[i], data) for i, data in enumerate(outputs) if data is not None]
1209
+ if plan.cached:
1210
+ sources_out.append(([c for c, _ in plan.cached], {"output": cached_output, "labels": {}}))
1211
+ for batch, data in sources_out:
1212
+ ids = {c["id"] for c in batch}
1213
+ for cand in data["output"].get("candidates") or []:
1214
+ label = registry.get(cand.get("id")) or (data.get("labels") or {}).get(cand.get("id"))
1215
+ if cand.get("id") in ids and label: # an id that was not in the batch is the agent's mistake: dropped
1216
+ candidates.append(_candidate(cand, by_id[cand["id"]], label, engine))
1217
+ returned = {c["id"] for c in candidates}
1218
+ rejected += [r for r in data["output"].get("rejected") or [] if r.get("id") in ids and r["id"] not in returned]
1219
+ a = data.get("agent") or {}
1220
+ usage.update({k: v for k, v in (a.get("usage") or {}).items() if isinstance(v, (int, float))})
1221
+ if a.get("model"):
1222
+ models.append(a["model"])
1223
+ seen: set[str] = set()
1224
+ candidates = [c for c in sorted(candidates, key=lambda c: _label_number(c["finding"])) if not (c["id"] in seen or seen.add(c["id"]))]
1225
+ for c in candidates:
1226
+ if c["id"] in cached_ids:
1227
+ c["answered_before"] = True # a stored verdict, not asked again (verdicts.py)
1228
+ fresh_records = [r for r in records if r and not r["reused"]]
1229
+ # A table the catalog has is built from its real definition, whatever a batch returned for it. Only the tables
1230
+ # a candidate reads are kept from the catalog: the sandbox loads every definition listed.
1231
+ if facts: # `prod.events` in a candidate is the catalog's `events`: one name for the definition, the profile and the sandbox
1232
+ for c in candidates:
1233
+ c["tables"] = list(dict.fromkeys((facts.definition(engine, t) or {"name": t})["name"] for t in c["tables"]))
1234
+ real = [{k: v for k, v in d.items() if k != "note"} for d in real_for({t for c in candidates for t in c["tables"]})]
1235
+ real_names = {d["name"] for d in real}
1236
+ final_definitions = real + [d for d in merge_definitions([d for batch in defs_by_batch for d in batch] + cached_defs, engine)
1237
+ if d["name"] not in real_names]
1238
+ # What earlier runs found: the rank.json this result replaces, then every stored batch this result is not made of.
1239
+ carried = {"candidates": 0, "variants": 0, "from": (earlier or {}).get("generated_at", "")}
1240
+ sources = [earlier] if earlier else []
1241
+ used = {data.get("key") for data in outputs if data}
1242
+ for d in sorted(on_disk, key=lambda d: d.get("finished_at", "")):
1243
+ if d.get("status") != "done" or d.get("key") in used:
1244
+ continue
1245
+ old = [_candidate(c, by_id[c["id"]], registry.get(c["id"]) or (d.get("labels") or {}).get(c["id"], ""), engine)
1246
+ for c in (d.get("output") or {}).get("candidates") or []
1247
+ if c.get("id") in by_id and (d.get("sql_hashes") or {}).get(c["id"], by_id[c["id"]].get("sql_hash")) == by_id[c["id"]].get("sql_hash")]
1248
+ sources.append({"engine": engine, "generated_at": d.get("finished_at", ""), "candidates": [c for c in old if c["finding"]],
1249
+ "table_definitions": (d.get("output") or {}).get("table_definitions") or []})
1250
+ if asked_ids is not None:
1251
+ carried["unasked"] = 0
1252
+ for source in sources if (keep_earlier or plan.focus) else []:
1253
+ got = merge_earlier(candidates, rejected, final_definitions, source, full_inventory or inventory, engine, asked_ids)
1254
+ carried["candidates"] += got["candidates"]
1255
+ carried["variants"] += got["variants"]
1256
+ if asked_ids is not None:
1257
+ carried["unasked"] += got["unasked"]
1258
+ carried["from"] = carried["from"] or got["from"]
1259
+ candidates.sort(key=lambda c: _label_number(c["finding"]))
1260
+ if plan.focus == "assembled":
1261
+ # the statements this pass wrote out from their builders: where their SQL comes from (assemble.label)
1262
+ from .assemble import label as assembled_label
1263
+ for c in candidates:
1264
+ if c["id"] in (asked_ids or set()) and c["id"] in by_id:
1265
+ c.update(assembled_label(c, by_id[c["id"]]))
1266
+ # what this pass did not write out and gave no known code for ("too large to assemble", "not assembled in this
1267
+ # pass") is still SQL built at run time: never "nothing to gain" on prose
1268
+ for r in rejected:
1269
+ if r.get("id") in (asked_ids or set()) and (r.get("code") or "other") not in REJECTION_CODES:
1270
+ r.update(code="unresolved_sql", agent_code=r.get("code") or "other")
1271
+ # the queries rejected by rule before the agent (skip_rules): listed with the agent's rejections, `by_rule` and the
1272
+ # measured numbers saying who decided. A query an earlier run made a candidate stays one (merge_earlier).
1273
+ have_ids = {c["id"] for c in candidates} | {r.get("id") for r in rejected}
1274
+ rejected += [r for r in plan.skipped if r["id"] not in have_ids]
1275
+ # every column a candidate reads is in its table's definition, from the repository's schema when no batch kept it,
1276
+ # or the candidate says why it is not (definitions.py); and the definitions carry the schema's indexes
1277
+ from .definitions import complete
1278
+ done, completed = complete({"engine": engine, "candidates": candidates, "table_definitions": final_definitions}, inventory)
1279
+ candidates, final_definitions = done["candidates"], done["table_definitions"]
1280
+ save_memory()
1281
+ batch_records = [r for r in records if r]
1282
+ shortlist = [{**{k: c[k] for k in ("id", "file", "line", "score", "flags")}, "batch": i,
1283
+ **({"measured_read_bytes": c["measured"]["read_bytes"], "measured_executions": c["measured"]["executions"],
1284
+ **({"located": True} if c["measured"].get("located") else {})}
1285
+ if c.get("measured") else {})}
1286
+ for i, batch in enumerate(plan.batches) for c in batch]
1287
+ extra_index = total
1288
+ if plan.cached:
1289
+ batch_records.append({"index": extra_index, "key": "stored-verdicts", "queries": len(plan.cached), "status": "done", "reason": "",
1290
+ "reused": True, "answered_before": True, "cost_usd": 0.0, "turns": 0, "duration_s": 0.0,
1291
+ "candidates": len(cached_output["candidates"]), "rejected": len(cached_output["rejected"])})
1292
+ shortlist += [{**{k: c[k] for k in ("id", "file", "line", "score", "flags")}, "batch": extra_index, "answered_before": True}
1293
+ for c, _ in plan.cached]
1294
+ extra_index += 1
1295
+ if plan.unasked:
1296
+ # left out to stay within the run budget: not asked yet, with the step that would judge them (budget.py)
1297
+ batch_records.append({"index": extra_index, "key": "not-asked", "queries": len(plan.unasked), "status": "skipped", "reason": "budget",
1298
+ "reused": False, "cost_usd": 0.0, "turns": 0, "duration_s": 0.0, "candidates": 0, "rejected": 0,
1299
+ "next_step": "ask_agent_to_rank"})
1300
+ shortlist += [{**{k: c[k] for k in ("id", "file", "line", "score", "flags")}, "batch": extra_index, "not_asked": True}
1301
+ for c in plan.unasked]
1302
+ result = {
1303
+ "schema_version": 1,
1304
+ "tool_version": __version__,
1305
+ "generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
1306
+ "commit": (inventory.get("repo") or {}).get("commit", ""),
1307
+ "engine": engine,
1308
+ "engine_version": engine_version,
1309
+ # candidates and variants kept from the rank.json this one replaces (merge_earlier): {candidates, variants, from}
1310
+ "carried": carried,
1311
+ "agent": {
1312
+ "runner": runner.name,
1313
+ **billing(runner),
1314
+ "model": Counter(models).most_common(1)[0][0] if models else "",
1315
+ # every batch that makes up this result (queries answered before cost nothing here: they were paid once)
1316
+ "cost_usd": round(sum(r["cost_usd"] for r in records if r), 4),
1317
+ "cost_this_invocation_usd": round(sum(float(c.get("cost_usd") or 0) for c in invocation["calls"]), 4),
1318
+ # everything the agent was paid for in this out dir: every invocation, batches that were run again or
1319
+ # replaced and the area classification included (rank_batches/ledger.json)
1320
+ "cost_total_usd": ledger_total(ledger),
1321
+ "invocations": sum(1 for i in ledger["invocations"] if i.get("calls")) or 1,
1322
+ "duration_s": round(time.monotonic() - started, 1) if fresh_records else 0.0, # wall clock of this invocation
1323
+ "turns": sum(r["turns"] for r in records if r),
1324
+ "usage": dict(usage),
1325
+ "answered_before": len(plan.cached),
1326
+ "not_asked": len(plan.unasked),
1327
+ },
1328
+ "depth": plan.depth,
1329
+ # the prompt showed each query's SQL up to this length; `sql_cut` lists the queries it cut (sql_too_long_for_agent)
1330
+ "max_sql_chars": plan.max_sql_chars,
1331
+ "sql_cut": [{"id": c["id"], "chars": len((c.get("sql") or "").strip())} for c in plan.cut_items()],
1332
+ "select_sites": plan.select_sites,
1333
+ "unique_queries": plan.unique_queries,
1334
+ "paths": plan.paths, # the --path filter, so coverage can recount the same sites later
1335
+ "batches": batch_records,
1336
+ "shortlist": shortlist,
1337
+ "candidates": candidates,
1338
+ "table_definitions": final_definitions,
1339
+ "scoring": "measured load" if any(c.get("measured") for c in every) else "static heuristics",
1340
+ "located_pieces": sum(1 for c in every if (c.get("measured") or {}).get("located")),
1341
+ "rejected": rejected,
1342
+ # skipped by rule before the agent (skip_rules): counts and the estimate of what they would have cost
1343
+ "skipped_by_rule": plan.skip_estimate(),
1344
+ # what the per-statement verdicts did for this run (verdicts.py)
1345
+ "verdicts": {"answered_before": len(plan.cached), "asked": sum(len(b) for b in plan.batches), "not_asked": len(plan.unasked),
1346
+ "stored": verdict_store.count()},
1347
+ **({"definitions_completed": completed} if completed else {}),
1348
+ }
1349
+ if plan.pool is not None: # the plan as it was planned: a later run_plan of it takes the stored answers out again
1350
+ plan.batches, plan.unasked = plan.pool
1351
+ plan.cached, plan.cache_ready, plan.pool = [], False, None
1352
+ return merge_focused(result, earlier, asked_ids, plan.focus) if plan.focus else result
1353
+
1354
+
1355
+ def merge_focused(result: dict, earlier: dict | None, asked: set[str] | None, focus: str) -> dict:
1356
+ """A focused run's result laid over the ranking it adds to. The candidates are merged already (merge_earlier with
1357
+ `asked`); here the rest: the earlier rejections, shortlist entries and batch records of the queries this run did not
1358
+ ask about are kept, this run's batches are numbered after the earlier ones (a shortlist entry names its batch), and
1359
+ the ranking keeps the earlier scope (depth, paths, SELECT call sites). `focus_runs` lists the focused runs."""
1360
+ if not earlier:
1361
+ return {**result, "focus_runs": [{"focus": focus, "generated_at": result["generated_at"], "queries": len(result["shortlist"]),
1362
+ "candidates": len(result["candidates"])}]}
1363
+ asked = asked or set()
1364
+ old_batches = list(earlier.get("batches") or [])
1365
+ offset = max((int(b.get("index", -1)) for b in old_batches), default=-1) + 1
1366
+ batches = old_batches + [{**b, "index": int(b["index"]) + offset, "focus": focus} for b in result["batches"]]
1367
+ shortlist = [s for s in earlier.get("shortlist") or [] if s.get("id") not in asked] + [
1368
+ {**s, "batch": int(s["batch"]) + offset, "focus": focus} for s in result["shortlist"]]
1369
+ here = {r.get("id") for r in result["rejected"]} | {c["id"] for c in result["candidates"]}
1370
+ rejected = [r for r in earlier.get("rejected") or [] if r.get("id") not in asked and r.get("id") not in here] + result["rejected"]
1371
+ out = {**result, "batches": batches, "shortlist": shortlist, "rejected": rejected}
1372
+ for key in ("depth", "paths", "select_sites", "unique_queries", "max_sql_chars", "scoring"):
1373
+ if key in earlier:
1374
+ out[key] = earlier[key]
1375
+ out["located_pieces"] = int(earlier.get("located_pieces") or 0) + int(result.get("located_pieces") or 0)
1376
+ out["sql_cut"] = [x for x in earlier.get("sql_cut") or [] if x.get("id") not in asked] + list(result.get("sql_cut") or [])
1377
+ out["focus_runs"] = list(earlier.get("focus_runs") or []) + [{"focus": focus, "generated_at": result["generated_at"],
1378
+ "queries": len(result["shortlist"]),
1379
+ "candidates": sum(1 for c in result["candidates"] if c["id"] in asked)}]
1380
+ return out
1381
+
1382
+
1383
+ def rank(inventory: dict, root: Path, runner: AgentRunner, *, engine: str, engine_version: str, top: int = 10,
1384
+ shortlist_size: int = BATCH_SIZE, paths: list[str] | None = None, model: str | None = None,
1385
+ max_budget_usd: float | None = None, depth: str = "top", **options) -> dict:
1386
+ """Plan and run in one call. `options` are passed to run_plan (out_dir, resume, concurrency, on_event)."""
1387
+ return run_plan(inventory, root, runner, plan(inventory, engine, depth=depth, shortlist_size=shortlist_size, paths=paths),
1388
+ engine_version=engine_version, top=top, model=model, max_budget_usd=max_budget_usd, **options)
1389
+
1390
+
1391
+ # ---- areas: the agent says what each part of the repo is ----------------
1392
+
1393
+ def group_areas(inventory: dict) -> list[dict]:
1394
+ """Directory groups with call sites. discover writes `areas`; older inventories get top-level directories."""
1395
+ if inventory.get("areas"):
1396
+ return inventory["areas"]
1397
+ groups: dict[str, dict] = {}
1398
+ for c in inventory["call_sites"]:
1399
+ parts = c["file"].split("/")
1400
+ path = "/".join(parts[:2]) if len(parts) > 2 else (parts[0] if len(parts) > 1 else ".")
1401
+ g = groups.setdefault(path, {"path": path, "role": "", "description": "", "basis": "path", "sites": 0, "sample_files": []})
1402
+ g["sites"] += 1
1403
+ if len(g["sample_files"]) < 5 and c["file"] not in g["sample_files"]:
1404
+ g["sample_files"].append(c["file"])
1405
+ g.setdefault("_roles", Counter())[site_role(c)] += 1
1406
+ for g in groups.values():
1407
+ g["role"] = g.pop("_roles").most_common(1)[0][0]
1408
+ return sorted(groups.values(), key=lambda g: -g["sites"])
1409
+
1410
+
1411
+ AREAS_FILE = "agent_areas.json" # in the out dir: the agent's verdict per code area, so an unchanged area is not asked again
1412
+
1413
+
1414
+ def classify_areas(inventory: dict, root: Path, runner: AgentRunner | None, *, model: str | None = None,
1415
+ max_budget_usd: float | None = None, limit: int = 80, out_dir: Path | None = None, fresh: bool = False) -> dict:
1416
+ """One agent call that corrects the path-based role of each code area, then applies it to the call sites.
1417
+
1418
+ A role that came from a traced entry point is kept: the agent's verdict replaces path guesses only. With `out_dir`
1419
+ the verdicts are stored per area (agent_areas.json) and only areas not answered before are asked about; when every
1420
+ area was answered before no agent is started (`runner` may then be None) and the cost is 0."""
1421
+ areas = group_areas(inventory)[:limit]
1422
+ stored = {} if fresh or not out_dir else {k: v for k, v in (_read_json(out_dir / AREAS_FILE, {}) or {}).get("areas", {}).items()
1423
+ if isinstance(v, dict)}
1424
+ todo = [a for a in areas if a["path"] not in stored]
1425
+ cost = duration = 0.0
1426
+ model_used = ""
1427
+ verdicts = {p: v for p, v in stored.items()}
1428
+ if todo:
1429
+ if runner is None:
1430
+ raise AgentError("no agent to classify the code areas")
1431
+ listing = "\n".join(
1432
+ f"- {a['path']} (path guess: {a['role'] or 'unknown'}; {a['sites']} call sites; e.g. {', '.join(a.get('sample_files', [])[:3])})"
1433
+ for a in todo)
1434
+ result = runner.run(_fill(load_prompt("areas"), {"areas": listing}), load_schema("areas_output"), root,
1435
+ model=model, max_budget_usd=max_budget_usd)
1436
+ got = {a["path"]: a for a in result.output.get("areas", [])}
1437
+ verdicts.update(got)
1438
+ cost, duration, model_used = float(result.cost_usd or 0), float(result.duration_s or 0), result.model
1439
+ if out_dir:
1440
+ try:
1441
+ out_dir.mkdir(parents=True, exist_ok=True)
1442
+ (out_dir / AREAS_FILE).write_text(json.dumps({"schema_version": 1, "areas": {**stored, **{p: {k: v.get(k) for k in (
1443
+ "path", "role", "description", "confidence")} for p, v in got.items()}}}, indent=1, ensure_ascii=False))
1444
+ except OSError:
1445
+ pass
1446
+ for a in areas:
1447
+ v = verdicts.get(a["path"])
1448
+ if v:
1449
+ a.update(role=v.get("role") or a.get("role") or "unknown", description=v.get("description") or "", basis="agent",
1450
+ confidence=v.get("confidence") or "medium")
1451
+ inventory["areas"] = areas
1452
+ by_len = sorted((a for a in areas if a["basis"] == "agent" and a["role"] != "unknown"), key=lambda a: -len(a["path"]))
1453
+ changed = 0
1454
+ for c in inventory["call_sites"]:
1455
+ if c.get("role_basis") == "entry_point" and c.get("role") not in (None, "", "unknown"):
1456
+ continue
1457
+ area = next((a for a in by_len if a["path"] == "." or c["file"] == a["path"] or c["file"].startswith(a["path"].rstrip("/") + "/")), None)
1458
+ if area is None:
1459
+ continue
1460
+ # tests inside an app directory stay tests: the agent classifies the area, not each file
1461
+ role = "test" if c.get("is_test") and area["role"] != "test" else area["role"]
1462
+ if role != "test" and RUNS_ONCE_PATH.search(c["file"]):
1463
+ role = "migration" # a migration, seed or backfill inside an app area still runs once
1464
+ if c.get("role") != role:
1465
+ changed += 1
1466
+ c["role"], c["role_basis"] = role, "path"
1467
+ continue
1468
+ if c.get("role") != role:
1469
+ changed += 1
1470
+ c["role"], c["role_basis"] = role, "agent"
1471
+ c["is_test"] = role == "test"
1472
+ return {"areas": areas, "changed_sites": changed, "cost_usd": cost, "duration_s": duration, "model": model_used,
1473
+ "asked": len(todo), "answered_before": len(areas) - len(todo)}