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.
- codecop/__init__.py +7 -0
- codecop/access.py +140 -0
- codecop/access_postgres.py +284 -0
- codecop/advisor.py +1512 -0
- codecop/advisor_bench.py +493 -0
- codecop/advisor_ch.py +2080 -0
- codecop/advisor_view.py +381 -0
- codecop/advisors.py +184 -0
- codecop/agent.py +221 -0
- codecop/agentfacts.py +745 -0
- codecop/apply/__init__.py +327 -0
- codecop/apply/check.py +344 -0
- codecop/apply/cli.py +162 -0
- codecop/apply/clickhouse.py +379 -0
- codecop/apply/common.py +238 -0
- codecop/apply/html.py +264 -0
- codecop/apply/patch.py +213 -0
- codecop/apply/postgres.py +102 -0
- codecop/apply/trial.py +166 -0
- codecop/assemble.py +104 -0
- codecop/baseline.py +1043 -0
- codecop/bench.py +2464 -0
- codecop/blockers.py +935 -0
- codecop/budget.py +980 -0
- codecop/catalog_profile.py +525 -0
- codecop/changed.py +261 -0
- codecop/cicmd.py +1002 -0
- codecop/cli.py +5421 -0
- codecop/client.py +729 -0
- codecop/coverage.py +1067 -0
- codecop/coverage_reasons.py +116 -0
- codecop/crashlog.py +70 -0
- codecop/datagen.py +766 -0
- codecop/datagen_postgres.py +630 -0
- codecop/datagen_sqlite.py +323 -0
- codecop/dbcli.py +885 -0
- codecop/definitions.py +457 -0
- codecop/discover/__init__.py +702 -0
- codecop/discover/arms.py +160 -0
- codecop/discover/base.py +234 -0
- codecop/discover/dialect.py +296 -0
- codecop/discover/elixir.py +64 -0
- codecop/discover/engine_go.py +320 -0
- codecop/discover/go.py +1947 -0
- codecop/discover/java.py +1528 -0
- codecop/discover/loops.py +1671 -0
- codecop/discover/named_go.py +258 -0
- codecop/discover/origins.py +4565 -0
- codecop/discover/origins_ts.py +1584 -0
- codecop/discover/orm_django.py +2772 -0
- codecop/discover/orm_django_models.py +814 -0
- codecop/discover/orm_django_sql.py +662 -0
- codecop/discover/orm_ent.py +565 -0
- codecop/discover/orm_ex_ecto.py +2138 -0
- codecop/discover/orm_go.py +2134 -0
- codecop/discover/orm_go_bun.py +602 -0
- codecop/discover/orm_go_run.py +636 -0
- codecop/discover/orm_go_types.py +1082 -0
- codecop/discover/orm_java.py +1450 -0
- codecop/discover/orm_jdbi.py +743 -0
- codecop/discover/orm_jooq.py +806 -0
- codecop/discover/orm_jpa.py +1307 -0
- codecop/discover/orm_mybatis.py +730 -0
- codecop/discover/orm_py.py +557 -0
- codecop/discover/orm_py_peewee.py +1266 -0
- codecop/discover/orm_py_prisma.py +298 -0
- codecop/discover/orm_rb_activerecord.py +1906 -0
- codecop/discover/orm_rust.py +1248 -0
- codecop/discover/orm_rust_seaorm.py +734 -0
- codecop/discover/orm_sqlalchemy.py +2475 -0
- codecop/discover/orm_stats.py +307 -0
- codecop/discover/orm_tables.py +29 -0
- codecop/discover/orm_ts.py +503 -0
- codecop/discover/orm_ts_drizzle.py +697 -0
- codecop/discover/orm_ts_knex.py +1117 -0
- codecop/discover/orm_ts_kysely.py +861 -0
- codecop/discover/orm_ts_prisma.py +1045 -0
- codecop/discover/orm_ts_schema.py +169 -0
- codecop/discover/orm_ts_sequelize.py +1401 -0
- codecop/discover/orm_ts_typeorm.py +1067 -0
- codecop/discover/probes.py +323 -0
- codecop/discover/python.py +595 -0
- codecop/discover/ruby.py +793 -0
- codecop/discover/rust.py +2378 -0
- codecop/discover/schema.py +520 -0
- codecop/discover/schema_ent.py +145 -0
- codecop/discover/schema_ts.py +420 -0
- codecop/discover/tsresolve.py +257 -0
- codecop/discover/typescript.py +1728 -0
- codecop/discover/xml_mapper.py +526 -0
- codecop/engines/__init__.py +515 -0
- codecop/engines/base.py +498 -0
- codecop/engines/clickhouse.py +1558 -0
- codecop/engines/pg_ddl.py +444 -0
- codecop/engines/pg_hints.py +137 -0
- codecop/engines/postgres.py +1060 -0
- codecop/engines/sqlite.py +742 -0
- codecop/families/__init__.py +3 -0
- codecop/families/build.py +280 -0
- codecop/families/cli.py +177 -0
- codecop/families/coverage_hook.py +62 -0
- codecop/families/driver.py +221 -0
- codecop/families/goslice.py +229 -0
- codecop/families/goslice_tool/go.mod +3 -0
- codecop/families/goslice_tool/main.go +403 -0
- codecop/families/holes.py +451 -0
- codecop/families/images/Dockerfile.go +5 -0
- codecop/families/images/Dockerfile.python +4 -0
- codecop/families/images/Dockerfile.rust +4 -0
- codecop/families/isolate.py +171 -0
- codecop/families/locate.py +270 -0
- codecop/families/model.py +301 -0
- codecop/families/plangate.py +271 -0
- codecop/families/tagpatch.py +174 -0
- codecop/fidelity.py +671 -0
- codecop/fixgroups.py +130 -0
- codecop/formerly.py +91 -0
- codecop/grantscript.py +254 -0
- codecop/groupbench.py +1375 -0
- codecop/groups.py +594 -0
- codecop/groups_view.py +186 -0
- codecop/heat.py +1405 -0
- codecop/heatcli.py +219 -0
- codecop/joins.py +1749 -0
- codecop/joins_view.py +127 -0
- codecop/kinds/__init__.py +507 -0
- codecop/kinds/calls/__init__.py +501 -0
- codecop/kinds/calls/extract.py +1097 -0
- codecop/kinds/calls/harness.py +408 -0
- codecop/kinds/calls/measure.py +342 -0
- codecop/kinds/calls/rules.py +139 -0
- codecop/kinds/calls/runners/RunCalls.java +167 -0
- codecop/kinds/calls/runners/run_go.go +141 -0
- codecop/kinds/calls/runners/run_node.js +186 -0
- codecop/kinds/calls/runners/run_python.py +319 -0
- codecop/kinds/calls/runners/run_rust.rs +200 -0
- codecop/kinds/calls/standin.py +340 -0
- codecop/kinds/pipeline.py +288 -0
- codecop/kinds/regex/__init__.py +1167 -0
- codecop/kinds/regex/engines/RegexHarness.java +129 -0
- codecop/kinds/regex/engines/run_go.go +294 -0
- codecop/kinds/regex/engines/run_node.js +99 -0
- codecop/kinds/regex/engines/run_python.py +295 -0
- codecop/kinds/regex/engines/run_rust.rs +149 -0
- codecop/kinds/regex/extract.py +1438 -0
- codecop/kinds/regex/harness.py +235 -0
- codecop/kinds/regex/measure.py +270 -0
- codecop/kinds/regex/shapes.py +418 -0
- codecop/kinds/regex/syntax.py +1721 -0
- codecop/kinds/testkind.py +107 -0
- codecop/kinds/transaction/__init__.py +228 -0
- codecop/kinds/transaction/bind.py +355 -0
- codecop/kinds/transaction/measure.py +264 -0
- codecop/kinds/transaction/plan.py +462 -0
- codecop/kinds/transaction/rules.py +540 -0
- codecop/kinds/transaction/sandbox.py +94 -0
- codecop/kinds/transaction/scenarios.py +520 -0
- codecop/kinds/transaction/schedule.py +483 -0
- codecop/kinds/transaction/shapes.py +418 -0
- codecop/kinds/transaction/verify.py +293 -0
- codecop/live.py +237 -0
- codecop/loopbench.py +2071 -0
- codecop/loopschema.py +591 -0
- codecop/mcpserver.py +120 -0
- codecop/mechanism.py +214 -0
- codecop/members.py +200 -0
- codecop/multi.py +443 -0
- codecop/observed.py +1868 -0
- codecop/parts.py +102 -0
- codecop/patterns.py +830 -0
- codecop/patterns_view.py +559 -0
- codecop/plangate.py +242 -0
- codecop/profile.py +439 -0
- codecop/prompts/areas.md +19 -0
- codecop/prompts/observed_variants.md +20 -0
- codecop/prompts/profile.md +60 -0
- codecop/prompts/profile_postgres.md +68 -0
- codecop/prompts/profile_sizes.md +26 -0
- codecop/prompts/profile_sqlite.md +69 -0
- codecop/prompts/rank.md +84 -0
- codecop/prompts/rank_postgres.md +96 -0
- codecop/prompts/rank_sqlite.md +94 -0
- codecop/prompts/scenario_variants.md +20 -0
- codecop/rank.py +1473 -0
- codecop/realdb/__init__.py +688 -0
- codecop/realdb/clickhouse.py +1223 -0
- codecop/realdb/facts.py +815 -0
- codecop/realdb/locality.py +964 -0
- codecop/realdb/locks.py +355 -0
- codecop/realdb/match.py +531 -0
- codecop/realdb/postgres.py +643 -0
- codecop/realdb/ratios.py +77 -0
- codecop/realdb/sample.py +126 -0
- codecop/relations.py +227 -0
- codecop/report.py +1854 -0
- codecop/resources.py +332 -0
- codecop/resources_view.py +266 -0
- codecop/rules/entry_points.toml +1013 -0
- codecop/rules/sinks.toml +362 -0
- codecop/runsonce.py +8 -0
- codecop/sandboxschema.py +555 -0
- codecop/scenario_agent.py +172 -0
- codecop/scenario_bind.py +507 -0
- codecop/scenario_sql.py +971 -0
- codecop/scenarios.py +675 -0
- codecop/scenarios_view.py +274 -0
- codecop/schemacli.py +67 -0
- codecop/schemas/areas_output.schema.json +21 -0
- codecop/schemas/profile_output.schema.json +362 -0
- codecop/schemas/rank_output.schema.json +385 -0
- codecop/sizes.py +200 -0
- codecop/sqlinfo.py +558 -0
- codecop/typedparams.py +576 -0
- codecop/verdicts.py +212 -0
- codecop/writebench.py +720 -0
- codecop/writecost.py +440 -0
- codecop/writes.py +1208 -0
- codecop-0.1.0.dist-info/METADATA +42 -0
- codecop-0.1.0.dist-info/RECORD +222 -0
- codecop-0.1.0.dist-info/WHEEL +4 -0
- codecop-0.1.0.dist-info/entry_points.txt +2 -0
- codecop-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
"""CodeCop's call harness for CPython (run in a child: `python -I run_python.py`, one JSON request on stdin, one JSON line
|
|
2
|
+
out). It replays a call shape with the library as the repository names it, against CodeCop's stand-in server; nothing of
|
|
3
|
+
the repository is imported or run.
|
|
4
|
+
|
|
5
|
+
ops:
|
|
6
|
+
version the interpreter and the libraries this interpreter has
|
|
7
|
+
client {lib, kwargs, verb, base, calls, mode: per_call|shared, cafile}
|
|
8
|
+
`calls` calls, the client built on every call (as written) or once (the fix)
|
|
9
|
+
block {call, call_ms, handlers, heartbeat_ms, mode: before|after, base, sleep_s}
|
|
10
|
+
`handlers` concurrent asyncio handlers doing the blocking call on the event loop
|
|
11
|
+
(before) or off it (after); a heartbeat task measures how late the loop runs
|
|
12
|
+
hang {call, url, timeout_s} one call against a listener that never answers; returns when the call returns
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import asyncio
|
|
16
|
+
import hashlib
|
|
17
|
+
import importlib
|
|
18
|
+
import json
|
|
19
|
+
import platform
|
|
20
|
+
import subprocess
|
|
21
|
+
import sys
|
|
22
|
+
import time
|
|
23
|
+
|
|
24
|
+
LIBS = ("requests", "httpx", "aiohttp", "redis", "urllib3", "boto3")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def out(obj):
|
|
28
|
+
sys.stdout.write(json.dumps(obj) + "\n")
|
|
29
|
+
sys.stdout.flush()
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def version():
|
|
33
|
+
libs = {}
|
|
34
|
+
for name in LIBS:
|
|
35
|
+
try:
|
|
36
|
+
m = importlib.import_module(name)
|
|
37
|
+
libs[name] = str(getattr(m, "__version__", "") or "?")
|
|
38
|
+
except Exception: # noqa: BLE001
|
|
39
|
+
pass
|
|
40
|
+
out({"python": platform.python_version(), "implementation": platform.python_implementation(), "libs": libs})
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
# --- client per call ---------------------------------------------------------------------------------------------------
|
|
44
|
+
|
|
45
|
+
def _ssl_ctx(cafile):
|
|
46
|
+
import ssl
|
|
47
|
+
return ssl.create_default_context(cafile=cafile) if cafile else None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def client(req):
|
|
51
|
+
lib, kw, verb, base, n, mode = req["lib"], dict(req.get("kwargs") or {}), req.get("verb") or "get", req["base"], int(req["calls"]), req["mode"]
|
|
52
|
+
cafile = req.get("cafile") or ""
|
|
53
|
+
h = hashlib.sha256()
|
|
54
|
+
payload = {"q": 1} if verb in ("post", "put", "patch") else None
|
|
55
|
+
t0 = time.perf_counter()
|
|
56
|
+
per = []
|
|
57
|
+
if lib in ("httpx.Client", "httpx.AsyncClient"):
|
|
58
|
+
import httpx
|
|
59
|
+
if cafile:
|
|
60
|
+
kw["verify"] = _ssl_ctx(cafile)
|
|
61
|
+
if lib == "httpx.Client":
|
|
62
|
+
def one(c, i):
|
|
63
|
+
r = c.request(verb.upper(), f"{base}/k{i}", json=payload)
|
|
64
|
+
h.update(r.content)
|
|
65
|
+
if mode == "per_call":
|
|
66
|
+
for i in range(n):
|
|
67
|
+
t = time.perf_counter()
|
|
68
|
+
with httpx.Client(**kw) as c:
|
|
69
|
+
one(c, i)
|
|
70
|
+
per.append(time.perf_counter() - t)
|
|
71
|
+
else:
|
|
72
|
+
with httpx.Client(**kw) as c:
|
|
73
|
+
for i in range(n):
|
|
74
|
+
t = time.perf_counter()
|
|
75
|
+
one(c, i)
|
|
76
|
+
per.append(time.perf_counter() - t)
|
|
77
|
+
else:
|
|
78
|
+
async def run():
|
|
79
|
+
async def one(c, i):
|
|
80
|
+
r = await c.request(verb.upper(), f"{base}/k{i}", json=payload)
|
|
81
|
+
h.update(r.content)
|
|
82
|
+
if mode == "per_call":
|
|
83
|
+
for i in range(n):
|
|
84
|
+
t = time.perf_counter()
|
|
85
|
+
async with httpx.AsyncClient(**kw) as c:
|
|
86
|
+
await one(c, i)
|
|
87
|
+
per.append(time.perf_counter() - t)
|
|
88
|
+
else:
|
|
89
|
+
async with httpx.AsyncClient(**kw) as c:
|
|
90
|
+
for i in range(n):
|
|
91
|
+
t = time.perf_counter()
|
|
92
|
+
await one(c, i)
|
|
93
|
+
per.append(time.perf_counter() - t)
|
|
94
|
+
asyncio.run(run())
|
|
95
|
+
elif lib == "aiohttp.ClientSession":
|
|
96
|
+
import aiohttp
|
|
97
|
+
|
|
98
|
+
async def run():
|
|
99
|
+
ctx = _ssl_ctx(cafile)
|
|
100
|
+
|
|
101
|
+
async def one(s, i):
|
|
102
|
+
async with s.request(verb.upper(), f"{base}/k{i}", json=payload, ssl=ctx if ctx else None) as r:
|
|
103
|
+
h.update(await r.read())
|
|
104
|
+
if mode == "per_call":
|
|
105
|
+
for i in range(n):
|
|
106
|
+
t = time.perf_counter()
|
|
107
|
+
async with aiohttp.ClientSession(**kw) as s:
|
|
108
|
+
await one(s, i)
|
|
109
|
+
per.append(time.perf_counter() - t)
|
|
110
|
+
else:
|
|
111
|
+
async with aiohttp.ClientSession(**kw) as s:
|
|
112
|
+
for i in range(n):
|
|
113
|
+
t = time.perf_counter()
|
|
114
|
+
await one(s, i)
|
|
115
|
+
per.append(time.perf_counter() - t)
|
|
116
|
+
asyncio.run(run())
|
|
117
|
+
elif lib in ("requests.Session", "requests.module"):
|
|
118
|
+
import requests
|
|
119
|
+
verify = cafile or True
|
|
120
|
+
if lib == "requests.module" and mode == "per_call":
|
|
121
|
+
for i in range(n):
|
|
122
|
+
t = time.perf_counter()
|
|
123
|
+
r = requests.request(verb.upper(), f"{base}/k{i}", json=payload, verify=verify, timeout=30)
|
|
124
|
+
h.update(r.content)
|
|
125
|
+
per.append(time.perf_counter() - t)
|
|
126
|
+
elif mode == "per_call":
|
|
127
|
+
for i in range(n):
|
|
128
|
+
t = time.perf_counter()
|
|
129
|
+
with requests.Session() as s:
|
|
130
|
+
r = s.request(verb.upper(), f"{base}/k{i}", json=payload, verify=verify, timeout=30)
|
|
131
|
+
h.update(r.content)
|
|
132
|
+
per.append(time.perf_counter() - t)
|
|
133
|
+
else:
|
|
134
|
+
with requests.Session() as s:
|
|
135
|
+
for i in range(n):
|
|
136
|
+
t = time.perf_counter()
|
|
137
|
+
r = s.request(verb.upper(), f"{base}/k{i}", json=payload, verify=verify, timeout=30)
|
|
138
|
+
h.update(r.content)
|
|
139
|
+
per.append(time.perf_counter() - t)
|
|
140
|
+
elif lib == "boto3.client":
|
|
141
|
+
# an S3 client against CodeCop's stand-in (path-style, made-up credentials): one get_object per call
|
|
142
|
+
import boto3
|
|
143
|
+
from botocore.config import Config
|
|
144
|
+
endpoint = base.split("/d/")[0]
|
|
145
|
+
kw2 = dict(endpoint_url=endpoint, region_name="us-east-1", aws_access_key_id="codecop", aws_secret_access_key="codecop",
|
|
146
|
+
verify=cafile or None, config=Config(s3={"addressing_style": "path"}, retries={"max_attempts": 1}))
|
|
147
|
+
|
|
148
|
+
def one(c, i):
|
|
149
|
+
r = c.get_object(Bucket="codecop", Key=f"k{i}")
|
|
150
|
+
h.update(r["Body"].read())
|
|
151
|
+
if mode == "per_call":
|
|
152
|
+
for i in range(n):
|
|
153
|
+
t = time.perf_counter()
|
|
154
|
+
one(boto3.client("s3", **kw2), i)
|
|
155
|
+
per.append(time.perf_counter() - t)
|
|
156
|
+
else:
|
|
157
|
+
c = boto3.client("s3", **kw2)
|
|
158
|
+
for i in range(n):
|
|
159
|
+
t = time.perf_counter()
|
|
160
|
+
one(c, i)
|
|
161
|
+
per.append(time.perf_counter() - t)
|
|
162
|
+
elif lib in ("redis.Redis", "redis.from_url"):
|
|
163
|
+
import redis
|
|
164
|
+
host, port = req["redis"]
|
|
165
|
+
kw.pop("host", None)
|
|
166
|
+
kw.pop("port", None)
|
|
167
|
+
kw.pop("url", None)
|
|
168
|
+
if mode == "per_call":
|
|
169
|
+
for i in range(n):
|
|
170
|
+
t = time.perf_counter()
|
|
171
|
+
c = redis.Redis(host=host, port=port, **kw)
|
|
172
|
+
v = c.get(f"k{i}")
|
|
173
|
+
h.update(v or b"")
|
|
174
|
+
c.close()
|
|
175
|
+
per.append(time.perf_counter() - t)
|
|
176
|
+
else:
|
|
177
|
+
c = redis.Redis(host=host, port=port, **kw)
|
|
178
|
+
for i in range(n):
|
|
179
|
+
t = time.perf_counter()
|
|
180
|
+
v = c.get(f"k{i}")
|
|
181
|
+
h.update(v or b"")
|
|
182
|
+
per.append(time.perf_counter() - t)
|
|
183
|
+
c.close()
|
|
184
|
+
else:
|
|
185
|
+
out({"error": f"no replay for {lib}"})
|
|
186
|
+
return
|
|
187
|
+
total = time.perf_counter() - t0
|
|
188
|
+
out({"ms_per_call": total * 1000 / n, "per_call_ms": [round(x * 1000, 3) for x in per], "hash": h.hexdigest()})
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
# --- blocking call in an async handler -----------------------------------------------------------------------------------
|
|
192
|
+
|
|
193
|
+
def _blocking(req):
|
|
194
|
+
"""The blocking call as a plain function, and its async counterpart for the fix when the library has one."""
|
|
195
|
+
call, ms = req["call"], float(req["call_ms"])
|
|
196
|
+
base = req.get("base") or ""
|
|
197
|
+
if call == "time.sleep":
|
|
198
|
+
s = float(req.get("sleep_s") or ms / 1000)
|
|
199
|
+
return (lambda i: (time.sleep(s), i)[1]), (lambda i: _asleep(s, i))
|
|
200
|
+
if call.startswith("requests."):
|
|
201
|
+
import requests
|
|
202
|
+
verb = call.split(".", 1)[1]
|
|
203
|
+
verb = "get" if verb in ("request",) else verb
|
|
204
|
+
return (lambda i: hashlib.sha256(requests.request(verb.upper(), f"{base}/h{i}", timeout=60).content).hexdigest()), None
|
|
205
|
+
if call.startswith("httpx."):
|
|
206
|
+
import httpx
|
|
207
|
+
verb = call.split(".", 1)[1]
|
|
208
|
+
verb = "get" if verb in ("request", "stream") else verb
|
|
209
|
+
return (lambda i: hashlib.sha256(httpx.request(verb.upper(), f"{base}/h{i}", timeout=60).content).hexdigest()), None
|
|
210
|
+
if call == "urllib.request.urlopen":
|
|
211
|
+
import urllib.request
|
|
212
|
+
return (lambda i: hashlib.sha256(urllib.request.urlopen(f"{base}/h{i}", timeout=60).read()).hexdigest()), None
|
|
213
|
+
if call.startswith("subprocess.") or call in ("os.system",):
|
|
214
|
+
# a stand-in child that takes call_ms: the repository's own command is never run
|
|
215
|
+
code = f"import time; time.sleep({ms / 1000!r}); print('done')"
|
|
216
|
+
|
|
217
|
+
def run(i):
|
|
218
|
+
r = subprocess.run([sys.executable, "-I", "-c", code], capture_output=True, text=True, timeout=120)
|
|
219
|
+
return r.stdout.strip() + str(i)
|
|
220
|
+
return run, None
|
|
221
|
+
raise ValueError(f"no replay for {call}")
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
async def _asleep(s, i):
|
|
225
|
+
await asyncio.sleep(s)
|
|
226
|
+
return i
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def block(req):
|
|
230
|
+
fn, afn = _blocking(req)
|
|
231
|
+
C, beat_ms, mode = int(req["handlers"]), float(req["heartbeat_ms"]), req["mode"]
|
|
232
|
+
use_async = bool(req.get("use_async")) and afn is not None
|
|
233
|
+
|
|
234
|
+
async def main():
|
|
235
|
+
late, stop = [], False
|
|
236
|
+
spans = []
|
|
237
|
+
t0 = time.perf_counter()
|
|
238
|
+
|
|
239
|
+
async def beat():
|
|
240
|
+
while not stop:
|
|
241
|
+
t = time.perf_counter()
|
|
242
|
+
await asyncio.sleep(beat_ms / 1000)
|
|
243
|
+
e = time.perf_counter()
|
|
244
|
+
late.append(((t - t0) * 1000, (e - t - beat_ms / 1000) * 1000))
|
|
245
|
+
|
|
246
|
+
async def handler(i):
|
|
247
|
+
s = time.perf_counter()
|
|
248
|
+
if mode == "before":
|
|
249
|
+
v = fn(i)
|
|
250
|
+
elif use_async:
|
|
251
|
+
v = await afn(i)
|
|
252
|
+
else:
|
|
253
|
+
v = await asyncio.to_thread(fn, i)
|
|
254
|
+
spans.append([i, round((s - t0) * 1000, 2), round((time.perf_counter() - t0) * 1000, 2)])
|
|
255
|
+
return v
|
|
256
|
+
b = asyncio.create_task(beat())
|
|
257
|
+
await asyncio.sleep(max(0.02, 4 * beat_ms / 1000))
|
|
258
|
+
ts = time.perf_counter()
|
|
259
|
+
outs = await asyncio.gather(*[handler(i) for i in range(C)])
|
|
260
|
+
wall = (time.perf_counter() - ts) * 1000
|
|
261
|
+
await asyncio.sleep(max(0.02, 4 * beat_ms / 1000))
|
|
262
|
+
stop = True
|
|
263
|
+
await b
|
|
264
|
+
stalls = [x for x in late if x[1] > 2 * beat_ms]
|
|
265
|
+
return {"wall_ms": wall, "stall_ms": max((x[1] for x in late), default=0.0), "beats": len(late),
|
|
266
|
+
"stalls": [[round(a, 1), round(b_, 1)] for a, b_ in stalls[:64]], "spans": sorted(spans)[:64],
|
|
267
|
+
"start_ms": round((ts - t0) * 1000, 2), "hash": hashlib.sha256(repr(outs).encode()).hexdigest()}
|
|
268
|
+
out(asyncio.run(main()))
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
# --- no timeout ----------------------------------------------------------------------------------------------------------
|
|
272
|
+
|
|
273
|
+
def hang(req):
|
|
274
|
+
call, url, timeout = req["call"], req["url"], req.get("timeout_s")
|
|
275
|
+
t = time.perf_counter()
|
|
276
|
+
err = ""
|
|
277
|
+
try:
|
|
278
|
+
if call.startswith("requests."):
|
|
279
|
+
import requests
|
|
280
|
+
verb = call.split(".", 1)[1]
|
|
281
|
+
verb = "get" if verb in ("request", "session") else verb
|
|
282
|
+
kw = {"timeout": timeout} if timeout else {}
|
|
283
|
+
requests.request(verb.upper(), url, **kw)
|
|
284
|
+
elif call == "urllib.request.urlopen":
|
|
285
|
+
import urllib.request
|
|
286
|
+
if timeout:
|
|
287
|
+
urllib.request.urlopen(url, timeout=timeout).read()
|
|
288
|
+
else:
|
|
289
|
+
urllib.request.urlopen(url).read()
|
|
290
|
+
elif call.startswith("httpx."):
|
|
291
|
+
import httpx
|
|
292
|
+
kw = {"timeout": timeout} if timeout else {}
|
|
293
|
+
httpx.get(url, **kw)
|
|
294
|
+
else:
|
|
295
|
+
out({"error": f"no replay for {call}"})
|
|
296
|
+
return
|
|
297
|
+
err = "returned"
|
|
298
|
+
except Exception as e: # noqa: BLE001
|
|
299
|
+
err = type(e).__name__
|
|
300
|
+
out({"returned": True, "seconds": time.perf_counter() - t, "error": err})
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def main():
|
|
304
|
+
req = json.loads(sys.stdin.read() or "{}")
|
|
305
|
+
op = req.get("op")
|
|
306
|
+
if op == "version":
|
|
307
|
+
version()
|
|
308
|
+
elif op == "client":
|
|
309
|
+
client(req)
|
|
310
|
+
elif op == "block":
|
|
311
|
+
block(req)
|
|
312
|
+
elif op == "hang":
|
|
313
|
+
hang(req)
|
|
314
|
+
else:
|
|
315
|
+
out({"error": f"unknown op {op}"})
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
if __name__ == "__main__":
|
|
319
|
+
main()
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
// CodeCop's call harness for Rust (built once into CodeCop's cache, offline, with crates from the local cargo cache: reqwest
|
|
2
|
+
// with rustls, tokio, redis, serde_json). One JSON request on stdin, one JSON line out. The call shape is replayed
|
|
3
|
+
// against CodeCop's stand-in server; nothing of the repository is compiled or run.
|
|
4
|
+
//
|
|
5
|
+
// ops:
|
|
6
|
+
// version
|
|
7
|
+
// client {lib: reqwest|redis, base, calls, mode: per_call|shared, cafile, redis: [host, port]}
|
|
8
|
+
// block {call: thread_sleep|command_output, call_ms, handlers, heartbeat_ms, workers, mode: before|after}
|
|
9
|
+
// `handlers` tokio tasks on a runtime of `workers` threads, the blocking call on a worker (before) or in
|
|
10
|
+
// spawn_blocking / its async form (after); a heartbeat task measures how late the runtime runs
|
|
11
|
+
// hang {url, timeout_ms} one reqwest call against a listener that never answers
|
|
12
|
+
use serde_json::{json, Value};
|
|
13
|
+
use std::io::Read;
|
|
14
|
+
use std::sync::{Arc, Mutex};
|
|
15
|
+
use std::time::{Duration, Instant};
|
|
16
|
+
|
|
17
|
+
fn ms(d: Duration) -> f64 {
|
|
18
|
+
d.as_secs_f64() * 1000.0
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
fn client_builder(cafile: &str) -> reqwest::ClientBuilder {
|
|
22
|
+
let mut b = reqwest::Client::builder();
|
|
23
|
+
if !cafile.is_empty() {
|
|
24
|
+
if let Ok(pem) = std::fs::read(cafile) {
|
|
25
|
+
if let Ok(c) = reqwest::Certificate::from_pem(&pem) {
|
|
26
|
+
b = b.add_root_certificate(c);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
b
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
fn hash(acc: &mut u64, bytes: &[u8]) {
|
|
34
|
+
for b in bytes {
|
|
35
|
+
*acc = acc.wrapping_mul(1099511628211).wrapping_add(*b as u64);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async fn client(r: &Value) -> Value {
|
|
40
|
+
let n = r["calls"].as_u64().unwrap_or(10) as usize;
|
|
41
|
+
let mode = r["mode"].as_str().unwrap_or("per_call").to_string();
|
|
42
|
+
let lib = r["lib"].as_str().unwrap_or("reqwest").to_string();
|
|
43
|
+
let base = r["base"].as_str().unwrap_or("").to_string();
|
|
44
|
+
let cafile = r["cafile"].as_str().unwrap_or("").to_string();
|
|
45
|
+
let mut h: u64 = 1469598103934665603;
|
|
46
|
+
let mut per = vec![];
|
|
47
|
+
let t0 = Instant::now();
|
|
48
|
+
if lib == "redis" {
|
|
49
|
+
let host = r["redis"][0].as_str().unwrap_or("127.0.0.1").to_string();
|
|
50
|
+
let port = r["redis"][1].as_u64().unwrap_or(6379);
|
|
51
|
+
let url = format!("redis://{}:{}/", host, port);
|
|
52
|
+
let res = tokio::task::spawn_blocking(move || {
|
|
53
|
+
let mut per = vec![];
|
|
54
|
+
let mut h: u64 = 1469598103934665603;
|
|
55
|
+
let shared = if mode == "shared" { Some(redis::Client::open(url.as_str()).unwrap().get_connection().unwrap()) } else { None };
|
|
56
|
+
let mut shared = shared;
|
|
57
|
+
for i in 0..n {
|
|
58
|
+
let t = Instant::now();
|
|
59
|
+
let v: Option<Vec<u8>> = match shared.as_mut() {
|
|
60
|
+
Some(c) => redis::cmd("GET").arg(format!("k{}", i)).query(c).ok(),
|
|
61
|
+
None => {
|
|
62
|
+
let mut c = redis::Client::open(url.as_str()).unwrap().get_connection().unwrap();
|
|
63
|
+
redis::cmd("GET").arg(format!("k{}", i)).query(&mut c).ok()
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
hash(&mut h, &v.unwrap_or_default());
|
|
67
|
+
per.push(ms(t.elapsed()));
|
|
68
|
+
}
|
|
69
|
+
(per, h)
|
|
70
|
+
})
|
|
71
|
+
.await
|
|
72
|
+
.unwrap();
|
|
73
|
+
per = res.0;
|
|
74
|
+
h = res.1;
|
|
75
|
+
} else {
|
|
76
|
+
let shared = if mode == "shared" { Some(client_builder(&cafile).build().unwrap()) } else { None };
|
|
77
|
+
for i in 0..n {
|
|
78
|
+
let t = Instant::now();
|
|
79
|
+
let c = match &shared {
|
|
80
|
+
Some(c) => c.clone(),
|
|
81
|
+
None => client_builder(&cafile).build().unwrap(),
|
|
82
|
+
};
|
|
83
|
+
match c.get(format!("{}/k{}", base, i)).send().await {
|
|
84
|
+
Ok(resp) => {
|
|
85
|
+
let b = resp.bytes().await.unwrap_or_default();
|
|
86
|
+
hash(&mut h, &b);
|
|
87
|
+
}
|
|
88
|
+
Err(e) => return json!({"error": e.to_string()}),
|
|
89
|
+
}
|
|
90
|
+
drop(c);
|
|
91
|
+
per.push(ms(t.elapsed()));
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
json!({"ms_per_call": ms(t0.elapsed()) / n as f64, "per_call_ms": per, "hash": format!("{:x}", h)})
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
fn block(r: &Value) -> Value {
|
|
98
|
+
let call = r["call"].as_str().unwrap_or("thread_sleep").to_string();
|
|
99
|
+
let call_ms = r["call_ms"].as_f64().unwrap_or(50.0);
|
|
100
|
+
let handlers = r["handlers"].as_u64().unwrap_or(20) as usize;
|
|
101
|
+
let beat = r["heartbeat_ms"].as_f64().unwrap_or(5.0);
|
|
102
|
+
let workers = r["workers"].as_u64().unwrap_or(4) as usize;
|
|
103
|
+
let before = r["mode"].as_str().unwrap_or("before") == "before";
|
|
104
|
+
let rt = tokio::runtime::Builder::new_multi_thread().worker_threads(workers).enable_all().build().unwrap();
|
|
105
|
+
rt.block_on(async move {
|
|
106
|
+
let t0 = Instant::now();
|
|
107
|
+
let late = Arc::new(Mutex::new(Vec::<(f64, f64)>::new()));
|
|
108
|
+
let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
|
109
|
+
let (l2, s2) = (late.clone(), stop.clone());
|
|
110
|
+
let hb = tokio::spawn(async move {
|
|
111
|
+
while !s2.load(std::sync::atomic::Ordering::Relaxed) {
|
|
112
|
+
let t = Instant::now();
|
|
113
|
+
tokio::time::sleep(Duration::from_micros((beat * 1000.0) as u64)).await;
|
|
114
|
+
l2.lock().unwrap().push((ms(t - t0), ms(t.elapsed()) - beat));
|
|
115
|
+
}
|
|
116
|
+
});
|
|
117
|
+
tokio::time::sleep(Duration::from_millis((4.0 * beat).max(20.0) as u64)).await;
|
|
118
|
+
let ts = Instant::now();
|
|
119
|
+
let mut tasks = vec![];
|
|
120
|
+
for i in 0..handlers {
|
|
121
|
+
let call = call.clone();
|
|
122
|
+
tasks.push(tokio::spawn(async move {
|
|
123
|
+
let s = Instant::now();
|
|
124
|
+
let out: String = if before {
|
|
125
|
+
run_blocking(&call, call_ms)
|
|
126
|
+
} else if call == "thread_sleep" {
|
|
127
|
+
tokio::time::sleep(Duration::from_micros((call_ms * 1000.0) as u64)).await;
|
|
128
|
+
"slept".to_string()
|
|
129
|
+
} else {
|
|
130
|
+
let c = call.clone();
|
|
131
|
+
tokio::task::spawn_blocking(move || run_blocking(&c, call_ms)).await.unwrap()
|
|
132
|
+
};
|
|
133
|
+
(i, ms(s - t0), ms(s.elapsed()) + ms(s - t0), out)
|
|
134
|
+
}));
|
|
135
|
+
}
|
|
136
|
+
let mut spans = vec![];
|
|
137
|
+
let mut outs = vec![];
|
|
138
|
+
for t in tasks {
|
|
139
|
+
let (i, a, b, o) = t.await.unwrap();
|
|
140
|
+
spans.push(json!([i, (a * 100.0).round() / 100.0, (b * 100.0).round() / 100.0]));
|
|
141
|
+
outs.push(o);
|
|
142
|
+
}
|
|
143
|
+
let wall = ms(ts.elapsed());
|
|
144
|
+
tokio::time::sleep(Duration::from_millis((4.0 * beat).max(20.0) as u64)).await;
|
|
145
|
+
stop.store(true, std::sync::atomic::Ordering::Relaxed);
|
|
146
|
+
let _ = hb.await;
|
|
147
|
+
let late = late.lock().unwrap().clone();
|
|
148
|
+
let stall = late.iter().map(|x| x.1).fold(0.0, f64::max);
|
|
149
|
+
let stalls: Vec<Value> = late.iter().filter(|x| x.1 > 2.0 * beat).take(64).map(|x| json!([x.0, x.1])).collect();
|
|
150
|
+
let mut h: u64 = 1469598103934665603;
|
|
151
|
+
for o in &outs {
|
|
152
|
+
hash(&mut h, o.as_bytes());
|
|
153
|
+
}
|
|
154
|
+
json!({"wall_ms": wall, "stall_ms": stall, "beats": late.len(), "stalls": stalls, "spans": spans,
|
|
155
|
+
"start_ms": ms(ts - t0), "hash": format!("{:x}", h)})
|
|
156
|
+
})
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
fn run_blocking(call: &str, call_ms: f64) -> String {
|
|
160
|
+
if call == "command_output" {
|
|
161
|
+
// a stand-in child that takes call_ms: the repository's own command is never run
|
|
162
|
+
let o = std::process::Command::new("sleep").arg(format!("{}", call_ms / 1000.0)).output();
|
|
163
|
+
return format!("{}", o.map(|o| o.status.success()).unwrap_or(false));
|
|
164
|
+
}
|
|
165
|
+
std::thread::sleep(Duration::from_micros((call_ms * 1000.0) as u64));
|
|
166
|
+
"slept".to_string()
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
async fn hang(r: &Value) -> Value {
|
|
170
|
+
let url = r["url"].as_str().unwrap_or("").to_string();
|
|
171
|
+
let to = r["timeout_ms"].as_f64().unwrap_or(0.0);
|
|
172
|
+
let mut b = reqwest::Client::builder();
|
|
173
|
+
if to > 0.0 {
|
|
174
|
+
b = b.timeout(Duration::from_millis(to as u64));
|
|
175
|
+
}
|
|
176
|
+
let c = b.build().unwrap();
|
|
177
|
+
let t = Instant::now();
|
|
178
|
+
let err = match c.get(&url).send().await {
|
|
179
|
+
Ok(_) => "returned".to_string(),
|
|
180
|
+
Err(e) => if e.is_timeout() { "timeout".to_string() } else { "error".to_string() },
|
|
181
|
+
};
|
|
182
|
+
json!({"returned": true, "seconds": t.elapsed().as_secs_f64(), "error": err})
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
fn main() {
|
|
186
|
+
let mut s = String::new();
|
|
187
|
+
std::io::stdin().read_to_string(&mut s).unwrap();
|
|
188
|
+
let r: Value = serde_json::from_str(&s).unwrap_or(json!({}));
|
|
189
|
+
let op = r["op"].as_str().unwrap_or("");
|
|
190
|
+
let out = match op {
|
|
191
|
+
"version" => json!({"rust": env!("CARGO_PKG_VERSION"), "reqwest": "0.12"}),
|
|
192
|
+
"block" => block(&r),
|
|
193
|
+
"client" | "hang" => {
|
|
194
|
+
let rt = tokio::runtime::Builder::new_multi_thread().worker_threads(2).enable_all().build().unwrap();
|
|
195
|
+
rt.block_on(async { if op == "client" { client(&r).await } else { hang(&r).await } })
|
|
196
|
+
}
|
|
197
|
+
_ => json!({"error": format!("unknown op {}", op)}),
|
|
198
|
+
};
|
|
199
|
+
println!("{}", out);
|
|
200
|
+
}
|