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,340 @@
|
|
|
1
|
+
"""The stand-in upstream: a small HTTP(S) and Redis-protocol server CodeCop starts on loopback, so a call shape can be replayed
|
|
2
|
+
without the repository's code or its real upstream.
|
|
3
|
+
|
|
4
|
+
- `http(tls, rtt_ms, server_ms)`: a URL. Every request gets a deterministic JSON body (its path and body length) after
|
|
5
|
+
`server_ms`. With `rtt_ms`, the client talks to a delaying relay in front of the server: a new connection waits one
|
|
6
|
+
round trip before its first byte goes through (the TCP handshake), and every chunk after that is delivered half a
|
|
7
|
+
round trip later in each direction, so a TLS handshake pays its own round trips as it would on a real link.
|
|
8
|
+
- `hang()`: a URL whose listener accepts, reads, and never answers ("never answers" mode).
|
|
9
|
+
- `redis()`: (host, port) of a server that answers every RESP command with a fixed reply.
|
|
10
|
+
|
|
11
|
+
What the verdicts rest on is counted here, not timed: connections accepted, TLS handshakes completed and requests
|
|
12
|
+
answered, read with `counts()` before and after a run. Only 127.0.0.1 is ever bound. The TLS certificate is
|
|
13
|
+
self-signed for 127.0.0.1 and made with the `openssl` command into CodeCop's cache; without `openssl`, TLS is not
|
|
14
|
+
available and the stand-in serves plain HTTP only.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import asyncio
|
|
20
|
+
import hashlib
|
|
21
|
+
import json
|
|
22
|
+
import os
|
|
23
|
+
import shutil
|
|
24
|
+
import ssl
|
|
25
|
+
import subprocess
|
|
26
|
+
import threading
|
|
27
|
+
import time
|
|
28
|
+
from pathlib import Path
|
|
29
|
+
|
|
30
|
+
HOST = "127.0.0.1"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def cache_dir() -> Path:
|
|
34
|
+
base = os.environ.get("CODECOP_CACHE_DIR") or str(Path.home() / ".cache" / "codecop")
|
|
35
|
+
return Path(base) / "calls"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def certificate() -> tuple[str, str, str] | None:
|
|
39
|
+
"""(leaf cert.pem, leaf key.pem, ca.pem) for 127.0.0.1 in the cache, made once with openssl: a small CA and a leaf it
|
|
40
|
+
signs (rustls and webpki refuse a self-signed CA certificate used as the server's own)."""
|
|
41
|
+
d = cache_dir() / "standin-tls2"
|
|
42
|
+
cert, key, ca, cakey = d / "cert.pem", d / "key.pem", d / "ca.pem", d / "ca.key"
|
|
43
|
+
if cert.exists() and key.exists() and ca.exists():
|
|
44
|
+
return str(cert), str(key), str(ca)
|
|
45
|
+
exe = shutil.which("openssl")
|
|
46
|
+
if not exe:
|
|
47
|
+
return None
|
|
48
|
+
d.mkdir(parents=True, exist_ok=True)
|
|
49
|
+
ext = d / "leaf.ext"
|
|
50
|
+
ext.write_text("basicConstraints=CA:FALSE\nkeyUsage=digitalSignature,keyEncipherment\nextendedKeyUsage=serverAuth\n"
|
|
51
|
+
"subjectAltName=IP:127.0.0.1,DNS:localhost\n")
|
|
52
|
+
steps = [
|
|
53
|
+
[exe, "req", "-x509", "-newkey", "rsa:2048", "-nodes", "-keyout", str(cakey), "-out", str(ca), "-days", "3650",
|
|
54
|
+
"-subj", "/CN=codecop stand-in CA"],
|
|
55
|
+
[exe, "req", "-newkey", "rsa:2048", "-nodes", "-keyout", str(key), "-out", str(d / "leaf.csr"), "-subj", "/CN=127.0.0.1"],
|
|
56
|
+
[exe, "x509", "-req", "-in", str(d / "leaf.csr"), "-CA", str(ca), "-CAkey", str(cakey), "-CAcreateserial", "-out", str(cert),
|
|
57
|
+
"-days", "3650", "-extfile", str(ext)],
|
|
58
|
+
]
|
|
59
|
+
try:
|
|
60
|
+
for cmd in steps:
|
|
61
|
+
r = subprocess.run(cmd, capture_output=True, timeout=60)
|
|
62
|
+
if r.returncode != 0:
|
|
63
|
+
return None
|
|
64
|
+
except (OSError, subprocess.SubprocessError):
|
|
65
|
+
return None
|
|
66
|
+
if not cert.exists():
|
|
67
|
+
return None
|
|
68
|
+
return str(cert), str(key), str(ca)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def body_for(path: str, n: int) -> bytes:
|
|
72
|
+
"""The deterministic answer to one request: the same path and body length give the same bytes."""
|
|
73
|
+
return json.dumps({"path": path, "received": n, "tag": hashlib.sha256(f"{path}|{n}".encode()).hexdigest()[:16]}).encode()
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class StandIn:
|
|
77
|
+
"""One stand-in per measurement session, served from its own thread and event loop. Use as a context manager."""
|
|
78
|
+
|
|
79
|
+
def __init__(self, tls: bool = True):
|
|
80
|
+
self.counts_lock = threading.Lock()
|
|
81
|
+
self._counts = {"connections": 0, "tls_handshakes": 0, "requests": 0, "hang_connections": 0, "redis_connections": 0,
|
|
82
|
+
"redis_commands": 0, "relay_connections": 0}
|
|
83
|
+
self.loop: asyncio.AbstractEventLoop | None = None
|
|
84
|
+
self.thread: threading.Thread | None = None
|
|
85
|
+
self.servers: list = []
|
|
86
|
+
self.ports: dict = {}
|
|
87
|
+
self.relays: dict = {}
|
|
88
|
+
self.cert = certificate() if tls else None
|
|
89
|
+
self.tls_ok = self.cert is not None
|
|
90
|
+
self._hang_writers: list = []
|
|
91
|
+
|
|
92
|
+
# --- life ------------------------------------------------------------------------------------------------------------
|
|
93
|
+
def __enter__(self):
|
|
94
|
+
self.start()
|
|
95
|
+
return self
|
|
96
|
+
|
|
97
|
+
def __exit__(self, *a):
|
|
98
|
+
self.stop()
|
|
99
|
+
|
|
100
|
+
def start(self) -> None:
|
|
101
|
+
ready = threading.Event()
|
|
102
|
+
|
|
103
|
+
def run():
|
|
104
|
+
self.loop = asyncio.new_event_loop()
|
|
105
|
+
asyncio.set_event_loop(self.loop)
|
|
106
|
+
self.loop.run_until_complete(self._open())
|
|
107
|
+
ready.set()
|
|
108
|
+
self.loop.run_forever()
|
|
109
|
+
|
|
110
|
+
self.thread = threading.Thread(target=run, name="codecop-standin", daemon=True)
|
|
111
|
+
self.thread.start()
|
|
112
|
+
if not ready.wait(30):
|
|
113
|
+
raise RuntimeError("the stand-in server did not start")
|
|
114
|
+
|
|
115
|
+
def stop(self) -> None:
|
|
116
|
+
if self.loop is None:
|
|
117
|
+
return
|
|
118
|
+
|
|
119
|
+
async def close():
|
|
120
|
+
for w in self._hang_writers:
|
|
121
|
+
try:
|
|
122
|
+
w.close()
|
|
123
|
+
except Exception: # noqa: BLE001
|
|
124
|
+
pass
|
|
125
|
+
for s in self.servers:
|
|
126
|
+
s.close()
|
|
127
|
+
try:
|
|
128
|
+
asyncio.run_coroutine_threadsafe(close(), self.loop).result(10)
|
|
129
|
+
except Exception: # noqa: BLE001
|
|
130
|
+
pass
|
|
131
|
+
self.loop.call_soon_threadsafe(self.loop.stop)
|
|
132
|
+
if self.thread:
|
|
133
|
+
self.thread.join(10)
|
|
134
|
+
self.loop = None
|
|
135
|
+
|
|
136
|
+
async def _open(self) -> None:
|
|
137
|
+
s = await asyncio.start_server(lambda r, w: self._http(r, w, tls=False), HOST, 0)
|
|
138
|
+
self.servers.append(s)
|
|
139
|
+
self.ports["http"] = s.sockets[0].getsockname()[1]
|
|
140
|
+
if self.tls_ok:
|
|
141
|
+
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
|
142
|
+
ctx.load_cert_chain(self.cert[0], self.cert[1])
|
|
143
|
+
s = await asyncio.start_server(lambda r, w: self._http(r, w, tls=True), HOST, 0, ssl=ctx)
|
|
144
|
+
self.servers.append(s)
|
|
145
|
+
self.ports["https"] = s.sockets[0].getsockname()[1]
|
|
146
|
+
s = await asyncio.start_server(self._hang, HOST, 0)
|
|
147
|
+
self.servers.append(s)
|
|
148
|
+
self.ports["hang"] = s.sockets[0].getsockname()[1]
|
|
149
|
+
s = await asyncio.start_server(self._redis, HOST, 0)
|
|
150
|
+
self.servers.append(s)
|
|
151
|
+
self.ports["redis"] = s.sockets[0].getsockname()[1]
|
|
152
|
+
|
|
153
|
+
# --- counts ----------------------------------------------------------------------------------------------------------
|
|
154
|
+
def _bump(self, key: str, n: int = 1) -> None:
|
|
155
|
+
with self.counts_lock:
|
|
156
|
+
self._counts[key] += n
|
|
157
|
+
|
|
158
|
+
def counts(self) -> dict:
|
|
159
|
+
with self.counts_lock:
|
|
160
|
+
return dict(self._counts)
|
|
161
|
+
|
|
162
|
+
@staticmethod
|
|
163
|
+
def delta(a: dict, b: dict) -> dict:
|
|
164
|
+
return {k: b[k] - a.get(k, 0) for k in b}
|
|
165
|
+
|
|
166
|
+
# --- URLs ------------------------------------------------------------------------------------------------------------
|
|
167
|
+
@property
|
|
168
|
+
def cafile(self) -> str:
|
|
169
|
+
return self.cert[2] if self.cert else ""
|
|
170
|
+
|
|
171
|
+
def http(self, tls: bool = False, rtt_ms: float = 0.0, server_ms: float = 0.0) -> str:
|
|
172
|
+
"""The base URL of the HTTP(S) stand-in (no trailing slash); requests under `/d/<server_ms>/...` wait that long."""
|
|
173
|
+
if tls and not self.tls_ok:
|
|
174
|
+
raise RuntimeError("TLS is not available (no openssl to make the stand-in's certificate)")
|
|
175
|
+
port = self.ports["https" if tls else "http"]
|
|
176
|
+
if rtt_ms:
|
|
177
|
+
port = self._relay(port, float(rtt_ms))
|
|
178
|
+
return f"{'https' if tls else 'http'}://{HOST}:{port}/d/{float(server_ms):g}"
|
|
179
|
+
|
|
180
|
+
def hang(self) -> str:
|
|
181
|
+
return f"http://{HOST}:{self.ports['hang']}/never"
|
|
182
|
+
|
|
183
|
+
def redis(self, rtt_ms: float = 0.0) -> tuple[str, int]:
|
|
184
|
+
"""(host, port) of the RESP stand-in, behind the delaying relay when `rtt_ms` is given."""
|
|
185
|
+
return HOST, (self._relay(self.ports["redis"], float(rtt_ms)) if rtt_ms else self.ports["redis"])
|
|
186
|
+
|
|
187
|
+
def _relay(self, upstream: int, rtt_ms: float) -> int:
|
|
188
|
+
key = (upstream, rtt_ms)
|
|
189
|
+
if key not in self.relays:
|
|
190
|
+
fut = asyncio.run_coroutine_threadsafe(self._open_relay(upstream, rtt_ms), self.loop)
|
|
191
|
+
self.relays[key] = fut.result(10)
|
|
192
|
+
return self.relays[key]
|
|
193
|
+
|
|
194
|
+
# --- the HTTP server -------------------------------------------------------------------------------------------------
|
|
195
|
+
async def _http(self, reader, writer, tls: bool) -> None:
|
|
196
|
+
self._bump("connections")
|
|
197
|
+
if tls:
|
|
198
|
+
self._bump("tls_handshakes")
|
|
199
|
+
try:
|
|
200
|
+
while True:
|
|
201
|
+
head = await reader.readuntil(b"\r\n\r\n")
|
|
202
|
+
lines = head.decode("latin-1").split("\r\n")
|
|
203
|
+
parts = lines[0].split(" ")
|
|
204
|
+
path = parts[1] if len(parts) > 1 else "/"
|
|
205
|
+
headers = {}
|
|
206
|
+
for ln in lines[1:]:
|
|
207
|
+
if ":" in ln:
|
|
208
|
+
k, v = ln.split(":", 1)
|
|
209
|
+
headers[k.strip().lower()] = v.strip()
|
|
210
|
+
n = 0
|
|
211
|
+
if headers.get("transfer-encoding", "").lower() == "chunked":
|
|
212
|
+
while True:
|
|
213
|
+
size = int((await reader.readuntil(b"\r\n")).strip().split(b";")[0] or b"0", 16)
|
|
214
|
+
if size == 0:
|
|
215
|
+
await reader.readuntil(b"\r\n")
|
|
216
|
+
break
|
|
217
|
+
n += len(await reader.readexactly(size))
|
|
218
|
+
await reader.readexactly(2)
|
|
219
|
+
elif headers.get("content-length"):
|
|
220
|
+
n = len(await reader.readexactly(int(headers["content-length"])))
|
|
221
|
+
self._bump("requests")
|
|
222
|
+
seg = path.split("/")
|
|
223
|
+
if len(seg) > 2 and seg[1] == "d":
|
|
224
|
+
try:
|
|
225
|
+
wait = float(seg[2])
|
|
226
|
+
except ValueError:
|
|
227
|
+
wait = 0.0
|
|
228
|
+
if wait > 0:
|
|
229
|
+
await asyncio.sleep(wait / 1000)
|
|
230
|
+
body = body_for(path, n)
|
|
231
|
+
close = headers.get("connection", "").lower() == "close" or parts[-1].upper() == "HTTP/1.0"
|
|
232
|
+
writer.write(b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: " + str(len(body)).encode()
|
|
233
|
+
+ (b"\r\nConnection: close" if close else b"\r\nConnection: keep-alive") + b"\r\n\r\n" + body)
|
|
234
|
+
await writer.drain()
|
|
235
|
+
if close:
|
|
236
|
+
break
|
|
237
|
+
except (asyncio.IncompleteReadError, asyncio.LimitOverrunError, ConnectionError, ValueError, ssl.SSLError, OSError):
|
|
238
|
+
pass
|
|
239
|
+
finally:
|
|
240
|
+
try:
|
|
241
|
+
writer.close()
|
|
242
|
+
except Exception: # noqa: BLE001
|
|
243
|
+
pass
|
|
244
|
+
|
|
245
|
+
async def _hang(self, reader, writer) -> None:
|
|
246
|
+
"""Accept, read whatever comes, never answer: the upstream that never responds."""
|
|
247
|
+
self._bump("hang_connections")
|
|
248
|
+
self._hang_writers.append(writer)
|
|
249
|
+
try:
|
|
250
|
+
while await reader.read(65536):
|
|
251
|
+
pass
|
|
252
|
+
except (ConnectionError, OSError):
|
|
253
|
+
pass
|
|
254
|
+
|
|
255
|
+
async def _redis(self, reader, writer) -> None:
|
|
256
|
+
"""RESP: every command gets `+OK` (PING gets PONG, GET a fixed bulk string). Enough for a client to connect and call."""
|
|
257
|
+
self._bump("redis_connections")
|
|
258
|
+
try:
|
|
259
|
+
while True:
|
|
260
|
+
line = await reader.readuntil(b"\r\n")
|
|
261
|
+
if not line.startswith(b"*"):
|
|
262
|
+
continue
|
|
263
|
+
argc = int(line[1:].strip())
|
|
264
|
+
args = []
|
|
265
|
+
for _ in range(argc):
|
|
266
|
+
ln = await reader.readuntil(b"\r\n")
|
|
267
|
+
size = int(ln[1:].strip())
|
|
268
|
+
args.append((await reader.readexactly(size + 2))[:-2])
|
|
269
|
+
self._bump("redis_commands")
|
|
270
|
+
cmd = (args[0] if args else b"").upper()
|
|
271
|
+
if cmd == b"PING":
|
|
272
|
+
writer.write(b"+PONG\r\n")
|
|
273
|
+
elif cmd == b"GET":
|
|
274
|
+
v = body_for("redis/" + (args[1].decode("latin-1") if len(args) > 1 else ""), 0)
|
|
275
|
+
writer.write(b"$" + str(len(v)).encode() + b"\r\n" + v + b"\r\n")
|
|
276
|
+
elif cmd == b"INFO":
|
|
277
|
+
v = b"# Server\r\nredis_version:7.0.0\r\nloading:0\r\n"
|
|
278
|
+
writer.write(b"$" + str(len(v)).encode() + b"\r\n" + v + b"\r\n")
|
|
279
|
+
elif cmd == b"HELLO": # answered in RESP2: the client stays on protocol 2
|
|
280
|
+
writer.write(b"*6\r\n$6\r\nserver\r\n$5\r\nredis\r\n$7\r\nversion\r\n$5\r\n7.0.0\r\n$5\r\nproto\r\n:2\r\n")
|
|
281
|
+
else:
|
|
282
|
+
writer.write(b"+OK\r\n")
|
|
283
|
+
await writer.drain()
|
|
284
|
+
except (asyncio.IncompleteReadError, asyncio.LimitOverrunError, ConnectionError, ValueError, OSError):
|
|
285
|
+
pass
|
|
286
|
+
finally:
|
|
287
|
+
try:
|
|
288
|
+
writer.close()
|
|
289
|
+
except Exception: # noqa: BLE001
|
|
290
|
+
pass
|
|
291
|
+
|
|
292
|
+
# --- the delaying relay ----------------------------------------------------------------------------------------------
|
|
293
|
+
async def _open_relay(self, upstream: int, rtt_ms: float) -> int:
|
|
294
|
+
half = rtt_ms / 2000.0
|
|
295
|
+
|
|
296
|
+
async def pipe(src, dst):
|
|
297
|
+
q: asyncio.Queue = asyncio.Queue()
|
|
298
|
+
|
|
299
|
+
async def deliver():
|
|
300
|
+
while True:
|
|
301
|
+
due, data = await q.get()
|
|
302
|
+
if data is None:
|
|
303
|
+
break
|
|
304
|
+
wait = due - time.monotonic()
|
|
305
|
+
if wait > 0:
|
|
306
|
+
await asyncio.sleep(wait)
|
|
307
|
+
dst.write(data)
|
|
308
|
+
try:
|
|
309
|
+
await dst.drain()
|
|
310
|
+
except (ConnectionError, OSError):
|
|
311
|
+
break
|
|
312
|
+
try:
|
|
313
|
+
dst.close()
|
|
314
|
+
except Exception: # noqa: BLE001
|
|
315
|
+
pass
|
|
316
|
+
task = asyncio.ensure_future(deliver())
|
|
317
|
+
try:
|
|
318
|
+
while True:
|
|
319
|
+
data = await src.read(65536)
|
|
320
|
+
if not data:
|
|
321
|
+
break
|
|
322
|
+
q.put_nowait((time.monotonic() + half, data))
|
|
323
|
+
except (ConnectionError, OSError):
|
|
324
|
+
pass
|
|
325
|
+
q.put_nowait((time.monotonic() + half, None))
|
|
326
|
+
await task
|
|
327
|
+
|
|
328
|
+
async def on(r, w):
|
|
329
|
+
self._bump("relay_connections")
|
|
330
|
+
await asyncio.sleep(2 * half) # the TCP handshake's round trip, which loopback does not have
|
|
331
|
+
try:
|
|
332
|
+
ur, uw = await asyncio.open_connection(HOST, upstream)
|
|
333
|
+
except OSError:
|
|
334
|
+
w.close()
|
|
335
|
+
return
|
|
336
|
+
await asyncio.gather(pipe(r, uw), pipe(ur, w), return_exceptions=True)
|
|
337
|
+
|
|
338
|
+
s = await asyncio.start_server(on, HOST, 0)
|
|
339
|
+
self.servers.append(s)
|
|
340
|
+
return s.sockets[0].getsockname()[1]
|
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
"""Running the kinds of finding: discover into the inventory, rules, the agent's questions under the one run budget,
|
|
2
|
+
the sandbox verifier, and the merge into findings.json. One stage file per kind: `<out>/kinds/<name>.json`."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
from collections import Counter
|
|
8
|
+
from datetime import datetime, timezone
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from . import QUERY, STATES, Context, ContractError, all_kinds, get, handoff_text, site_id
|
|
12
|
+
|
|
13
|
+
DIR = "kinds"
|
|
14
|
+
# the fields discovery adds to a kind's site from the shared trace (origins.annotate): entry points, request path, loops
|
|
15
|
+
TRACE_FIELDS = ("role", "role_basis", "origins", "origin_count", "origin_count_certain", "test_origin_count", "is_test",
|
|
16
|
+
"loop_context", "loop_count", "loop_depth", "loop_summary", "in_loop", "loop_collection")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def now() -> str:
|
|
20
|
+
return datetime.now(timezone.utc).isoformat(timespec="seconds")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def stage_path(out_dir: Path, name: str) -> Path:
|
|
24
|
+
return Path(out_dir) / DIR / f"{name}.json"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def load(out_dir: Path, name: str) -> dict | None:
|
|
28
|
+
p = stage_path(out_dir, name)
|
|
29
|
+
try:
|
|
30
|
+
doc = json.loads(p.read_text())
|
|
31
|
+
except (OSError, ValueError):
|
|
32
|
+
return None
|
|
33
|
+
return doc if isinstance(doc, dict) else None
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def save(out_dir: Path, name: str, doc: dict) -> None:
|
|
37
|
+
p = stage_path(out_dir, name)
|
|
38
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
39
|
+
p.write_text(json.dumps(doc, indent=1, ensure_ascii=False))
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def selected_kinds(names: list[str] | None) -> list:
|
|
43
|
+
"""The registered kinds among `names` (None: every default-on, not hidden kind), in registry order."""
|
|
44
|
+
if names is None:
|
|
45
|
+
return [k for k in all_kinds() if k.default_on and not k.hidden]
|
|
46
|
+
return [k for k in all_kinds() if k.name in names]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
# --- discover ----------------------------------------------------------------------------------------------------------
|
|
50
|
+
|
|
51
|
+
def raw_sites(root: Path, by_lang: dict, names: list[str] | None, settings: dict | None = None, log=None) -> dict[str, list[dict]]:
|
|
52
|
+
"""Each selected kind's raw call sites ({file, line, language, symbol?, ...}), before the shared trace. A kind whose
|
|
53
|
+
discover raises is reported and left out: one kind must not lose the inventory."""
|
|
54
|
+
out: dict[str, list[dict]] = {}
|
|
55
|
+
for k in selected_kinds(names):
|
|
56
|
+
ctx = Context(root=root, out_dir=root, kind=k.name, settings=(settings or {}).get(k.name) or {}, by_lang=by_lang, log=log)
|
|
57
|
+
try:
|
|
58
|
+
sites = [s for s in k.discover(ctx) or [] if isinstance(s, dict) and s.get("file") and s.get("line")]
|
|
59
|
+
except Exception as e: # noqa: BLE001
|
|
60
|
+
if log:
|
|
61
|
+
log(f"kind {k.name}: discover stopped ({type(e).__name__}: {e})")
|
|
62
|
+
sites = []
|
|
63
|
+
for s in sites:
|
|
64
|
+
s.setdefault("language", "")
|
|
65
|
+
s.setdefault("symbol", "")
|
|
66
|
+
s.setdefault("id", site_id(k.name, s["file"], s.get("symbol") or "", str(s.get("text") or s["line"])))
|
|
67
|
+
out[k.name] = sites
|
|
68
|
+
return out
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def trace_proxies(raw: dict[str, list[dict]], is_test) -> list[dict]:
|
|
72
|
+
"""Stand-ins the shared trace (origins.annotate) can walk like query sites; their facts are copied back by
|
|
73
|
+
`take_trace`. Each carries `_kind_site` (the raw site)."""
|
|
74
|
+
proxies = []
|
|
75
|
+
for sites in raw.values():
|
|
76
|
+
for s in sites:
|
|
77
|
+
proxies.append({"id": s["id"], "file": s["file"], "line": int(s["line"]), "end_line": int(s.get("end_line") or s["line"]),
|
|
78
|
+
"language": s.get("language") or "", "symbol": s.get("symbol") or "", "kind": "call",
|
|
79
|
+
"is_test": bool(s.get("is_test", is_test(s["file"]))), "_kind_site": s})
|
|
80
|
+
return proxies
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def take_trace(proxies: list[dict]) -> None:
|
|
84
|
+
for p in proxies:
|
|
85
|
+
s = p["_kind_site"]
|
|
86
|
+
for k in TRACE_FIELDS:
|
|
87
|
+
if k in p:
|
|
88
|
+
s[k] = p[k]
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def inventory_section(raw: dict[str, list[dict]]) -> dict:
|
|
92
|
+
"""`inventory.kinds`: per kind {schema_version, sites[], summary{sites, by_language, by_role, on_request_path, in_loop}}."""
|
|
93
|
+
out = {}
|
|
94
|
+
for name, sites in raw.items():
|
|
95
|
+
live = [s for s in sites if not s.get("is_test")]
|
|
96
|
+
out[name] = {"schema_version": 1, "sites": sites,
|
|
97
|
+
"summary": {"sites": len(sites), "tests": len(sites) - len(live),
|
|
98
|
+
"by_language": dict(Counter(s.get("language") or "unknown" for s in sites).most_common()),
|
|
99
|
+
"by_role": dict(Counter(s.get("role") or "unknown" for s in sites).most_common()),
|
|
100
|
+
"on_request_path": sum(1 for s in live if any((o or {}).get("kind") == "http" for o in s.get("origins") or [])),
|
|
101
|
+
"in_loop": sum(1 for s in live if s.get("loop_count"))}}
|
|
102
|
+
return out
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
# --- rules, questions, ask, verify ---------------------------------------------------------------------------------------
|
|
106
|
+
|
|
107
|
+
def context(root: Path, out_dir: Path, name: str, *, inventory: dict | None, settings: dict | None = None, run=None, verdicts=None,
|
|
108
|
+
no_agent: bool = False, fresh=False, log=None) -> Context:
|
|
109
|
+
return Context(root=root, out_dir=out_dir, kind=name, settings=(settings or {}).get(name) or {}, inventory=inventory, run=run,
|
|
110
|
+
verdicts=verdicts, no_agent=no_agent, fresh=fresh, log=log)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def candidates(k, ctx: Context) -> list[dict]:
|
|
114
|
+
"""The kind's rule pass over its inventory sites (cheap, no agent). Each candidate keeps its site's trace facts."""
|
|
115
|
+
sites = ctx.sites()
|
|
116
|
+
by_id = {s.get("id"): s for s in sites}
|
|
117
|
+
out = []
|
|
118
|
+
for c in k.rules(ctx, sites) or []:
|
|
119
|
+
if not isinstance(c, dict) or not c.get("id"):
|
|
120
|
+
continue
|
|
121
|
+
s = by_id.get(c["id"]) or {}
|
|
122
|
+
for f in ("file", "line", "symbol", "role", "origins", "loop_summary"):
|
|
123
|
+
if f not in c and f in s:
|
|
124
|
+
c[f] = s[f]
|
|
125
|
+
out.append(c)
|
|
126
|
+
return out
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def queue_items(root: Path, out_dir: Path, inventory: dict | None, names: list[str], settings: dict | None = None, verdicts=None,
|
|
130
|
+
fresh=False, log=None) -> list[dict]:
|
|
131
|
+
"""The budget items of every selected kind (its `questions` hook over its rule candidates), for the one plan."""
|
|
132
|
+
items = []
|
|
133
|
+
for k in selected_kinds(names):
|
|
134
|
+
ctx = context(root, out_dir, k.name, inventory=inventory, settings=settings, verdicts=verdicts, fresh=fresh, log=log)
|
|
135
|
+
try:
|
|
136
|
+
cands = candidates(k, ctx)
|
|
137
|
+
for it in k.questions(ctx, cands) or []:
|
|
138
|
+
if isinstance(it, dict) and it.get("kind") == k.queue_kind:
|
|
139
|
+
items.append(it)
|
|
140
|
+
except Exception as e: # noqa: BLE001
|
|
141
|
+
if log:
|
|
142
|
+
log(f"kind {k.name}: questions stopped ({type(e).__name__}: {e})")
|
|
143
|
+
return items
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def run_kind(k, ctx: Context, chosen: set[str] | None = None, runner=None) -> dict:
|
|
147
|
+
"""One kind's stage: rules, the agent for the chosen items (through the run budget), the verifier. Writes and returns
|
|
148
|
+
`<out>/kinds/<name>.json`: {schema_version, kind, generated_at, sites, candidates, asked, findings, summary}."""
|
|
149
|
+
cands = candidates(k, ctx)
|
|
150
|
+
asked = 0
|
|
151
|
+
if runner is not None and not ctx.no_agent:
|
|
152
|
+
# what the plan chose (over budget), else every item the kind's questions name: only those are asked
|
|
153
|
+
refs = chosen if chosen is not None else {it.get("ref") for it in k.questions(ctx, cands) or [] if isinstance(it, dict)}
|
|
154
|
+
mine = [c for c in cands if c["id"] in refs]
|
|
155
|
+
if mine:
|
|
156
|
+
if ctx.run is not None:
|
|
157
|
+
runner = ctx.run.wrap(runner)
|
|
158
|
+
ctx.run.tell(k.queue_kind, len(mine))
|
|
159
|
+
try:
|
|
160
|
+
k.ask(ctx, mine, runner)
|
|
161
|
+
asked = len(mine)
|
|
162
|
+
except Exception as e: # noqa: BLE001 -- a budget stop or a failed call: what was answered is kept
|
|
163
|
+
ctx.say(f"kind {k.name}: the agent step stopped ({type(e).__name__}: {e})")
|
|
164
|
+
found = []
|
|
165
|
+
sites = {s.get("id"): s for s in ctx.sites()}
|
|
166
|
+
for f in k.verify(ctx, cands) or []:
|
|
167
|
+
check(f, k.name)
|
|
168
|
+
site = sites.get(f["id"])
|
|
169
|
+
if site is not None and (f.get("origin") or {}).get("kind") in (None, "unknown"):
|
|
170
|
+
f["origin"] = origin_of(site)
|
|
171
|
+
found.append(f)
|
|
172
|
+
found = with_heat(found, ctx)
|
|
173
|
+
doc = {"schema_version": 1, "kind": k.name, "generated_at": now(), "sites": len(ctx.sites()),
|
|
174
|
+
"candidates": [{kk: v for kk, v in c.items() if kk not in ("origins",)} for c in cands], "asked": asked,
|
|
175
|
+
"findings": found, "summary": summary(found, len(ctx.sites()))}
|
|
176
|
+
save(ctx.out_dir, k.name, doc)
|
|
177
|
+
return doc
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def with_heat(found: list[dict], ctx: Context) -> list[dict]:
|
|
181
|
+
"""The kind's findings with `heat` (heat.py: how hot the code path is) in rank order: proven gain first, then heat x
|
|
182
|
+
gain. Heat never loses a finding: on any error the findings are returned as they were."""
|
|
183
|
+
try:
|
|
184
|
+
from .. import heat
|
|
185
|
+
facts = heat.load(ctx.out_dir, root=ctx.root, config=heat.config_of(ctx.root), inventory=ctx.inventory, verdicts=ctx.verdicts)
|
|
186
|
+
return heat.annotate(found, facts)
|
|
187
|
+
except Exception as e: # noqa: BLE001
|
|
188
|
+
ctx.say(f"heat: not worked out ({type(e).__name__}: {e})")
|
|
189
|
+
return found
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def origin_of(site: dict) -> dict:
|
|
193
|
+
"""A finding's `origin` (the query findings' shape) from its call site's shared trace: role, the nearest entry point's
|
|
194
|
+
kind, the entry points, whether the path was traced without a guess, and whether it runs in a loop."""
|
|
195
|
+
origins = [o for o in site.get("origins") or [] if isinstance(o, dict)]
|
|
196
|
+
first = origins[0] if origins else {}
|
|
197
|
+
loop = site.get("loop_summary") or {}
|
|
198
|
+
return {"role": site.get("role") or "unknown", "kind": first.get("kind") or "unknown",
|
|
199
|
+
"entry_points": [{k: o.get(k) for k in ("kind", "name", "file", "line", "hops")} for o in origins][:5],
|
|
200
|
+
"verified": bool(origins) and all(o.get("verified", True) for o in origins[:1]),
|
|
201
|
+
"frequency": {"trigger": first.get("kind") or "unknown", "every_seconds": 0, "in_loop": bool(loop), "cache_seconds": 0, "note": ""},
|
|
202
|
+
**({"loop": {k: loop.get(k) for k in ("kind", "file", "line", "hop")}} if loop else {})}
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def check(f: dict, kind: str) -> None:
|
|
206
|
+
"""The contract a finding must meet before it leaves the kind (docs/kinds.md)."""
|
|
207
|
+
if f.get("kind") != kind:
|
|
208
|
+
raise ContractError(f"a {kind} finding must say kind {kind!r}")
|
|
209
|
+
o = f.get("outcome") or {}
|
|
210
|
+
if o.get("state") not in STATES:
|
|
211
|
+
raise ContractError(f"{kind} finding {f.get('id')}: outcome.state must be one of {', '.join(STATES)}")
|
|
212
|
+
if not f.get("id"):
|
|
213
|
+
raise ContractError(f"{kind} finding: id (the call site's stable id) is required")
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def summary(found: list[dict], sites: int) -> dict:
|
|
217
|
+
states = Counter((f.get("outcome") or {}).get("state") for f in found)
|
|
218
|
+
return {"sites": sites, "findings": len(found), "states": {s: states.get(s, 0) for s in STATES},
|
|
219
|
+
"harm": dict(Counter(f.get("harm") or "speed" for f in found)),
|
|
220
|
+
"reasons": [{"state": s, "reason": r, "findings": n} for (s, r), n in
|
|
221
|
+
Counter(((f.get("outcome") or {}).get("state"), (f.get("outcome") or {}).get("reason")) for f in found).most_common()]}
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
# --- the merge into findings.json ---------------------------------------------------------------------------------------
|
|
225
|
+
|
|
226
|
+
def merge(data: dict, out_dir: Path, names: list[str] | None = None, heat_facts=None) -> dict:
|
|
227
|
+
"""findings.json with every kind stage file's findings appended (ids R-001 by the kind's prefix) and `kinds`: per kind
|
|
228
|
+
{label, sites, findings, states, harm, reasons}. The query findings and the query roll-up (`outcomes`) are untouched.
|
|
229
|
+
`heat_facts` (heat.Facts): heat worked out again from what is known now (codecop.toml overrides, imported counts, the
|
|
230
|
+
pulled workload), every kind re-ranked by it; the query findings get `heat` from their measured executions, order kept."""
|
|
231
|
+
out = dict(data)
|
|
232
|
+
out.setdefault("findings", [])
|
|
233
|
+
section = {}
|
|
234
|
+
for k in all_kinds():
|
|
235
|
+
if names is not None and k.name not in names:
|
|
236
|
+
continue
|
|
237
|
+
doc = load(out_dir, k.name)
|
|
238
|
+
if doc is None:
|
|
239
|
+
continue
|
|
240
|
+
found = []
|
|
241
|
+
for i, f in enumerate(doc.get("findings") or [], 1):
|
|
242
|
+
if isinstance(f, dict):
|
|
243
|
+
found.append({**f, "finding": f.get("finding") or f"{k.prefix}-{i:03d}", "kind": k.name})
|
|
244
|
+
out["findings"] = [f for f in out["findings"] if (f.get("kind") or QUERY) != k.name] + found
|
|
245
|
+
section[k.name] = {"label": k.label, **summary(found, int(doc.get("sites") or 0))}
|
|
246
|
+
if section:
|
|
247
|
+
out["kinds"] = section
|
|
248
|
+
if heat_facts is not None:
|
|
249
|
+
from .. import heat
|
|
250
|
+
try:
|
|
251
|
+
out = heat.apply_to_report(out, heat_facts)
|
|
252
|
+
except Exception: # noqa: BLE001 -- heat must never lose the report
|
|
253
|
+
pass
|
|
254
|
+
return out
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def report_html(out_dir: Path, data: dict, root: Path | None = None) -> str:
|
|
258
|
+
"""report.html's sections of the other kinds: each kind's own `report_html`, else a generic table."""
|
|
259
|
+
from ..report import e
|
|
260
|
+
parts = []
|
|
261
|
+
for name, meta in (data.get("kinds") or {}).items():
|
|
262
|
+
k = get(name)
|
|
263
|
+
found = [f for f in data.get("findings") or [] if f.get("kind") == name]
|
|
264
|
+
custom = ""
|
|
265
|
+
if k is not None:
|
|
266
|
+
try:
|
|
267
|
+
custom = k.report_html(context(root or out_dir, out_dir, name, inventory=None), found) or ""
|
|
268
|
+
except Exception: # noqa: BLE001
|
|
269
|
+
custom = ""
|
|
270
|
+
if custom:
|
|
271
|
+
parts.append(custom)
|
|
272
|
+
heated = [f for f in found if (f.get("heat") or {}).get("words")]
|
|
273
|
+
if heated: # the kind's own section is kept; how often each finding runs is listed under it, in rank order
|
|
274
|
+
parts.append(f"<h3>{e(meta.get('label') or name)}: how often each runs</h3><table><tr><th>finding</th><th>where</th>"
|
|
275
|
+
"<th>state</th><th>heat</th><th>basis</th></tr>" + "".join(
|
|
276
|
+
f"<tr><td>{e(f.get('finding'))}</td><td>{e((f.get('site') or {}).get('file'))}:{e((f.get('site') or {}).get('line'))}</td>"
|
|
277
|
+
f"<td>{e((f.get('outcome') or {}).get('state'))}</td><td>{e(f['heat'].get('level'))} "
|
|
278
|
+
f"({e(f['heat'].get('source'))}, {e(f['heat'].get('confidence'))})</td><td>{e(f['heat']['words'])}</td></tr>"
|
|
279
|
+
for f in heated) + "</table>")
|
|
280
|
+
continue
|
|
281
|
+
rows = "".join(f"<tr><td>{e(f.get('finding'))}</td><td>{e((f.get('site') or {}).get('file'))}:{e((f.get('site') or {}).get('line'))}</td>"
|
|
282
|
+
f"<td>{e(f.get('title'))}</td><td>{e((f.get('outcome') or {}).get('state'))}</td>"
|
|
283
|
+
f"<td>{e(((f.get('heat') or {}).get('words')) or '')}</td><td><pre>{e(handoff_text(f))}</pre></td></tr>"
|
|
284
|
+
for f in found)
|
|
285
|
+
parts.append(f"<h2>{e(meta.get('label') or name)}</h2><p class=muted>{meta.get('sites', 0)} call sites, {meta.get('findings', 0)} findings</p>"
|
|
286
|
+
f"<table><tr><th>finding</th><th>where</th><th>what</th><th>state</th><th>how often it runs</th><th>proof and hand-off</th></tr>"
|
|
287
|
+
f"{rows}</table>")
|
|
288
|
+
return "".join(parts)
|