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,235 @@
|
|
|
1
|
+
"""The regex sandbox: run a pattern on its own engine in a child process with a hard timeout and resource limits.
|
|
2
|
+
|
|
3
|
+
One small program per engine lives in `engines/` (run_python.py, run_node.js, RegexHarness.java, run_go.go, run_rust.rs).
|
|
4
|
+
Each reads one JSON request on stdin and writes JSON lines, flushed as it goes, so a run that is killed at the timeout
|
|
5
|
+
keeps the sizes it measured. Go, Rust and Java programs are built once per toolchain into CodeCop's cache directory (Go and
|
|
6
|
+
Rust offline: no download; a Rust build needs the `regex` crate in the local cargo cache). An engine whose toolchain is
|
|
7
|
+
missing is reported as not available: its patterns are "could not be judged", never measured on another engine.
|
|
8
|
+
|
|
9
|
+
Nothing from the repository is run: the child gets the extracted pattern and strings CodeCop generated.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import hashlib
|
|
15
|
+
import json
|
|
16
|
+
import os
|
|
17
|
+
import shutil
|
|
18
|
+
import subprocess
|
|
19
|
+
import sys
|
|
20
|
+
import tempfile
|
|
21
|
+
import threading
|
|
22
|
+
import time
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
|
|
25
|
+
HERE = Path(__file__).parent / "engines"
|
|
26
|
+
HARNESS_VERSION = "1"
|
|
27
|
+
# engine name -> the flavor the parser reads it in, the program, and the module the program loads
|
|
28
|
+
ENGINES = {
|
|
29
|
+
"python": {"flavor": "python", "label": "CPython re", "module": "re"},
|
|
30
|
+
"python-regex": {"flavor": "python", "label": "Python regex module", "module": "regex"},
|
|
31
|
+
"node": {"flavor": "js", "label": "Node (V8 irregexp)"},
|
|
32
|
+
"java": {"flavor": "java", "label": "java.util.regex"},
|
|
33
|
+
"go": {"flavor": "go", "label": "Go regexp"},
|
|
34
|
+
"rust": {"flavor": "rust", "label": "Rust regex crate", "module": "regex"},
|
|
35
|
+
"rust-fancy": {"flavor": "rust", "label": "Rust fancy-regex", "module": "fancy"},
|
|
36
|
+
}
|
|
37
|
+
LINEAR = {"go", "rust"}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def cache_dir() -> Path:
|
|
41
|
+
base = os.environ.get("CODECOP_CACHE_DIR") or str(Path.home() / ".cache" / "codecop")
|
|
42
|
+
return Path(base) / "regex-engines"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class Unavailable(RuntimeError):
|
|
46
|
+
"""The engine's toolchain is not on this machine (or its harness could not be built)."""
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class Engines:
|
|
50
|
+
"""Which engines this machine has, their versions, and the call into each harness. `settings`: the `[kinds.regex]`
|
|
51
|
+
table (python: an interpreter path; timeout_s; memory_mb)."""
|
|
52
|
+
|
|
53
|
+
def __init__(self, settings: dict | None = None):
|
|
54
|
+
self.settings = dict(settings or {})
|
|
55
|
+
self._cmd: dict[str, list[str] | None] = {}
|
|
56
|
+
self._why: dict[str, str] = {}
|
|
57
|
+
self._version: dict[str, str] = {}
|
|
58
|
+
self._lock = threading.Lock()
|
|
59
|
+
|
|
60
|
+
# --- availability --------------------------------------------------------------------------------------------------
|
|
61
|
+
def command(self, name: str) -> list[str]:
|
|
62
|
+
with self._lock:
|
|
63
|
+
if name not in self._cmd:
|
|
64
|
+
try:
|
|
65
|
+
self._cmd[name] = self._build(name)
|
|
66
|
+
except Unavailable as e:
|
|
67
|
+
self._cmd[name], self._why[name] = None, str(e)
|
|
68
|
+
except (OSError, subprocess.SubprocessError) as e:
|
|
69
|
+
self._cmd[name], self._why[name] = None, f"{type(e).__name__}: {e}"[:200]
|
|
70
|
+
cmd = self._cmd[name]
|
|
71
|
+
if cmd is None:
|
|
72
|
+
raise Unavailable(self._why.get(name) or f"{name} is not available")
|
|
73
|
+
return cmd
|
|
74
|
+
|
|
75
|
+
def available(self, name: str) -> tuple[bool, str]:
|
|
76
|
+
try:
|
|
77
|
+
self.command(name)
|
|
78
|
+
return True, self.version(name)
|
|
79
|
+
except Unavailable as e:
|
|
80
|
+
return False, str(e)
|
|
81
|
+
|
|
82
|
+
def version(self, name: str) -> str:
|
|
83
|
+
if name not in self._version:
|
|
84
|
+
v = ""
|
|
85
|
+
try:
|
|
86
|
+
lines, _, _ = self.call(name, {"op": "version"}, timeout_s=60)
|
|
87
|
+
v = (lines[0] if lines else {}).get("version", "")
|
|
88
|
+
except Unavailable:
|
|
89
|
+
pass
|
|
90
|
+
if name.startswith("rust"):
|
|
91
|
+
v = self._rust_versions("fancy-regex" if name == "rust-fancy" else "regex") or v
|
|
92
|
+
self._version[name] = v
|
|
93
|
+
return self._version[name]
|
|
94
|
+
|
|
95
|
+
def _build(self, name: str) -> list[str]:
|
|
96
|
+
if name in ("python", "python-regex"):
|
|
97
|
+
exe = self.settings.get("python") or sys.executable
|
|
98
|
+
if not exe or not (Path(exe).exists() or shutil.which(exe)):
|
|
99
|
+
raise Unavailable("no Python interpreter")
|
|
100
|
+
if name == "python-regex":
|
|
101
|
+
ok = subprocess.run([exe, "-I", "-c", "import regex"], capture_output=True, timeout=30).returncode == 0
|
|
102
|
+
if not ok:
|
|
103
|
+
raise Unavailable("the Python `regex` module is not installed for this interpreter")
|
|
104
|
+
return [exe, "-I", str(HERE / "run_python.py")]
|
|
105
|
+
if name == "node":
|
|
106
|
+
node = shutil.which(self.settings.get("node") or "node")
|
|
107
|
+
if not node:
|
|
108
|
+
raise Unavailable("node is not installed")
|
|
109
|
+
return [node, "--stack-size=984", str(HERE / "run_node.js")]
|
|
110
|
+
if name == "java":
|
|
111
|
+
java, javac = shutil.which("java"), shutil.which("javac")
|
|
112
|
+
if not java or not javac:
|
|
113
|
+
raise Unavailable("a JDK (java and javac) is not installed")
|
|
114
|
+
ver = subprocess.run([java, "-version"], capture_output=True, text=True, timeout=60).stderr.splitlines()
|
|
115
|
+
tag = hashlib.sha256(((ver[0] if ver else "") + HARNESS_VERSION + (HERE / "RegexHarness.java").read_text()).encode()).hexdigest()[:12]
|
|
116
|
+
d = cache_dir() / f"java-{tag}"
|
|
117
|
+
if not (d / "RegexHarness.class").exists():
|
|
118
|
+
d.mkdir(parents=True, exist_ok=True)
|
|
119
|
+
r = subprocess.run([javac, "-d", str(d), str(HERE / "RegexHarness.java")], capture_output=True, text=True, timeout=300)
|
|
120
|
+
if r.returncode != 0:
|
|
121
|
+
raise Unavailable("the Java harness did not compile: " + (r.stderr or r.stdout)[-200:])
|
|
122
|
+
return [java, "-XX:-UsePerfData", "-XX:+UseSerialGC", "-Xshare:auto", "-cp", str(d), "RegexHarness"]
|
|
123
|
+
if name == "go":
|
|
124
|
+
go = shutil.which("go")
|
|
125
|
+
if not go:
|
|
126
|
+
raise Unavailable("go is not installed")
|
|
127
|
+
ver = subprocess.run([go, "version"], capture_output=True, text=True, timeout=60).stdout.strip()
|
|
128
|
+
src = (HERE / "run_go.go").read_text()
|
|
129
|
+
tag = hashlib.sha256((ver + HARNESS_VERSION + src).encode()).hexdigest()[:12]
|
|
130
|
+
d = cache_dir() / f"go-{tag}"
|
|
131
|
+
exe = d / "harness"
|
|
132
|
+
if not exe.exists():
|
|
133
|
+
d.mkdir(parents=True, exist_ok=True)
|
|
134
|
+
(d / "go.mod").write_text("module codecopregex\n\ngo 1.18\n")
|
|
135
|
+
(d / "main.go").write_text(src)
|
|
136
|
+
env = {**os.environ, "GOFLAGS": "-mod=mod", "GOPROXY": "off", "GOTOOLCHAIN": "local", "CGO_ENABLED": "0"}
|
|
137
|
+
r = subprocess.run([go, "build", "-o", str(exe), "."], cwd=d, capture_output=True, text=True, timeout=600, env=env)
|
|
138
|
+
if r.returncode != 0:
|
|
139
|
+
raise Unavailable("the Go harness did not build: " + (r.stderr or r.stdout)[-200:])
|
|
140
|
+
return [str(exe)]
|
|
141
|
+
if name in ("rust", "rust-fancy"):
|
|
142
|
+
cargo = shutil.which("cargo")
|
|
143
|
+
if not cargo:
|
|
144
|
+
raise Unavailable("cargo is not installed")
|
|
145
|
+
ver = subprocess.run([cargo, "--version"], capture_output=True, text=True, timeout=60).stdout.strip()
|
|
146
|
+
src = (HERE / "run_rust.rs").read_text()
|
|
147
|
+
tag = hashlib.sha256((ver + HARNESS_VERSION + src).encode()).hexdigest()[:12]
|
|
148
|
+
d = cache_dir() / f"rust-{tag}"
|
|
149
|
+
exe = d / "target" / "release" / "codecop-regex-harness"
|
|
150
|
+
if not exe.exists():
|
|
151
|
+
(d / "src").mkdir(parents=True, exist_ok=True)
|
|
152
|
+
(d / "Cargo.toml").write_text('[package]\nname = "codecop-regex-harness"\nversion = "0.1.0"\nedition = "2021"\n\n'
|
|
153
|
+
'[dependencies]\nregex = "1"\nfancy-regex = "0"\nserde_json = "1"\n\n'
|
|
154
|
+
'[profile.release]\nopt-level = 3\n')
|
|
155
|
+
(d / "src" / "main.rs").write_text(src)
|
|
156
|
+
env = {**os.environ, "CARGO_NET_OFFLINE": "true"}
|
|
157
|
+
r = subprocess.run([cargo, "build", "--release", "--offline", "--quiet"], cwd=d, capture_output=True, text=True,
|
|
158
|
+
timeout=900, env=env)
|
|
159
|
+
if r.returncode != 0:
|
|
160
|
+
raise Unavailable("the Rust harness did not build offline (the regex crate must be in the local cargo cache): "
|
|
161
|
+
+ (r.stderr or r.stdout)[-160:])
|
|
162
|
+
self._rust_dir = d
|
|
163
|
+
return [str(exe)]
|
|
164
|
+
raise Unavailable(f"unknown engine {name}")
|
|
165
|
+
|
|
166
|
+
def _rust_versions(self, only: str = "") -> str:
|
|
167
|
+
d = getattr(self, "_rust_dir", None)
|
|
168
|
+
if d is None or not (d / "Cargo.lock").exists():
|
|
169
|
+
return ""
|
|
170
|
+
text = (d / "Cargo.lock").read_text()
|
|
171
|
+
out = []
|
|
172
|
+
for crate in ((only,) if only else ("regex", "fancy-regex")):
|
|
173
|
+
i = text.find(f'name = "{crate}"\nversion = "')
|
|
174
|
+
if i >= 0:
|
|
175
|
+
j = i + len(f'name = "{crate}"\nversion = "')
|
|
176
|
+
out.append(f"{crate} {text[j:text.find(chr(34), j)]}")
|
|
177
|
+
return ", ".join(out)
|
|
178
|
+
|
|
179
|
+
# --- one call --------------------------------------------------------------------------------------------------------
|
|
180
|
+
def call(self, name: str, request: dict, *, timeout_s: float | None = None) -> tuple[list[dict], bool, float]:
|
|
181
|
+
"""Run one request; returns (the JSON lines written, whether the hard timeout killed it, seconds taken)."""
|
|
182
|
+
cmd = self.command(name)
|
|
183
|
+
mod = ENGINES.get(name, {}).get("module")
|
|
184
|
+
if mod and "module" not in request:
|
|
185
|
+
request = {**request, "module": mod}
|
|
186
|
+
timeout = float(timeout_s if timeout_s is not None else self.settings.get("timeout_s", 20))
|
|
187
|
+
mem = int(self.settings.get("memory_mb", 2048))
|
|
188
|
+
payload = json.dumps(request).encode()
|
|
189
|
+
with tempfile.TemporaryDirectory(prefix="codecop-rx-") as tmp:
|
|
190
|
+
env = {"PATH": os.environ.get("PATH", ""), "HOME": tmp, "LANG": "C.UTF-8", "LC_ALL": "C.UTF-8",
|
|
191
|
+
"TMPDIR": tmp, "GOGC": "off" if name == "go" else "100"}
|
|
192
|
+
started = time.monotonic()
|
|
193
|
+
p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=tmp, env=env,
|
|
194
|
+
preexec_fn=_limits(timeout, mem, name) if os.name == "posix" else None)
|
|
195
|
+
killed = False
|
|
196
|
+
try:
|
|
197
|
+
out, _ = p.communicate(payload, timeout=timeout)
|
|
198
|
+
except subprocess.TimeoutExpired:
|
|
199
|
+
p.kill()
|
|
200
|
+
out, _ = p.communicate()
|
|
201
|
+
killed = True
|
|
202
|
+
took = time.monotonic() - started
|
|
203
|
+
lines = []
|
|
204
|
+
for ln in out.decode("utf-8", "replace").splitlines():
|
|
205
|
+
try:
|
|
206
|
+
lines.append(json.loads(ln))
|
|
207
|
+
except ValueError:
|
|
208
|
+
continue
|
|
209
|
+
return lines, killed, took
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _limits(timeout: float, mem_mb: int, name: str):
|
|
213
|
+
def apply():
|
|
214
|
+
import resource
|
|
215
|
+
cpu = int(timeout) + 2
|
|
216
|
+
try:
|
|
217
|
+
resource.setrlimit(resource.RLIMIT_CPU, (cpu, cpu + 1))
|
|
218
|
+
resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
|
|
219
|
+
resource.setrlimit(resource.RLIMIT_FSIZE, (1 << 20, 1 << 20))
|
|
220
|
+
if sys.platform.startswith("linux") and name in ("python", "python-regex", "rust", "rust-fancy"):
|
|
221
|
+
resource.setrlimit(resource.RLIMIT_AS, (mem_mb << 20, mem_mb << 20))
|
|
222
|
+
except (ValueError, OSError):
|
|
223
|
+
pass
|
|
224
|
+
os.setsid() if hasattr(os, "setsid") else None
|
|
225
|
+
return apply
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def doctor(settings: dict | None = None) -> list[tuple[bool, str, str]]:
|
|
229
|
+
"""(available, engine label, version or why not) for each engine, for `codecop doctor`."""
|
|
230
|
+
e = Engines(settings)
|
|
231
|
+
out = []
|
|
232
|
+
for name in ("python", "node", "java", "go", "rust"):
|
|
233
|
+
ok, detail = e.available(name)
|
|
234
|
+
out.append((ok, ENGINES[name]["label"], detail))
|
|
235
|
+
return out
|
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
"""Measurements on the engine: a growth curve (time against input size for an attack family), the same-matches check
|
|
2
|
+
of two patterns on a corpus, compile cost per call, and the fit that names the growth order.
|
|
3
|
+
|
|
4
|
+
Every number here comes from harness.Engines.call: the pattern ran on its own engine in a child process.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import hashlib
|
|
10
|
+
import json
|
|
11
|
+
import math
|
|
12
|
+
import statistics
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from . import harness
|
|
16
|
+
from .syntax import attack
|
|
17
|
+
|
|
18
|
+
NOISE_MS = 0.02 # below this a timing is noise for the fit
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def settings_of(cfg: dict | None) -> dict:
|
|
22
|
+
"""The `[kinds.regex]` settings with generous defaults: nothing here is a fixed limit."""
|
|
23
|
+
c = dict(cfg or {})
|
|
24
|
+
return {
|
|
25
|
+
"max_input_bytes": int(c.get("max_input_bytes", 128 * 1024)), # the largest attack string measured
|
|
26
|
+
"min_input_bytes": int(c.get("min_input_bytes", 16)),
|
|
27
|
+
"budget_ms": float(c.get("budget_ms", 1000)), # one run slower than this stops the curve
|
|
28
|
+
"timeout_s": float(c.get("timeout_s", 10)), # hard timeout of one child process
|
|
29
|
+
"runs": int(c.get("runs", 5)), # repeated runs per size (fewer once slow)
|
|
30
|
+
"slow_ms": float(c.get("slow_ms", 100)), # verified slow: this long at the stated size
|
|
31
|
+
"superlinear_slope": float(c.get("superlinear_slope", 1.5)),
|
|
32
|
+
"max_pattern_chars": int(c.get("max_exp_chars", 64)),
|
|
33
|
+
"corpus_size": int(c.get("corpus_size", 2000)),
|
|
34
|
+
"families": int(c.get("families", 6)),
|
|
35
|
+
"compile_calls": int(c.get("compile_calls", 200)),
|
|
36
|
+
"typical_bytes": int(c.get("typical_bytes", 256 * 1024)),
|
|
37
|
+
"workers": int(c.get("workers", 0)),
|
|
38
|
+
"memory_mb": int(c.get("memory_mb", 2048)),
|
|
39
|
+
"python": c.get("python") or "",
|
|
40
|
+
"seed": int(c.get("seed", 7)),
|
|
41
|
+
"bounded_ok_ms": float(c.get("bounded_ok_ms", c.get("slow_ms", 100))),
|
|
42
|
+
"restart_skip": bool(c.get("restart_skip", True)), # offer the scan helper where no pattern can fix a restart
|
|
43
|
+
"typical_cost_ms": float(c.get("typical_cost_ms", 1.0)), # what a fix may add on ordinary text before it is a trade-off
|
|
44
|
+
"class_strings": int(c.get("class_strings", 20000)), # strings with one character per alphabet class swapped in
|
|
45
|
+
"table_sizes": [int(x) for x in (c.get("table_sizes") or [4096, 65536, 262144])], # ordinary text a table or word loop runs on
|
|
46
|
+
"plant_every": int(c.get("plant_every", 4096)), # one string a pattern matches every this many characters
|
|
47
|
+
"min_gain_ms": float(c.get("min_gain_ms", 1.0)), # a saving smaller than this at the largest size is not a finding
|
|
48
|
+
"literal_min": int(c.get("literal_min", 3)), # the shortest required literal worth looking for first
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class Cache:
|
|
53
|
+
"""Measurements kept between runs (`<out>/kinds/regex-measure.json`): the same pattern, engine version, request and
|
|
54
|
+
harness version are never measured twice."""
|
|
55
|
+
|
|
56
|
+
def __init__(self, path: Path | None):
|
|
57
|
+
self.path = path
|
|
58
|
+
self.data: dict = {}
|
|
59
|
+
if path and path.exists():
|
|
60
|
+
try:
|
|
61
|
+
self.data = json.loads(path.read_text())
|
|
62
|
+
except ValueError:
|
|
63
|
+
self.data = {}
|
|
64
|
+
self.dirty = False
|
|
65
|
+
|
|
66
|
+
@staticmethod
|
|
67
|
+
def key(*parts) -> str:
|
|
68
|
+
return hashlib.sha256(json.dumps(parts, sort_keys=True, ensure_ascii=False).encode()).hexdigest()[:24]
|
|
69
|
+
|
|
70
|
+
def get(self, k):
|
|
71
|
+
return self.data.get(k)
|
|
72
|
+
|
|
73
|
+
def put(self, k, v):
|
|
74
|
+
self.data[k] = v
|
|
75
|
+
self.dirty = True
|
|
76
|
+
|
|
77
|
+
def save(self):
|
|
78
|
+
if self.path and self.dirty:
|
|
79
|
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
80
|
+
self.path.write_text(json.dumps(self.data))
|
|
81
|
+
self.dirty = False
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def sizes(fam: dict, lo: int, hi: int) -> list[int]:
|
|
85
|
+
"""Pump counts that make the attack string about lo, 2lo, 4lo ... hi characters."""
|
|
86
|
+
unit = max(1, len(fam["pump"]))
|
|
87
|
+
fixed = len(fam["prefix"]) + len(fam["suffix"])
|
|
88
|
+
out, L = [], lo
|
|
89
|
+
while L <= hi:
|
|
90
|
+
n = max(1, (L - fixed) // unit)
|
|
91
|
+
if not out or n > out[-1]:
|
|
92
|
+
out.append(n)
|
|
93
|
+
L *= 2
|
|
94
|
+
return out
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _median(xs):
|
|
98
|
+
return statistics.median(xs) if xs else None
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def time_inputs(eng: harness.Engines, engine: str, pattern: str, flags: str, mode: str, inputs: list[str], st: dict, *,
|
|
102
|
+
take: int | None = None, runs: int | None = None, code: dict | None = None, op: dict | None = None) -> dict:
|
|
103
|
+
"""Times of one pattern on growing inputs: points [[len, median ms, min, max, runs]], `stopped` when a run passed
|
|
104
|
+
the budget, `killed` when the hard timeout ended the child (the next size took at least that long). `code`: a fix
|
|
105
|
+
written as a function ({code, entry}) runs in place of the pattern; `op`: another request (a table, a word loop)."""
|
|
106
|
+
req = {"op": "time", "pattern": pattern, "flags": flags, "mode": mode, "inputs": inputs, "runs": runs or st["runs"],
|
|
107
|
+
"budget_ms": st["budget_ms"], "take": take, **(code or {}), **(op or {})}
|
|
108
|
+
lines, killed, took = eng.call(engine, req, timeout_s=st["timeout_s"])
|
|
109
|
+
pts, err, stopped = [], None, None
|
|
110
|
+
for ln in lines:
|
|
111
|
+
if "error" in ln and "i" not in ln:
|
|
112
|
+
err = ln.get("detail") or ln["error"]
|
|
113
|
+
elif "stopped" in ln:
|
|
114
|
+
stopped = ln["stopped"]
|
|
115
|
+
elif "i" in ln:
|
|
116
|
+
ms = [float(x) for x in ln.get("ms") or []]
|
|
117
|
+
if ln.get("error"):
|
|
118
|
+
err = ln["error"]
|
|
119
|
+
pts.append([int(ln["len"]), _median(ms), min(ms), max(ms), len(ms)])
|
|
120
|
+
out = {"points": pts, "killed": killed, "stopped": stopped is not None, "error": err}
|
|
121
|
+
if killed:
|
|
122
|
+
done = len(pts)
|
|
123
|
+
if done < len(inputs):
|
|
124
|
+
out["censored"] = [len(inputs[done]), round(took * 1000, 1)] # at least this long at this size
|
|
125
|
+
return out
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _regress(xs, ys):
|
|
129
|
+
mx, my = sum(xs) / len(xs), sum(ys) / len(ys)
|
|
130
|
+
den = sum((x - mx) ** 2 for x in xs)
|
|
131
|
+
if not den:
|
|
132
|
+
return 0.0, 0.0
|
|
133
|
+
b = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / den
|
|
134
|
+
ss = sum((y - my) ** 2 for y in ys)
|
|
135
|
+
return b, (b * b * den / ss) if ss else 0.0
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def fit(points: list[list]) -> dict:
|
|
139
|
+
"""The growth order of a curve: the slope of log time against log size over the top points above the noise floor
|
|
140
|
+
(1 linear, 2 quadratic, ...); when log time is linear in the size itself and that slope is steep, exponential, with
|
|
141
|
+
its factor per character."""
|
|
142
|
+
pts = [(p[0], p[1]) for p in points if p[1] is not None and p[1] >= NOISE_MS and p[0] > 0]
|
|
143
|
+
if len(pts) < 2:
|
|
144
|
+
return {"order": "flat", "slope": None}
|
|
145
|
+
top = pts[-min(len(pts), 5):]
|
|
146
|
+
k, r2_poly = _regress([math.log(p[0]) for p in top], [math.log(p[1]) for p in top])
|
|
147
|
+
b, r2_exp = _regress([float(p[0]) for p in top], [math.log(p[1]) for p in top])
|
|
148
|
+
if len(top) >= 3 and k >= 2.6 and r2_exp >= 0.9 and (r2_exp >= r2_poly or k >= 4.5) and math.exp(b) >= 1.05:
|
|
149
|
+
return {"order": "exponential", "slope": round(k, 2), "per_char": round(math.exp(b), 3)}
|
|
150
|
+
if k >= 4.5:
|
|
151
|
+
order = "exponential"
|
|
152
|
+
elif k >= 2.6:
|
|
153
|
+
order = "cubic"
|
|
154
|
+
elif k >= 1.6:
|
|
155
|
+
order = "quadratic"
|
|
156
|
+
elif k >= 1.25:
|
|
157
|
+
order = "super-linear"
|
|
158
|
+
else:
|
|
159
|
+
order = "linear"
|
|
160
|
+
return {"order": order, "slope": round(k, 2)}
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
SUPER = ("exponential", "cubic", "quadratic", "super-linear")
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def grow(eng: harness.Engines, engine: str, pattern: str, flags: str, mode: str, fam: dict, st: dict, cache: Cache | None = None,
|
|
167
|
+
*, take: int | None = None, version: str = "", code: dict | None = None) -> dict:
|
|
168
|
+
"""The curve of one attack family: doubling sizes up to `max_input_bytes`; when it jumps (a doubling costs more
|
|
169
|
+
than 16x) or the child is killed, the steps between the last two sizes are measured one pump at a time so an
|
|
170
|
+
exponential curve shows its factor per character."""
|
|
171
|
+
k = Cache.key("grow", harness.HARNESS_VERSION, engine, version, pattern, flags, mode, fam, take, st["max_input_bytes"],
|
|
172
|
+
st["min_input_bytes"], st["budget_ms"], st["runs"], *([code] if code else []))
|
|
173
|
+
if cache is not None and cache.get(k):
|
|
174
|
+
return cache.get(k)
|
|
175
|
+
ns = sizes(fam, st["min_input_bytes"], st["max_input_bytes"])
|
|
176
|
+
got = time_inputs(eng, engine, pattern, flags, mode, [attack(fam, n) for n in ns], st, take=take, code=code)
|
|
177
|
+
pts = list(got["points"])
|
|
178
|
+
censored = got.get("censored")
|
|
179
|
+
killed, stopped, err = got["killed"], got["stopped"], got.get("error")
|
|
180
|
+
# A curve that ran out of budget between two doublings: measure the steps between the last size that finished in
|
|
181
|
+
# time and the one that did not, finer each round, so an exponential curve shows its factor per character.
|
|
182
|
+
lo_i = max((i for i, p in enumerate(pts) if p[1] is not None and p[1] <= st["budget_ms"]), default=-1)
|
|
183
|
+
a_ms = pts[lo_i][1] if lo_i >= 0 else 0.0
|
|
184
|
+
b_ms = pts[lo_i + 1][1] if lo_i + 1 < len(pts) else (censored[1] if censored else None)
|
|
185
|
+
jumped = (killed or stopped) and b_ms is not None and (a_ms or NOISE_MS) * 16 < b_ms
|
|
186
|
+
if jumped:
|
|
187
|
+
n_lo = ns[lo_i] if lo_i >= 0 else 0
|
|
188
|
+
n_hi = ns[lo_i + 1] if lo_i + 1 < len(ns) else ns[-1]
|
|
189
|
+
fine_st = {**st, "timeout_s": max(2.0, min(st["timeout_s"], 3 * st["budget_ms"] / 1000))}
|
|
190
|
+
for _ in range(3):
|
|
191
|
+
step = max(1, (n_hi - n_lo) // 8)
|
|
192
|
+
seq = list(range(n_lo + step, n_hi, step))
|
|
193
|
+
if not seq:
|
|
194
|
+
break
|
|
195
|
+
more = time_inputs(eng, engine, pattern, flags, mode, [attack(fam, n) for n in seq], fine_st, take=take, runs=min(st["runs"], 3),
|
|
196
|
+
code=code)
|
|
197
|
+
pts += more["points"]
|
|
198
|
+
if more.get("censored"):
|
|
199
|
+
censored = more["censored"] if not censored or more["censored"][0] < censored[0] else censored
|
|
200
|
+
fine = [i for i, p in enumerate(more["points"]) if p[1] is not None and p[1] <= st["budget_ms"]]
|
|
201
|
+
if step == 1 or len(more["points"]) == len(seq) and not more["stopped"]:
|
|
202
|
+
break
|
|
203
|
+
last = fine[-1] if fine else -1
|
|
204
|
+
n_lo = seq[last] if last >= 0 else n_lo
|
|
205
|
+
n_hi = seq[last + 1] if last + 1 < len(seq) else n_hi
|
|
206
|
+
pts = sorted({p[0]: p for p in pts}.values())
|
|
207
|
+
g = fit(pts)
|
|
208
|
+
out = {"family": fam, "points": pts, "fit": g, "killed": killed, "stopped": stopped, "censored": censored, "error": err}
|
|
209
|
+
if cache is not None:
|
|
210
|
+
cache.put(k, out)
|
|
211
|
+
return out
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def at(curve: dict, length: int) -> list | None:
|
|
215
|
+
"""The measured point at a length (exact), or None."""
|
|
216
|
+
for p in curve.get("points") or []:
|
|
217
|
+
if p[0] == length:
|
|
218
|
+
return p
|
|
219
|
+
return None
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def results(eng: harness.Engines, engine: str, pattern: str, flags: str, mode: str, inputs: list[str], st: dict, *,
|
|
223
|
+
take: int | None = None, code: dict | None = None, op: dict | None = None) -> list | None:
|
|
224
|
+
req = {"op": "results", "pattern": pattern, "flags": flags, "mode": mode, "inputs": inputs, "take": take, **(code or {})}
|
|
225
|
+
if op:
|
|
226
|
+
req.update({**op, "results": True})
|
|
227
|
+
lines, killed, _ = eng.call(engine, req, timeout_s=st["timeout_s"] * 2)
|
|
228
|
+
for ln in lines:
|
|
229
|
+
if "results" in ln:
|
|
230
|
+
return ln["results"]
|
|
231
|
+
return None
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def same_matches(eng: harness.Engines, engine: str, before: str, after: str, flags: str, mode: str, corpus: list[str], st: dict, *,
|
|
235
|
+
take_before: int | None = None, take_after: int | None = None, cmp=None, code_after: dict | None = None,
|
|
236
|
+
op_before: dict | None = None, op_after: dict | None = None) -> dict:
|
|
237
|
+
"""Both sides on the same corpus on the engine: compared, differed, the first differing string (generated, never
|
|
238
|
+
a customer's) or None when a side could not run. `cmp(a, b)` compares two results (default: equal). `code_after`:
|
|
239
|
+
the after side is a fix written as a function; `op_before`/`op_after`: a table or word-loop request per side."""
|
|
240
|
+
a = results(eng, engine, before, flags, mode, corpus, st, take=take_before, op=op_before)
|
|
241
|
+
b = results(eng, engine, after, flags, mode, corpus, st, take=take_after, code=code_after, op=op_after)
|
|
242
|
+
if a is None or b is None or len(a) != len(corpus) or len(b) != len(corpus):
|
|
243
|
+
return {"held": None, "compared": 0, "differed": 0, "example": None, "matching": 0}
|
|
244
|
+
eq = cmp or (lambda x, y: x == y)
|
|
245
|
+
diff = [i for i in range(len(corpus)) if not eq(a[i], b[i])]
|
|
246
|
+
matching = sum(1 for r in a if r not in (None, False, 0, []))
|
|
247
|
+
return {"held": not diff, "compared": len(corpus), "differed": len(diff), "matching": matching,
|
|
248
|
+
"example": (corpus[diff[0]][:80] if diff else None)}
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def compile_cost(eng: harness.Engines, engine: str, pattern: str, flags: str, mode: str, sample: str, st: dict) -> dict | None:
|
|
252
|
+
lines, _, _ = eng.call(engine, {"op": "compile", "pattern": pattern, "flags": flags, "mode": mode, "inputs": [sample],
|
|
253
|
+
"n": st["compile_calls"], "runs": st["runs"]}, timeout_s=st["timeout_s"])
|
|
254
|
+
for ln in lines:
|
|
255
|
+
if "per_call_compiled_each_ms" in ln:
|
|
256
|
+
return ln
|
|
257
|
+
if "error" in ln:
|
|
258
|
+
return {"error": ln.get("detail") or ln["error"]}
|
|
259
|
+
return None
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def spread_of(p: list | None) -> tuple | None:
|
|
263
|
+
return (p[2], p[3]) if p else None
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def gain_beyond_spread(before: list | None, after: list | None) -> bool:
|
|
267
|
+
"""A gain only when the slowest after-run is faster than the fastest before-run."""
|
|
268
|
+
if not before or not after:
|
|
269
|
+
return False
|
|
270
|
+
return after[3] < before[2]
|