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,408 @@
1
+ """The runtimes a call shape is replayed on: CPython (with the HTTP library the repository names), Node and Go. Each
2
+ harness is a small program of CodeCop's own (`runners/`) run in a child process with a hard timeout; it gets one JSON
3
+ request and answers one JSON line. Nothing of the repository is run.
4
+
5
+ - Python: the interpreter in `[kinds.calls] python`, else CodeCop's own. A library the interpreter lacks (requests, httpx,
6
+ aiohttp, redis) is installed once into a venv in CodeCop's cache when `provision` is on (the default), at the version
7
+ the repository pins when it pins one; otherwise the library is "not available" and its sites are "could not be
8
+ judged: runtime not available".
9
+ - Node: `node` on PATH (built-in modules only).
10
+ - Go: the local toolchain builds `run_go.go` once into the cache (standard library only, offline).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import hashlib
16
+ import json
17
+ import os
18
+ import re
19
+ import shutil
20
+ import subprocess
21
+ import sys
22
+ import threading
23
+ import time
24
+ from pathlib import Path
25
+
26
+ from .standin import cache_dir
27
+
28
+ HERE = Path(__file__).parent / "runners"
29
+ HARNESS_VERSION = "1"
30
+ PY_LIBS = ("requests", "httpx", "aiohttp", "redis", "boto3")
31
+ NODE_PKGS = ("axios", "ioredis")
32
+
33
+
34
+ class Unavailable(RuntimeError):
35
+ """The runtime or library is not on this machine."""
36
+
37
+
38
+ def pinned_versions(root: Path) -> dict[str, str]:
39
+ """The versions the repository pins for the replayed libraries ({name: version}), from requirements files, uv.lock,
40
+ poetry.lock or pyproject.toml. Exact pins only."""
41
+ out: dict[str, str] = {}
42
+ names = "|".join(PY_LIBS)
43
+ root = Path(root)
44
+ cands = [p for pat in ("requirements*.txt", "*/requirements*.txt", "pyproject.toml", "*/pyproject.toml") for p in root.glob(pat)]
45
+ for p in cands[:40]:
46
+ try:
47
+ text = p.read_text(errors="replace")
48
+ except OSError:
49
+ continue
50
+ for m in re.finditer(rf"(?im)^\s*[\"']?({names})(?:\[[^\]]*\])?\s*==\s*([0-9][0-9A-Za-z.\-]*)", text):
51
+ out.setdefault(m.group(1).lower(), m.group(2))
52
+ for lock in ("uv.lock", "poetry.lock"):
53
+ p = root / lock
54
+ try:
55
+ text = p.read_text(errors="replace")
56
+ except OSError:
57
+ continue
58
+ for m in re.finditer(rf'(?m)^name = "({names})"\s*\nversion = "([^"]+)"', text):
59
+ out.setdefault(m.group(1).lower(), m.group(2))
60
+ return out
61
+
62
+
63
+ RUST_TOML = ('[package]\nname = "codecop-calls-harness"\nversion = "0.1.0"\nedition = "2021"\n\n[dependencies]\n'
64
+ 'reqwest = { version = "0.12", default-features = false, features = ["rustls-tls"] }\n'
65
+ 'tokio = { version = "1", features = ["full"] }\nredis = { version = "0.32", default-features = false }\n'
66
+ 'serde_json = "1"\n\n[profile.release]\nopt-level = 2\n')
67
+
68
+
69
+ def node_pins(root: Path) -> dict[str, str]:
70
+ """The version ranges package.json files name for the replayed Node packages."""
71
+ out: dict[str, str] = {}
72
+ for p in [Path(root) / "package.json"] + list(Path(root).glob("*/package.json"))[:20]:
73
+ try:
74
+ doc = json.loads(p.read_text())
75
+ except (OSError, ValueError):
76
+ continue
77
+ for sec in ("dependencies", "devDependencies"):
78
+ for name in NODE_PKGS:
79
+ v = (doc.get(sec) or {}).get(name)
80
+ if isinstance(v, str) and re.fullmatch(r"[\^~]?\d[\w.\-]*", v):
81
+ out.setdefault(name, v)
82
+ return out
83
+
84
+
85
+ class Runtimes:
86
+ """Which runtimes and libraries this machine has, and the call into each harness."""
87
+
88
+ def __init__(self, settings: dict | None = None, root: Path | None = None):
89
+ self.settings = dict(settings or {})
90
+ self.root = root
91
+ self._lock = threading.Lock()
92
+ self._py: dict[str, tuple[str | None, str]] = {} # lib -> (interpreter, why not / version)
93
+ self._go: tuple[list[str] | None, str] | None = None
94
+ self._node: tuple[list[str] | None, str] | None = None
95
+ self.pins = pinned_versions(root) if root else {}
96
+ self.node_pins = node_pins(root) if root else {}
97
+ self._rust: tuple[list[str] | None, str] | None = None
98
+ self._java: tuple[list[str] | None, str] | None = None
99
+ self._npm: dict[str, tuple[str | None, str]] = {}
100
+ self.rust_versions: dict[str, str] = {}
101
+
102
+ # --- Python ----------------------------------------------------------------------------------------------------------
103
+ def _base_python(self) -> str:
104
+ exe = self.settings.get("python") or sys.executable
105
+ if not exe or not (Path(exe).exists() or shutil.which(exe)):
106
+ raise Unavailable("no Python interpreter")
107
+ return exe
108
+
109
+ @staticmethod
110
+ def _has(exe: str, lib: str) -> str | None:
111
+ try:
112
+ r = subprocess.run([exe, "-I", "-c", f"import {lib}; print(getattr({lib}, '__version__', '?'))"], capture_output=True,
113
+ text=True, timeout=60)
114
+ except (OSError, subprocess.SubprocessError):
115
+ return None
116
+ return r.stdout.strip() if r.returncode == 0 else None
117
+
118
+ def python_for(self, lib: str) -> tuple[str, str]:
119
+ """(interpreter, library version) that can replay `lib` ('' for the standard library). Raises Unavailable."""
120
+ with self._lock:
121
+ if lib not in self._py:
122
+ try:
123
+ self._py[lib] = (*self._find_python(lib),)
124
+ except Unavailable as e:
125
+ self._py[lib] = (None, str(e))
126
+ exe, detail = self._py[lib]
127
+ if exe is None:
128
+ raise Unavailable(detail)
129
+ return exe, detail
130
+
131
+ def _find_python(self, lib: str) -> tuple[str, str]:
132
+ base = self._base_python()
133
+ if not lib:
134
+ return base, ""
135
+ want = self.pins.get(lib)
136
+ have = self._has(base, lib)
137
+ if have and (not want or have == want):
138
+ return base, have
139
+ if not self.settings.get("provision", True):
140
+ if have:
141
+ return base, have
142
+ raise Unavailable(f"the Python library `{lib}` is not installed for {base} (setting provision is off)")
143
+ ver = subprocess.run([base, "-I", "-c", "import sys; print('%d.%d' % sys.version_info[:2])"], capture_output=True, text=True,
144
+ timeout=60).stdout.strip() or "py"
145
+ for spec in ([f"{lib}=={want}"] if want else []) + [lib]:
146
+ d = cache_dir() / "python" / f"{ver}-{spec.replace('==', '-')}"
147
+ exe = d / "bin" / "python"
148
+ if not exe.exists():
149
+ try:
150
+ subprocess.run([base, "-m", "venv", str(d)], capture_output=True, timeout=300, check=True)
151
+ r = subprocess.run([str(exe), "-m", "pip", "install", "-q", "--disable-pip-version-check", spec], capture_output=True,
152
+ text=True, timeout=600)
153
+ if r.returncode != 0:
154
+ shutil.rmtree(d, ignore_errors=True)
155
+ continue
156
+ except (OSError, subprocess.SubprocessError):
157
+ shutil.rmtree(d, ignore_errors=True)
158
+ continue
159
+ got = self._has(str(exe), lib)
160
+ if got:
161
+ return str(exe), got
162
+ if have:
163
+ return base, have
164
+ raise Unavailable(f"the Python library `{lib}` is not installed and could not be installed into CodeCop's cache")
165
+
166
+ # --- Node and Go -----------------------------------------------------------------------------------------------------
167
+ def node(self) -> list[str]:
168
+ with self._lock:
169
+ if self._node is None:
170
+ exe = shutil.which(self.settings.get("node") or "node")
171
+ self._node = ([exe, str(HERE / "run_node.js")], "") if exe else (None, "node is not installed")
172
+ cmd, why = self._node
173
+ if cmd is None:
174
+ raise Unavailable(why)
175
+ return cmd
176
+
177
+ def go(self) -> list[str]:
178
+ with self._lock:
179
+ if self._go is None:
180
+ try:
181
+ self._go = (self._build_go(), "")
182
+ except Unavailable as e:
183
+ self._go = (None, str(e))
184
+ except (OSError, subprocess.SubprocessError) as e:
185
+ self._go = (None, f"{type(e).__name__}: {e}"[:200])
186
+ cmd, why = self._go
187
+ if cmd is None:
188
+ raise Unavailable(why)
189
+ return cmd
190
+
191
+ def _build_go(self) -> list[str]:
192
+ go = shutil.which(self.settings.get("go") or "go")
193
+ if not go:
194
+ raise Unavailable("the Go toolchain is not installed")
195
+ v = subprocess.run([go, "version"], capture_output=True, text=True, timeout=60).stdout.strip()
196
+ src = (HERE / "run_go.go").read_text()
197
+ tag = hashlib.sha256((v + HARNESS_VERSION + src).encode()).hexdigest()[:12]
198
+ d = cache_dir() / f"go-{tag}"
199
+ exe = d / "run_go"
200
+ if not exe.exists():
201
+ d.mkdir(parents=True, exist_ok=True)
202
+ (d / "main.go").write_text(src)
203
+ (d / "go.mod").write_text("module codecopcalls\n\ngo 1.21\n")
204
+ env = {**os.environ, "GOFLAGS": "-mod=mod", "GOPROXY": "off", "GOTOOLCHAIN": "local", "CGO_ENABLED": "0"}
205
+ r = subprocess.run([go, "build", "-o", str(exe), "."], cwd=d, capture_output=True, text=True, timeout=600, env=env)
206
+ if r.returncode != 0:
207
+ raise Unavailable(f"the Go harness did not build: {r.stderr.strip()[:200]}")
208
+ return [str(exe)]
209
+
210
+ def node_package(self, pkg: str) -> tuple[str, str]:
211
+ """(a node_modules directory holding `pkg`, its version): installed once into CodeCop's cache with npm, at the
212
+ version range the repository's package.json names, when `provision` is on. Raises Unavailable."""
213
+ with self._lock:
214
+ if pkg not in self._npm:
215
+ self._npm[pkg] = self._find_npm(pkg)
216
+ d, why = self._npm[pkg]
217
+ if d is None:
218
+ raise Unavailable(why)
219
+ return d, why
220
+
221
+ def _find_npm(self, pkg: str) -> tuple[str | None, str]:
222
+ spec = self.node_pins.get(pkg) or "latest"
223
+ safe = re.sub(r"[^A-Za-z0-9.]+", "_", spec)
224
+ d = cache_dir() / "node" / f"{pkg}-{safe}"
225
+ mod = d / "node_modules" / pkg / "package.json"
226
+ if not mod.exists():
227
+ npm = shutil.which("npm")
228
+ if not npm:
229
+ return None, f"the Node package `{pkg}` is not available (npm is not installed)"
230
+ if not self.settings.get("provision", True):
231
+ return None, f"the Node package `{pkg}` is not installed in CodeCop's cache (setting provision is off)"
232
+ d.mkdir(parents=True, exist_ok=True)
233
+ try:
234
+ r = subprocess.run([npm, "install", "--prefix", str(d), f"{pkg}@{spec}", "--no-audit", "--no-fund", "--silent",
235
+ "--ignore-scripts"], capture_output=True, text=True, timeout=600)
236
+ except (OSError, subprocess.SubprocessError) as e:
237
+ return None, f"the Node package `{pkg}` could not be installed ({type(e).__name__})"
238
+ if r.returncode != 0 or not mod.exists():
239
+ return None, f"the Node package `{pkg}` could not be installed into CodeCop's cache"
240
+ try:
241
+ ver = json.loads(mod.read_text()).get("version", "?")
242
+ except (OSError, ValueError):
243
+ ver = "?"
244
+ return str(d / "node_modules"), ver
245
+
246
+ def rust(self) -> list[str]:
247
+ with self._lock:
248
+ if self._rust is None:
249
+ try:
250
+ self._rust = (self._build_rust(), "")
251
+ except Unavailable as e:
252
+ self._rust = (None, str(e))
253
+ except (OSError, subprocess.SubprocessError) as e:
254
+ self._rust = (None, f"{type(e).__name__}: {e}"[:200])
255
+ cmd, why = self._rust
256
+ if cmd is None:
257
+ raise Unavailable(why)
258
+ return cmd
259
+
260
+ def _build_rust(self) -> list[str]:
261
+ cargo = shutil.which(self.settings.get("cargo") or "cargo")
262
+ if not cargo:
263
+ raise Unavailable("cargo is not installed")
264
+ ver = subprocess.run([cargo, "--version"], capture_output=True, text=True, timeout=60).stdout.strip()
265
+ src = (HERE / "run_rust.rs").read_text()
266
+ tag = hashlib.sha256((ver + HARNESS_VERSION + RUST_TOML + src).encode()).hexdigest()[:12]
267
+ d = cache_dir() / f"rust-{tag}"
268
+ exe = d / "target" / "release" / "codecop-calls-harness"
269
+ if not exe.exists():
270
+ (d / "src").mkdir(parents=True, exist_ok=True)
271
+ (d / "Cargo.toml").write_text(RUST_TOML)
272
+ (d / "src" / "main.rs").write_text(src)
273
+ env = {**os.environ, "CARGO_NET_OFFLINE": "true"}
274
+ r = subprocess.run([cargo, "build", "--release", "--offline", "--quiet"], cwd=d, capture_output=True, text=True,
275
+ timeout=1800, env=env)
276
+ if r.returncode != 0:
277
+ raise Unavailable("the Rust harness did not build offline (reqwest, tokio and redis must be in the local cargo "
278
+ "cache): " + (r.stderr or r.stdout)[-160:])
279
+ try:
280
+ lock = (d / "Cargo.lock").read_text()
281
+ for name in ("reqwest", "tokio", "redis"):
282
+ m = re.search(rf'name = "{name}"\nversion = "([^"]+)"', lock)
283
+ if m:
284
+ self.rust_versions[name] = m.group(1)
285
+ except OSError:
286
+ pass
287
+ return [str(exe)]
288
+
289
+ def java(self) -> list[str]:
290
+ with self._lock:
291
+ if self._java is None:
292
+ try:
293
+ self._java = (self._build_java(), "")
294
+ except Unavailable as e:
295
+ self._java = (None, str(e))
296
+ except (OSError, subprocess.SubprocessError) as e:
297
+ self._java = (None, f"{type(e).__name__}: {e}"[:200])
298
+ cmd, why = self._java
299
+ if cmd is None:
300
+ raise Unavailable(why)
301
+ return cmd
302
+
303
+ def _build_java(self) -> list[str]:
304
+ java, javac = shutil.which(self.settings.get("java") or "java"), shutil.which("javac")
305
+ if not java or not javac:
306
+ raise Unavailable("a JDK (java and javac, 11 or newer) is not installed")
307
+ v = subprocess.run([java, "-version"], capture_output=True, text=True, timeout=60).stderr.splitlines()
308
+ src = (HERE / "RunCalls.java").read_text()
309
+ tag = hashlib.sha256(((v[0] if v else "") + HARNESS_VERSION + src).encode()).hexdigest()[:12]
310
+ d = cache_dir() / f"java-{tag}"
311
+ if not (d / "RunCalls.class").exists():
312
+ d.mkdir(parents=True, exist_ok=True)
313
+ r = subprocess.run([javac, "-d", str(d), str(HERE / "RunCalls.java")], capture_output=True, text=True, timeout=300)
314
+ if r.returncode != 0:
315
+ raise Unavailable("the Java harness did not compile: " + (r.stderr or "")[-160:])
316
+ pool = int(self.settings.get("java_pool") or 4)
317
+ return [java, "-XX:+UseSerialGC", f"-Djava.util.concurrent.ForkJoinPool.common.parallelism={pool}", "-cp", str(d), "RunCalls"]
318
+
319
+ # --- availability ----------------------------------------------------------------------------------------------------
320
+ def command(self, runtime: str, lib: str = "") -> list[str]:
321
+ if runtime == "python":
322
+ exe, _ = self.python_for(lib)
323
+ return [exe, "-I", str(HERE / "run_python.py")]
324
+ if runtime == "node":
325
+ return self.node()
326
+ if runtime == "go":
327
+ return self.go()
328
+ if runtime == "rust":
329
+ return self.rust()
330
+ if runtime == "java":
331
+ return self.java()
332
+ raise Unavailable(f"no harness for {runtime}")
333
+
334
+ def env_for(self, runtime: str, lib: str) -> dict:
335
+ """Environment of a harness child: a provisioned Node package's directory on NODE_PATH."""
336
+ if runtime == "node" and lib in NODE_PKGS:
337
+ return {"NODE_PATH": self.node_package(lib)[0]}
338
+ return {}
339
+
340
+ def available(self, runtime: str, lib: str = "") -> tuple[bool, str]:
341
+ try:
342
+ self.command(runtime, lib)
343
+ self.env_for(runtime, lib)
344
+ return True, self.version(runtime, lib)
345
+ except Unavailable as e:
346
+ return False, str(e)
347
+
348
+ def version(self, runtime: str, lib: str = "") -> str:
349
+ try:
350
+ got, _, _ = self.call(runtime, {"op": "version"}, lib=lib, timeout_s=60)
351
+ except Unavailable:
352
+ return ""
353
+ if runtime == "python":
354
+ v = f"CPython {got.get('python', '')}"
355
+ if lib:
356
+ v += f", {lib} {(got.get('libs') or {}).get(lib, '?')}"
357
+ return v
358
+ if runtime == "node":
359
+ return f"Node {got.get('node', '')}" + (f", {lib} {self.node_package(lib)[1]}" if lib in NODE_PKGS else "")
360
+ if runtime == "rust":
361
+ return "Rust, " + ", ".join(f"{k} {v}" for k, v in self.rust_versions.items()) if self.rust_versions else "Rust"
362
+ if runtime == "java":
363
+ return f"Java {got.get('java', '')} (java.net.http, common pool {got.get('common_pool', '?')})"
364
+ return str(got.get("go") or "")
365
+
366
+ # --- one call --------------------------------------------------------------------------------------------------------
367
+ def call(self, runtime: str, req: dict, *, lib: str = "", timeout_s: float = 120, env: dict | None = None) -> tuple[dict, float, bool]:
368
+ """(the harness's answer, seconds the child ran, whether it was stopped at the timeout). A child stopped at the
369
+ timeout answers {} : the caller reads that as "still waiting"."""
370
+ cmd = self.command(runtime, lib)
371
+ env = {**self.env_for(runtime, lib), **(env or {})}
372
+ t = time.perf_counter()
373
+ p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
374
+ env={**os.environ, **(env or {})}, start_new_session=True)
375
+ try:
376
+ so, se = p.communicate(json.dumps(req), timeout=timeout_s)
377
+ killed = False
378
+ except subprocess.TimeoutExpired:
379
+ p.kill()
380
+ so, se = p.communicate()
381
+ killed = True
382
+ secs = time.perf_counter() - t
383
+ lines = [ln for ln in (so or "").splitlines() if ln.strip().startswith("{")]
384
+ try:
385
+ got = json.loads(lines[-1]) if lines else {}
386
+ except ValueError:
387
+ got = {}
388
+ if not killed and not got:
389
+ got = {"error": (se or "").strip()[-300:] or f"exit {p.returncode}"}
390
+ return got, secs, killed
391
+
392
+
393
+ def doctor(settings: dict | None = None) -> list[tuple[bool, str, str]]:
394
+ """(available, runtime, version or why not) per runtime, for `codecop doctor`. Python libraries are checked, never
395
+ installed here."""
396
+ r = Runtimes({**(settings or {}), "provision": False})
397
+ out = []
398
+ try:
399
+ base = r._base_python()
400
+ libs = [f"{lib} {v}" for lib in PY_LIBS if (v := Runtimes._has(base, lib))]
401
+ out.append((True, "CPython", (r.version("python") or "CPython") + (f" ({', '.join(libs)})" if libs else
402
+ " (HTTP libraries are installed into CodeCop's cache when first needed)")))
403
+ except Unavailable as e:
404
+ out.append((False, "CPython", str(e)))
405
+ for name, label in (("node", "Node"), ("go", "Go"), ("rust", "Rust (cargo, offline)"), ("java", "Java (JDK)")):
406
+ ok, detail = r.available(name)
407
+ out.append((ok, label, detail))
408
+ return out