codecop 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (222) hide show
  1. codecop/__init__.py +7 -0
  2. codecop/access.py +140 -0
  3. codecop/access_postgres.py +284 -0
  4. codecop/advisor.py +1512 -0
  5. codecop/advisor_bench.py +493 -0
  6. codecop/advisor_ch.py +2080 -0
  7. codecop/advisor_view.py +381 -0
  8. codecop/advisors.py +184 -0
  9. codecop/agent.py +221 -0
  10. codecop/agentfacts.py +745 -0
  11. codecop/apply/__init__.py +327 -0
  12. codecop/apply/check.py +344 -0
  13. codecop/apply/cli.py +162 -0
  14. codecop/apply/clickhouse.py +379 -0
  15. codecop/apply/common.py +238 -0
  16. codecop/apply/html.py +264 -0
  17. codecop/apply/patch.py +213 -0
  18. codecop/apply/postgres.py +102 -0
  19. codecop/apply/trial.py +166 -0
  20. codecop/assemble.py +104 -0
  21. codecop/baseline.py +1043 -0
  22. codecop/bench.py +2464 -0
  23. codecop/blockers.py +935 -0
  24. codecop/budget.py +980 -0
  25. codecop/catalog_profile.py +525 -0
  26. codecop/changed.py +261 -0
  27. codecop/cicmd.py +1002 -0
  28. codecop/cli.py +5421 -0
  29. codecop/client.py +729 -0
  30. codecop/coverage.py +1067 -0
  31. codecop/coverage_reasons.py +116 -0
  32. codecop/crashlog.py +70 -0
  33. codecop/datagen.py +766 -0
  34. codecop/datagen_postgres.py +630 -0
  35. codecop/datagen_sqlite.py +323 -0
  36. codecop/dbcli.py +885 -0
  37. codecop/definitions.py +457 -0
  38. codecop/discover/__init__.py +702 -0
  39. codecop/discover/arms.py +160 -0
  40. codecop/discover/base.py +234 -0
  41. codecop/discover/dialect.py +296 -0
  42. codecop/discover/elixir.py +64 -0
  43. codecop/discover/engine_go.py +320 -0
  44. codecop/discover/go.py +1947 -0
  45. codecop/discover/java.py +1528 -0
  46. codecop/discover/loops.py +1671 -0
  47. codecop/discover/named_go.py +258 -0
  48. codecop/discover/origins.py +4565 -0
  49. codecop/discover/origins_ts.py +1584 -0
  50. codecop/discover/orm_django.py +2772 -0
  51. codecop/discover/orm_django_models.py +814 -0
  52. codecop/discover/orm_django_sql.py +662 -0
  53. codecop/discover/orm_ent.py +565 -0
  54. codecop/discover/orm_ex_ecto.py +2138 -0
  55. codecop/discover/orm_go.py +2134 -0
  56. codecop/discover/orm_go_bun.py +602 -0
  57. codecop/discover/orm_go_run.py +636 -0
  58. codecop/discover/orm_go_types.py +1082 -0
  59. codecop/discover/orm_java.py +1450 -0
  60. codecop/discover/orm_jdbi.py +743 -0
  61. codecop/discover/orm_jooq.py +806 -0
  62. codecop/discover/orm_jpa.py +1307 -0
  63. codecop/discover/orm_mybatis.py +730 -0
  64. codecop/discover/orm_py.py +557 -0
  65. codecop/discover/orm_py_peewee.py +1266 -0
  66. codecop/discover/orm_py_prisma.py +298 -0
  67. codecop/discover/orm_rb_activerecord.py +1906 -0
  68. codecop/discover/orm_rust.py +1248 -0
  69. codecop/discover/orm_rust_seaorm.py +734 -0
  70. codecop/discover/orm_sqlalchemy.py +2475 -0
  71. codecop/discover/orm_stats.py +307 -0
  72. codecop/discover/orm_tables.py +29 -0
  73. codecop/discover/orm_ts.py +503 -0
  74. codecop/discover/orm_ts_drizzle.py +697 -0
  75. codecop/discover/orm_ts_knex.py +1117 -0
  76. codecop/discover/orm_ts_kysely.py +861 -0
  77. codecop/discover/orm_ts_prisma.py +1045 -0
  78. codecop/discover/orm_ts_schema.py +169 -0
  79. codecop/discover/orm_ts_sequelize.py +1401 -0
  80. codecop/discover/orm_ts_typeorm.py +1067 -0
  81. codecop/discover/probes.py +323 -0
  82. codecop/discover/python.py +595 -0
  83. codecop/discover/ruby.py +793 -0
  84. codecop/discover/rust.py +2378 -0
  85. codecop/discover/schema.py +520 -0
  86. codecop/discover/schema_ent.py +145 -0
  87. codecop/discover/schema_ts.py +420 -0
  88. codecop/discover/tsresolve.py +257 -0
  89. codecop/discover/typescript.py +1728 -0
  90. codecop/discover/xml_mapper.py +526 -0
  91. codecop/engines/__init__.py +515 -0
  92. codecop/engines/base.py +498 -0
  93. codecop/engines/clickhouse.py +1558 -0
  94. codecop/engines/pg_ddl.py +444 -0
  95. codecop/engines/pg_hints.py +137 -0
  96. codecop/engines/postgres.py +1060 -0
  97. codecop/engines/sqlite.py +742 -0
  98. codecop/families/__init__.py +3 -0
  99. codecop/families/build.py +280 -0
  100. codecop/families/cli.py +177 -0
  101. codecop/families/coverage_hook.py +62 -0
  102. codecop/families/driver.py +221 -0
  103. codecop/families/goslice.py +229 -0
  104. codecop/families/goslice_tool/go.mod +3 -0
  105. codecop/families/goslice_tool/main.go +403 -0
  106. codecop/families/holes.py +451 -0
  107. codecop/families/images/Dockerfile.go +5 -0
  108. codecop/families/images/Dockerfile.python +4 -0
  109. codecop/families/images/Dockerfile.rust +4 -0
  110. codecop/families/isolate.py +171 -0
  111. codecop/families/locate.py +270 -0
  112. codecop/families/model.py +301 -0
  113. codecop/families/plangate.py +271 -0
  114. codecop/families/tagpatch.py +174 -0
  115. codecop/fidelity.py +671 -0
  116. codecop/fixgroups.py +130 -0
  117. codecop/formerly.py +91 -0
  118. codecop/grantscript.py +254 -0
  119. codecop/groupbench.py +1375 -0
  120. codecop/groups.py +594 -0
  121. codecop/groups_view.py +186 -0
  122. codecop/heat.py +1405 -0
  123. codecop/heatcli.py +219 -0
  124. codecop/joins.py +1749 -0
  125. codecop/joins_view.py +127 -0
  126. codecop/kinds/__init__.py +507 -0
  127. codecop/kinds/calls/__init__.py +501 -0
  128. codecop/kinds/calls/extract.py +1097 -0
  129. codecop/kinds/calls/harness.py +408 -0
  130. codecop/kinds/calls/measure.py +342 -0
  131. codecop/kinds/calls/rules.py +139 -0
  132. codecop/kinds/calls/runners/RunCalls.java +167 -0
  133. codecop/kinds/calls/runners/run_go.go +141 -0
  134. codecop/kinds/calls/runners/run_node.js +186 -0
  135. codecop/kinds/calls/runners/run_python.py +319 -0
  136. codecop/kinds/calls/runners/run_rust.rs +200 -0
  137. codecop/kinds/calls/standin.py +340 -0
  138. codecop/kinds/pipeline.py +288 -0
  139. codecop/kinds/regex/__init__.py +1167 -0
  140. codecop/kinds/regex/engines/RegexHarness.java +129 -0
  141. codecop/kinds/regex/engines/run_go.go +294 -0
  142. codecop/kinds/regex/engines/run_node.js +99 -0
  143. codecop/kinds/regex/engines/run_python.py +295 -0
  144. codecop/kinds/regex/engines/run_rust.rs +149 -0
  145. codecop/kinds/regex/extract.py +1438 -0
  146. codecop/kinds/regex/harness.py +235 -0
  147. codecop/kinds/regex/measure.py +270 -0
  148. codecop/kinds/regex/shapes.py +418 -0
  149. codecop/kinds/regex/syntax.py +1721 -0
  150. codecop/kinds/testkind.py +107 -0
  151. codecop/kinds/transaction/__init__.py +228 -0
  152. codecop/kinds/transaction/bind.py +355 -0
  153. codecop/kinds/transaction/measure.py +264 -0
  154. codecop/kinds/transaction/plan.py +462 -0
  155. codecop/kinds/transaction/rules.py +540 -0
  156. codecop/kinds/transaction/sandbox.py +94 -0
  157. codecop/kinds/transaction/scenarios.py +520 -0
  158. codecop/kinds/transaction/schedule.py +483 -0
  159. codecop/kinds/transaction/shapes.py +418 -0
  160. codecop/kinds/transaction/verify.py +293 -0
  161. codecop/live.py +237 -0
  162. codecop/loopbench.py +2071 -0
  163. codecop/loopschema.py +591 -0
  164. codecop/mcpserver.py +120 -0
  165. codecop/mechanism.py +214 -0
  166. codecop/members.py +200 -0
  167. codecop/multi.py +443 -0
  168. codecop/observed.py +1868 -0
  169. codecop/parts.py +102 -0
  170. codecop/patterns.py +830 -0
  171. codecop/patterns_view.py +559 -0
  172. codecop/plangate.py +242 -0
  173. codecop/profile.py +439 -0
  174. codecop/prompts/areas.md +19 -0
  175. codecop/prompts/observed_variants.md +20 -0
  176. codecop/prompts/profile.md +60 -0
  177. codecop/prompts/profile_postgres.md +68 -0
  178. codecop/prompts/profile_sizes.md +26 -0
  179. codecop/prompts/profile_sqlite.md +69 -0
  180. codecop/prompts/rank.md +84 -0
  181. codecop/prompts/rank_postgres.md +96 -0
  182. codecop/prompts/rank_sqlite.md +94 -0
  183. codecop/prompts/scenario_variants.md +20 -0
  184. codecop/rank.py +1473 -0
  185. codecop/realdb/__init__.py +688 -0
  186. codecop/realdb/clickhouse.py +1223 -0
  187. codecop/realdb/facts.py +815 -0
  188. codecop/realdb/locality.py +964 -0
  189. codecop/realdb/locks.py +355 -0
  190. codecop/realdb/match.py +531 -0
  191. codecop/realdb/postgres.py +643 -0
  192. codecop/realdb/ratios.py +77 -0
  193. codecop/realdb/sample.py +126 -0
  194. codecop/relations.py +227 -0
  195. codecop/report.py +1854 -0
  196. codecop/resources.py +332 -0
  197. codecop/resources_view.py +266 -0
  198. codecop/rules/entry_points.toml +1013 -0
  199. codecop/rules/sinks.toml +362 -0
  200. codecop/runsonce.py +8 -0
  201. codecop/sandboxschema.py +555 -0
  202. codecop/scenario_agent.py +172 -0
  203. codecop/scenario_bind.py +507 -0
  204. codecop/scenario_sql.py +971 -0
  205. codecop/scenarios.py +675 -0
  206. codecop/scenarios_view.py +274 -0
  207. codecop/schemacli.py +67 -0
  208. codecop/schemas/areas_output.schema.json +21 -0
  209. codecop/schemas/profile_output.schema.json +362 -0
  210. codecop/schemas/rank_output.schema.json +385 -0
  211. codecop/sizes.py +200 -0
  212. codecop/sqlinfo.py +558 -0
  213. codecop/typedparams.py +576 -0
  214. codecop/verdicts.py +212 -0
  215. codecop/writebench.py +720 -0
  216. codecop/writecost.py +440 -0
  217. codecop/writes.py +1208 -0
  218. codecop-0.1.0.dist-info/METADATA +42 -0
  219. codecop-0.1.0.dist-info/RECORD +222 -0
  220. codecop-0.1.0.dist-info/WHEEL +4 -0
  221. codecop-0.1.0.dist-info/entry_points.txt +2 -0
  222. codecop-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,498 @@
1
+ """What every sandbox adapter shares: errors, the container runtime, and the measurement record.
2
+
3
+ A sandbox is one throwaway server in a container. bench.py drives it through the
4
+ same few methods whatever the engine:
5
+
6
+ create_table(definition) drop and rebuild one table from the agent's definition; returns notes on what was stripped
7
+ column_types(name) column name -> type, as the server reports it
8
+ insert_statements(...) set-based INSERTs that generate the profiled data
9
+ finish_table(definition) whatever must follow a load (Postgres: the remaining indexes, VACUUM ANALYZE)
10
+ plan_parts, load, add_versions optional (ClickHouse): the physical state of a loaded table, see engines/clickhouse.py.
11
+ bench.py calls them when the adapter has them.
12
+ realism which parts of data realism are on (datagen.REALISM); bench.run sets it
13
+ table_stats(name) rows and bytes on disk
14
+ free_bytes() disk left for data
15
+ apply_setup(statements) run a variant's setup
16
+ undo_setup(statements) remove what the setup created
17
+ storage_bytes(tables, setup) bytes used by the tables plus what the setup created
18
+ measure(sql, params, runs) run a SELECT and return a Measurement
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import re
24
+ import shutil
25
+ import subprocess
26
+ from dataclasses import dataclass, field
27
+
28
+
29
+ class SandboxError(RuntimeError):
30
+ pass
31
+
32
+
33
+ class QueryError(SandboxError):
34
+ """The server rejected a statement. Carries the server's own message."""
35
+
36
+
37
+ def find_runtime() -> str:
38
+ """docker first, then podman: the first one whose daemon answers."""
39
+ for name in ("docker", "podman"):
40
+ if shutil.which(name) and subprocess.run([name, "info"], capture_output=True).returncode == 0:
41
+ return name
42
+ raise SandboxError("No container runtime is running. Install and start Docker or Podman.")
43
+
44
+
45
+ QUOTED = re.compile(r"'(?:[^']|'')*'|\"(?:[^\"]|\"\")*\"|`[^`]*`|\$(\w*)\$.*?\$\1\$|--[^\n]*|/\*.*?\*/", re.S)
46
+
47
+
48
+ QUOTED_OR_PARAM = re.compile(QUOTED.pattern + r"|\{\w+(?::[^{}]+)?\}", re.S)
49
+
50
+
51
+ def outside_quotes(sql: str, change) -> str:
52
+ """Apply `change(text) -> text` to the parts of a statement that are not inside a string, a quoted name or a comment."""
53
+ out, pos = [], 0
54
+ for m in QUOTED.finditer(sql):
55
+ out.append(change(sql[pos:m.start()]))
56
+ out.append(m.group(0))
57
+ pos = m.end()
58
+ out.append(change(sql[pos:]))
59
+ return "".join(out)
60
+
61
+
62
+ def split_limit(sql: str) -> dict | None:
63
+ """The statement without its outermost ORDER BY ... LIMIT / OFFSET / FETCH FIRST, for comparing results.
64
+
65
+ Returns {sql, order_by, has_order} or None when the statement has no outermost LIMIT (a LIMIT inside a
66
+ subquery or a CTE is part of what the query computes and is left alone; so is ClickHouse's LIMIT n BY).
67
+ `order_by` is the text of the removed ORDER BY, spaces normalised."""
68
+ text = sql.rstrip().rstrip(";")
69
+ marks: list[tuple[int, str]] = []
70
+ depth, pos = 0, 0
71
+ word = re.compile(r"\b(ORDER\s+BY|LIMIT|OFFSET|FETCH\s+(?:FIRST|NEXT)|SETTINGS|FORMAT|BY|UNION|INTERSECT|EXCEPT)\b", re.I)
72
+
73
+ def scan(piece: str, base: int) -> None:
74
+ nonlocal depth
75
+ last = 0
76
+ for m in re.finditer(r"[()]", piece):
77
+ if depth == 0:
78
+ marks.extend((base + last + w.start(), re.sub(r"\s+", " ", w.group(1).upper())) for w in word.finditer(piece[last:m.start()]))
79
+ depth += 1 if m.group(0) == "(" else -1
80
+ last = m.end()
81
+ if depth == 0:
82
+ marks.extend((base + last + w.start(), re.sub(r"\s+", " ", w.group(1).upper())) for w in word.finditer(piece[last:]))
83
+
84
+ for m in QUOTED_OR_PARAM.finditer(text): # a parameter may be called {limit:int}
85
+ scan(text[pos:m.start()], pos)
86
+ pos = m.end()
87
+ scan(text[pos:], pos)
88
+ marks.sort()
89
+ limits = []
90
+ for i, (at, kind) in enumerate(marks):
91
+ if kind == "LIMIT" or kind.startswith("FETCH"):
92
+ following = marks[i + 1][1] if i + 1 < len(marks) else ""
93
+ if kind == "LIMIT" and following == "BY":
94
+ continue # LIMIT n BY columns: a deduplication, not a cut of the result
95
+ limits.append(at)
96
+ if not limits:
97
+ return None
98
+ cut = limits[-1]
99
+ # a set operation after the LIMIT means the LIMIT belongs to one branch, not to the whole result
100
+ if any(kind in ("UNION", "INTERSECT", "EXCEPT") and at > cut for at, kind in marks):
101
+ return None
102
+ order = [at for at, kind in marks if kind == "ORDER BY" and at < cut]
103
+ offsets = [at for at, kind in marks if kind == "OFFSET" and at < cut and (not order or at > order[-1])]
104
+ start = order[-1] if order else (offsets[0] if offsets else cut)
105
+ tail = next((at for at, kind in marks if kind in ("SETTINGS", "FORMAT") and at > cut), len(text))
106
+ order_text = ""
107
+ if order:
108
+ end = min([at for at in offsets + [cut] if at > order[-1]])
109
+ order_text = " ".join(text[order[-1]:end].split()).lower()
110
+ return {"sql": (text[:start].rstrip() + " " + text[tail:]).strip(), "order_by": order_text, "has_order": bool(order)}
111
+
112
+
113
+ def image_ready(image: str, runtime: str | None = None, pull: bool = True, log=lambda msg: None) -> tuple[bool, str]:
114
+ """Is the sandbox image there to start a container from? (True, "local" | "pulled") or (False, why).
115
+
116
+ A scan asks this before any paid stage, so a version nobody can pull stops the run before the agent is paid."""
117
+ rt = runtime or find_runtime()
118
+ if subprocess.run([rt, "image", "inspect", image], capture_output=True).returncode == 0:
119
+ return True, "local"
120
+ if not pull:
121
+ return False, "not pulled"
122
+ log(f"pulling {image}")
123
+ proc = subprocess.run([rt, "pull", "-q", image], capture_output=True, text=True)
124
+ if proc.returncode == 0:
125
+ return True, "pulled"
126
+ lines = [x for x in (proc.stderr or proc.stdout).strip().splitlines() if x.strip()]
127
+ return False, (lines[-1][:200] if lines else "pull failed")
128
+
129
+
130
+ @dataclass
131
+ class Measurement:
132
+ """What one query read. `read_rows` and `read_bytes` are the evidence on every engine.
133
+
134
+ ClickHouse: rows and uncompressed bytes read, from system.query_log.
135
+ Postgres: rows the scan nodes fetched (returned plus removed by filters), and shared
136
+ buffers touched (hit + read) x 8 kB, from EXPLAIN (ANALYZE, BUFFERS)."""
137
+ ok: bool
138
+ error: str = ""
139
+ read_rows: int = 0
140
+ read_bytes: int = 0
141
+ result_rows: int = 0
142
+ memory_bytes: int = 0
143
+ duration_ms: float = 0.0 # best of the timed runs, server-side
144
+ selected_parts: int = 0
145
+ selected_marks: int = 0
146
+ total_marks: int = 0
147
+ result_hash: str = "" # order-insensitive hash of the result rows
148
+ explain: str = ""
149
+ runs: list[float] = field(default_factory=list)
150
+ projections: list[str] = field(default_factory=list) # ClickHouse: the projections the server read (system.query_log)
151
+ # The resource profile of the run (all optional: None where the engine or this run does not count it). CPU is the
152
+ # median of the timed runs, user + system (getrusage; ClickHouse ProfileEvents, PostgreSQL log_statement_stats);
153
+ # SQLite has no CPU time, its CPU work is `vm_steps` (cpu_kind vm_steps, cpu_ms None).
154
+ cpu_ms: float | None = None
155
+ cpu_user_ms: float | None = None
156
+ cpu_system_ms: float | None = None
157
+ cpu_kind: str = "" # rusage | vm_steps | "" (not counted)
158
+ io_wait_ms: float | None = None # ClickHouse OSIOWaitMicroseconds when the kernel counts it (a warm sandbox: about 0)
159
+ threads: int | None = None # ClickHouse: threads the run used (peak at once where the server says, else ever used)
160
+ threads_setting: int | None = None # max_threads the run was given ([bench] resource_threads or production's)
161
+ result_bytes: int | None = None # bytes of the result as the server counted them; None where it does not
162
+ spill_bytes: int | None = None # sort or aggregation written to disk (ClickHouse External*; PostgreSQL temp blocks x block size)
163
+ memory_kind: str = "" # tracker (ClickHouse) | plan_nodes (PostgreSQL sort and hash memory) | highwater (SQLite)
164
+ runs_detail: dict | None = None # {cpu_ms[], memory_bytes[], duration_ms[]} of the timed runs
165
+ noisy: bool | None = None # other containers ran beside the sandbox: CPU and time are not the sandbox's own
166
+
167
+ def to_dict(self) -> dict:
168
+ return dict(self.__dict__)
169
+
170
+
171
+ def median(values: list[float]) -> float | None:
172
+ got = sorted(float(v) for v in values if v is not None)
173
+ if not got:
174
+ return None
175
+ mid = len(got) // 2
176
+ return got[mid] if len(got) % 2 else (got[mid - 1] + got[mid]) / 2
177
+
178
+
179
+ def fill_resources(m: Measurement, samples: list[dict], cpu_kind: str, memory_kind: str) -> None:
180
+ """Put the resource profile of the timed runs on a measurement: CPU and the OS counters as the median of the runs,
181
+ threads and spill as the most of any run, and every run's CPU, memory and time in `runs_detail`. `samples` are
182
+ the engines' per-run dicts (cpu_ms, cpu_user_ms, cpu_system_ms, memory_bytes, duration_ms, threads, spill_bytes,
183
+ result_bytes, io_wait_ms; a key that is absent or None is not counted)."""
184
+ samples = [s for s in samples if s]
185
+ if not samples:
186
+ return
187
+ m.cpu_kind, m.memory_kind = cpu_kind if any(s.get("cpu_ms") is not None for s in samples) else "", memory_kind
188
+ for key in ("cpu_ms", "cpu_user_ms", "cpu_system_ms", "io_wait_ms"):
189
+ value = median([s.get(key) for s in samples])
190
+ setattr(m, key, round(value, 3) if value is not None else None)
191
+ threads = [s["threads"] for s in samples if s.get("threads")]
192
+ m.threads = max(threads) if threads else None
193
+ spill = [s["spill_bytes"] for s in samples if s.get("spill_bytes") is not None]
194
+ m.spill_bytes = max(spill) if spill else None
195
+ result = [s["result_bytes"] for s in samples if s.get("result_bytes") is not None]
196
+ m.result_bytes = int(median(result)) if result else None
197
+ m.runs_detail = {k: [s.get(k) for s in samples] for k in ("cpu_ms", "memory_bytes", "duration_ms")}
198
+
199
+
200
+ # ---- a sandbox's container and its data volume ----------------------------------------------------------------------
201
+ # A server image declares its data directory a VOLUME: run without a volume of its own, the container gets an anonymous
202
+ # one, and a container removed without -v, or never removed (the process killed: SIGTERM, Ctrl-C in the wrong place,
203
+ # a crash), leaves it behind. A few of those can fill a disk ("No space left on device"). So each sandbox
204
+ # gets a named volume carrying CodeCop's labels, removed with the container, and a run first removes the containers and
205
+ # volumes of CodeCop sandboxes whose process is gone. Only what carries these labels is ever removed.
206
+ SANDBOX_LABEL = "codecop.sandbox=1"
207
+ OWNER_LABEL = "codecop.owner_pid"
208
+ CONTAINER_LABEL = "codecop.container"
209
+
210
+
211
+ SANDBOX_NETWORK_ENV = "CODECOP_SANDBOX_NETWORK"
212
+
213
+
214
+ def sandbox_network() -> str:
215
+ """The network a hosted job's sandbox joins (CODECOP_SANDBOX_NETWORK), or "" to publish a port on 127.0.0.1 as
216
+ usual. In a hosted job the CLI runs in a container on that network and reaches the sandbox by its container name;
217
+ nothing is published on the host."""
218
+ import os
219
+ return os.environ.get(SANDBOX_NETWORK_ENV, "").strip()
220
+
221
+
222
+ def publish_args(container_port: int, host_port: int = 0) -> list[str]:
223
+ """`run` arguments that make the sandbox reachable: --network <name> in a hosted job, else a port on 127.0.0.1."""
224
+ net = sandbox_network()
225
+ if net:
226
+ return ["--network", net]
227
+ return ["-p", f"127.0.0.1:{host_port or ''}:{container_port}"]
228
+
229
+
230
+ def volume_name(container: str) -> str:
231
+ return f"{container}-data"
232
+
233
+
234
+ def image_volumes(runtime: str, image: str, default: str) -> list[str]:
235
+ """The data directories the image declares as volumes (each would get an anonymous volume); [default] when unknown."""
236
+ import json as _json
237
+ text = subprocess.run([runtime, "image", "inspect", "--format", "{{json .Config.Volumes}}", image], capture_output=True, text=True).stdout.strip()
238
+ try:
239
+ found = sorted((_json.loads(text) or {}).keys()) if text and text != "null" else []
240
+ except ValueError:
241
+ found = []
242
+ return found or [default]
243
+
244
+
245
+ class Activity:
246
+ """Seconds the sandbox's statements took, by what they do (bench.json `timing.statements`): the client's wall time
247
+ of each statement, summed. Statements that ran side by side (partitions cut by worker threads) are each counted,
248
+ so a kind's seconds can exceed the wall time it spanned; `wall_s` is the union of its statements' intervals."""
249
+
250
+ def __init__(self):
251
+ import threading
252
+ self.lock = threading.Lock()
253
+ self.s: dict[str, float] = {}
254
+ self.n: dict[str, int] = {}
255
+ self.spans: dict[str, list[list[float]]] = {}
256
+
257
+ def add(self, kind: str, began: float, ended: float) -> None:
258
+ with self.lock:
259
+ self.s[kind] = self.s.get(kind, 0.0) + max(ended - began, 0.0)
260
+ self.n[kind] = self.n.get(kind, 0) + 1
261
+ spans = self.spans.setdefault(kind, [])
262
+ if spans and began <= spans[-1][1]:
263
+ spans[-1][1] = max(spans[-1][1], ended)
264
+ else:
265
+ spans.append([began, ended])
266
+
267
+ def record(self) -> dict:
268
+ with self.lock:
269
+ return {k: {"s": round(v, 1), "n": self.n.get(k, 0), "wall_s": round(sum(b - a for a, b in self.spans.get(k, [])), 1)}
270
+ for k, v in sorted(self.s.items(), key=lambda kv: -kv[1])}
271
+
272
+
273
+ def statement_kind(sql: str) -> str:
274
+ """What a sandbox statement does, for Activity: load.generate (rows made from numbers), load.copy (rows copied between
275
+ tables: the cuts, staging, variant copies), load.merge (OPTIMIZE), load.parts (partitions attached, dropped, moved),
276
+ load.vacuum (VACUUM, ANALYZE, CHECKPOINT), build (indexes, projections, materialisations: the variants' and the
277
+ definitions'), ddl (the rest of CREATE, DROP, ALTER), measure (SELECT, EXPLAIN, WITH), system (SYSTEM, SET, SHOW)."""
278
+ head = re.sub(r"^(?:\s|--[^\n]*\n|/\*.*?\*/|SET\s[^;]*;|\\\w+[^\n]*\n)*", "", sql[:4000], flags=re.S | re.I)
279
+ up = head[:400].upper()
280
+ first = (re.match(r"\(|[A-Z_]+", up) or [""])[0]
281
+ if first == "INSERT":
282
+ if re.search(r"\bFROM\s+(?:NUMBERS(?:_MT)?\s*\(|GENERATE_SERIES\s*\(|GENERATERANDOM\s*\()|\bcodecop_n AS number\b", sql[:200000], re.I):
283
+ return "load.generate"
284
+ return "load.copy"
285
+ if first == "OPTIMIZE":
286
+ return "load.merge"
287
+ if first in ("VACUUM", "ANALYZE", "CHECKPOINT", "CLUSTER", "REINDEX"):
288
+ return "load.vacuum"
289
+ if first == "ALTER":
290
+ if re.search(r"\b(?:ATTACH|DETACH|DROP|MOVE|REPLACE)\s+PARTITION\b", up):
291
+ return "load.parts"
292
+ if re.search(r"\b(?:MATERIALIZE|ADD\s+INDEX|ADD\s+PROJECTION|CLEAR\s+(?:INDEX|PROJECTION))\b", up):
293
+ return "build"
294
+ return "ddl"
295
+ if first == "CREATE":
296
+ if re.search(r"^CREATE\s+(?:UNIQUE\s+)?INDEX\b", up):
297
+ return "build"
298
+ if re.search(r"\bAS\s+SELECT\b", up):
299
+ return "load.copy"
300
+ return "ddl"
301
+ if first in ("DROP", "TRUNCATE", "RENAME", "COMMENT", "DETACH", "ATTACH"):
302
+ return "ddl"
303
+ if first in ("SELECT", "EXPLAIN", "WITH", "(", "VALUES", "TABLE", "BEGIN", "DO"):
304
+ return "measure"
305
+ return "system"
306
+
307
+
308
+ # What one sandbox container may use (`[bench] sandbox_cpus`, `sandbox_memory`; or CODECOP_SANDBOX_CPUS / CODECOP_SANDBOX_MEMORY).
309
+ # Empty: no cap, as before. On a shared host a cap keeps the sandbox from taking every core; the servers read their cgroup
310
+ # (ClickHouse sizes its pools and its memory limit from it), so a capped run is slower, never different in what it measures.
311
+ #
312
+ # Disk writes, not CPU, are what a ClickHouse load costs a shared host: loads writing at full speed leave the host
313
+ # waiting on I/O. So the sandbox also gets an I/O share by default: a low block-I/O weight (`sandbox_blkio_weight`,
314
+ # default 100 of 10..1000; it only acts where the kernel's I/O scheduler supports weights), and only on explicit request a
315
+ # write-rate cap on one device (`sandbox_write_bps`, e.g. "/dev/sdb:60mb"; never a default: on some block devices a
316
+ # throttle stalls writeback for the whole disk and can wedge the Docker daemon; the real lever is writing fewer bytes).
317
+ # The CPU cap defaults to half the host's cores (at least 2): a sandbox never takes the whole machine. "none" turns a cap off. A runtime that refuses a cap starts the sandbox
318
+ # without it (start_container) and says so.
319
+ LIMITS: dict = {"cpus": "", "memory": "", "blkio_weight": "", "write_bps": ""}
320
+ DEFAULT_BLKIO_WEIGHT = "100"
321
+
322
+
323
+ def set_limits(cpus=None, memory=None, blkio_weight=None, write_bps=None) -> None:
324
+ """The caps of the sandboxes started from now on (see LIMITS)."""
325
+ for k, v in (("cpus", cpus), ("memory", memory), ("blkio_weight", blkio_weight), ("write_bps", write_bps)):
326
+ if v is not None:
327
+ LIMITS[k] = str(v).strip()
328
+
329
+
330
+ def _default_cpus() -> str:
331
+ import os
332
+ n = os.cpu_count() or 2
333
+ return str(max(n // 2, 2)) if n > 2 else ""
334
+
335
+
336
+ def limit_args() -> list[str]:
337
+ """`--cpus N --memory M --blkio-weight W --device-write-bps D:R` for the sandbox's `run`, from LIMITS, else the
338
+ environment (CODECOP_SANDBOX_CPUS, CODECOP_SANDBOX_MEMORY, CODECOP_SANDBOX_BLKIO_WEIGHT, CODECOP_SANDBOX_WRITE_BPS), else the
339
+ defaults (half the cores, I/O weight 100)."""
340
+ import os
341
+
342
+ def pick(key: str, env: str, default: str) -> str:
343
+ return LIMITS.get(key) or os.environ.get(env, "").strip() or default
344
+ cpus = pick("cpus", "CODECOP_SANDBOX_CPUS", _default_cpus())
345
+ memory = pick("memory", "CODECOP_SANDBOX_MEMORY", "")
346
+ weight = pick("blkio_weight", "CODECOP_SANDBOX_BLKIO_WEIGHT", DEFAULT_BLKIO_WEIGHT)
347
+ write = pick("write_bps", "CODECOP_SANDBOX_WRITE_BPS", "")
348
+ out = []
349
+ if cpus and cpus not in ("0", "none"):
350
+ out += ["--cpus", cpus]
351
+ if memory and memory not in ("0", "none"):
352
+ out += ["--memory", memory]
353
+ if weight and weight not in ("0", "none"):
354
+ out += ["--blkio-weight", weight]
355
+ if write and write not in ("0", "none"):
356
+ out += ["--device-write-bps", write]
357
+ return out
358
+
359
+
360
+ IO_FLAGS = ("--blkio-weight", "--device-write-bps")
361
+
362
+
363
+ def start_container(cmd: list[str], log=None) -> subprocess.CompletedProcess:
364
+ """`<runtime> run ...` with the caps; when the runtime refuses an I/O cap (no weight support in the kernel's
365
+ scheduler, no such device, podman on a laptop), once more without the I/O caps. CPU and memory caps stay."""
366
+ proc = subprocess.run(cmd, capture_output=True, text=True)
367
+ if proc.returncode == 0 or not any(f in cmd for f in IO_FLAGS):
368
+ return proc
369
+ bare, skip = [], False
370
+ for x in cmd:
371
+ if skip:
372
+ skip = False
373
+ continue
374
+ if x in IO_FLAGS:
375
+ skip = True
376
+ continue
377
+ bare.append(x)
378
+ name = bare[bare.index("--name") + 1] if "--name" in bare else None
379
+ if name:
380
+ subprocess.run([cmd[0], "rm", "-f", name], capture_output=True)
381
+ again = subprocess.run(bare, capture_output=True, text=True)
382
+ if again.returncode == 0 and log:
383
+ log(f"the container runtime refused the sandbox's I/O cap ({proc.stderr.strip()[:160]}); started without it")
384
+ return again
385
+
386
+
387
+ def sandbox_run_args(runtime: str, name: str, data_dir: str, image: str | None = None) -> list[str]:
388
+ """`run` arguments that label the container with its owner and give it a labelled data volume (created here) on the
389
+ image's data directory (the first volume it declares; any other gets an anonymous one, which `rm -v` removes), and
390
+ the caps of LIMITS."""
391
+ import os
392
+ if image:
393
+ data_dir = image_volumes(runtime, image, data_dir)[0]
394
+ vol = volume_name(name)
395
+ subprocess.run([runtime, "volume", "create", "--label", SANDBOX_LABEL, "--label", f"{CONTAINER_LABEL}={name}",
396
+ "--label", f"{OWNER_LABEL}={os.getpid()}", vol], capture_output=True)
397
+ return ["--label", SANDBOX_LABEL, "--label", f"{OWNER_LABEL}={os.getpid()}", "-v", f"{vol}:{data_dir}", *limit_args()]
398
+
399
+
400
+ REMOVE_TIMEOUT_S = 120 # a removal the runtime does not finish in this long is left behind (it is retried next start)
401
+
402
+
403
+ def remove_sandbox(runtime: str, name: str, timeout_s: float = REMOVE_TIMEOUT_S) -> bool:
404
+ """The container, its anonymous volumes and its data volume. False when the runtime did not finish within
405
+ `timeout_s`: under heavy I/O wait a `docker rm -f` of a sandbox that wrote a lot can hang for many minutes, and the
406
+ next run's start (reap_orphans) must not wait on it."""
407
+ try:
408
+ subprocess.run([runtime, "rm", "-f", "-v", name], capture_output=True, timeout=timeout_s)
409
+ subprocess.run([runtime, "volume", "rm", "-f", volume_name(name)], capture_output=True, timeout=timeout_s)
410
+ return True
411
+ except subprocess.TimeoutExpired:
412
+ return False
413
+
414
+
415
+ def _alive(pid: int) -> bool:
416
+ import os
417
+ try:
418
+ os.kill(pid, 0)
419
+ except ProcessLookupError:
420
+ return False
421
+ except PermissionError:
422
+ return True
423
+ return True
424
+
425
+
426
+ def reap_orphans(runtime: str) -> dict:
427
+ """Remove the CodeCop sandboxes whose owning process is gone (a killed run) and CodeCop's data volumes no container uses.
428
+ A container or volume without CodeCop's owner label (an older sandbox, a developer's container, anything else) is
429
+ never touched. Returns {containers, volumes} removed."""
430
+ out = {"containers": 0, "volumes": 0}
431
+ ps = subprocess.run([runtime, "ps", "-a", "--filter", f"label={SANDBOX_LABEL}", "--format", "{{.Names}}\t{{.Labels}}"],
432
+ capture_output=True, text=True).stdout
433
+ names = set()
434
+ for line in ps.splitlines():
435
+ name, _, labels = line.partition("\t")
436
+ names.add(name.strip())
437
+ m = re.search(rf"{re.escape(OWNER_LABEL)}[=:](\d+)", labels)
438
+ if m and not _alive(int(m.group(1))):
439
+ if remove_sandbox(runtime, name.strip()):
440
+ names.discard(name.strip())
441
+ out["containers"] += 1
442
+ else:
443
+ out["stuck"] = out.get("stuck", 0) + 1 # the runtime did not remove it in time: left, retried next start
444
+ vols = subprocess.run([runtime, "volume", "ls", "--filter", f"label={SANDBOX_LABEL}", "--format", "{{.Name}}"],
445
+ capture_output=True, text=True).stdout.split()
446
+ for vol in vols:
447
+ if vol.endswith("-data") and vol[:-5] not in names:
448
+ info = subprocess.run([runtime, "volume", "inspect", "--format", "{{json .Labels}}", vol], capture_output=True, text=True).stdout
449
+ if OWNER_LABEL in info:
450
+ subprocess.run([runtime, "volume", "rm", "-f", vol], capture_output=True)
451
+ out["volumes"] += 1
452
+ return out
453
+
454
+
455
+ def dangling_volumes(runtime: str) -> int:
456
+ """Volumes no container uses (CodeCop's or anyone's): counted for the disk message, never removed here."""
457
+ out = subprocess.run([runtime, "volume", "ls", "--filter", "dangling=true", "--format", "{{.Name}}"], capture_output=True, text=True).stdout
458
+ return len(out.split())
459
+
460
+
461
+ class StopOnSignal:
462
+ """While a sandbox is open: SIGTERM (and SIGHUP) end the run like Ctrl-C does, so the `with` block removes the
463
+ container and its volume instead of the process dying with them left behind. Main thread only; restored on close."""
464
+
465
+ def __init__(self):
466
+ self.saved: dict = {}
467
+
468
+ def __enter__(self):
469
+ import signal
470
+ import threading
471
+ if threading.current_thread() is not threading.main_thread():
472
+ return self
473
+
474
+ def stop(signum, frame):
475
+ raise KeyboardInterrupt(f"signal {signum}")
476
+ for sig in (signal.SIGTERM, getattr(signal, "SIGHUP", None)):
477
+ if sig is not None:
478
+ try:
479
+ self.saved[sig] = signal.signal(sig, stop)
480
+ except (ValueError, OSError):
481
+ pass
482
+ return self
483
+
484
+ def __exit__(self, *exc):
485
+ import signal
486
+ for sig, handler in self.saved.items():
487
+ try:
488
+ signal.signal(sig, handler)
489
+ except (ValueError, OSError):
490
+ pass
491
+ self.saved = {}
492
+
493
+
494
+ def list_sandboxes(runtime: str | None = None) -> list[str]:
495
+ rt = runtime or find_runtime()
496
+ out = subprocess.run([rt, "ps", "-a", "--filter", "label=codecop.sandbox=1", "--format", "{{.Names}}"],
497
+ capture_output=True, text=True).stdout
498
+ return [n for n in out.split() if n]