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,342 @@
1
+ """Measurements of one call shape on its runtime against the stand-in, and the verdict each rests on.
2
+
3
+ - client per call: `calls` calls with the client built on every call (as written) and built once (the fix), runs
4
+ interleaved, at a simulated round trip (`rtt_ms`, TLS when available) and on bare loopback (shown, not judged). The
5
+ verdict rests on counts the stand-in keeps (connections opened, TLS handshakes) and on the time ratio only when the
6
+ runs' spreads do not overlap and the ratio clears `min_gain`.
7
+ - blocking in async: `handlers` concurrent handlers doing the call on the event loop (as written) and off it (the fix),
8
+ with a heartbeat; the verdict rests on the longest event-loop stall (the calls ran one after another, or overlapped).
9
+ - no timeout: one call against a listener that never answers, without and with a timeout; the verdict is whether the
10
+ call returned by the deadline (`deadline_s`).
11
+
12
+ Measurements are cached per shape, runtime version and settings in `<out>/kinds/calls-measure.json`.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import hashlib
18
+ import json
19
+ import statistics
20
+ import threading
21
+ from pathlib import Path
22
+
23
+ from .harness import Runtimes, Unavailable
24
+ from .standin import StandIn
25
+
26
+ MEASURE_VERSION = "1"
27
+ SETTINGS = {
28
+ "python": "", # the interpreter that replays Python shapes ("" = CodeCop's own)
29
+ "node": "", "go": "", # executables ("" = on PATH)
30
+ "provision": True, # install a missing Python HTTP library into CodeCop's cache (at the repository's pinned version)
31
+ "calls": 20, # calls per client run
32
+ "runs": 5, # repeated runs per side, interleaved (client)
33
+ "rtt_ms": 20, # the simulated round trip the client verdict is measured at
34
+ "loopback_runs": 3, # runs on bare loopback (shown, not judged); 0 skips them
35
+ "tls": True, # measure clients over TLS (the stand-in's own certificate)
36
+ "handlers": 20, # concurrent handlers sharing the event loop (blocking in async)
37
+ "call_ms": 50, # how long a replayed blocking call takes (sleep, upstream answer, child process)
38
+ "heartbeat_ms": 5, # the event loop's heartbeat
39
+ "block_runs": 3,
40
+ "deadline_s": 10, # how long a call against an upstream that never answers is given
41
+ "fix_timeout_s": 3, # the timeout the fix sets when measured
42
+ "hang_runs": 1,
43
+ "min_gain": 1.3, # a time ratio below this is not a gain, even beyond the spread
44
+ "child_timeout_s": 600, # one harness child's hard limit
45
+ "max_sites": 50000,
46
+ "max_loop_hops": 3,
47
+ "rust_workers": 4, # tokio worker threads of the blocking-in-async replay (a service's runtime has a few)
48
+ "java_pool": 4, # the JVM common pool's parallelism in the replay (CompletableFuture without an executor) # a caller's per-item loop this many calls up shows the call repeats; further is not counted
49
+ }
50
+
51
+
52
+ REDIS_SHAPES = ("redis.Redis", "ioredis", "redis")
53
+
54
+
55
+ def settings_of(cfg: dict | None) -> dict:
56
+ return {**SETTINGS, **{k: v for k, v in (cfg or {}).items() if k in SETTINGS}}
57
+
58
+
59
+ class Cache:
60
+ def __init__(self, path: Path | None):
61
+ self.path = path
62
+ self.data: dict = {}
63
+ self.lock = threading.Lock()
64
+ if path and path.exists():
65
+ try:
66
+ self.data = json.loads(path.read_text())
67
+ except ValueError:
68
+ self.data = {}
69
+
70
+ @staticmethod
71
+ def key(*parts) -> str:
72
+ return hashlib.sha256(json.dumps([MEASURE_VERSION, *parts], sort_keys=True, default=str).encode()).hexdigest()[:24]
73
+
74
+ def get(self, k):
75
+ with self.lock:
76
+ return self.data.get(k)
77
+
78
+ def put(self, k, v):
79
+ with self.lock:
80
+ self.data[k] = v
81
+ self.save()
82
+
83
+ def save(self):
84
+ if self.path:
85
+ try:
86
+ self.path.parent.mkdir(parents=True, exist_ok=True)
87
+ with self.lock:
88
+ self.path.write_text(json.dumps(self.data, indent=1))
89
+ except OSError:
90
+ pass
91
+
92
+
93
+ def med(xs):
94
+ xs = [x for x in xs if isinstance(x, (int, float))]
95
+ return round(statistics.median(xs), 4) if xs else None
96
+
97
+
98
+ def spread(xs):
99
+ xs = [x for x in xs if isinstance(x, (int, float))]
100
+ return [round(min(xs), 4), round(max(xs), 4)] if xs else None
101
+
102
+
103
+ # replayed keyword arguments per Python client: what changes the measured cost, never a host, a credential or verify
104
+ PY_KW = {"httpx": {"timeout", "follow_redirects", "http1", "headers", "max_redirects", "trust_env"},
105
+ "aiohttp": {"headers", "raise_for_status", "auto_decompress", "trust_env"},
106
+ "requests": set(), "redis": {"decode_responses", "db", "socket_timeout", "socket_connect_timeout", "health_check_interval"}}
107
+
108
+
109
+ def replay_kwargs(lib: str, kwargs: dict) -> tuple[dict, list[str]]:
110
+ keep = PY_KW.get(lib, set())
111
+ got = {k: v for k, v in (kwargs or {}).items() if k in keep and not (k == "headers" and not isinstance(v, dict))}
112
+ return got, sorted(k for k in (kwargs or {}) if k not in got)
113
+
114
+
115
+ class Measurer:
116
+ """One measurement session: the runtimes, the stand-in (started on first use) and the cache."""
117
+
118
+ def __init__(self, settings: dict, root: Path | None, out_dir: Path | None):
119
+ self.st = settings_of(settings)
120
+ self.rt = Runtimes(self.st, root)
121
+ self.cache = Cache(Path(out_dir) / "kinds" / "calls-measure.json" if out_dir else None)
122
+ self._standin: StandIn | None = None
123
+ self._lock = threading.Lock() # one measurement at a time: two would load each other's timings
124
+
125
+ def standin(self) -> StandIn:
126
+ if self._standin is None:
127
+ self._standin = StandIn(tls=bool(self.st["tls"]))
128
+ self._standin.start()
129
+ return self._standin
130
+
131
+ def close(self):
132
+ if self._standin is not None:
133
+ self._standin.stop()
134
+ self._standin = None
135
+
136
+ def runtime_label(self, runtime: str, lib: str = "") -> str:
137
+ return self.rt.version(runtime, lib)
138
+
139
+ # --- client per call -------------------------------------------------------------------------------------------------
140
+ def client(self, c: dict) -> dict:
141
+ rt, st = c["runtime"], self.st
142
+ lib = c.get("lib") or ""
143
+ if rt == "python":
144
+ shape = "requests.module" if c.get("implicit") else c["shape"]
145
+ pylib = shape.split(".")[0]
146
+ kwargs, dropped = replay_kwargs(pylib, c.get("kwargs") or {})
147
+ label_lib = pylib
148
+ else:
149
+ shape, kwargs, dropped = c["shape"], {}, []
150
+ label_lib = shape if rt == "node" and shape in ("axios", "ioredis") else ""
151
+ ok, version = self.rt.available(rt, label_lib)
152
+ if not ok:
153
+ raise Unavailable(version)
154
+ tls = bool(st["tls"]) and self.standin().tls_ok and shape not in REDIS_SHAPES
155
+ key = Cache.key("client", rt, shape, kwargs, c.get("verb") or "get", version, tls,
156
+ {k: st[k] for k in ("calls", "runs", "rtt_ms", "loopback_runs")}, self.rt.pins.get(label_lib))
157
+ got = self.cache.get(key)
158
+ if got:
159
+ return got
160
+ with self._lock:
161
+ s = self.standin()
162
+ res = {"shape": shape, "runtime": version, "tls": tls, "kwargs": kwargs, "not_replayed": dropped, "calls": int(st["calls"]),
163
+ "rtt_ms": float(st["rtt_ms"])}
164
+ for label, rtt, runs in (("rtt", float(st["rtt_ms"]), int(st["runs"])), ("loopback", 0.0, int(st["loopback_runs"]))):
165
+ if runs <= 0:
166
+ continue
167
+ sides = {"before": {"ms": [], "conns": [], "tls": [], "hash": set()}, "after": {"ms": [], "conns": [], "tls": [], "hash": set()}}
168
+ for _ in range(runs):
169
+ for side in ("before", "after"):
170
+ req = self._client_req(rt, shape, kwargs, c, side, tls, rtt)
171
+ a = s.counts()
172
+ out, _, killed = self.rt.call(rt, req, lib=label_lib, timeout_s=float(st["child_timeout_s"]))
173
+ d = s.delta(a, s.counts())
174
+ if killed or out.get("error"):
175
+ raise RuntimeError(f"harness: {out.get('error') or 'stopped at the timeout'}"[:200])
176
+ sd = sides[side]
177
+ sd["ms"].append(float(out["ms_per_call"]))
178
+ sd["conns"].append(d["redis_connections"] if shape in REDIS_SHAPES else d["connections"])
179
+ sd["tls"].append(d["tls_handshakes"])
180
+ sd["hash"].add(out.get("hash"))
181
+ res[label] = {side: {"ms": med(v["ms"]), "spread": spread(v["ms"]), "runs": len(v["ms"]), "connections": med(v["conns"]),
182
+ "tls_handshakes": med(v["tls"]), "hashes": len(v["hash"])} for side, v in sides.items()}
183
+ res[label]["same"] = sides["before"]["hash"] == sides["after"]["hash"]
184
+ self.cache.put(key, res)
185
+ return res
186
+
187
+ def _client_req(self, rt, shape, kwargs, c, side, tls, rtt):
188
+ s, st = self.standin(), self.st
189
+ if rt == "python":
190
+ req = {"op": "client", "lib": shape, "kwargs": kwargs, "verb": c.get("verb") or "get", "calls": int(st["calls"]),
191
+ "mode": "per_call" if side == "before" else "shared", "cafile": s.cafile if tls else ""}
192
+ if shape == "redis.Redis":
193
+ req["redis"] = list(s.redis(rtt))
194
+ req["base"] = ""
195
+ else:
196
+ req["base"] = s.http(tls=tls, rtt_ms=rtt)
197
+ return req
198
+ mode = "per_call" if side == "before" else "shared"
199
+ if rt == "node":
200
+ return {"op": "client", "lib": shape if shape in ("axios", "ioredis") else "agent", "base": s.http(tls=tls, rtt_ms=rtt),
201
+ "redis": list(s.redis(rtt)), "calls": int(st["calls"]), "mode": mode, "cafile": s.cafile if tls else "",
202
+ "agent_options": {k: v for k, v in (c.get("kwargs") or {}).items()
203
+ if k in ("keepAlive", "maxSockets", "maxFreeSockets", "timeout")}}
204
+ if rt == "rust":
205
+ return {"op": "client", "lib": "redis" if shape == "redis" else "reqwest", "base": s.http(tls=tls, rtt_ms=rtt),
206
+ "redis": list(s.redis(rtt)), "calls": int(st["calls"]), "mode": mode, "cafile": s.cafile if tls else ""}
207
+ if rt == "java":
208
+ return {"op": "client", "base": s.http(tls=tls, rtt_ms=rtt), "calls": int(st["calls"]), "mode": mode, "cafile": s.cafile if tls else ""}
209
+ return {"op": "client", "base": s.http(tls=tls, rtt_ms=rtt), "calls": int(st["calls"]),
210
+ "mode": "transport_per_call" if side == "before" else "shared", "cafile": s.cafile if tls else ""}
211
+
212
+ # --- blocking in async -----------------------------------------------------------------------------------------------
213
+ def block(self, c: dict) -> dict:
214
+ rt, st, call = c["runtime"], self.st, c["call"]
215
+ lib = call.split(".")[0] if rt == "python" and call.split(".")[0] in ("requests", "httpx") else ""
216
+ ok, version = self.rt.available(rt, lib)
217
+ if not ok:
218
+ raise Unavailable(version)
219
+ params = {"call_ms": float(st["call_ms"]), "handlers": int(st["handlers"]), "heartbeat_ms": float(st["heartbeat_ms"])}
220
+ if rt == "rust":
221
+ call = "command_output" if "Command" in call or call.endswith(("output", "status")) else "thread_sleep"
222
+ params["workers"] = int(st["rust_workers"])
223
+ elif rt == "java":
224
+ call = "thread_sleep" if "sleep" in call.lower() else "url_connection"
225
+ params["pool"] = int(st["java_pool"])
226
+ if call == "time.sleep" and isinstance(c.get("sleep_s"), (int, float)) and 0 < float(c["sleep_s"]) <= 5:
227
+ params["sleep_s"] = float(c["sleep_s"])
228
+ for k in ("iterations", "keylen", "digest"):
229
+ if c.get(k):
230
+ params[k] = c[k]
231
+ key = Cache.key("block", rt, call, version, params, int(st["block_runs"]))
232
+ got = self.cache.get(key)
233
+ if got:
234
+ return got
235
+ with self._lock:
236
+ s = self.standin()
237
+ sides = {"before": [], "after": []}
238
+ for _ in range(int(st["block_runs"])):
239
+ for side in ("before", "after"):
240
+ req = {"op": "block", "call": call, "mode": side, "base": s.http(server_ms=float(st["call_ms"])),
241
+ "use_async": call == "time.sleep", **params}
242
+ out, _, killed = self.rt.call(rt, req, lib=lib, timeout_s=float(st["child_timeout_s"]))
243
+ if killed or out.get("error"):
244
+ raise RuntimeError(f"harness: {out.get('error') or 'stopped at the timeout'}"[:200])
245
+ sides[side].append(out)
246
+ res = {"call": call, "runtime": version, **params, "runs": int(st["block_runs"]),
247
+ "same": {o.get("hash") for o in sides["before"]} == {o.get("hash") for o in sides["after"]}}
248
+ for side, outs in sides.items():
249
+ mid = sorted(outs, key=lambda o: o["wall_ms"])[len(outs) // 2]
250
+ res[side] = {"stall_ms": med([o["stall_ms"] for o in outs]), "stall_spread": spread([o["stall_ms"] for o in outs]),
251
+ "wall_ms": med([o["wall_ms"] for o in outs]), "wall_spread": spread([o["wall_ms"] for o in outs]),
252
+ "timeline": {"start_ms": mid.get("start_ms"), "wall_ms": round(mid["wall_ms"], 2), "spans": mid.get("spans") or [],
253
+ "stalls": mid.get("stalls") or []}}
254
+ self.cache.put(key, res)
255
+ return res
256
+
257
+ # --- no timeout ------------------------------------------------------------------------------------------------------
258
+ def hang(self, c: dict) -> dict:
259
+ rt, st, call = c["runtime"], self.st, c["call"]
260
+ lib = "requests" if rt == "python" and call.startswith("requests.") else ""
261
+ ok, version = self.rt.available(rt, lib)
262
+ if not ok:
263
+ raise Unavailable(version)
264
+ if rt == "python":
265
+ hcall = "requests.get" if call.startswith("requests.") else call
266
+ elif rt == "node":
267
+ hcall = call if call in ("fetch", "axios") else "http.request"
268
+ lib = "axios" if call == "axios" else ""
269
+ elif rt == "rust":
270
+ hcall = "reqwest"
271
+ elif rt == "java":
272
+ hcall = "url_connection" if "URLConnection" in call or "openConnection" in call else "http_client"
273
+ else:
274
+ hcall = "default_client" if call != "http.Client{}" else "client"
275
+ deadline, fix = float(st["deadline_s"]), float(st["fix_timeout_s"])
276
+ key = Cache.key("hang", rt, hcall, version, deadline, fix, int(st["hang_runs"]))
277
+ got = self.cache.get(key)
278
+ if got:
279
+ return got
280
+ with self._lock:
281
+ s = self.standin()
282
+ sides = {"before": [], "after": []}
283
+ for _ in range(int(st["hang_runs"])):
284
+ for side in ("before", "after"):
285
+ to = None if side == "before" else fix
286
+ if rt == "python":
287
+ req = {"op": "hang", "call": hcall, "url": s.hang(), "timeout_s": to}
288
+ elif rt in ("node", "rust", "java"):
289
+ req = {"op": "hang", "call": hcall, "url": s.hang(), "timeout_ms": (to or 0) * 1000}
290
+ else:
291
+ req = {"op": "hang", "url": s.hang(), "mode": hcall if side == "before" else "client", "timeout_ms": (to or 0) * 1000}
292
+ out, secs, killed = self.rt.call(rt, req, lib=lib, timeout_s=deadline)
293
+ if not killed and out.get("error") and not out.get("returned"):
294
+ raise RuntimeError(f"harness: {out.get('error')}"[:200])
295
+ sides[side].append({"returned": not killed, "seconds": round(min(secs, deadline) if killed else float(out.get("seconds") or secs), 3),
296
+ "error": "" if killed else str(out.get("error") or "")})
297
+ res = {"call": hcall, "runtime": version, "deadline_s": deadline, "fix_timeout_s": fix, "runs": int(st["hang_runs"])}
298
+ for side, outs in sides.items():
299
+ res[side] = {"returned": sum(1 for o in outs if o["returned"]), "of": len(outs), "seconds": med([o["seconds"] for o in outs]),
300
+ "spread": spread([o["seconds"] for o in outs]), "error": outs[-1]["error"] if outs else ""}
301
+ self.cache.put(key, res)
302
+ return res
303
+
304
+
305
+ # --- verdicts ----------------------------------------------------------------------------------------------------------------
306
+
307
+ def client_verdict(m: dict, min_gain: float) -> str:
308
+ """'gain' | 'shared' (connections already reused: nothing to gain) | 'no_gain' | 'differs'."""
309
+ r = m.get("rtt") or {}
310
+ b, a = r.get("before") or {}, r.get("after") or {}
311
+ if not r.get("same", True):
312
+ return "differs"
313
+ if (b.get("connections") or 0) <= (a.get("connections") or 0):
314
+ return "shared"
315
+ sb, sa = b.get("spread") or [0, 0], a.get("spread") or [0, 0]
316
+ if a.get("ms") and b.get("ms") and b["ms"] / a["ms"] >= min_gain and sb[0] > sa[1]:
317
+ return "gain"
318
+ return "no_gain"
319
+
320
+
321
+ def block_verdict(m: dict) -> str:
322
+ """'gain' when the calls stalled the loop one after another before and overlapped after (beyond the spread, at least
323
+ handlers/2 times shorter), 'no_gain', or 'differs'."""
324
+ b, a = m.get("before") or {}, m.get("after") or {}
325
+ if not m.get("same", True):
326
+ return "differs"
327
+ sb, sa = b.get("stall_spread") or [0, 0], a.get("stall_spread") or [0, 0]
328
+ need = max(2.0, float(m.get("handlers") or 2) / 2)
329
+ if a.get("stall_ms") is not None and b.get("stall_ms") and sb[0] > sa[1] and b["stall_ms"] >= need * max(a["stall_ms"], 0.001):
330
+ return "gain"
331
+ return "no_gain"
332
+
333
+
334
+ def hang_verdict(m: dict) -> str:
335
+ """'gain' when the call as written was still waiting at the deadline on every run and the fixed call returned on every
336
+ run within its timeout (plus one second); 'has_default' when the call as written returned by itself; 'no_gain'."""
337
+ b, a = m.get("before") or {}, m.get("after") or {}
338
+ if b.get("returned"):
339
+ return "has_default"
340
+ if a.get("returned") == a.get("of") and (a.get("seconds") or 1e9) <= float(m.get("fix_timeout_s") or 0) + 1.0:
341
+ return "gain"
342
+ return "no_gain"
@@ -0,0 +1,139 @@
1
+ """Rules over the discovered call sites: what is set aside (and why), what is a candidate, and for each candidate the gate
2
+ its verdict needs: whether the code shows the call repeats (client per call) or shares its event loop with other work
3
+ (blocking in async). What the code cannot show is one agent question per site (`ask`).
4
+
5
+ Free and cheap: no agent, no harness.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from collections import Counter
12
+
13
+ SET_ASIDE_ROLES = {"test", "script", "tooling", "migration"}
14
+ REPEAT_ENTRY = {"http", "consumer", "job", "workflow", "activity"} # an entry point that runs many times
15
+ SHARED_LOOP_ENTRY = {"http", "consumer", "activity", "workflow", "job"} # async code that shares its loop with other work
16
+ ONE_OFF_PATH = re.compile(r"(^|/)[\w-]*(examples?|samples?|demos?)(/|$)|(^|/)(scripts?|migrations?|alembic|benchmarks?|bench|docs?|notebooks?|tools?|"
17
+ r"hack|dev|devtools|fixtures?|e2e|__tests__|__mocks__|tests?|testdata|testing|seeds?|seeders?|playground|"
18
+ r"sandbox|demo|demos|cli|bin|cmd/tools?|evals?|load_?tests?|locust)(/|$)|(^|/)(test_[^/]*|[^/]*_test|conftest|"
19
+ r"setup|manage|noxfile|fabfile|tasks)\.py$|_test\.go$|\.(test|spec|stories)\.[jt]sx?$", re.I)
20
+ TEST_DOUBLE = re.compile(r"(^|/)(testFixtures|test-fixtures|test_fixtures|[\w-]*-testing|testing-[\w-]+|testutils?|test-utils?|"
21
+ r"test_utils?|testkit|test-support|mocks?|fakes?)(/|$)", re.I)
22
+ NODE_SERVER_PATH = re.compile(r"(^|/)(server|servers|backend|api|routes|functions|lambdas?|workers?|services?|jobs|handlers|"
23
+ r"pages/api|app/api)/|(^|/)route\.[jt]s$|\.server\.[jt]sx?$|(^|/)server\.[cm]?[jt]s$", re.I)
24
+ # replayed on the stand-in: (runtime, call) -> the harness's name for the shape
25
+ REPLAY_CLIENT = {
26
+ ("python", "httpx.Client"): "httpx.Client", ("python", "httpx.AsyncClient"): "httpx.AsyncClient",
27
+ ("python", "aiohttp.ClientSession"): "aiohttp.ClientSession", ("python", "requests.Session"): "requests.Session",
28
+ ("python", "requests.session"): "requests.Session", ("python", "redis.Redis"): "redis.Redis",
29
+ ("python", "redis.StrictRedis"): "redis.Redis", ("python", "redis.from_url"): "redis.Redis",
30
+ ("python", "redis.Redis.from_url"): "redis.Redis",
31
+ ("node", "https.Agent"): "agent", ("node", "http.Agent"): "agent", ("go", "http.Transport"): "transport_per_call",
32
+ ("python", "boto3.client"): "boto3.client", ("node", "axios.create"): "axios", ("node", "ioredis"): "ioredis",
33
+ ("rust", "reqwest::Client"): "reqwest", ("rust", "reqwest::get"): "reqwest", ("rust", "redis::Client"): "redis",
34
+ ("java", "java.net.http.HttpClient"): "http_client",
35
+ }
36
+ REPLAY_BLOCK = {("python", c) for c in ("time.sleep", "urllib.request.urlopen", "subprocess.run", "subprocess.call", "subprocess.check_call",
37
+ "subprocess.check_output", "os.system")} | {("node", c) for c in ("execSync", "execFileSync", "spawnSync",
38
+ "pbkdf2Sync", "scryptSync")} | \
39
+ {("rust", "std::thread::sleep"), ("rust", "std::process::Command.output"), ("java", "Thread.sleep")}
40
+ REPLAY_HANG = {"python": {"urllib.request.urlopen"}, "node": {"fetch", "http.get", "http.request", "https.get", "https.request", "axios"},
41
+ "rust": {"reqwest::Client", "reqwest::get"}, "java": {"HttpRequest.newBuilder", "HttpURLConnection"},
42
+ "go": {"http.Get", "http.Post", "http.Head", "http.PostForm", "http.DefaultClient.Do", "http.DefaultClient.Get",
43
+ "http.DefaultClient.Post", "http.DefaultClient.Head", "http.DefaultClient.PostForm", "http.Client{}"}}
44
+
45
+
46
+ def replayable(s: dict) -> bool:
47
+ rt, call, sc = s.get("runtime"), s.get("call") or "", s.get("scenario")
48
+ if sc == "client_per_call":
49
+ if call == "boto3.client":
50
+ return s.get("service") == "s3" # the stand-in answers S3 object reads only
51
+ return (rt, call) in REPLAY_CLIENT or bool(rt == "python" and s.get("implicit") and call.startswith("requests."))
52
+ if sc == "blocking_in_async":
53
+ return (rt, call) in REPLAY_BLOCK or (rt == "python" and call.split(".")[0] in ("requests", "httpx")) or \
54
+ (rt == "java" and call.startswith("blocking I/O"))
55
+ if sc == "no_timeout":
56
+ return call in REPLAY_HANG.get(rt, set()) or (rt == "python" and call.startswith("requests."))
57
+ return False
58
+
59
+
60
+ def set_aside(s: dict) -> str:
61
+ """Why a site is not a candidate ('' when it is one)."""
62
+ if s.get("is_test") or s.get("role") == "test":
63
+ return "test code"
64
+ if s.get("role") in SET_ASIDE_ROLES:
65
+ return f"not on a server or job path ({s['role']})"
66
+ if ONE_OFF_PATH.search(s.get("file") or ""):
67
+ return "script, migration, example or tool path"
68
+ if TEST_DOUBLE.search(s.get("file") or "") or re.search(r"(?i)(^|_)(mock|fake|stub)s?(_|$)|Mock|Fake|Stub", s.get("function") or ""):
69
+ return "test support code (fixtures, mocks, test harnesses)"
70
+ if s.get("browser"): # a front-end tree: an entry point traced into it is a guess across the network
71
+ return "browser code"
72
+ kinds = {(o or {}).get("kind") for o in s.get("origins") or []}
73
+ if s.get("runtime") == "node" and not (kinds & REPEAT_ENTRY) and not NODE_SERVER_PATH.search(s.get("file") or ""):
74
+ # JS/TS runs in browsers as often as on servers: without a traced server entry or a server path it is not judged
75
+ return "not shown to run on a server (no server entry point traced)"
76
+ # reached only from programs: a command-line tool's code is a one-off; a service's `main` (role app) is not decided
77
+ if kinds and kinds <= {"cli", "test"} or (kinds and kinds <= {"main", "cli", "test"} and s.get("role") != "app"):
78
+ return "reached only from a program's start (main or a CLI command)"
79
+ if not s.get("in_function", bool(s.get("function"))) and s.get("scenario") != "client_per_call" and s.get("call") != "http.Client{}":
80
+ return "runs once at import"
81
+ if s.get("aside"):
82
+ return s["aside"]
83
+ return ""
84
+
85
+
86
+ def _entry_words(o: dict) -> str:
87
+ return f"{o.get('kind')} entry {o.get('name') or ''} at {o.get('file')}:{o.get('line')}".replace(" ", " ")
88
+
89
+
90
+ def gate(s: dict, max_hops: int = 3) -> dict:
91
+ """What the code itself shows about how often the site runs (client per call) or whether its event loop is shared
92
+ (blocking in async): {known: bool, basis: words, repeat/shared: bool}."""
93
+ sc = s.get("scenario")
94
+ origins = [o for o in s.get("origins") or [] if isinstance(o, dict)]
95
+ loop = s.get("loop_summary") or {}
96
+ if sc == "client_per_call":
97
+ if s.get("loop") == "each":
98
+ return {"known": True, "repeat": True, "basis": "built inside a loop over items in the same function"}
99
+ # a per-item loop of the caller counts when it is near (the setting `max_loop_hops`), traced without a guess and
100
+ # not in a script: a loop six calls up in a helper script says nothing about the service
101
+ if loop.get("kind") in ("per-item", "chunk") and s.get("loop") != "retry" and int(loop.get("hop") or 0) <= max_hops \
102
+ and loop.get("verified", True) and not ONE_OFF_PATH.search(str(loop.get("file") or "")):
103
+ return {"known": True, "repeat": True, "basis": f"called from a per-item loop at {loop.get('file')}:{loop.get('line')}"
104
+ + (f" ({loop.get('hop')} calls up)" if loop.get("hop") else "")}
105
+ hit = next((o for o in origins if o.get("kind") in REPEAT_ENTRY and o.get("verified", True)), None)
106
+ if hit:
107
+ return {"known": True, "repeat": True, "basis": f"runs on every call of the {_entry_words(hit)}"}
108
+ return {"known": False, "basis": "how often the function runs is not in the code: asked"}
109
+ if sc == "blocking_in_async":
110
+ if s.get("pool") == "common":
111
+ return {"known": True, "shared": True, "basis": "CompletableFuture without an executor runs on the JVM's common pool, "
112
+ "shared by every such task and parallel stream in the process"}
113
+ hit = next((o for o in origins if o.get("kind") in SHARED_LOOP_ENTRY and o.get("verified", True)), None)
114
+ if hit:
115
+ return {"known": True, "shared": True, "basis": f"the event loop serves the {_entry_words(hit)}"}
116
+ return {"known": False, "basis": "whether other work shares this event loop is not in the code: asked"}
117
+ return {"known": True, "basis": "a call that can wait forever holds its worker; frequency does not change that"}
118
+
119
+
120
+ def classify(sites: list[dict], max_hops: int = 3) -> tuple[list[dict], dict]:
121
+ """(candidates, counts{sites, set_aside{reason: n}, by_scenario{...}})."""
122
+ cands, aside = [], Counter()
123
+ for s in sites:
124
+ why = set_aside(s)
125
+ if why:
126
+ aside[f"{s.get('scenario')}: {why}"] += 1
127
+ continue
128
+ g = gate(s, max_hops)
129
+ cands.append({"id": s["id"], "scenario": s["scenario"], "call": s.get("call"), "runtime": s.get("runtime"),
130
+ "language": s.get("language"), "lib": s.get("lib") or "", "verb": s.get("verb") or "", "kwargs": s.get("kwargs") or {},
131
+ "dynamic": s.get("dynamic") or [], "code": s.get("code") or "", "function": s.get("function") or "",
132
+ "in_async": s.get("in_async"), "loop": s.get("loop") or "", "implicit": bool(s.get("implicit")),
133
+ "sleep_s": s.get("sleep_s"), "iterations": s.get("iterations"), "keylen": s.get("keylen"), "digest": s.get("digest"),
134
+ "via": s.get("via") or "", "service": s.get("service"), "replay": replayable(s), "gate": g, "ask": not g.get("known"),
135
+ "file": s.get("file"), "line": s.get("line"), "symbol": s.get("symbol") or ""})
136
+ counts = {"sites": len(sites), "set_aside": dict(aside.most_common()), "candidates": len(cands),
137
+ "by_scenario": dict(Counter(s.get("scenario") for s in sites)),
138
+ "candidates_by_scenario": dict(Counter(c["scenario"] for c in cands))}
139
+ return cands, counts