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,501 @@
|
|
|
1
|
+
"""The calls kind: outbound calls that waste time or can hang, proven by replaying the call shape in CodeCop's own harness
|
|
2
|
+
against a stand-in server CodeCop starts on loopback. docs/kinds.md is the contract; this package:
|
|
3
|
+
|
|
4
|
+
extract.py discovery per language (Python ast, TypeScript/JavaScript and Go tree-sitter): the call shape and facts
|
|
5
|
+
rules.py what is set aside and why; for each candidate the gate its verdict needs (repeats / shares its loop)
|
|
6
|
+
standin.py the stand-in upstream: HTTP(S) with a simulated round trip, a listener that never answers, RESP
|
|
7
|
+
harness.py the runtimes (CPython with the repository's HTTP library, Node, Go) and the call into each runner
|
|
8
|
+
measure.py the measurements (counts the stand-in keeps, event-loop stalls, the deadline) and the verdicts
|
|
9
|
+
runners/ run_python.py, run_node.js, run_go.go: CodeCop's own small programs, one JSON request each
|
|
10
|
+
|
|
11
|
+
Three scenarios: `client_per_call` (speed), `blocking_in_async` (speed), `no_timeout` (harm: correctness: a call that can
|
|
12
|
+
wait forever holds its worker). Nothing of the repository is executed: only the call's library, verb and literal
|
|
13
|
+
arguments are replayed, never its URLs, credentials or commands.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import json
|
|
19
|
+
import re
|
|
20
|
+
import threading
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
|
|
23
|
+
from .. import Kind, finding, handoff_text, measure as kmeasure, outcome, proof, register, sameness
|
|
24
|
+
from . import extract, measure as M, rules
|
|
25
|
+
from .harness import Unavailable
|
|
26
|
+
|
|
27
|
+
PROMPT_VERSION = "calls-1"
|
|
28
|
+
SCENARIOS = ("client_per_call", "blocking_in_async", "no_timeout")
|
|
29
|
+
ANSWER_SCHEMA = {"type": "object", "properties": {"answers": {"type": "array", "items": {"type": "object", "properties": {
|
|
30
|
+
"id": {"type": "string"},
|
|
31
|
+
"answer": {"type": ["boolean", "null"], "description": "client_per_call: true if the function runs many times while the process "
|
|
32
|
+
"lives; blocking_in_async: true if other work runs on the same event loop while the call waits; null if you cannot tell"},
|
|
33
|
+
"evidence": {"type": ["string", "null"], "description": "path:line of the caller, loop, route, scheduler or entry point that shows it"},
|
|
34
|
+
"why": {"type": ["string", "null"]}}, "required": ["id", "answer"]}}}, "required": ["answers"]}
|
|
35
|
+
RUNTIME_WORDS = {"python": "CPython", "node": "Node", "go": "Go", "rust": "Rust (cargo)", "java": "a JDK"}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@register
|
|
39
|
+
class Calls(Kind):
|
|
40
|
+
name = "calls"
|
|
41
|
+
label = "Outbound calls"
|
|
42
|
+
one = "outbound call"
|
|
43
|
+
prefix = "C"
|
|
44
|
+
items_per_call = 6
|
|
45
|
+
cost_per_item_usd = (0.03, 0.08)
|
|
46
|
+
harm_words = {"correctness": "can hang: no timeout"}
|
|
47
|
+
doctor_word = "runtime"
|
|
48
|
+
doctor_missing = "its call sites are reported as could not be judged: runtime not available"
|
|
49
|
+
reasons = {
|
|
50
|
+
"calls.already_shared": ("nothing_to_gain", "already shares its connections (measured)"),
|
|
51
|
+
"calls.runs_once": ("nothing_to_gain", "runs once per process (cited)"),
|
|
52
|
+
"calls.loop_not_shared": ("nothing_to_gain", "nothing else runs on its event loop (cited)"),
|
|
53
|
+
"calls.has_default_timeout": ("nothing_to_gain", "returns by itself before the deadline (a library default)"),
|
|
54
|
+
"calls.runtime_not_available": ("not_judged", "runtime not available"),
|
|
55
|
+
"calls.no_stand_in": ("not_judged", "no stand-in for this library or protocol yet"),
|
|
56
|
+
}
|
|
57
|
+
measures = {"connections_opened": ("connections opened", "count"), "tls_handshakes": ("TLS handshakes", "count"),
|
|
58
|
+
"time_per_call": ("time per call at the stated round trip", "ms"), "time_per_call_loopback": ("time per call on loopback", "ms"),
|
|
59
|
+
"loop_stall_ms": ("longest event-loop stall", "ms"), "handlers_wall_ms": ("time for the concurrent handlers", "ms"),
|
|
60
|
+
"returned_by_deadline": ("returned by the deadline", "runs"), "seconds_until_return": ("seconds until the call returned", "s")}
|
|
61
|
+
|
|
62
|
+
def __init__(self):
|
|
63
|
+
self._lock = threading.Lock()
|
|
64
|
+
self._memo: dict = {}
|
|
65
|
+
|
|
66
|
+
# --- discover --------------------------------------------------------------------------------------------------------
|
|
67
|
+
def discover(self, ctx):
|
|
68
|
+
st = M.settings_of(ctx.settings)
|
|
69
|
+
out = extract.sites(ctx.root, ctx.by_lang, log=ctx.say)
|
|
70
|
+
if len(out) > int(st["max_sites"]):
|
|
71
|
+
ctx.say(f"calls: kept the first {st['max_sites']} of {len(out)} sites (setting max_sites)")
|
|
72
|
+
out = out[: int(st["max_sites"])]
|
|
73
|
+
return out
|
|
74
|
+
|
|
75
|
+
# --- rules -----------------------------------------------------------------------------------------------------------
|
|
76
|
+
def rules(self, ctx, sites):
|
|
77
|
+
cands, counts = rules.classify(sites, int(M.settings_of(ctx.settings)["max_loop_hops"]))
|
|
78
|
+
for c in cands:
|
|
79
|
+
c["shape"] = rules.REPLAY_CLIENT.get((c["runtime"], c["call"]), c["call"])
|
|
80
|
+
self._save(ctx, "calls-rules.json", counts)
|
|
81
|
+
return cands
|
|
82
|
+
|
|
83
|
+
# --- measurement -----------------------------------------------------------------------------------------------------
|
|
84
|
+
def _measurer(self, ctx) -> M.Measurer:
|
|
85
|
+
with self._lock:
|
|
86
|
+
k = ("m", str(ctx.out_dir))
|
|
87
|
+
if k not in self._memo:
|
|
88
|
+
self._memo[k] = M.Measurer(ctx.settings, Path(ctx.root), Path(ctx.out_dir))
|
|
89
|
+
return self._memo[k]
|
|
90
|
+
|
|
91
|
+
def judge(self, ctx, c) -> dict:
|
|
92
|
+
"""The measurement and the measured verdict of one candidate (memoised): {verdict, m} or {error, why}."""
|
|
93
|
+
mk = ("j", str(ctx.out_dir), c["id"])
|
|
94
|
+
with self._lock:
|
|
95
|
+
if mk in self._memo:
|
|
96
|
+
return self._memo[mk]
|
|
97
|
+
if not c.get("replay"):
|
|
98
|
+
j = {"error": "no_stand_in"}
|
|
99
|
+
else:
|
|
100
|
+
ms = self._measurer(ctx)
|
|
101
|
+
try:
|
|
102
|
+
if c["scenario"] == "client_per_call":
|
|
103
|
+
m = ms.client(c)
|
|
104
|
+
j = {"m": m, "verdict": M.client_verdict(m, float(ms.st["min_gain"]))}
|
|
105
|
+
elif c["scenario"] == "blocking_in_async":
|
|
106
|
+
m = ms.block(c)
|
|
107
|
+
j = {"m": m, "verdict": M.block_verdict(m)}
|
|
108
|
+
else:
|
|
109
|
+
m = ms.hang(c)
|
|
110
|
+
j = {"m": m, "verdict": M.hang_verdict(m)}
|
|
111
|
+
except Unavailable as e:
|
|
112
|
+
j = {"error": "runtime", "why": str(e)[:200]}
|
|
113
|
+
except Exception as e: # noqa: BLE001 -- one shape must not lose the others
|
|
114
|
+
ctx.say(f"calls {c.get('file')}:{c.get('line')}: could not be measured ({type(e).__name__}: {str(e)[:120]})")
|
|
115
|
+
j = {"error": "harness", "why": f"{type(e).__name__}: {str(e)[:160]}"}
|
|
116
|
+
with self._lock:
|
|
117
|
+
self._memo[mk] = j
|
|
118
|
+
return j
|
|
119
|
+
|
|
120
|
+
# --- the agent -------------------------------------------------------------------------------------------------------
|
|
121
|
+
def _key(self, ctx, c):
|
|
122
|
+
return ctx.answer_key(f"{c['scenario']}|{c.get('file')}|{c.get('symbol')}|{c.get('code')}", runtime=c.get("runtime") or "",
|
|
123
|
+
prompt_version=PROMPT_VERSION)
|
|
124
|
+
|
|
125
|
+
def _wants_agent(self, ctx, c) -> bool:
|
|
126
|
+
if not c.get("ask") or ctx.answer(self._key(ctx, c)) is not None:
|
|
127
|
+
return False
|
|
128
|
+
return self.judge(ctx, c).get("verdict") == "gain"
|
|
129
|
+
|
|
130
|
+
def questions(self, ctx, cands):
|
|
131
|
+
out = []
|
|
132
|
+
for c in cands:
|
|
133
|
+
if not self._wants_agent(ctx, c):
|
|
134
|
+
continue
|
|
135
|
+
out.append(ctx.item(c["id"], label=f"{c['call']} in {c.get('function') or c.get('symbol') or '?'}", file=c.get("file", ""),
|
|
136
|
+
line=c.get("line") or 0, score=2.0 if c["scenario"] == "blocking_in_async" else 1.0,
|
|
137
|
+
why="measured gain; " + (c.get("gate") or {}).get("basis", "")))
|
|
138
|
+
return out
|
|
139
|
+
|
|
140
|
+
def ask(self, ctx, cands, runner):
|
|
141
|
+
todo = [c for c in cands if self._wants_agent(ctx, c)]
|
|
142
|
+
per = max(1, int(self.items_per_call))
|
|
143
|
+
for i in range(0, len(todo), per):
|
|
144
|
+
part = todo[i:i + per]
|
|
145
|
+
result = runner.run(prompt_for(part), ANSWER_SCHEMA, ctx.root)
|
|
146
|
+
answers = (getattr(result, "output", None) or {}).get("answers") or []
|
|
147
|
+
by = {str(a.get("id")): a for a in answers if isinstance(a, dict)}
|
|
148
|
+
for c in part:
|
|
149
|
+
a = by.get(c["id"])
|
|
150
|
+
if a is not None:
|
|
151
|
+
ctx.remember(self._key(ctx, c), {"answer": a.get("answer"), "evidence": a.get("evidence"), "why": (a.get("why") or "")[:300]})
|
|
152
|
+
|
|
153
|
+
def _cited(self, ctx, ev) -> str:
|
|
154
|
+
"""The agent's `path:line` when that line exists in the repository, else ''."""
|
|
155
|
+
m = re.match(r"^\s*([^\s:]+):(\d+)", str(ev or ""))
|
|
156
|
+
if not m:
|
|
157
|
+
return ""
|
|
158
|
+
try:
|
|
159
|
+
p = (Path(ctx.root) / m.group(1)).resolve()
|
|
160
|
+
if Path(ctx.root).resolve() not in p.parents:
|
|
161
|
+
return ""
|
|
162
|
+
n = len(p.read_text(errors="replace").splitlines())
|
|
163
|
+
except (OSError, ValueError):
|
|
164
|
+
return ""
|
|
165
|
+
return f"{m.group(1)}:{m.group(2)}" if 1 <= int(m.group(2)) <= n else ""
|
|
166
|
+
|
|
167
|
+
# --- verify ----------------------------------------------------------------------------------------------------------
|
|
168
|
+
def verify(self, ctx, cands):
|
|
169
|
+
out = []
|
|
170
|
+
try:
|
|
171
|
+
for c in cands:
|
|
172
|
+
out.append(self._finding(ctx, c))
|
|
173
|
+
finally:
|
|
174
|
+
with self._lock:
|
|
175
|
+
m = self._memo.pop(("m", str(ctx.out_dir)), None)
|
|
176
|
+
if m is not None:
|
|
177
|
+
m.close()
|
|
178
|
+
return out
|
|
179
|
+
|
|
180
|
+
def _finding(self, ctx, c) -> dict:
|
|
181
|
+
sc = c["scenario"]
|
|
182
|
+
j = self.judge(ctx, c)
|
|
183
|
+
site = {"file": c.get("file"), "line": c.get("line"), "symbol": c.get("symbol") or ""}
|
|
184
|
+
harm = "correctness" if sc == "no_timeout" else "speed"
|
|
185
|
+
info = {"scenario": sc, "call": c["call"], "runtime": c.get("runtime"), "code": c.get("code"), "function": c.get("function"),
|
|
186
|
+
"gate": c.get("gate") or {}}
|
|
187
|
+
title = self._title(c)
|
|
188
|
+
if j.get("error") == "no_stand_in":
|
|
189
|
+
o = outcome(self.name, "not_judged", "calls.no_stand_in", source="claimed", evidence={"library": c.get("lib") or c["call"]},
|
|
190
|
+
next_step="replay this library's protocol on a stand-in")
|
|
191
|
+
return finding(self.name, id=c["id"], title=title, site=site, outcome=o, harm=harm, severity="low", confidence="low",
|
|
192
|
+
summary=f"{c['call']}: CodeCop has no stand-in for this library yet; nothing measured", extra={"calls": info})
|
|
193
|
+
if j.get("error") == "runtime":
|
|
194
|
+
o = outcome(self.name, "not_judged", "calls.runtime_not_available", source="claimed",
|
|
195
|
+
evidence={"runtime": c.get("runtime")}, next_step=f"install {RUNTIME_WORDS.get(c.get('runtime'), c.get('runtime'))}")
|
|
196
|
+
return finding(self.name, id=c["id"], title=title, site=site, outcome=o, harm=harm, severity="low", confidence="low",
|
|
197
|
+
summary=f"could not be judged: runtime not available ({j.get('why')})"[:300], extra={"calls": info})
|
|
198
|
+
if j.get("error"):
|
|
199
|
+
o = outcome(self.name, "not_judged", "sandbox_could_not_run", evidence={"error": (j.get("why") or "")[:80]})
|
|
200
|
+
return finding(self.name, id=c["id"], title=title, site=site, outcome=o, harm=harm, severity="low", confidence="low",
|
|
201
|
+
summary=(j.get("why") or "")[:300], extra={"calls": info})
|
|
202
|
+
m, verdict = j["m"], j["verdict"]
|
|
203
|
+
pr, fix, panel = {"client_per_call": self._client_proof, "blocking_in_async": self._block_proof,
|
|
204
|
+
"no_timeout": self._hang_proof}[sc](ctx, c, m)
|
|
205
|
+
info.update(panel)
|
|
206
|
+
o = self._outcome(ctx, c, m, verdict, info)
|
|
207
|
+
state = o["state"]
|
|
208
|
+
sev = "high" if state == "fixed" and (sc != "client_per_call" or (info.get("per_call") or {}).get("saved_ms", 0) >= 20) else \
|
|
209
|
+
"medium" if state == "fixed" else "low"
|
|
210
|
+
return finding(self.name, id=c["id"], title=title, site=site, outcome=o, proof=pr, harm=harm, severity=sev,
|
|
211
|
+
confidence="high" if state in ("fixed", "nothing_to_gain") else "medium",
|
|
212
|
+
summary=self._summary(c, m, o, info), fix=fix if verdict == "gain" else None, extra={"calls": info})
|
|
213
|
+
|
|
214
|
+
@staticmethod
|
|
215
|
+
def _title(c) -> str:
|
|
216
|
+
fn = c.get("function") or c.get("symbol") or "a function"
|
|
217
|
+
if c["scenario"] == "client_per_call":
|
|
218
|
+
if c.get("implicit"):
|
|
219
|
+
return f"{c['call']} in a loop: a new session and connection per item ({fn})"
|
|
220
|
+
return f"{c['call']} built on every call of {fn}"
|
|
221
|
+
if c["scenario"] == "blocking_in_async":
|
|
222
|
+
return f"{c['call']} blocks the event loop inside async {fn}"
|
|
223
|
+
return f"{c['call']} without a timeout in {fn}"
|
|
224
|
+
|
|
225
|
+
def _outcome(self, ctx, c, m, verdict, info) -> dict:
|
|
226
|
+
sc = c["scenario"]
|
|
227
|
+
if verdict == "differs":
|
|
228
|
+
return outcome(self.name, "blocked", "fix_results_differ")
|
|
229
|
+
if verdict == "shared":
|
|
230
|
+
r = m.get("rtt") or {}
|
|
231
|
+
return outcome(self.name, "nothing_to_gain", "calls.already_shared",
|
|
232
|
+
evidence={"connections_before": (r.get("before") or {}).get("connections"),
|
|
233
|
+
"connections_after": (r.get("after") or {}).get("connections")})
|
|
234
|
+
if verdict == "has_default":
|
|
235
|
+
return outcome(self.name, "nothing_to_gain", "calls.has_default_timeout", evidence={"seconds": (m.get("before") or {}).get("seconds")})
|
|
236
|
+
if verdict != "gain":
|
|
237
|
+
return outcome(self.name, "blocked", "no_gain_measured", next_step="measure another fix")
|
|
238
|
+
g = c.get("gate") or {}
|
|
239
|
+
if sc == "no_timeout" or g.get("known"):
|
|
240
|
+
info["gate"] = {**g, "by": "code"}
|
|
241
|
+
return outcome(self.name, "fixed", "verified", evidence={"gate": g.get("basis", "")[:120]})
|
|
242
|
+
ans = ctx.answer(self._key(ctx, c))
|
|
243
|
+
if ans is None:
|
|
244
|
+
return outcome(self.name, "not_judged", "not_asked", evidence={"measured": "gain"}, next_step="ask_agent_about_calls")
|
|
245
|
+
cited = self._cited(ctx, ans.get("evidence"))
|
|
246
|
+
if ans.get("answer") is None or not cited:
|
|
247
|
+
info["gate"] = {**g, "by": "agent", "answer": None, "why": (ans.get("why") or "")[:200]}
|
|
248
|
+
return outcome(self.name, "not_judged", "agent_no_answer", source="claimed",
|
|
249
|
+
evidence={"measured": "gain", "cited": bool(cited)}, next_step="ask_agent_about_calls")
|
|
250
|
+
info["gate"] = {"known": True, "by": "agent", "answer": bool(ans["answer"]), "evidence": cited, "why": (ans.get("why") or "")[:200],
|
|
251
|
+
"basis": f"agent, citing {cited}"}
|
|
252
|
+
if ans["answer"]:
|
|
253
|
+
return outcome(self.name, "fixed", "verified", evidence={"gate": f"agent: {cited}"})
|
|
254
|
+
code = "calls.runs_once" if sc == "client_per_call" else "calls.loop_not_shared"
|
|
255
|
+
return outcome(self.name, "nothing_to_gain", code, source="claimed", evidence={"cited": cited})
|
|
256
|
+
|
|
257
|
+
# --- proofs ------------------------------------------------------------------------------------------------------------
|
|
258
|
+
def _client_proof(self, ctx, c, m):
|
|
259
|
+
r, lb = m.get("rtt") or {}, m.get("loopback") or {}
|
|
260
|
+
b, a = r.get("before") or {}, r.get("after") or {}
|
|
261
|
+
n = m.get("calls")
|
|
262
|
+
ms = [kmeasure("connections_opened", "count", b.get("connections"), a.get("connections"), of=n, runs=b.get("runs")),
|
|
263
|
+
kmeasure("time_per_call", "ms", b.get("ms"), a.get("ms"), spread_before=b.get("spread"), spread_after=a.get("spread"), runs=b.get("runs"))]
|
|
264
|
+
if m.get("tls"):
|
|
265
|
+
ms.insert(1, kmeasure("tls_handshakes", "count", b.get("tls_handshakes"), a.get("tls_handshakes"), of=n, runs=b.get("runs")))
|
|
266
|
+
if lb:
|
|
267
|
+
lbb, lba = lb.get("before") or {}, lb.get("after") or {}
|
|
268
|
+
ms.append(kmeasure("time_per_call_loopback", "ms", lbb.get("ms"), lba.get("ms"), spread_before=lbb.get("spread"),
|
|
269
|
+
spread_after=lba.get("spread"), runs=lbb.get("runs"), verdict=False))
|
|
270
|
+
pr = proof(source="sandbox", measures=ms,
|
|
271
|
+
same=sameness("same_output", bool(r.get("same")), compared=n, basis=f"{n} response bodies hashed, as written and with one client"),
|
|
272
|
+
runtime={"engine": m.get("runtime") or RUNTIME_WORDS.get(c.get("runtime")), "version": "",
|
|
273
|
+
"settings": {"round trip": f"{m.get('rtt_ms'):g} ms (simulated)", "TLS": "yes, stand-in certificate" if m.get("tls") else "no",
|
|
274
|
+
**({"not replayed": ", ".join(m["not_replayed"])[:80]} if m.get("not_replayed") else {})}},
|
|
275
|
+
scale={"name": "calls", "unit": "calls", "points": [n], "at": n},
|
|
276
|
+
inputs={"family": "stand-in server on loopback", "typical": f"{m.get('rtt_ms'):g} ms round trip"})
|
|
277
|
+
fix = {"change": "reuse_client", "before": c.get("code") or c["call"], "after": reuse_text(c, m)}
|
|
278
|
+
saved = round((b.get("ms") or 0) - (a.get("ms") or 0), 2)
|
|
279
|
+
panel = {"conns": {"before": b.get("connections"), "after": a.get("connections"), "calls": n},
|
|
280
|
+
"handshakes": {"before": b.get("tls_handshakes"), "after": a.get("tls_handshakes")} if m.get("tls") else None,
|
|
281
|
+
"per_call": {"before": b.get("ms"), "after": a.get("ms"), "saved_ms": saved, "rtt_ms": m.get("rtt_ms"),
|
|
282
|
+
"loopback_before": (lb.get("before") or {}).get("ms"), "loopback_after": (lb.get("after") or {}).get("ms")},
|
|
283
|
+
"runtime_label": m.get("runtime"), "kwargs": m.get("kwargs"), "not_replayed": m.get("not_replayed")}
|
|
284
|
+
return pr, fix, panel
|
|
285
|
+
|
|
286
|
+
def _block_proof(self, ctx, c, m):
|
|
287
|
+
b, a = m.get("before") or {}, m.get("after") or {}
|
|
288
|
+
ms = [kmeasure("loop_stall_ms", "ms", b.get("stall_ms"), a.get("stall_ms"), spread_before=b.get("stall_spread"),
|
|
289
|
+
spread_after=a.get("stall_spread"), runs=m.get("runs")),
|
|
290
|
+
kmeasure("handlers_wall_ms", "ms", b.get("wall_ms"), a.get("wall_ms"), spread_before=b.get("wall_spread"),
|
|
291
|
+
spread_after=a.get("wall_spread"), runs=m.get("runs"), verdict=False)]
|
|
292
|
+
dur = f"{m['sleep_s'] * 1000:g} ms (the literal)" if m.get("sleep_s") else \
|
|
293
|
+
(f"{m.get('iterations')} iterations (the literal)" if m.get("iterations") else f"{m.get('call_ms'):g} ms (stated)")
|
|
294
|
+
pr = proof(source="sandbox", measures=ms,
|
|
295
|
+
same=sameness("same_output", bool(m.get("same")), compared=m.get("handlers"), basis=f"{m.get('handlers')} handlers' results hashed"),
|
|
296
|
+
runtime={"engine": m.get("runtime") or RUNTIME_WORDS.get(c.get("runtime")), "version": "",
|
|
297
|
+
"settings": {"call duration": dur, "heartbeat": f"{m.get('heartbeat_ms'):g} ms"}},
|
|
298
|
+
schedule={"handlers": m.get("handlers"), "call_ms": m.get("call_ms"), "heartbeat_ms": m.get("heartbeat_ms")},
|
|
299
|
+
inputs={"family": blocking_stand_in(c), "typical": dur})
|
|
300
|
+
fix = {"change": "off_the_loop", "before": c.get("code") or c["call"], "after": unblock_text(c)}
|
|
301
|
+
panel = {"stall": {"before": b.get("stall_ms"), "after": a.get("stall_ms")}, "wall": {"before": b.get("wall_ms"), "after": a.get("wall_ms")},
|
|
302
|
+
"handlers": m.get("handlers"), "call_ms": (m["sleep_s"] * 1000 if m.get("sleep_s") else m.get("call_ms")),
|
|
303
|
+
"heartbeat_ms": m.get("heartbeat_ms"), "timeline": {"before": b.get("timeline"), "after": a.get("timeline")},
|
|
304
|
+
"runtime_label": m.get("runtime"), "stand_in": blocking_stand_in(c)}
|
|
305
|
+
return pr, fix, panel
|
|
306
|
+
|
|
307
|
+
def _hang_proof(self, ctx, c, m):
|
|
308
|
+
b, a = m.get("before") or {}, m.get("after") or {}
|
|
309
|
+
ms = [kmeasure("returned_by_deadline", "runs", b.get("returned"), a.get("returned"), better="higher", of=b.get("of")),
|
|
310
|
+
kmeasure("seconds_until_return", "s", b.get("seconds"), a.get("seconds"), spread_before=b.get("spread"), spread_after=a.get("spread"),
|
|
311
|
+
runs=m.get("runs"), verdict=False)]
|
|
312
|
+
pr = proof(source="sandbox", measures=ms,
|
|
313
|
+
same=sameness("same_output", None, basis="no output to compare: the call's behaviour is the result"),
|
|
314
|
+
runtime={"engine": m.get("runtime") or RUNTIME_WORDS.get(c.get("runtime")), "version": "",
|
|
315
|
+
"settings": {"deadline": f"{m.get('deadline_s'):g} s", "timeout in the fix": f"{m.get('fix_timeout_s'):g} s"}},
|
|
316
|
+
schedule={"deadline_s": m.get("deadline_s"), "fix_timeout_s": m.get("fix_timeout_s")},
|
|
317
|
+
inputs={"family": "a stand-in that accepts the connection and never answers"})
|
|
318
|
+
fix = {"change": "add_timeout", "before": c.get("code") or c["call"], "after": timeout_text(c, m)}
|
|
319
|
+
panel = {"deadline_s": m.get("deadline_s"), "fix_timeout_s": m.get("fix_timeout_s"),
|
|
320
|
+
"before": {"returned": bool(b.get("returned")), "seconds": b.get("seconds"), "error": b.get("error")},
|
|
321
|
+
"after": {"returned": bool(a.get("returned")), "seconds": a.get("seconds"), "error": a.get("error")},
|
|
322
|
+
"runtime_label": m.get("runtime")}
|
|
323
|
+
return pr, fix, panel
|
|
324
|
+
|
|
325
|
+
@staticmethod
|
|
326
|
+
def _summary(c, m, o, info) -> str:
|
|
327
|
+
sc = c["scenario"]
|
|
328
|
+
if sc == "client_per_call":
|
|
329
|
+
cn, pc = info.get("conns") or {}, info.get("per_call") or {}
|
|
330
|
+
return (f"{cn.get('calls')} calls opened {cn.get('before'):g} connections as written, {cn.get('after'):g} with one client; "
|
|
331
|
+
f"{pc.get('before'):.1f} -> {pc.get('after'):.1f} ms per call at {pc.get('rtt_ms'):g} ms round trip. "
|
|
332
|
+
f"{(info.get('gate') or {}).get('basis', '')}")[:300] if cn.get("before") is not None and pc.get("before") else ""
|
|
333
|
+
if sc == "blocking_in_async":
|
|
334
|
+
s = info.get("stall") or {}
|
|
335
|
+
return (f"{info.get('handlers')} concurrent handlers: the event loop stalled {s.get('before'):.0f} ms as written, {s.get('after'):.1f} ms off the loop. "
|
|
336
|
+
f"{(info.get('gate') or {}).get('basis', '')}")[:300] if s.get("before") is not None else ""
|
|
337
|
+
b, a = info.get("before") or {}, info.get("after") or {}
|
|
338
|
+
before = f"returned after {b.get('seconds'):.1f} s" if b.get("returned") else f"still waiting at {info.get('deadline_s'):g} s"
|
|
339
|
+
after = f"{a.get('error') or 'returned'} at {a.get('seconds'):.1f} s" if a.get("returned") else "still waiting"
|
|
340
|
+
return f"Against an upstream that never answers: as written {before}; with a {info.get('fix_timeout_s'):g} s timeout {after}."[:300]
|
|
341
|
+
|
|
342
|
+
# --- report and hand-off -------------------------------------------------------------------------------------------------
|
|
343
|
+
def report_html(self, ctx, found):
|
|
344
|
+
from ...report import e
|
|
345
|
+
rows = []
|
|
346
|
+
for f in found:
|
|
347
|
+
o, p, cl = f.get("outcome") or {}, f.get("proof") or {}, f.get("calls") or {}
|
|
348
|
+
first = (p.get("measures") or [{}])[0]
|
|
349
|
+
rows.append(f"<tr><td>{e(f.get('finding'))}</td><td>{e(cl.get('scenario'))}</td><td>{e((f.get('site') or {}).get('file'))}:"
|
|
350
|
+
f"{e((f.get('site') or {}).get('line'))}</td><td>{e(f.get('title'))}</td><td>{e(o.get('state'))} ({e(o.get('reason'))})</td>"
|
|
351
|
+
f"<td>{e(first.get('name', ''))} {e(first.get('before', ''))} → {e(first.get('after', ''))}</td></tr>")
|
|
352
|
+
return ("<h2>Outbound calls</h2><p class=muted>Call shapes replayed by CodeCop's own harness against a stand-in server on "
|
|
353
|
+
"loopback; counts (connections, handshakes, event-loop stalls, the deadline) decide.</p><table><tr><th>finding</th>"
|
|
354
|
+
f"<th>scenario</th><th>where</th><th>what</th><th>state</th><th>verdict measure</th></tr>{''.join(rows)}</table>")
|
|
355
|
+
|
|
356
|
+
def handoff(self, f):
|
|
357
|
+
text = handoff_text(f)
|
|
358
|
+
cl = f.get("calls") or {}
|
|
359
|
+
add = [f"Scenario: {str(cl.get('scenario') or '').replace('_', ' ')}; call `{cl.get('call')}` ({cl.get('runtime_label') or cl.get('runtime')})"]
|
|
360
|
+
g = cl.get("gate") or {}
|
|
361
|
+
if g.get("basis"):
|
|
362
|
+
add.append(f"Why it matters here: {g['basis']}")
|
|
363
|
+
if cl.get("scenario") == "client_per_call":
|
|
364
|
+
add.append("Fix: build the client once (module level, the app's lifespan or a dependency), pass it in, close it at shutdown. "
|
|
365
|
+
"Per-call settings (headers, auth) go on each request, not on the client.")
|
|
366
|
+
elif cl.get("scenario") == "blocking_in_async":
|
|
367
|
+
add.append("Fix: move the call off the event loop (asyncio.to_thread / the library's async API; Node: the async form). "
|
|
368
|
+
"Python's default thread pool runs min(32, CPUs + 4) calls at once.")
|
|
369
|
+
else:
|
|
370
|
+
add.append("Fix: set a timeout on the call or the client; the value is yours to choose (from the upstream's p99 when known).")
|
|
371
|
+
lines = text.split("\n")
|
|
372
|
+
return "\n".join(lines[:3] + add + lines[3:])
|
|
373
|
+
|
|
374
|
+
def doctor(self) -> list:
|
|
375
|
+
from .harness import doctor
|
|
376
|
+
return doctor()
|
|
377
|
+
|
|
378
|
+
def _save(self, ctx, name, doc):
|
|
379
|
+
try:
|
|
380
|
+
p = Path(ctx.out_dir) / "kinds" / name
|
|
381
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
382
|
+
p.write_text(json.dumps(doc, indent=1))
|
|
383
|
+
except OSError:
|
|
384
|
+
pass
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def blocking_stand_in(c) -> str:
|
|
388
|
+
call = c.get("call") or ""
|
|
389
|
+
if call == "std::process::Command.output":
|
|
390
|
+
return "a stand-in child process, `sleep` (the repository's command is never run)"
|
|
391
|
+
if call.startswith("blocking I/O"):
|
|
392
|
+
return "an HttpURLConnection call to the stand-in server answering after the stated time"
|
|
393
|
+
if call.startswith(("subprocess.", "os.system", "exec", "spawn")):
|
|
394
|
+
return "a stand-in child process (the repository's command is never run)"
|
|
395
|
+
if call.startswith(("requests.", "httpx.", "urllib.")):
|
|
396
|
+
return "the stand-in server answering after the stated time"
|
|
397
|
+
if call in ("pbkdf2Sync", "scryptSync"):
|
|
398
|
+
return "the same key derivation with the call's literal parameters"
|
|
399
|
+
return "the call itself"
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def reuse_text(c, m) -> str:
|
|
403
|
+
call = c["call"]
|
|
404
|
+
if c.get("implicit"):
|
|
405
|
+
return f"with requests.Session() as s: # once, outside the loop\n ...s.{c.get('verb') or 'get'}(...) # inside the loop"
|
|
406
|
+
rt = c.get("runtime")
|
|
407
|
+
if rt == "python":
|
|
408
|
+
kw = ", ".join(f"{k}={v!r}" for k, v in (c.get("kwargs") or {}).items())
|
|
409
|
+
return (f"# once, at start-up (module level, the app's lifespan or a dependency):\nclient = {call}({kw})\n"
|
|
410
|
+
f"# in {c.get('function') or 'the function'}: use `client`; close it at shutdown")
|
|
411
|
+
if rt == "node":
|
|
412
|
+
if call == "axios.create":
|
|
413
|
+
return f"// once, at module load:\nconst api = axios.create({{ /* same options */ }});\n// in {c.get('function') or 'the handler'}: use `api`"
|
|
414
|
+
if call == "ioredis":
|
|
415
|
+
return f"// once, at module load:\nconst redis = new Redis(/* same options */);\n// in {c.get('function') or 'the handler'}: use `redis`"
|
|
416
|
+
return f"// once, at module load:\nconst agent = new {call}({{ keepAlive: true }});\n// in {c.get('function') or 'the handler'}: pass `agent`"
|
|
417
|
+
if rt == "rust":
|
|
418
|
+
if call == "redis::Client":
|
|
419
|
+
return ("// once, at start-up: a pooled or multiplexed connection kept in the app state\n"
|
|
420
|
+
"let conn = redis::Client::open(url)?.get_multiplexed_async_connection().await?;\n"
|
|
421
|
+
f"// in {c.get('function') or 'the function'}: clone `conn`")
|
|
422
|
+
return ("// once, at start-up (app state, a OnceLock or an Arc in the handler's state):\n"
|
|
423
|
+
"static CLIENT: std::sync::LazyLock<reqwest::Client> = std::sync::LazyLock::new(reqwest::Client::new);\n"
|
|
424
|
+
f"// in {c.get('function') or 'the function'}: CLIENT.get(url) (reqwest::Client is an Arc inside: clone it freely)")
|
|
425
|
+
if rt == "java":
|
|
426
|
+
return ("// once: a field or a bean (java.net.http.HttpClient is thread-safe)\n"
|
|
427
|
+
"private static final HttpClient CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();\n"
|
|
428
|
+
f"// in {c.get('function') or 'the method'}: CLIENT.send(...)")
|
|
429
|
+
return (f"// once, at start-up:\nvar client = &http.Client{{Transport: &http.Transport{{ /* same fields */ }}}}\n"
|
|
430
|
+
f"// in {c.get('function') or 'the function'}: use `client`")
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
def unblock_text(c) -> str:
|
|
434
|
+
call, rt = c["call"], c.get("runtime")
|
|
435
|
+
if rt == "python":
|
|
436
|
+
if call == "time.sleep":
|
|
437
|
+
return "await asyncio.sleep(...)"
|
|
438
|
+
if call.startswith("subprocess.") or call == "os.system":
|
|
439
|
+
return f"await asyncio.to_thread({call}, ...) # or asyncio.create_subprocess_exec(...)"
|
|
440
|
+
if call.startswith("requests.") or call.startswith("httpx."):
|
|
441
|
+
return f"await asyncio.to_thread({call}, ...) # or the same request on a shared httpx.AsyncClient"
|
|
442
|
+
return f"await asyncio.to_thread({call}, ...)"
|
|
443
|
+
if rt == "rust":
|
|
444
|
+
if call == "std::thread::sleep":
|
|
445
|
+
return "tokio::time::sleep(d).await;"
|
|
446
|
+
return "tokio::task::spawn_blocking(move || std::process::Command::new(..).output()).await? // or tokio::process::Command"
|
|
447
|
+
if rt == "java":
|
|
448
|
+
return "CompletableFuture.supplyAsync(task, ioExecutor) // an executor sized for blocking work, not the common pool"
|
|
449
|
+
if call in ("pbkdf2Sync", "scryptSync"):
|
|
450
|
+
base = call[:-4]
|
|
451
|
+
return f"await util.promisify(crypto.{base})(...)"
|
|
452
|
+
return "await util.promisify(child_process.execFile)(...) // or exec / spawn with a callback"
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
def timeout_text(c, m) -> str:
|
|
456
|
+
code, call, rt = c.get("code") or c["call"], c["call"], c.get("runtime")
|
|
457
|
+
fix = m.get("fix_timeout_s") or 3
|
|
458
|
+
if rt == "python":
|
|
459
|
+
if code.rstrip().endswith(")"):
|
|
460
|
+
return code.rstrip()[:-1].rstrip() + f", timeout={fix:g}) # seconds; choose from the upstream's p99"
|
|
461
|
+
return f"{call}(..., timeout={fix:g})"
|
|
462
|
+
if rt == "rust":
|
|
463
|
+
if call == "reqwest::get":
|
|
464
|
+
return f"CLIENT.get(url).timeout(Duration::from_secs({fix:g})).send().await // a shared client with a timeout"
|
|
465
|
+
return f"reqwest::Client::builder().timeout(Duration::from_secs({fix:g})).build()?"
|
|
466
|
+
if rt == "java":
|
|
467
|
+
if call == "HttpURLConnection":
|
|
468
|
+
return f"conn.setConnectTimeout({int(fix * 1000)}); conn.setReadTimeout({int(fix * 1000)});"
|
|
469
|
+
return f"HttpRequest.newBuilder(uri).timeout(Duration.ofSeconds({fix:g})) // .build()"
|
|
470
|
+
if rt == "node":
|
|
471
|
+
if call == "axios":
|
|
472
|
+
return f"axios.get(url, {{ timeout: {int(fix * 1000)} }}) // or axios.create({{ timeout }}) once"
|
|
473
|
+
if call == "fetch":
|
|
474
|
+
return f"fetch(url, {{ ...options, signal: AbortSignal.timeout({int(fix * 1000)}) }})"
|
|
475
|
+
return f"{call}(url, {{ timeout: {int(fix * 1000)} }}, cb).on('timeout', function () {{ this.destroy() }})"
|
|
476
|
+
if call == "http.Client{}":
|
|
477
|
+
return f"&http.Client{{Timeout: {fix:g} * time.Second /* , same fields */}}"
|
|
478
|
+
return f"client := &http.Client{{Timeout: {fix:g} * time.Second}} // once\nclient.{call.split('.')[-1]}(...)"
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
def prompt_for(cands: list[dict]) -> str:
|
|
482
|
+
parts = ["You check facts the code shows about outbound calls CodeCop found and measured (read the files; do not run anything). "
|
|
483
|
+
"Each item asks one question. Answer `answer` true, false or null, and `evidence` as `path:line` of the line that "
|
|
484
|
+
"shows it (the caller, the loop, the route, the scheduler, the worker set-up, or the start-up code). An answer without "
|
|
485
|
+
"a `path:line` that exists is ignored. Say null when you cannot tell from the code. Never open `.env` files or "
|
|
486
|
+
"anything under an `envs/` directory.", ""]
|
|
487
|
+
for c in cands:
|
|
488
|
+
where = f"{c.get('file')}:{c.get('line')} in `{c.get('function') or c.get('symbol') or '?'}`"
|
|
489
|
+
if c["scenario"] == "client_per_call":
|
|
490
|
+
parts.append(f"- id {c['id']}: {where} builds `{c['call']}` on every call. Does this function run many times while the process "
|
|
491
|
+
f"lives (per request, per message or job, per item, on a schedule)? false if it runs once (start-up, a one-off "
|
|
492
|
+
f"command). Code: `{(c.get('code') or '')[:160]}`")
|
|
493
|
+
else:
|
|
494
|
+
parts.append(f"- id {c['id']}: {where} calls `{c['call']}` (blocking) inside an async function. While it waits, can other work run "
|
|
495
|
+
f"on the same event loop (other requests of a server, other messages or activities of a worker, other tasks "
|
|
496
|
+
f"gathered together)? false if the loop runs only this task (a script's asyncio.run(main())). "
|
|
497
|
+
f"Code: `{(c.get('code') or '')[:160]}`")
|
|
498
|
+
return "\n".join(parts)
|
|
499
|
+
|
|
500
|
+
|
|
501
|
+
__all__ = ["Calls", "SCENARIOS"]
|