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/mcpserver.py ADDED
@@ -0,0 +1,120 @@
1
+ """`codecop mcp`: a local, read-only Model Context Protocol server over the stage files of one out dir (docs/mcp.md).
2
+
3
+ The stdio transport of MCP: one JSON-RPC 2.0 message per line on stdin, one per line on stdout, nothing else on stdout
4
+ (logs go to stderr). The handshake revisions (`initialize`, 2024-11-05 to 2025-11-25) are served; a client that first
5
+ probes `server/discover` (the stateless 2026-07-28 revision) gets "method not found" and falls back to `initialize`, as
6
+ the official SDK's client does. Written here rather than on the official `mcp` package: that package brings about
7
+ thirty dependencies (pydantic, starlette, uvicorn, cryptography, ...) into a CLI that keeps six; the server needs four
8
+ methods. tests/test_mcp.py runs a real stdio round trip, and, when the official SDK is installed, its client against
9
+ this server.
10
+
11
+ What it serves is agentfacts.py: six tools, plain text, every answer with its source and basis. No network, no database,
12
+ no agent call, nothing that runs SQL.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import sys
19
+ from pathlib import Path
20
+ from typing import IO, Any
21
+
22
+ from . import agentfacts
23
+
24
+ # The initialize-handshake revisions, oldest to newest; the newest is answered when the client asks for another.
25
+ PROTOCOL_VERSIONS = ("2024-11-05", "2025-03-26", "2025-06-18", "2025-11-25")
26
+ SERVER_NAME = "codecop"
27
+ INSTRUCTIONS = (
28
+ "CodeCop's measured evidence about this repository's database statements, from the stage files of one scan (local, "
29
+ "read-only). Use `priorities` to choose what to work on (ranked by measured production load), `statement` before "
30
+ "proposing or reviewing a query or index change (what the sandbox measured, same rows, insert cost, fidelity), "
31
+ "`table` for a table's real size, indexes and readers, `call_patterns` for loops that query per item, `not_asked` for "
32
+ "what CodeCop has not judged yet. Every answer says where each figure comes from: [production] measured in production, "
33
+ "[sandbox] a ratio measured on generated data, [claimed] not measured. Nothing is a win unless the sandbox verified it; "
34
+ "a trade-off is not a win; 'not judged' means the sandbox was not like production. Quote the basis with any number.")
35
+
36
+
37
+ def _version() -> str:
38
+ try:
39
+ from importlib.metadata import version
40
+ return version("codecop")
41
+ except Exception: # pragma: no cover - not installed as a package
42
+ return "0"
43
+
44
+
45
+ def _result(mid: Any, result: dict) -> dict:
46
+ return {"jsonrpc": "2.0", "id": mid, "result": result}
47
+
48
+
49
+ def _error(mid: Any, code: int, message: str) -> dict:
50
+ return {"jsonrpc": "2.0", "id": mid, "error": {"code": code, "message": message}}
51
+
52
+
53
+ class Server:
54
+ def __init__(self, stage: agentfacts.Stage):
55
+ self.stage = stage
56
+
57
+ def handle(self, msg: Any) -> dict | list | None:
58
+ """One parsed message (or a batch) in, the response out; None for a notification or a response."""
59
+ if isinstance(msg, list):
60
+ out = [r for r in (self.handle(m) for m in msg) if r is not None]
61
+ return out or None
62
+ if not isinstance(msg, dict) or msg.get("jsonrpc") != "2.0":
63
+ return _error(msg.get("id") if isinstance(msg, dict) else None, -32600, "Invalid Request")
64
+ method, mid = msg.get("method"), msg.get("id")
65
+ if method is None:
66
+ return None # a response to a request we never send
67
+ if "id" not in msg:
68
+ return None # notifications/initialized, notifications/cancelled, ...
69
+ params = msg.get("params") if isinstance(msg.get("params"), dict) else {}
70
+ if method == "initialize":
71
+ asked = params.get("protocolVersion")
72
+ return _result(mid, {
73
+ "protocolVersion": asked if asked in PROTOCOL_VERSIONS else PROTOCOL_VERSIONS[-1],
74
+ "capabilities": {"tools": {"listChanged": False}},
75
+ "serverInfo": {"name": SERVER_NAME, "title": "CodeCop evidence (read-only)", "version": _version()},
76
+ "instructions": INSTRUCTIONS})
77
+ if method == "ping":
78
+ return _result(mid, {})
79
+ if method == "tools/list":
80
+ tools = [{**t, "annotations": {"readOnlyHint": True, "destructiveHint": False, "idempotentHint": True, "openWorldHint": False}}
81
+ for t in agentfacts.TOOLS]
82
+ return _result(mid, {"tools": tools})
83
+ if method == "tools/call":
84
+ name = params.get("name")
85
+ if name not in {t["name"] for t in agentfacts.TOOLS}:
86
+ return _error(mid, -32602, f"Unknown tool: {name}")
87
+ try:
88
+ text = agentfacts.call(self.stage, name, params.get("arguments") or {})
89
+ return _result(mid, {"content": [{"type": "text", "text": text}], "isError": False})
90
+ except Exception as e: # a tool error is a result the agent can read, not a protocol error
91
+ return _result(mid, {"content": [{"type": "text", "text": f"CodeCop: {e}"}], "isError": True})
92
+ if method in ("resources/list", "prompts/list"):
93
+ return _result(mid, {method.split("/")[0]: []})
94
+ return _error(mid, -32601, f"Method not found: {method}")
95
+
96
+
97
+ def serve(stage: agentfacts.Stage, stdin: IO[str] | None = None, stdout: IO[str] | None = None) -> None:
98
+ """Read messages until stdin closes."""
99
+ stdin = stdin or sys.stdin
100
+ stdout = stdout or sys.stdout
101
+ server = Server(stage)
102
+ for line in stdin:
103
+ line = line.strip()
104
+ if not line:
105
+ continue
106
+ try:
107
+ msg = json.loads(line)
108
+ except ValueError:
109
+ reply: Any = _error(None, -32700, "Parse error")
110
+ else:
111
+ reply = server.handle(msg)
112
+ if reply is not None:
113
+ stdout.write(json.dumps(reply, ensure_ascii=False) + "\n")
114
+ stdout.flush()
115
+
116
+
117
+ def client_config(out_dir: Path, repo: Path | None, command: str) -> dict:
118
+ """The JSON snippet Claude Code (.mcp.json) and Cursor (.cursor/mcp.json) read: one stdio server named codecop."""
119
+ args = ["mcp"] + ([str(repo)] if repo else []) + ["--out", str(out_dir)]
120
+ return {"mcpServers": {SERVER_NAME: {"type": "stdio", "command": command, "args": args}}}
codecop/mechanism.py ADDED
@@ -0,0 +1,214 @@
1
+ """How the SQL of a call site comes to exist: one mechanism class per site, and whether its statement is obtained.
2
+
3
+ Classes: literal, constant_concat, template_values_only, conditional_fragments, loop_built,
4
+ identifier_template, builder_unresolved, across_functions, from_config_db_or_request, query_builder, orm_api,
5
+ orm_api_in_loop, orm_raw_fragment, generated_code, sqlfile_loaded_by_code, sqlfile_query, sqlfile_dbt_jinja,
6
+ sqlfile_procedure_trigger, sqlfile_migration_ddl; `missed` is the class of a site only the library probes found
7
+ (discover/probes.py).
8
+
9
+ Obtained, per site:
10
+ obtained SQL text with no run-time part, or run-time parts only in value position (a bind)
11
+ partial SQL text with a structural run-time part («…» as a clause, identifier or list)
12
+ none no text (unresolved, handed in as a parameter) or not found by discovery
13
+
14
+ Discover stores both on every call site (`mechanism`, `obtained`); coverage.py recomputes them for an inventory from
15
+ before they existed. Pure text rules, no repository code runs.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import re
21
+ from collections import Counter
22
+ from pathlib import Path
23
+
24
+ CLASSES = ("literal", "constant_concat", "template_values_only", "conditional_fragments", "loop_built", "identifier_template",
25
+ "builder_unresolved", "across_functions", "from_config_db_or_request", "query_builder", "orm_api", "orm_api_in_loop",
26
+ "orm_raw_fragment", "generated_code", "sqlfile_loaded_by_code", "sqlfile_query", "sqlfile_dbt_jinja",
27
+ "sqlfile_procedure_trigger", "sqlfile_migration_ddl", "missed")
28
+ # the words for each class, for tables and the console
29
+ LABELS = {
30
+ "literal": "Literal", "constant_concat": "Constant or concatenation", "template_values_only": "Template, values only",
31
+ "conditional_fragments": "Conditional fragments", "identifier_template": "Table or column from a variable",
32
+ "loop_built": "Loop-built lists", "across_functions": "Assembled across functions", "builder_unresolved": "Builder, unresolved",
33
+ "from_config_db_or_request": "From configuration, a database or the request", "query_builder": "Query-builder DSL",
34
+ "orm_api": "ORM model API", "orm_api_in_loop": "ORM call in a loop", "orm_raw_fragment": "ORM raw fragment",
35
+ "generated_code": "Generated code (sqlc, ent)", "sqlfile_query": "SQL file query", "sqlfile_loaded_by_code": "SQL file loaded by code",
36
+ "sqlfile_dbt_jinja": "dbt / Jinja SQL", "sqlfile_procedure_trigger": "Procedure or trigger body",
37
+ "sqlfile_migration_ddl": "Migration DDL", "missed": "Not found by discovery (probe)",
38
+ }
39
+ OBTAINED = ("obtained", "partial", "none")
40
+
41
+ PH = re.compile(r"«([^»]*)»")
42
+ FRAG_OTHER = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|…", re.S)
43
+ VALUE_BEFORE = re.compile(r"(?:=|<>|!=|<=|>=|<|>|\bLIKE|\bILIKE|\bIN\s*\(|\bANY\s*\(|\bLIMIT|\bOFFSET|\bVALUES\s*\(|,|\(|\bBETWEEN|\bAND|\bTHEN|\bELSE|"
44
+ r"\bSET\s+\w+\s*=|::\w+\s*|\bINTERVAL|'|%)\s*['\"%]*$", re.I)
45
+ COND_NAME = re.compile(r"where|filter|cond|clause|predic|criteria|having|extra|suffix|prefix|order|sort|limit|offset|group|join|scope|"
46
+ r"search|query|sql|stmt|select|cte|with|parts?|fragment|tail|pagination|paging|settings|final", re.I)
47
+ LOOP_EXPR = re.compile(r"join\s*\(|\.join|strings\.Repeat|repeat\(|placeholders?|qmarks|\?\s*,|bind_?vars|in_?list|values_?(sql|clause|list|str)|"
48
+ r"\bcolumns?\b|\bcols?\b|fields|\bkeys\b|set_?clause|updates?\b|rows\b|sep\.|implode|collect", re.I)
49
+ IDENT_BEFORE = re.compile(r"(?:\bFROM|\bJOIN|\bINTO|\bUPDATE|\bTABLE(?:\s+IF\s+(?:NOT\s+)?EXISTS)?|\bINDEX|\bON|\bDATABASE|\bSCHEMA|\bVIEW|"
50
+ r"\bTRUNCATE|\bDESCRIBE|\bEXISTS|\bDICTIONARY|\.|\")\s*[\"`\[]?$", re.I)
51
+ # The value helpers of SQL template libraries (a quoted, escaped or typed literal, never SQL text): openpanel-style
52
+ # `sql.string(x)` / `sql.uint64(n)` / `sql.array('String', xs)`, `escape(x)`, `escapeLiteral(x)`, `quoteLiteral(x)`.
53
+ VALUE_CALL = re.compile(r"^\s*(?:[\w$]+\.)*(?:string|str|u?int(?:8|16|32|64|128|256)?|float(?:32|64)?|number|num|bool(?:ean)?|"
54
+ r"date(?:time(?:64)?)?|timestamp|uuid|value|val|param|literal|lit|array|escape|escapeLiteral|quoteLiteral|"
55
+ r"escape_?string|escape_?literal|sqlstring|sqlString)\s*\(", re.I)
56
+ IDENT_NAME = re.compile(r"table|tbl|schema|database|\bdb\b|db_?name|relation|column|col_?name|field|index|view|cluster|namespace|tenant|"
57
+ r"prefix|ident|quote|ref\(|sql\.table|name\b", re.I)
58
+
59
+
60
+ def placeholder_kinds(sql: str) -> Counter:
61
+ """value | identifier | loop | conditional | other, for every «…» of a template."""
62
+ out: Counter = Counter()
63
+ for m in PH.finditer(sql):
64
+ expr = m.group(1)
65
+ before = sql[max(0, m.start() - 60):m.start()]
66
+ after = sql[m.end():m.end() + 3]
67
+ if re.search(r"\b(?:IN|ANY)\s*\(\s*$", before, re.I) and after[:1] == ")":
68
+ out["value"] += 1 # an IN list of values: one shape, any length
69
+ elif VALUE_CALL.match(expr) and not IDENT_BEFORE.search(before) and after[:1] != ".":
70
+ out["value"] += 1 # a typed-literal helper of a SQL template library: `sql.string(x)`, `sql.uint64(n)`
71
+ elif re.search(r"\?[^:]*:|\b(?:AND|WHERE|ORDER BY|GROUP BY|HAVING|JOIN|LIMIT|UNION)\b|\bif\b.*\belse\b|unwrap_or|\.map\(", expr):
72
+ out["conditional"] += 1 # the expression itself chooses or builds a clause
73
+ elif after[:1] == "." or IDENT_BEFORE.search(before) or re.search(r"[\"`]\w*$|\w_$", before):
74
+ out["identifier"] += 1
75
+ elif re.search(r"(?:=|<>|!=|<=|>=|<|>|\bLIMIT|\bOFFSET|\bLIKE|\bILIKE)\s*['%]*$", before, re.I):
76
+ out["value"] += 1
77
+ elif LOOP_EXPR.search(expr) and not re.search(r"=\s*$", before.strip()[-2:] or " "):
78
+ out["loop"] += 1
79
+ elif VALUE_BEFORE.search(before) and not re.search(r"\bAND\s*$|\(\s*$|,\s*$", before, re.I):
80
+ out["value"] += 1
81
+ elif COND_NAME.search(expr):
82
+ out["conditional"] += 1
83
+ elif VALUE_BEFORE.search(before) and re.search(r",\s*$|\(\s*$", before) and not COND_NAME.search(expr):
84
+ out["value"] += 1
85
+ elif IDENT_NAME.search(expr):
86
+ out["identifier"] += 1
87
+ else:
88
+ out["conditional" if re.search(r"\bAND\s*$|\bWHERE\s*$|^\s*$", before, re.I) or m.end() >= len(sql.rstrip()) else "other"] += 1
89
+ return out
90
+
91
+
92
+ QB_LIBS = {"kysely", "drizzle", "jooq", "knex", "squirrel", "goqu", "diesel", "sea_query", "sea-query", "bun", "sqlalchemy_core", "querydsl",
93
+ "jdbi", "sqlx_builder", "exposed"}
94
+ GEN_HEAD = re.compile(r"Code generated by (sqlc|ent|entc|sqlboiler|jet|gorm\.io/gen|xo)|This class is generated by jOOQ|@generated|"
95
+ r"generated by prisma|DO NOT EDIT", re.I)
96
+ GEN_PATH = re.compile(r"\.sql\.go$|(^|/)ent/(?!schema/)[^/]+\.go$|(^|/)ent/[^/]+/[^/]+\.go$|/generated/|/gen/|_gen\.go$|\.gen\.go$|"
97
+ r"/jooq/.*/tables/|\.pb\.go$|/sqlc/|/dbsqlc/|/models_gen")
98
+ RAW_ORM = re.compile(r"\btext\(|\.raw\(|RawSQL|\.extra\(|sql`|\$queryRaw|\$executeRaw|Sequelize\.literal|\.whereRaw|\.selectRaw|\.orderByRaw|"
99
+ r"sql\.raw|literal_column|nativeQuery|createNativeQuery|from_statement|\.Raw\(|\.Exec\(|sql_query|find_by_sql|Arel\.sql|"
100
+ r"fragment\(", re.I)
101
+ FROM_OUTSIDE = re.compile(r"getenv|os\.environ|yaml|\brow\[|record\.|\.get\(['\"](query|sql)|saved_?query|stored_?(query|sql)|user_?(query|sql)|"
102
+ r"\brequest\.|\breq\.|\bbody\.|\binput\.|\bargs\.|payload|(?:config|settings|cfg|conf)\w*\.\w*(?:sql|query)", re.I)
103
+ BUILDER_EXPR = re.compile(r"\.String\(\)|\.build\(|\.to_sql|\.toSql|\.ToSql|into_sql|\.sql\(\)|builder|Builder|\.join\(|\+|format!|Sprintf|f\"|"
104
+ r"\.format\(|push_str|qb\.|\.as_str\(\)|compile")
105
+
106
+
107
+ class Headers:
108
+ """Reads the first bytes of a file once, to tell generated code by its header. Without a root only the path counts."""
109
+
110
+ def __init__(self, root: Path | None):
111
+ self.root = root
112
+ self._cache: dict[str, bool] = {}
113
+
114
+ def generated(self, rel: str) -> bool:
115
+ if rel.endswith(".sql"):
116
+ return False
117
+ if GEN_PATH.search(rel) and "/ent/schema/" not in rel and self.root is None:
118
+ return True
119
+ if self.root is None:
120
+ return False
121
+ if rel not in self._cache:
122
+ try:
123
+ with open(self.root / rel, "r", errors="ignore") as f:
124
+ self._cache[rel] = bool(GEN_HEAD.search(f.read(600)))
125
+ except OSError:
126
+ self._cache[rel] = False
127
+ return self._cache[rel]
128
+
129
+
130
+ def sql_file_class(site: dict) -> str:
131
+ rel = (site.get("file") or "").lower()
132
+ sql = site.get("sql") or ""
133
+ if re.search(r"create\s+(or\s+replace\s+)?(function|procedure|trigger)|\$\$|language\s+plpgsql|\bNEW\.\w+", sql, re.I):
134
+ return "sqlfile_procedure_trigger"
135
+ if "{{" in sql or "{%" in sql or re.search(r"(^|/)(models|macros|snapshots|analyses)/", rel) and re.search(r"dbt|transform|warehouse", rel + " "):
136
+ return "sqlfile_dbt_jinja"
137
+ if site.get("statement") in ("ddl", "other", "unknown") or re.search(
138
+ r"migrat|schema|flyway|liquibase|alembic|changelog|/ddl/|init\.sql|structure\.sql|/up\.sql|/down\.sql|\.up\.sql|\.down\.sql|upgrade|bootstrap", rel):
139
+ return "sqlfile_migration_ddl"
140
+ return "sqlfile_query"
141
+
142
+
143
+ def obtained_of(sql: str) -> str:
144
+ """obtained | partial | none for a statement text."""
145
+ if not (sql or "").strip():
146
+ return "none"
147
+ kinds = placeholder_kinds(sql)
148
+ structural = sum(v for k, v in kinds.items() if k != "value") + len(FRAG_OTHER.findall(sql))
149
+ return "partial" if structural else "obtained"
150
+
151
+
152
+ def classify(site: dict, headers: Headers | None = None) -> tuple[str, str]:
153
+ """(mechanism class, obtained) for one inventory call site."""
154
+ headers = headers or Headers(None)
155
+ res = site.get("resolution")
156
+ sql = site.get("sql") or ""
157
+ got = obtained_of(sql)
158
+ expr = site.get("expr") or ""
159
+ if site.get("kind") == "sql_file" or site.get("language") == "sql":
160
+ c = sql_file_class(site)
161
+ if c == "sqlfile_dbt_jinja" and got == "obtained" and ("{{" in sql or "{%" in sql):
162
+ got = "partial"
163
+ return c, got
164
+ if headers.generated(site.get("file") or ""):
165
+ return "generated_code", got
166
+ if res == "orm":
167
+ lib = ((site.get("orm") or {}).get("library") or "").lower()
168
+ told = (site.get("orm") or {}).get("mechanism") # a translator that knows its class says so
169
+ if told in CLASSES and told != "missed":
170
+ return ("orm_api_in_loop" if told == "orm_api" and site.get("in_loop") else told), got
171
+ base = "query_builder" if lib in QB_LIBS else "orm_api"
172
+ if RAW_ORM.search(expr):
173
+ return "orm_raw_fragment", got
174
+ if base == "orm_api" and site.get("in_loop"):
175
+ return "orm_api_in_loop", got
176
+ return base, got
177
+ if res == "file":
178
+ return "sqlfile_loaded_by_code", got
179
+ if res == "literal":
180
+ return "literal", got
181
+ if res == "constant":
182
+ return "constant_concat", got
183
+ if res == "template":
184
+ kinds = placeholder_kinds(sql) if sql else Counter()
185
+ if kinds["conditional"] or kinds["other"]:
186
+ return "conditional_fragments", got
187
+ if kinds["loop"]:
188
+ return "loop_built", got
189
+ if kinds["identifier"]:
190
+ return "identifier_template", got
191
+ return "template_values_only", got
192
+ if res == "parameter":
193
+ return "across_functions", got
194
+ if RAW_ORM.search(expr) and re.match(r"\s*&?\s*(?:sa\.|sqlalchemy\.)?text\(|.*\.raw\(|.*sql`", expr):
195
+ return "orm_raw_fragment", got
196
+ if FROM_OUTSIDE.search(expr):
197
+ return "from_config_db_or_request", got
198
+ if BUILDER_EXPR.search(expr):
199
+ return "builder_unresolved", got
200
+ return "across_functions", got
201
+
202
+
203
+ def annotate(sites: list[dict], root: Path | None) -> None:
204
+ """Sets `mechanism` and `obtained` on every call site (discover calls this once, at the end)."""
205
+ headers = Headers(root)
206
+ for s in sites:
207
+ s["mechanism"], s["obtained"] = classify(s, headers)
208
+
209
+
210
+ def of(site: dict) -> tuple[str, str]:
211
+ """The stored class when discover wrote one, else computed now from the text alone."""
212
+ if site.get("mechanism") in CLASSES and site.get("obtained") in OBTAINED:
213
+ return site["mechanism"], site["obtained"]
214
+ return classify(site)
codecop/members.py ADDED
@@ -0,0 +1,200 @@
1
+ """Scan-group and loop members made runnable by rule, before the benchmark builds its tables. Local: no database, no agent.
2
+
3
+ A scan group (groups.py) or a loop pattern (patterns.py) is benchmarked from its members' candidates: a ranked one
4
+ (rank.json), an observed one (observed.json). A member the agent never ranked had none, so the group or loop was not
5
+ judged (`group_member_not_runnable`, `loop_member_not_runnable`, "a table it reads is not loaded in the sandbox"). With a pulled catalog, two forms are
6
+ runnable by rule:
7
+
8
+ code the member's own SQL, fixed text in the code (resolution literal or constant, a SELECT with no run-time
9
+ part), on tables of the pulled catalog: every `$n` typed from the column it is compared with (observed.runnable
10
+ on the code's own text), values chosen as for an observed statement (observed.choose_values).
11
+ query_log the statement production ran for a member the pull holds with no place in code: built as an observed
12
+ statement (fill from the catalog, the gate, values), whatever its share of the bytes read.
13
+
14
+ Each is a candidate of its own (`M-001`, `sql_from` code, or `OM-001`, `sql_from` query_log): catalog_profile.augment
15
+ adds its tables' real definitions and a profile from the catalog, and bench measures it like any other; the group and
16
+ loop benchmarks then find it by its call site or its shape. A member that is not built says why (`why`). PostgreSQL
17
+ only: ClickHouse members are built per scenario and advisor table (scenario_bind, advisor_ch). Settings under
18
+ `[members]` in codecop.toml: build (default true), max_candidates (default 300, heaviest measured first).
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import re
24
+ from collections import Counter
25
+ from datetime import datetime, timezone
26
+
27
+ DEFAULTS = {"build": True, "max_candidates": 300}
28
+ ENGINES = ("postgres",)
29
+
30
+
31
+ def settings_of(config: dict | None) -> dict:
32
+ out = dict(DEFAULTS)
33
+ for k, v in (config or {}).items():
34
+ if k == "build" and isinstance(v, bool):
35
+ out[k] = v
36
+ elif k == "max_candidates" and isinstance(v, int) and not isinstance(v, bool) and v >= 0:
37
+ out[k] = v
38
+ return out
39
+
40
+
41
+ def wanted(groups_doc: dict | None, patterns_doc: dict | None, engine: str, loop_settings: dict | None = None) -> list[dict]:
42
+ """The members of this engine's groups and qualifying loops: [{key, site_id, hash, sql_from, located, measured, of}]."""
43
+ from . import loopbench
44
+ out: dict[str, dict] = {}
45
+ for g in (groups_doc or {}).get("groups") or []:
46
+ if (g.get("engine") or "") != engine:
47
+ continue
48
+ for m in g.get("members") or []:
49
+ key = f"h:{m['hash']}" if m.get("sql_from") == "query_log" and m.get("hash") else f"s:{(m.get('site_ids') or [None])[0]}"
50
+ out.setdefault(key, {"key": key, "site_id": (m.get("site_ids") or [None])[0], "hash": m.get("hash"), "sql_from": m.get("sql_from"),
51
+ "located": m.get("located"), "measured": m.get("measured"), "of": set()})["of"].add(g["id"])
52
+ cfg = loopbench.settings_of(loop_settings)
53
+ for p in (patterns_doc or {}).get("patterns") or []:
54
+ ok, _ = loopbench.qualify(p, cfg)
55
+ if not ok:
56
+ continue
57
+ for m in loopbench.qualifying_members(p):
58
+ if (m.get("engine") or engine) != engine:
59
+ continue
60
+ key = f"s:{m['site_id']}"
61
+ out.setdefault(key, {"key": key, "site_id": m["site_id"], "hash": None, "sql_from": "code", "located": "site",
62
+ "measured": m.get("measured"), "of": set()})["of"].add(p["id"])
63
+ return sorted(out.values(), key=lambda m: (-int((m.get("measured") or {}).get("read_bytes") or 0), m["key"]))
64
+
65
+
66
+ def _covered(rank: dict | None) -> tuple[set[str], set[str]]:
67
+ sites, hashes = set(), set()
68
+ for c in (rank or {}).get("candidates") or []:
69
+ if c.get("sql_from") != "query_log" and c.get("id") and c.get("baseline_sql"):
70
+ sites.add(str(c["id"]))
71
+ h = (c.get("observed") or {}).get("hash")
72
+ if h and c.get("baseline_sql"):
73
+ hashes.add(str(h))
74
+ for sid in (c.get("observed") or {}).get("places") or []:
75
+ sites.add(str(sid))
76
+ return sites, hashes
77
+
78
+
79
+ def code_candidate(site: dict, facts, engine: str, finding: str, dyn: dict) -> tuple[dict | None, str]:
80
+ """A member's own fixed SQL as a candidate, typed from the pulled catalog. (candidate, '') or (None, why not)."""
81
+ from . import observed as O
82
+ from .realdb import match as match_mod
83
+ sql = site.get("sql") or ""
84
+ if site.get("resolution") not in ("literal", "constant") or not sql.strip():
85
+ return None, "the statement is not fixed text in the code"
86
+ if site.get("statement") != "select" or not O.is_read(sql):
87
+ return None, "not a read: candidates are reads only"
88
+ if O.has_fragment(sql):
89
+ return None, "the statement has run-time parts"
90
+ tables = O.tables_of(sql, site.get("tables") or [], engine)
91
+ user = [t for t in tables if not O.catalog_table(t, sql)]
92
+ if not user:
93
+ return None, "it reads no table of the pulled catalog (a server call such as pg_notify, not a read)"
94
+ missing = [t for t in user if facts.definition(engine, t) is None]
95
+ if missing:
96
+ return None, f"no loadable definition for {', '.join(missing[:4])} in the pulled catalog"
97
+ columns = O._columns_of(facts, engine, user)
98
+ built = O.runnable(sql, [], columns, neutral_values=dyn["neutral_values"], engine=engine, window_hours=float(dyn["time_window_hours"]))
99
+ g = O.gate(built["sql"], sql, [])
100
+ if not g["ok"] and g["reason"] in ("value_type_open", "identifier_masked"):
101
+ return None, f"a parameter could not be typed from the catalog ({g['reason'].replace('_', ' ')})"
102
+ now = datetime.now(timezone.utc).replace(minute=0, second=0, microsecond=0)
103
+ values, notes = O.choose_values(built["params"], O.value_columns(columns, engine), finding, now=now, window_hours=float(dyn["time_window_hours"]))
104
+ return {
105
+ "finding": finding, "id": site.get("id"), "title": f"Statement of {str(site.get('file', '')).split('/')[-1]}:{site.get('line', 0)} (a group or loop member)",
106
+ "severity": "medium", "confidence": "high", "baseline_sql": built["sql"], "params": values, "tables": user, "variants": [], "causes": [],
107
+ "assumptions": ["the code's own SQL, made runnable by rule: every parameter typed from the column of the pulled catalog it is "
108
+ "compared with; values are chosen"] + built["notes"] + notes,
109
+ "origin": {"role": site.get("role") or "unknown", "kind": ((site.get("origins") or [{}])[0]).get("kind", "unknown"),
110
+ "entry_points": [{k: o.get(k) for k in ("kind", "name", "file", "line")} for o in (site.get("origins") or [])[:3]],
111
+ "path": [], "frequency": {"trigger": "unknown", "every_seconds": 0, "in_loop": bool(site.get("in_loop")),
112
+ "cache_seconds": 0, "note": ""}, "verified": False},
113
+ "site": {**{k: site.get(k) for k in ("file", "line", "symbol", "sink", "resolution", "flags", "sql_hash")},
114
+ "same_sql_sites": 1, "score": 0.0, "role": site.get("role") or "unknown", "origins": site.get("origins") or [],
115
+ "origin_count": site.get("origin_count", 0)},
116
+ "original_sql": sql, "sql_from": "code", "located": "site", "built_for": "member",
117
+ "observed": {"params": {k: {x: v[x] for x in ("type", "column", "op", "source", "clause", "time", "bound") if v.get(x) is not None}
118
+ for k, v in built["params"].items()}, "time_window_hours": float(dyn["time_window_hours"]),
119
+ "filled": built["filled"]},
120
+ }, ""
121
+
122
+
123
+ def build(inventory: dict | None, groups_doc: dict | None, patterns_doc: dict | None, rank: dict | None, facts, engine: str,
124
+ settings: dict | None = None, dynamic: dict | None = None, loop_settings: dict | None = None) -> tuple[list[dict], dict]:
125
+ """(candidates, report) for the members of groups and loops that no candidate covers. report: {wanted, covered,
126
+ built: {code, query_log}, not_built: {why: n}, over_max}."""
127
+ from . import observed as O
128
+ cfg = settings_of(settings)
129
+ dyn = O.settings_of(dynamic)
130
+ report = {"wanted": 0, "covered": 0, "built": {"code": 0, "query_log": 0}, "not_built": {}, "over_max": 0, "why_by_site": {}}
131
+ if not cfg["build"] or engine not in ENGINES or facts is None:
132
+ return [], report
133
+ sites = {s.get("id"): s for s in (inventory or {}).get("call_sites") or [] if s.get("id")}
134
+ covered_sites, covered_hashes = _covered(rank)
135
+ want = wanted(groups_doc, patterns_doc, engine, loop_settings)
136
+ report["wanted"] = len(want)
137
+ why: Counter = Counter()
138
+ out: list[dict] = []
139
+ shapes = []
140
+ for m in want:
141
+ if (m["hash"] and str(m["hash"]) in covered_hashes) or (m["sql_from"] != "query_log" and str(m["site_id"]) in covered_sites):
142
+ report["covered"] += 1
143
+ continue
144
+ if len(out) + len(shapes) >= cfg["max_candidates"]:
145
+ report["over_max"] += 1
146
+ continue
147
+ if m["sql_from"] == "query_log" and m.get("hash"):
148
+ shapes.append(str(m["hash"]))
149
+ continue
150
+ cand, reason = code_candidate(sites.get(m["site_id"]) or {}, facts, engine, f"M-{len(out) + 1:03d}", dyn)
151
+ if cand is None:
152
+ # counted by kind: a table missing from the pulled catalog is one reason whatever the table
153
+ kind = ("a table it reads is not in the pulled catalog (another database or service)" if reason.startswith("no loadable definition")
154
+ else reason)
155
+ why[kind] += 1
156
+ report["why_by_site"][str(m["site_id"])] = kind
157
+ continue
158
+ out.append(cand)
159
+ report["built"]["code"] += 1
160
+ if shapes:
161
+ got, reasons = shape_candidates(shapes, facts, engine, dyn, inventory)
162
+ out += got
163
+ report["built"]["query_log"] = len(got)
164
+ why.update(reasons)
165
+ report["not_built"] = dict(why.most_common())
166
+ return out, report
167
+
168
+
169
+ def shape_candidates(hashes: list[str], facts, engine: str, dyn: dict, inventory: dict | None) -> tuple[list[dict], Counter]:
170
+ """Statements production ran, by shape, as observed candidates (OM-001...) whatever their share of the bytes read."""
171
+ from . import observed as O
172
+ m = facts.match(engine) or {}
173
+ wanted_ = set(hashes)
174
+ sub = {**m, "queries": [q for q in m.get("queries") or [] if str(q.get("hash")) in wanted_]}
175
+ texts = {}
176
+ from .scenarios import _workload_texts
177
+ texts = _workload_texts(facts, engine)
178
+ workload = next((w for w in (facts.workload.get("connections") or {}).values() if w.get("engine") == engine), None)
179
+ sites = {c["id"]: c for c in (inventory or {}).get("call_sites") or [] if c.get("id")}
180
+ settings = {**dyn, "unlocated_candidate_min_share": 0.0, "unlocated_candidates_max": len(hashes)}
181
+ n = [0]
182
+
183
+ def label(_key: str) -> str:
184
+ n[0] += 1
185
+ return f"OM-{n[0]:03d}"
186
+ total = int((m.get("workload") or {}).get("read_bytes") or 0)
187
+ user_names = {x.rsplit(".", 1)[-1].lower() for x in facts.tables(engine)}
188
+ cands: list[dict] = []
189
+ now = datetime.now(timezone.utc).replace(minute=0, second=0, microsecond=0)
190
+ # members located nowhere are `none` or `likely` rows: the same steps as observed's unlocated candidates
191
+ for q in sub["queries"]:
192
+ q.setdefault("match", "none")
193
+ rep = O._unlocated_candidates({**sub, "queries": [dict(q, match=q.get("match") if q.get("match") in ("none", "likely") else "none")
194
+ for q in sub["queries"]]},
195
+ {}, texts, sites, facts, engine, settings, O._databases(facts.catalog), total, user_names, workload, now,
196
+ label, {}, cands)
197
+ for c in cands:
198
+ c["built_for"] = "member"
199
+ reasons = Counter({f"query_log: {k.replace('_', ' ')}": v for k, v in (rep.get("reasons") or {}).items()})
200
+ return cands, reasons