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,1167 @@
|
|
|
1
|
+
"""The regex kind: slow regular expressions on a server path, proven on their own engine.
|
|
2
|
+
|
|
3
|
+
A regex is a finding only when (1) it is verified slow on the engine that runs it (CPython re, Node/V8, Java, Go regexp,
|
|
4
|
+
Rust regex or fancy-regex), (2) it runs on a server, request or job path (tests, scripts, build tooling and browser-only
|
|
5
|
+
code are set aside), and (3) its input is not shown to be bounded (a cut before the call ends it as "nothing to gain"
|
|
6
|
+
with the worst case at that bound). Go and Rust's default engines are linear: there the costs are a compile on every
|
|
7
|
+
call, a Unicode word boundary on ASCII text, and a count of every match where the caller needs the first few. Swapping to
|
|
8
|
+
a linear engine is never offered as a fix.
|
|
9
|
+
|
|
10
|
+
Flow (docs/kinds.md): discover (extract.py) -> rules (syntax.py: the static check, compile per call, Unicode boundary,
|
|
11
|
+
bounded count) -> questions/ask (the agent, for what rules cannot rewrite or bound) -> verify (harness.py, measure.py: the
|
|
12
|
+
growth curve on the engine, the same-matches check on a generated corpus, compile cost).
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import json
|
|
18
|
+
import random
|
|
19
|
+
import re
|
|
20
|
+
import threading
|
|
21
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
|
|
24
|
+
from .. import Kind, finding, measure as kmeasure, outcome, proof, register, sameness
|
|
25
|
+
from . import extract, harness, measure as M, shapes, syntax
|
|
26
|
+
|
|
27
|
+
PROMPT_VERSION = "regex-2"
|
|
28
|
+
OLD_PROMPTS = ("regex-1",) # answers to an earlier prompt still count (a re-run never pays again for them)
|
|
29
|
+
SET_ASIDE_ROLES = {"test", "script", "tooling", "migration"}
|
|
30
|
+
# test files the shared path check does not name (JS/TS test and spec files, end-to-end suites, Go tests)
|
|
31
|
+
TEST_FILE = re.compile(r"\.(?:test|spec)\.[cm]?[jt]sx?$|_test\.go$|(?:^|/)(?:__tests__|e2e|playwright|cypress)/")
|
|
32
|
+
BACKTRACKING = {"python", "python-regex", "node", "java", "rust-fancy"}
|
|
33
|
+
FIX_WORDS = {"possessive_quantifier": "the repeat gives nothing back", "lookbehind_guard": "no match starts inside a run",
|
|
34
|
+
"disjoint_branch": "the branches start differently", "ascii_word_boundary": "ASCII word boundary",
|
|
35
|
+
"bounded_count": "stop at the first N matches", "hoist_compile": "compile once", "agent_rewrite": "the agent's rewrite",
|
|
36
|
+
"restart_skip": "a scan helper skips the starts that must fail", "agent_code": "the agent's helper function",
|
|
37
|
+
"required_literal_prefilter": "a pattern runs only when its required literal is in the text",
|
|
38
|
+
"fold_once": "the text folded once instead of a case-insensitive flag", "one_alternation": "one alternation of all the words"}
|
|
39
|
+
HELPER_FIXES = {"restart_skip", "agent_code"} # the fix is a small function, not a pattern
|
|
40
|
+
PY_ENGINES = {"python", "python-regex"}
|
|
41
|
+
CANDIDATE = {"type": "object", "properties": {"kind": {"type": "string", "enum": ["pattern", "code", "bound"]},
|
|
42
|
+
"pattern": {"type": ["string", "null"]}, "code": {"type": ["string", "null"]},
|
|
43
|
+
"why": {"type": ["string", "null"]}}, "required": ["kind"]}
|
|
44
|
+
ANSWER_SCHEMA = {"type": "object", "properties": {"answers": {"type": "array", "items": {"type": "object", "properties": {
|
|
45
|
+
"id": {"type": "string"}, "candidates": {"type": "array", "items": CANDIDATE}, "rewrite": {"type": ["string", "null"]},
|
|
46
|
+
"bounded": {"type": ["boolean", "null"]}, "bound_chars": {"type": ["integer", "null"]}, "evidence": {"type": ["string", "null"]},
|
|
47
|
+
"note": {"type": ["string", "null"]}}, "required": ["id"]}}}, "required": ["answers"]}
|
|
48
|
+
MODE_WORDS = {"all": "every match (finditer, findall, sub)", "search": "the first match", "bool": "whether there is a match",
|
|
49
|
+
"match": "a match at the start", "full": "a whole-string match", "count": "the number of matches"}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _short(s: str | None, n: int = 60) -> str:
|
|
53
|
+
s = "" if s is None else s
|
|
54
|
+
s = s.replace("\n", "\\n").replace("\t", "\\t")
|
|
55
|
+
return s if len(s) <= n else s[: n - 1] + "…"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _python_floor(root: Path) -> tuple:
|
|
59
|
+
"""The lowest Python the repository says it supports (pyproject requires-python), for rewrites that need 3.11."""
|
|
60
|
+
for name in ("pyproject.toml", "setup.cfg"):
|
|
61
|
+
p = root / name
|
|
62
|
+
try:
|
|
63
|
+
text = p.read_text(errors="replace")
|
|
64
|
+
except OSError:
|
|
65
|
+
continue
|
|
66
|
+
m = re.search(r"(?:requires-python|python_requires)\s*=\s*[\"']?\s*(?:>=|~=|==|\^)\s*(\d+)\.(\d+)", text)
|
|
67
|
+
if m:
|
|
68
|
+
return int(m.group(1)), int(m.group(2))
|
|
69
|
+
return (3, 11)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@register
|
|
73
|
+
class Regex(Kind):
|
|
74
|
+
name = "regex"
|
|
75
|
+
label = "Regexes"
|
|
76
|
+
one = "regex"
|
|
77
|
+
prefix = "R"
|
|
78
|
+
items_per_call = 4
|
|
79
|
+
cost_per_item_usd = (0.04, 0.12)
|
|
80
|
+
reasons = {
|
|
81
|
+
"regex.input_bounded": ("nothing_to_gain", "bounded: input cut before the call"),
|
|
82
|
+
"regex.linear_on_engine": ("nothing_to_gain", "no growth faster than linear on its own engine"),
|
|
83
|
+
"regex.engine_not_available": ("not_judged", "its engine is not available on this machine"),
|
|
84
|
+
"regex.pattern_not_read": ("not_judged", "the pattern could not be read"),
|
|
85
|
+
"regex.rewrite_matches_differently": ("blocked", "the rewrite matches differently"),
|
|
86
|
+
"regex.costs_on_ordinary_text": ("blocked", "the fix is faster on the slow input but slower on ordinary text"),
|
|
87
|
+
"regex.no_required_literal": ("nothing_to_gain", "no pattern of the table has a literal to look for first"),
|
|
88
|
+
"regex.table_no_gain": ("nothing_to_gain", "no measured gain on ordinary text"),
|
|
89
|
+
}
|
|
90
|
+
measures = {"time_at_size": ("time at the stated size", "ms"), "growth_slope": ("growth (log-log slope)", ""),
|
|
91
|
+
"time_per_call": ("time per call", "ms"), "table_ms": ("all patterns of the crate on one text", "ms"),
|
|
92
|
+
"ascii_table_ms": ("same, pure ASCII text", "ms"), "compile_ms": ("compile once", "ms"),
|
|
93
|
+
"table_text_ms": ("the whole table on ordinary text", "ms"), "other_inputs_ms": ("time on the other inputs", "ms"),
|
|
94
|
+
"ordinary_ms": ("time on ordinary text", "ms"), "words_ms": ("the word loop on ordinary text", "ms")}
|
|
95
|
+
|
|
96
|
+
def __init__(self):
|
|
97
|
+
self._memo: dict = {}
|
|
98
|
+
self._lock = threading.Lock()
|
|
99
|
+
|
|
100
|
+
# --- discover --------------------------------------------------------------------------------------------------------
|
|
101
|
+
def discover(self, ctx):
|
|
102
|
+
sites = extract.sites(ctx.root, ctx.by_lang, log=ctx.say)
|
|
103
|
+
try:
|
|
104
|
+
sites += shapes.sites(ctx.root, ctx.by_lang)
|
|
105
|
+
except Exception as e: # noqa: BLE001 -- the call shapes must not lose the sites
|
|
106
|
+
ctx.say(f"regex: call shapes not read ({type(e).__name__}: {e})")
|
|
107
|
+
if (ctx.settings or {}).get("config_tables", True):
|
|
108
|
+
try:
|
|
109
|
+
sites += extract.config_tables(ctx.root, ctx.by_lang)
|
|
110
|
+
except OSError:
|
|
111
|
+
pass
|
|
112
|
+
return sites
|
|
113
|
+
|
|
114
|
+
# --- rules -----------------------------------------------------------------------------------------------------------
|
|
115
|
+
def set_aside(self, s: dict) -> str:
|
|
116
|
+
"""Why a site is not a candidate ('' when it is one): off the server path, or nothing to read."""
|
|
117
|
+
from ...discover.base import is_test_path
|
|
118
|
+
f = s.get("file") or ""
|
|
119
|
+
if s.get("is_test") or is_test_path(f) or TEST_FILE.search(f):
|
|
120
|
+
return "not on a server path (test)" # a test file, whatever role the trace gave one of its calls
|
|
121
|
+
if s.get("role") in SET_ASIDE_ROLES:
|
|
122
|
+
return f"not on a server path ({s.get('role')})"
|
|
123
|
+
if s.get("flows") == "vendored":
|
|
124
|
+
return "vendored or minified bundle"
|
|
125
|
+
if s.get("flows") == "browser" and not any((o or {}).get("kind") in ("http", "job", "workflow", "activity", "consumer")
|
|
126
|
+
for o in s.get("origins") or []):
|
|
127
|
+
return "browser only"
|
|
128
|
+
return ""
|
|
129
|
+
|
|
130
|
+
def rules(self, ctx, sites):
|
|
131
|
+
out, groups = [], {}
|
|
132
|
+
for s in sites:
|
|
133
|
+
if self.set_aside(s):
|
|
134
|
+
continue
|
|
135
|
+
pat, engine = s.get("pattern"), s.get("engine") or ""
|
|
136
|
+
flavor = harness.ENGINES.get(engine, {}).get("flavor", "python")
|
|
137
|
+
base = {"id": s["id"], "engine": engine, "pattern": pat, "flags": s.get("flags") or "", "api": s.get("api"),
|
|
138
|
+
"mode": s.get("mode") or "search", "bound": s.get("bound"), "compiled": s.get("compiled"), "ask": False,
|
|
139
|
+
"language": s.get("language"), "use": s.get("use") or "", "name": s.get("name") or "", "def_line": s.get("def_line"),
|
|
140
|
+
"def_file": s.get("def_file") or s.get("file")}
|
|
141
|
+
if s.get("mode") is None:
|
|
142
|
+
continue
|
|
143
|
+
if s.get("shape") == "table" and engine in ("python", "python-regex", "go"):
|
|
144
|
+
out.append({**base, "check": "table", "members": s.get("members"), "table": s.get("name"), "arg": s.get("arg")})
|
|
145
|
+
continue
|
|
146
|
+
if s.get("shape") == "words" and engine in PY_ENGINES:
|
|
147
|
+
words = s.get("members") or []
|
|
148
|
+
if len(words) >= 2 and all(re.fullmatch(r"[\w \-']+", w or "") for w, _ in words) \
|
|
149
|
+
and len({(w.lower() if "i" in (s.get("flags") or "") else w) for w, _ in words}) == len(words):
|
|
150
|
+
out.append({**base, "check": "word_loop", "words": words, "pre": s.get("pre") or "", "post": s.get("post") or "",
|
|
151
|
+
"word_kind": s.get("word_kind") or "sub", "arg": s.get("arg") or "text"})
|
|
152
|
+
continue
|
|
153
|
+
if pat is None:
|
|
154
|
+
if s.get("compiled") in ("function", "loop") and engine in ("go", "java"):
|
|
155
|
+
out.append({**base, "check": "compile_per_call", "why": "pattern built at run time"})
|
|
156
|
+
continue
|
|
157
|
+
try:
|
|
158
|
+
parsed = syntax.parse(pat, flavor, s.get("flags") or "")
|
|
159
|
+
except (syntax.Unsupported, ValueError, IndexError, OverflowError, TypeError, RecursionError):
|
|
160
|
+
if engine in BACKTRACKING:
|
|
161
|
+
out.append({**base, "check": "unreadable"})
|
|
162
|
+
continue
|
|
163
|
+
issues = []
|
|
164
|
+
try:
|
|
165
|
+
if engine in BACKTRACKING:
|
|
166
|
+
issues = [i for i in syntax.analyse(parsed, s.get("api") or "search") if i.code != "unicode_boundary"]
|
|
167
|
+
issues += syntax.lookahead_issues(parsed, s.get("api") or "search")
|
|
168
|
+
rust_boundary = engine == "rust" and any(i.code == "unicode_boundary" for i in syntax.analyse(parsed, "search"))
|
|
169
|
+
except Exception: # noqa: BLE001 -- the static check is a gate: a pattern it cannot read is not a candidate
|
|
170
|
+
continue
|
|
171
|
+
if issues:
|
|
172
|
+
out.append({**base, "check": "backtracking", "issues": [i.code for i in issues], "growth": issues[0].growth,
|
|
173
|
+
"note": issues[0].note})
|
|
174
|
+
continue
|
|
175
|
+
if s.get("take") and (engine.startswith("rust") and s.get("api") == "count" or engine in PY_ENGINES and s.get("api") == "findall"
|
|
176
|
+
or engine == "node" and s.get("api") == "match"):
|
|
177
|
+
out.append({**base, "check": "bounded_count", "take": s["take"]})
|
|
178
|
+
continue
|
|
179
|
+
if s.get("compiled") in ("function", "loop") and engine in ("go", "java", "node", "rust") and s.get("language") != "python":
|
|
180
|
+
out.append({**base, "check": "compile_per_call"})
|
|
181
|
+
continue
|
|
182
|
+
if engine == "python" and "i" in (s.get("flags") or "") and s.get("mode") in ("search", "bool", "all") \
|
|
183
|
+
and syntax.keyword_alternation(parsed) and syntax.fold_eligible(pat, "python", s.get("flags") or ""):
|
|
184
|
+
out.append({**base, "check": "fold_keywords", "keywords": syntax.keyword_alternation(parsed)})
|
|
185
|
+
continue
|
|
186
|
+
if rust_boundary:
|
|
187
|
+
# one group per crate: a worker runs its detectors' patterns on the same text
|
|
188
|
+
groups.setdefault(self._crate(ctx.root, s.get("def_file") or s["file"]), []).append(s)
|
|
189
|
+
for key, members in groups.items():
|
|
190
|
+
pats = {}
|
|
191
|
+
for m in members:
|
|
192
|
+
pats.setdefault((m["pattern"], m.get("flags") or ""), m)
|
|
193
|
+
first = min(members, key=lambda m: (m.get("role") not in ("app", "job"), m["file"], m.get("def_line") or m["line"]))
|
|
194
|
+
out.append({"id": first["id"], "engine": "rust", "check": "unicode_boundary", "ask": False, "def_file": key,
|
|
195
|
+
"patterns": [[p, f] for (p, f) in pats], "members": len(pats), "sites": len(members),
|
|
196
|
+
"pattern": first["pattern"], "flags": first.get("flags") or "", "mode": "count", "api": first.get("api"),
|
|
197
|
+
"language": "rust", "file": first["file"], "line": first["line"]})
|
|
198
|
+
return out
|
|
199
|
+
|
|
200
|
+
@staticmethod
|
|
201
|
+
def _crate(root: Path, rel: str) -> str:
|
|
202
|
+
"""The directory of the nearest Cargo.toml above a file (the crate), else the file's directory."""
|
|
203
|
+
p = Path(rel).parent
|
|
204
|
+
while True:
|
|
205
|
+
if (Path(root) / p / "Cargo.toml").exists():
|
|
206
|
+
return str(p)
|
|
207
|
+
if p == p.parent or str(p) in ("", "."):
|
|
208
|
+
return str(Path(rel).parent)
|
|
209
|
+
p = p.parent
|
|
210
|
+
|
|
211
|
+
# --- the agent -------------------------------------------------------------------------------------------------------
|
|
212
|
+
def _key(self, ctx, c, version: str = PROMPT_VERSION):
|
|
213
|
+
return ctx.answer_key(f"{c['engine']}|{c.get('pattern')}|{c.get('flags')}|{c.get('api')}|{c.get('file')}:{c.get('symbol')}",
|
|
214
|
+
runtime=c["engine"], prompt_version=version)
|
|
215
|
+
|
|
216
|
+
def _answers(self, ctx, c) -> list[dict]:
|
|
217
|
+
"""The agent's answers for a site: to this prompt, then to the earlier ones (kept: never paid for twice)."""
|
|
218
|
+
out = []
|
|
219
|
+
for v in (PROMPT_VERSION,) + OLD_PROMPTS:
|
|
220
|
+
a = ctx.answer(self._key(ctx, c, v))
|
|
221
|
+
if a is not None:
|
|
222
|
+
out.append(a)
|
|
223
|
+
return out
|
|
224
|
+
|
|
225
|
+
def _wants_agent(self, ctx, c) -> bool:
|
|
226
|
+
if c.get("check") != "backtracking":
|
|
227
|
+
return False
|
|
228
|
+
if ctx.answer(self._key(ctx, c)) is not None:
|
|
229
|
+
return False
|
|
230
|
+
j = self.judge(ctx, c, with_agent=False)
|
|
231
|
+
if not (j.get("slow") and j["outcome"]["state"] != "fixed" and j["outcome"]["reason"] != "regex.input_bounded"):
|
|
232
|
+
return False
|
|
233
|
+
if self._answers(ctx, c):
|
|
234
|
+
# answered under an earlier prompt: ask again only when that answer did not end it
|
|
235
|
+
jj = self.judge(ctx, c, with_agent=True)
|
|
236
|
+
return jj["outcome"]["state"] != "fixed" and jj["outcome"]["reason"] != "regex.input_bounded"
|
|
237
|
+
return True
|
|
238
|
+
|
|
239
|
+
def questions(self, ctx, cands):
|
|
240
|
+
out = []
|
|
241
|
+
for c in cands:
|
|
242
|
+
if not self._wants_agent(ctx, c):
|
|
243
|
+
continue
|
|
244
|
+
j = self.judge(ctx, c, with_agent=False)
|
|
245
|
+
on_path = any((o or {}).get("kind") == "http" for o in c.get("origins") or [])
|
|
246
|
+
out.append(ctx.item(c["id"], label=_short(c.get("pattern"), 50), file=c.get("file", ""), line=c.get("line", 0), path=on_path,
|
|
247
|
+
score=float(j.get("before_ms") or 0), why="verified slow; rules found no same-matching rewrite or bound"))
|
|
248
|
+
return out
|
|
249
|
+
|
|
250
|
+
def ask(self, ctx, cands, runner):
|
|
251
|
+
todo = [c for c in cands if self._wants_agent(ctx, c)]
|
|
252
|
+
per = max(1, int(self.items_per_call))
|
|
253
|
+
for i in range(0, len(todo), per):
|
|
254
|
+
batch = todo[i:i + per]
|
|
255
|
+
lines, code_ok = [], False
|
|
256
|
+
for c in batch:
|
|
257
|
+
j = self.judge(ctx, c, with_agent=False)
|
|
258
|
+
fam = j.get("family") or {}
|
|
259
|
+
eng = harness.ENGINES.get(c["engine"], {}).get("label", c["engine"])
|
|
260
|
+
code = c["engine"] in PY_ENGINES
|
|
261
|
+
code_ok = code_ok or code
|
|
262
|
+
tried = "; ".join(f"{FIX_WORDS.get(t[0], t[0])} `{_short(t[1], 70)}` "
|
|
263
|
+
+ (f"differed on {json.dumps(_short(t[2], 40))}" if t[2] is not None else "gave no gain")
|
|
264
|
+
for t in (j.get("tried") or [])[:4]) or "none"
|
|
265
|
+
lines.append(f"- id {c['id']}: {c.get('file')}:{c.get('line')} in {c.get('symbol') or '(module level)'}; engine {eng} "
|
|
266
|
+
f"{self._env(ctx)[1].version(c['engine'])}; call `{_short(c.get('use'), 120)}` (it uses "
|
|
267
|
+
f"{MODE_WORDS.get(c.get('mode'), c.get('mode'))}); pattern (flags '{c.get('flags')}'): {json.dumps(c.get('pattern'))}; "
|
|
268
|
+
f"measured {j.get('before_ms', 0):.1f} ms on {j.get('at_len')} characters of {json.dumps(_short(fam.get('prefix'), 20))} + "
|
|
269
|
+
f"{json.dumps(_short(fam.get('pump'), 20))}*n + {json.dumps(_short(fam.get('suffix'), 10))}, growth {j.get('order')}. "
|
|
270
|
+
f"Why: {j.get('note') or j.get('issue')}. Tried by rule: {tried}."
|
|
271
|
+
+ ("" if code else " (No `code` candidates for this engine.)"))
|
|
272
|
+
prompt = ("You review slow regular expressions found by CodeCop. Each item below was MEASURED slow on its own engine, and the "
|
|
273
|
+
"mechanical rewrites either changed the matches or did not remove the growth. Give up to 3 candidate fixes per item, "
|
|
274
|
+
"best first; every candidate is run against the original on tens of thousands of generated strings and on the slow "
|
|
275
|
+
"inputs, so do not hold back a candidate because you cannot prove it; say in `why`, in one sentence, why it is the "
|
|
276
|
+
"same.\nA candidate is ONE of:\n"
|
|
277
|
+
"- kind \"pattern\": a pattern for the SAME engine and flags that matches exactly the same strings with the same "
|
|
278
|
+
"groups. Do not switch engines.\n"
|
|
279
|
+
+ ("- kind \"code\" (Python engines only): the source of a function `def fixed(text):` that runs in linear time. For a "
|
|
280
|
+
"call that uses every match it returns an iterable of match objects whose span() and group(1..N) equal those of "
|
|
281
|
+
"PAT.finditer(text) (N = the original's group count); for the first match, that match object or None. It may use "
|
|
282
|
+
"the ORIGINAL compiled pattern as `PAT` (for example PAT.match(text, pos)), `re`, plain str methods and patterns it "
|
|
283
|
+
"compiles itself; nothing else can be imported. Use it when no pattern can remove the cost (for example the search "
|
|
284
|
+
"restarting at many start positions).\n" if code_ok else "")
|
|
285
|
+
+ "Also answer `bounded`: true only if the input string's length is cut or validated before this call on every path, "
|
|
286
|
+
"with `bound_chars` (the maximum length) and `evidence` as `path:line` of the cut; false if a caller can pass "
|
|
287
|
+
"unbounded text; null if you cannot tell. For the bound only, read the code and say nothing you have not read.\n"
|
|
288
|
+
+ "\n".join(lines))
|
|
289
|
+
result = runner.run(prompt, ANSWER_SCHEMA, ctx.root)
|
|
290
|
+
answers = (getattr(result, "output", None) or {}).get("answers") or []
|
|
291
|
+
by = {str(a.get("id")): a for a in answers if isinstance(a, dict)}
|
|
292
|
+
for c in batch:
|
|
293
|
+
a = by.get(c["id"])
|
|
294
|
+
if a is not None:
|
|
295
|
+
got = [x for x in (a.get("candidates") or []) if isinstance(x, dict)][:3]
|
|
296
|
+
if isinstance(a.get("rewrite"), str):
|
|
297
|
+
got.append({"kind": "pattern", "pattern": a["rewrite"]})
|
|
298
|
+
ctx.remember(self._key(ctx, c), {"candidates": got, **{k: a.get(k) for k in ("bounded", "bound_chars", "evidence", "note")}})
|
|
299
|
+
with self._lock:
|
|
300
|
+
self._memo.pop(("judge", str(ctx.out_dir), c["id"], True), None)
|
|
301
|
+
|
|
302
|
+
# --- verify ----------------------------------------------------------------------------------------------------------
|
|
303
|
+
def _env(self, ctx):
|
|
304
|
+
with self._lock:
|
|
305
|
+
env = self._memo.get(("env", str(ctx.out_dir)))
|
|
306
|
+
if env is None:
|
|
307
|
+
st = M.settings_of(ctx.settings)
|
|
308
|
+
eng = harness.Engines({"python": st["python"], "timeout_s": st["timeout_s"], "memory_mb": st["memory_mb"]})
|
|
309
|
+
cache = M.Cache(Path(ctx.out_dir) / "kinds" / "regex-measure.json")
|
|
310
|
+
env = self._memo[("env", str(ctx.out_dir))] = (st, eng, cache)
|
|
311
|
+
return env
|
|
312
|
+
|
|
313
|
+
def judge(self, ctx, c, *, with_agent: bool = True) -> dict:
|
|
314
|
+
"""Measure one candidate (memoised per run): the outcome, the proof, the fix."""
|
|
315
|
+
mk = ("judge", str(ctx.out_dir), c["id"], with_agent)
|
|
316
|
+
with self._lock:
|
|
317
|
+
if mk in self._memo:
|
|
318
|
+
return self._memo[mk]
|
|
319
|
+
st, eng, cache = self._env(ctx)
|
|
320
|
+
try:
|
|
321
|
+
ok, why = eng.available(c["engine"])
|
|
322
|
+
if not ok:
|
|
323
|
+
j = {"outcome": outcome(self.name, "not_judged", "regex.engine_not_available", evidence={"engine": c["engine"]},
|
|
324
|
+
next_step=f"install {harness.ENGINES.get(c['engine'], {}).get('label', c['engine'])}"), "why": why}
|
|
325
|
+
elif c["check"] == "unreadable":
|
|
326
|
+
j = {"outcome": outcome(self.name, "not_judged", "regex.pattern_not_read")}
|
|
327
|
+
elif c["check"] == "backtracking":
|
|
328
|
+
j = self._backtracking(ctx, c, st, eng, cache, with_agent)
|
|
329
|
+
elif c["check"] == "bounded_count":
|
|
330
|
+
j = self._bounded_count(ctx, c, st, eng, cache)
|
|
331
|
+
elif c["check"] == "compile_per_call":
|
|
332
|
+
j = self._compile(ctx, c, st, eng, cache)
|
|
333
|
+
elif c["check"] == "unicode_boundary":
|
|
334
|
+
j = self._unicode(ctx, c, st, eng, cache)
|
|
335
|
+
elif c["check"] == "table":
|
|
336
|
+
j = self._table(ctx, c, st, eng, cache)
|
|
337
|
+
elif c["check"] == "word_loop":
|
|
338
|
+
j = self._words(ctx, c, st, eng, cache)
|
|
339
|
+
elif c["check"] == "fold_keywords":
|
|
340
|
+
j = self._fold_keywords(ctx, c, st, eng, cache)
|
|
341
|
+
else:
|
|
342
|
+
j = {"outcome": outcome(self.name, "not_judged", "sandbox_could_not_run")}
|
|
343
|
+
except Exception as e: # noqa: BLE001 -- one pattern must not lose the others
|
|
344
|
+
ctx.say(f"regex {c.get('file')}:{c.get('line')}: could not be judged ({type(e).__name__}: {str(e)[:80]})")
|
|
345
|
+
j = {"outcome": outcome(self.name, "not_judged", "sandbox_could_not_run", evidence={"error": type(e).__name__})}
|
|
346
|
+
cache.save()
|
|
347
|
+
with self._lock:
|
|
348
|
+
self._memo[mk] = j
|
|
349
|
+
return j
|
|
350
|
+
|
|
351
|
+
def _runtime(self, eng, engine, st):
|
|
352
|
+
return {"engine": harness.ENGINES.get(engine, {}).get("label", engine), "version": eng.version(engine),
|
|
353
|
+
"settings": {"budget per run": f"{st['budget_ms']:g} ms", "timeout": f"{st['timeout_s']:g} s"}}
|
|
354
|
+
|
|
355
|
+
@staticmethod
|
|
356
|
+
def _series(curve: dict, name: str, unit_kb: bool, keep: int = 8) -> dict:
|
|
357
|
+
"""At most `keep` points, spread over the curve, the last one always kept (a dense table stays narrow)."""
|
|
358
|
+
pts = [[round(p[0] / 1024, 3) if unit_kb else p[0], round(p[1], 4)] for p in curve.get("points") or [] if p[1] is not None]
|
|
359
|
+
if len(pts) > keep:
|
|
360
|
+
idx = sorted({round(i * (len(pts) - 1) / (keep - 1)) for i in range(keep)})
|
|
361
|
+
pts = [pts[i] for i in idx]
|
|
362
|
+
return {"name": name, "x_unit": "KB" if unit_kb else "characters", "y_unit": "ms", "points": pts}
|
|
363
|
+
|
|
364
|
+
def _after_series(self, after: dict, before: dict, unit_kb: bool) -> dict:
|
|
365
|
+
"""The after curve at the sizes the before curve shows (plus its own largest), so both share one row of sizes."""
|
|
366
|
+
xs = {x for x, _ in before["points"]}
|
|
367
|
+
full = self._series(after, "after", unit_kb, keep=10 ** 6)
|
|
368
|
+
pts = [p for p in full["points"] if p[0] in xs]
|
|
369
|
+
if len(pts) < 2:
|
|
370
|
+
return self._series(after, "after", unit_kb)
|
|
371
|
+
if full["points"] and full["points"][-1] not in pts:
|
|
372
|
+
pts.append(full["points"][-1])
|
|
373
|
+
return {**full, "points": pts}
|
|
374
|
+
|
|
375
|
+
def _stated(self, curve: dict, st: dict):
|
|
376
|
+
"""The size the verdict is stated at: the largest one measured within the run budget (or the first over it)."""
|
|
377
|
+
pts = [p for p in curve.get("points") or [] if p[1] is not None]
|
|
378
|
+
if not pts:
|
|
379
|
+
return None
|
|
380
|
+
over = [p for p in pts if p[1] > st["budget_ms"]]
|
|
381
|
+
return over[0] if over else pts[-1]
|
|
382
|
+
|
|
383
|
+
def _backtracking(self, ctx, c, st, eng, cache, with_agent):
|
|
384
|
+
flavor = harness.ENGINES[c["engine"]]["flavor"]
|
|
385
|
+
parsed = syntax.parse(c["pattern"], flavor, c["flags"])
|
|
386
|
+
issues = [i for i in syntax.analyse(parsed, c.get("api") or "search", max_families=st["families"]) if i.code != "unicode_boundary"]
|
|
387
|
+
issues += syntax.lookahead_issues(parsed, c.get("api") or "search", max_families=st["families"])
|
|
388
|
+
version = eng.version(c["engine"])
|
|
389
|
+
mode = c["mode"]
|
|
390
|
+
curves = []
|
|
391
|
+
for iss in issues:
|
|
392
|
+
for fam in iss.families[:st["families"]]:
|
|
393
|
+
cv = {**M.grow(eng, c["engine"], c["pattern"], c["flags"], mode, fam, st, cache, version=version), "issue": iss}
|
|
394
|
+
curves.append(cv)
|
|
395
|
+
if cv["fit"]["order"] in M.SUPER and (cv["killed"] or cv["stopped"]):
|
|
396
|
+
break
|
|
397
|
+
if any(cv["fit"]["order"] in M.SUPER and (cv["killed"] or cv["stopped"]) for cv in curves):
|
|
398
|
+
break
|
|
399
|
+
if not curves:
|
|
400
|
+
return {"outcome": outcome(self.name, "nothing_to_gain", "regex.linear_on_engine")}
|
|
401
|
+
|
|
402
|
+
def worst_key(cv):
|
|
403
|
+
p = self._stated(cv, st)
|
|
404
|
+
return ((cv.get("censored") or [0, 0])[1] if cv.get("killed") else 0, (p[1] / max(p[0], 1)) if p else 0)
|
|
405
|
+
cv = max(curves, key=worst_key)
|
|
406
|
+
fam, iss = cv["family"], cv["issue"]
|
|
407
|
+
p = self._stated(cv, st)
|
|
408
|
+
order = cv["fit"]["order"]
|
|
409
|
+
before_ms = p[1] if p else 0.0
|
|
410
|
+
if cv.get("killed") and cv.get("censored") and (not p or cv["censored"][0] > p[0]):
|
|
411
|
+
p = [cv["censored"][0], cv["censored"][1], cv["censored"][1], cv["censored"][1], 1]
|
|
412
|
+
before_ms = p[1]
|
|
413
|
+
slow = order in M.SUPER and before_ms >= st["slow_ms"]
|
|
414
|
+
unit_kb = (p or [0])[0] >= 4096
|
|
415
|
+
base = {"family": fam, "order": order, "before_ms": before_ms, "at_len": p[0] if p else 0, "slow": slow, "issue": iss.code,
|
|
416
|
+
"curve": cv, "note": iss.note}
|
|
417
|
+
runtime = self._runtime(eng, c["engine"], st)
|
|
418
|
+
inputs = {"family": f"{_short(fam['prefix'], 16)!r} + {_short(fam['pump'], 16)!r} × n + {_short(fam['suffix'], 8)!r}",
|
|
419
|
+
"typical": "generated from the pattern", "observed": "none"}
|
|
420
|
+
scale = {"name": "input size", "unit": "KB" if unit_kb else "characters",
|
|
421
|
+
"points": [round(x[0] / 1024, 2) if unit_kb else x[0] for x in cv["points"]][-12:],
|
|
422
|
+
"at": round(p[0] / 1024, 2) if unit_kb and p else (p[0] if p else 0)}
|
|
423
|
+
series = [self._series(cv, "before", unit_kb)]
|
|
424
|
+
slope_m = kmeasure("growth_slope", "", cv["fit"].get("slope"), None, verdict=False)
|
|
425
|
+
if not slow:
|
|
426
|
+
ms = [kmeasure("time_at_size", "ms", before_ms, None, spread_before=(p[2], p[3]) if p else None, runs=p[4] if p else None), slope_m]
|
|
427
|
+
reason = "regex.linear_on_engine" if order not in M.SUPER else "already_cheap_measured"
|
|
428
|
+
return {**base, "outcome": outcome(self.name, "nothing_to_gain", reason, evidence={"time_ms": round(before_ms, 3), "at": p[0] if p else 0}),
|
|
429
|
+
"proof": proof(source="sandbox", measures=ms, runtime=runtime, scale=scale, series=series, inputs=inputs)}
|
|
430
|
+
# the input bound: a cut seen in the code (rules) or the agent's claim with its evidence line
|
|
431
|
+
bound, bound_from = c.get("bound"), "sandbox"
|
|
432
|
+
answers = self._answers(ctx, c) if with_agent else []
|
|
433
|
+
ans = answers[0] if answers else None
|
|
434
|
+
for a in answers:
|
|
435
|
+
if not bound and a.get("bounded") and isinstance(a.get("bound_chars"), int) and a["bound_chars"] > 0 \
|
|
436
|
+
and self._evidence_ok(ctx, a.get("evidence")):
|
|
437
|
+
bound, bound_from = {"n": a["bound_chars"], "line": a.get("evidence"), "text": "the agent's reading"}, "claimed"
|
|
438
|
+
if bound and isinstance(bound.get("n"), int):
|
|
439
|
+
n = max(1, (bound["n"] - len(fam["prefix"]) - len(fam["suffix"])) // max(1, len(fam["pump"])))
|
|
440
|
+
got = M.time_inputs(eng, c["engine"], c["pattern"], c["flags"], mode, [syntax.attack(fam, n)], st)
|
|
441
|
+
wc = got["points"][0] if got["points"] else None
|
|
442
|
+
worst = wc[1] if wc else (got.get("censored") or [0, st["timeout_s"] * 1000])[1]
|
|
443
|
+
if worst <= st["bounded_ok_ms"]:
|
|
444
|
+
where = bound.get("line")
|
|
445
|
+
where = f"{c.get('file')}:{where}" if isinstance(where, int) else str(where or "")
|
|
446
|
+
ev = {"worst_case_ms": round(worst, 3), "input_bound": bound["n"], "evidence": where[:120],
|
|
447
|
+
"cut": str(bound.get("text") or "")[:80]}
|
|
448
|
+
ms = [kmeasure("time_at_size", "ms", worst, None, spread_before=(wc[2], wc[3]) if wc else None, runs=wc[4] if wc else None), slope_m]
|
|
449
|
+
return {**base, "slow": False, "outcome": outcome(self.name, "nothing_to_gain", "regex.input_bounded", source=bound_from, evidence=ev),
|
|
450
|
+
"proof": proof(source="sandbox", measures=ms, runtime=runtime, scale={**scale, "at": bound["n"], "unit": "characters"},
|
|
451
|
+
series=series, inputs=inputs), "bound": bound}
|
|
452
|
+
base["bound"] = {**bound, "worst_case_ms": round(worst, 3)}
|
|
453
|
+
# rewrites: the rules', then the agent's; each needs the same matches and a gain on the same inputs
|
|
454
|
+
cands = []
|
|
455
|
+
for i in issues:
|
|
456
|
+
for r in syntax.rewrites(parsed, i, python_version=_python_floor(ctx.root) if flavor == "python" else (3, 11)):
|
|
457
|
+
cands.append((r.change, r.pattern))
|
|
458
|
+
codes = []
|
|
459
|
+
for a in answers:
|
|
460
|
+
for x in (a.get("candidates") or []) + ([{"kind": "pattern", "pattern": a["rewrite"]}] if isinstance(a.get("rewrite"), str) else []):
|
|
461
|
+
if x.get("kind") == "pattern" and isinstance(x.get("pattern"), str) and x["pattern"].strip() and x["pattern"] != c["pattern"]:
|
|
462
|
+
cands.append(("agent_rewrite", x["pattern"]))
|
|
463
|
+
elif x.get("kind") == "code" and isinstance(x.get("code"), str) and "def fixed" in x["code"] and c["engine"] in PY_ENGINES:
|
|
464
|
+
codes.append(("agent_code", x["code"], "fixed"))
|
|
465
|
+
seen, tried, differ = set(), [], None
|
|
466
|
+
rng = random.Random(st["seed"])
|
|
467
|
+
corpus = None
|
|
468
|
+
for change, after in cands:
|
|
469
|
+
if after in seen:
|
|
470
|
+
continue
|
|
471
|
+
seen.add(after)
|
|
472
|
+
try:
|
|
473
|
+
ap = syntax.parse(after, flavor, c["flags"])
|
|
474
|
+
except (syntax.Unsupported, ValueError, IndexError, OverflowError):
|
|
475
|
+
ap = None
|
|
476
|
+
if corpus is None:
|
|
477
|
+
corpus = syntax.corpus(parsed, rng, st["corpus_size"], families=[fam] + [f for x in issues for f in x.families[:2]],
|
|
478
|
+
extra=self._test_strings(ctx, c))
|
|
479
|
+
corp = corpus if ap is None else list(dict.fromkeys(corpus + syntax.corpus(ap, random.Random(st["seed"] + 1), st["corpus_size"] // 4)))
|
|
480
|
+
corp = self._with_classes(corp, [parsed] + ([ap] if ap else []), st)
|
|
481
|
+
same = M.same_matches(eng, c["engine"], c["pattern"], after, c["flags"], mode, corp, st)
|
|
482
|
+
if same["held"] is None:
|
|
483
|
+
tried.append((change, after, same, None))
|
|
484
|
+
continue
|
|
485
|
+
if not same["held"]:
|
|
486
|
+
differ = differ or (change, after, same)
|
|
487
|
+
tried.append((change, after, same, None))
|
|
488
|
+
continue
|
|
489
|
+
acv = M.grow(eng, c["engine"], after, c["flags"], mode, fam, st, cache, version=version)
|
|
490
|
+
ap_ = M.at(acv, p[0]) if p else None
|
|
491
|
+
if ap_ is None and acv["points"]:
|
|
492
|
+
# the after curve did not reach the stated size: measure that one input
|
|
493
|
+
n = max(1, (p[0] - len(fam["prefix"]) - len(fam["suffix"])) // max(1, len(fam["pump"])))
|
|
494
|
+
one = M.time_inputs(eng, c["engine"], after, c["flags"], mode, [syntax.attack(fam, n)], st)
|
|
495
|
+
ap_ = one["points"][0] if one["points"] else None
|
|
496
|
+
tried.append((change, after, same, acv))
|
|
497
|
+
if ap_ is not None and M.gain_beyond_spread(p, ap_) and (acv["fit"]["order"] not in M.SUPER or ap_[1] < st["slow_ms"]):
|
|
498
|
+
ms = [kmeasure("time_at_size", "ms", before_ms, ap_[1], spread_before=(p[2], p[3]), spread_after=(ap_[2], ap_[3]),
|
|
499
|
+
runs=max(p[4], ap_[4])),
|
|
500
|
+
kmeasure("growth_slope", "", cv["fit"].get("slope"), acv["fit"].get("slope"), verdict=False)]
|
|
501
|
+
pr = proof(source="sandbox", measures=ms, runtime=runtime, scale=scale,
|
|
502
|
+
same=sameness("same_matches", True, compared=same["compared"], differed=0,
|
|
503
|
+
basis=f"{same['compared']:,} generated strings, {same['matching']:,} matching"),
|
|
504
|
+
series=series + [self._after_series(acv, series[0], unit_kb)], inputs=inputs)
|
|
505
|
+
return {**base, "outcome": outcome(self.name, "fixed", "verified", evidence={"order_before": order, "order_after": acv["fit"]["order"]}),
|
|
506
|
+
"proof": pr, "fix": {"change": change, "before": c["pattern"], "after": after}, "after_curve": acv}
|
|
507
|
+
base["tried"] = [(t[0], t[1], (t[2] or {}).get("example") if t[2] and t[2].get("held") is False else None) for t in tried]
|
|
508
|
+
# no pattern does it: a small function around the call, the restart skip by rule, then the agent's code
|
|
509
|
+
plan = syntax.restart_plan(parsed) if st["restart_skip"] and mode in ("all", "search", "bool") and c["engine"] in PY_ENGINES | {"node"} else None
|
|
510
|
+
if plan:
|
|
511
|
+
code, entry = syntax.restart_helper(plan, c["pattern"], c["flags"], c["engine"], c.get("api") or "")
|
|
512
|
+
codes.insert(0, ("restart_skip", code, entry))
|
|
513
|
+
code_differ = tradeoff = None
|
|
514
|
+
for change, code, entry in codes:
|
|
515
|
+
got = self._try_code(ctx, c, st, eng, cache, parsed, issues, fam, p, cv, base, runtime, scale, series, inputs, unit_kb,
|
|
516
|
+
change, code, entry, plan if change == "restart_skip" else None)
|
|
517
|
+
if got.get("outcome", {}).get("state") == "fixed":
|
|
518
|
+
return got
|
|
519
|
+
if got.get("same") is not None and got["same"]["held"] is False:
|
|
520
|
+
code_differ = code_differ or got
|
|
521
|
+
elif got.get("outcome", {}).get("reason") == "regex.costs_on_ordinary_text":
|
|
522
|
+
tradeoff = tradeoff or got
|
|
523
|
+
if got.get("same") is not None:
|
|
524
|
+
if change != "restart_skip": # the rule's helper without a gain leaves the site for the agent
|
|
525
|
+
tried.append((change, code, got["same"], got.get("after_curve")))
|
|
526
|
+
base["tried"].append((change, "a scan helper" if change == "restart_skip" else "a helper function",
|
|
527
|
+
got["same"].get("example") if got["same"]["held"] is False else None))
|
|
528
|
+
if tradeoff:
|
|
529
|
+
return tradeoff
|
|
530
|
+
if code_differ and not differ:
|
|
531
|
+
return code_differ
|
|
532
|
+
ms = [kmeasure("time_at_size", "ms", before_ms, None, spread_before=(p[2], p[3]), runs=p[4]), slope_m]
|
|
533
|
+
if differ:
|
|
534
|
+
change, after, same = differ
|
|
535
|
+
pr = proof(source="sandbox", measures=ms, runtime=runtime, scale=scale, series=series, inputs=inputs,
|
|
536
|
+
same=sameness("same_matches", False, compared=same["compared"], differed=same["differed"],
|
|
537
|
+
basis=f"differs on {json.dumps(same['example'])[:60]}"))
|
|
538
|
+
return {**base, "outcome": outcome(self.name, "blocked", "regex.rewrite_matches_differently",
|
|
539
|
+
evidence={"differed": same["differed"], "compared": same["compared"]},
|
|
540
|
+
next_step="a rewrite that keeps every match"),
|
|
541
|
+
"proof": pr, "fix": {"change": change, "before": c["pattern"], "after": after}, "differs_on": same["example"]}
|
|
542
|
+
pr = proof(source="sandbox", measures=ms, runtime=runtime, scale=scale, series=series, inputs=inputs)
|
|
543
|
+
if any(t[3] is not None for t in tried):
|
|
544
|
+
change, after = next((t[0], t[1]) for t in tried if t[3] is not None)
|
|
545
|
+
return {**base, "outcome": outcome(self.name, "blocked", "no_gain_measured"), "proof": pr,
|
|
546
|
+
"fix": {"change": change, "before": c["pattern"], "after": after}}
|
|
547
|
+
if ans is not None:
|
|
548
|
+
return {**base, "outcome": outcome(self.name, "blocked", "no_variant_proposed"), "proof": pr}
|
|
549
|
+
return {**base, "outcome": outcome(self.name, "not_judged", "not_asked", next_step="ask_agent_about_regex"), "proof": pr}
|
|
550
|
+
|
|
551
|
+
@staticmethod
|
|
552
|
+
def _with_classes(corpus: list[str], parsed_list: list, st: dict) -> list[str]:
|
|
553
|
+
"""The corpus plus its strings with one character of every alphabet class put at each position."""
|
|
554
|
+
if not st["class_strings"]:
|
|
555
|
+
return corpus
|
|
556
|
+
reps = syntax.alphabet_classes([x for x in parsed_list if x is not None])
|
|
557
|
+
return corpus + syntax.class_variants(corpus, reps, st["class_strings"])
|
|
558
|
+
|
|
559
|
+
def _try_code(self, ctx, c, st, eng, cache, parsed, issues, fam, p, cv, base, runtime, scale, series, inputs, unit_kb,
|
|
560
|
+
change, code, entry, plan) -> dict:
|
|
561
|
+
"""A fix written as a function (CodeCop's restart skip, or the agent's code): the same matches as the original on the
|
|
562
|
+
corpus, a gain beyond the spread on the slow input, no super-linear growth left on any input family, and no cost
|
|
563
|
+
beyond `typical_cost_ms` on ordinary text (else a trade-off). Returns the judgement when it decides, else
|
|
564
|
+
{"same": ..., "after_curve": ...} for the record."""
|
|
565
|
+
engine, mode, version = c["engine"], c["mode"], eng.version(c["engine"])
|
|
566
|
+
cd = {"code": code, "entry": entry}
|
|
567
|
+
rng = random.Random(st["seed"] + 5)
|
|
568
|
+
fams, keys = [], set()
|
|
569
|
+
for f in [fam] + [f for x in issues for f in x.families[:2]] + (syntax.restart_families(parsed, plan) if plan else []):
|
|
570
|
+
k = (f["prefix"], f["pump"], f["suffix"])
|
|
571
|
+
if k not in keys:
|
|
572
|
+
keys.add(k)
|
|
573
|
+
fams.append(f)
|
|
574
|
+
corpus = syntax.corpus(parsed, rng, st["corpus_size"], families=fams, extra=self._test_strings(ctx, c))
|
|
575
|
+
corpus = self._with_classes(corpus, [parsed], st)
|
|
576
|
+
same = M.same_matches(eng, engine, c["pattern"], c["pattern"], c["flags"], mode, corpus, st, code_after=cd)
|
|
577
|
+
fix = {"change": change, "before": c.get("use") or c["pattern"], "after": code + self._call_hint(c, change, entry)}
|
|
578
|
+
before_m = kmeasure("time_at_size", "ms", p[1], None, spread_before=(p[2], p[3]), runs=p[4])
|
|
579
|
+
if same["held"] is None:
|
|
580
|
+
return {"same": None}
|
|
581
|
+
if not same["held"]:
|
|
582
|
+
pr = proof(source="sandbox", measures=[before_m], runtime=runtime, scale=scale, series=series, inputs=inputs,
|
|
583
|
+
same=sameness("same_matches", False, compared=same["compared"], differed=same["differed"],
|
|
584
|
+
basis=f"differs on {json.dumps(same['example'])[:60]}"))
|
|
585
|
+
return {**base, "same": same, "outcome": outcome(self.name, "blocked", "regex.rewrite_matches_differently",
|
|
586
|
+
evidence={"differed": same["differed"], "compared": same["compared"]},
|
|
587
|
+
next_step="a fix that keeps every match"),
|
|
588
|
+
"proof": pr, "fix": fix, "differs_on": same["example"]}
|
|
589
|
+
acv = M.grow(eng, engine, c["pattern"], c["flags"], mode, fam, st, cache, version=version, code=cd)
|
|
590
|
+
ap_ = M.at(acv, p[0])
|
|
591
|
+
if ap_ is None:
|
|
592
|
+
n = max(1, (p[0] - len(fam["prefix"]) - len(fam["suffix"])) // max(1, len(fam["pump"])))
|
|
593
|
+
one = M.time_inputs(eng, engine, c["pattern"], c["flags"], mode, [syntax.attack(fam, n)], st, code=cd)
|
|
594
|
+
ap_ = one["points"][0] if one["points"] else None
|
|
595
|
+
if not (ap_ is not None and M.gain_beyond_spread(p, ap_) and (acv["fit"]["order"] not in M.SUPER or ap_[1] < st["slow_ms"])):
|
|
596
|
+
return {"same": same, "after_curve": acv}
|
|
597
|
+
# every other input family: the fix must not stay super-linear and slow on any of them
|
|
598
|
+
worst_other, ob, oa = None, 0.0, 0.0
|
|
599
|
+
for f in fams[1:]:
|
|
600
|
+
b = M.grow(eng, engine, c["pattern"], c["flags"], mode, f, st, cache, version=version)
|
|
601
|
+
a = M.grow(eng, engine, c["pattern"], c["flags"], mode, f, st, cache, version=version, code=cd)
|
|
602
|
+
pb = self._stated(b, st)
|
|
603
|
+
pa = M.at(a, pb[0]) if pb else None
|
|
604
|
+
if a["fit"]["order"] in M.SUPER and pa is not None and pa[1] >= st["slow_ms"] or pa is None and a.get("killed"):
|
|
605
|
+
return {"same": same, "after_curve": acv}
|
|
606
|
+
if pb and pa:
|
|
607
|
+
ob, oa = ob + pb[1], oa + pa[1]
|
|
608
|
+
if worst_other is None or pb[1] > worst_other[2][1]:
|
|
609
|
+
worst_other = (f, b, pb, a)
|
|
610
|
+
# ordinary text of the stated size: the fix may not cost there beyond `typical_cost_ms`
|
|
611
|
+
text = syntax.typical_text([parsed], random.Random(st["seed"] + 9), max(p[0], 1024))
|
|
612
|
+
tb = M.time_inputs(eng, engine, c["pattern"], c["flags"], mode, [text], st)
|
|
613
|
+
ta = M.time_inputs(eng, engine, c["pattern"], c["flags"], mode, [text], st, code=cd)
|
|
614
|
+
tb_, ta_ = (tb["points"] or [None])[0], (ta["points"] or [None])[0]
|
|
615
|
+
ms = [kmeasure("time_at_size", "ms", p[1], ap_[1], spread_before=(p[2], p[3]), spread_after=(ap_[2], ap_[3]), runs=max(p[4], ap_[4])),
|
|
616
|
+
kmeasure("growth_slope", "", cv["fit"].get("slope"), acv["fit"].get("slope"), verdict=False)]
|
|
617
|
+
if fams[1:] and (ob or oa):
|
|
618
|
+
ms.append(kmeasure("other_inputs_ms", "ms", ob, oa, verdict=False))
|
|
619
|
+
if tb_ and ta_:
|
|
620
|
+
# shown, not judged: microseconds on ordinary text, where the spread is wider than the time itself
|
|
621
|
+
ms.append(kmeasure("ordinary_ms", "ms", tb_[1], ta_[1], verdict=False))
|
|
622
|
+
ser = series + [self._after_series(acv, series[0], unit_kb)]
|
|
623
|
+
if worst_other is not None:
|
|
624
|
+
f, b, pb, a = worst_other
|
|
625
|
+
nm = f.get("name") or "another input"
|
|
626
|
+
# the second input on the sizes the first one shows, so the table of points stays narrow
|
|
627
|
+
xs = {x for x, _ in series[0]["points"]}
|
|
628
|
+
for cv2, label in ((b, "before, 2nd input"), (a, "after, 2nd input")):
|
|
629
|
+
full = self._series(cv2, label, unit_kb, keep=10 ** 6)
|
|
630
|
+
pts = [q for q in full["points"] if q[0] in xs]
|
|
631
|
+
if len(pts) < 2:
|
|
632
|
+
pts = self._series(cv2, label, unit_kb, keep=3)["points"]
|
|
633
|
+
ser.append({**full, "points": pts})
|
|
634
|
+
basis = f"{same['compared']:,} generated strings, {same['matching']:,} matching"
|
|
635
|
+
pr = proof(source="sandbox", measures=ms, runtime=runtime, scale=scale, series=ser, inputs=inputs,
|
|
636
|
+
same=sameness("same_matches", True, compared=same["compared"], differed=0, basis=basis))
|
|
637
|
+
out = {**base, "same": same, "proof": pr, "fix": fix, "after_curve": acv, "helper": {"entry": entry, "families": len(fams)}}
|
|
638
|
+
if tb_ and ta_ and ta_[2] > tb_[3] and ta_[1] - tb_[1] > st["typical_cost_ms"]:
|
|
639
|
+
return {**out, "outcome": outcome(self.name, "blocked", "regex.costs_on_ordinary_text",
|
|
640
|
+
evidence={"ordinary_before_ms": round(tb_[1], 3), "ordinary_after_ms": round(ta_[1], 3)},
|
|
641
|
+
next_step="a fix that keeps ordinary text as fast")}
|
|
642
|
+
return {**out, "outcome": outcome(self.name, "fixed", "verified", evidence={"order_before": cv["fit"]["order"],
|
|
643
|
+
"order_after": acv["fit"]["order"], "families": len(fams)})}
|
|
644
|
+
|
|
645
|
+
@staticmethod
|
|
646
|
+
def _call_hint(c, change, entry) -> str:
|
|
647
|
+
api = c.get("api") or ""
|
|
648
|
+
if change == "agent_code":
|
|
649
|
+
return "\n\n# at the call: fixed(text) gives what the pattern's call read from"
|
|
650
|
+
if c.get("engine") == "node":
|
|
651
|
+
return "\n\n// at the call: for (const m of matchAllSkip(text)) … in place of text.matchAll(re)"
|
|
652
|
+
call = {"sub": "sub_skip(repl, text)", "subn": "sub_skip(repl, text)", "findall": "findall_skip(text)",
|
|
653
|
+
"search": "search_skip(text)"}.get(api, f"{entry}(text)")
|
|
654
|
+
return f"\n\n# at the call: {call} in place of the pattern's .{api}(…)"
|
|
655
|
+
|
|
656
|
+
def _evidence_ok(self, ctx, ev) -> bool:
|
|
657
|
+
"""The agent's `path:line` names a line that exists and cuts or checks a length."""
|
|
658
|
+
m = re.match(r"^(.+?):(\d+)$", str(ev or "").strip())
|
|
659
|
+
if not m:
|
|
660
|
+
return False
|
|
661
|
+
try:
|
|
662
|
+
lines = (Path(ctx.root) / m.group(1)).read_text(errors="replace").splitlines()
|
|
663
|
+
line = lines[int(m.group(2)) - 1]
|
|
664
|
+
except (OSError, IndexError, ValueError):
|
|
665
|
+
return False
|
|
666
|
+
return bool(re.search(r"\d|len|length|size|max|limit|truncat|slice|substr|\[:", line, re.I))
|
|
667
|
+
|
|
668
|
+
def _test_strings(self, ctx, c) -> list[str]:
|
|
669
|
+
"""Short string literals from the repository's tests that name the function or the pattern's name."""
|
|
670
|
+
names = {x for x in (c.get("name"), (c.get("symbol") or "").split(".")[-1]) if x and len(x) > 3}
|
|
671
|
+
if not names:
|
|
672
|
+
return []
|
|
673
|
+
mk = ("test_strings", str(ctx.root), tuple(sorted(names)))
|
|
674
|
+
with self._lock:
|
|
675
|
+
if mk in self._memo:
|
|
676
|
+
return self._memo[mk]
|
|
677
|
+
out = self._read_test_strings(ctx, c, names)
|
|
678
|
+
with self._lock:
|
|
679
|
+
self._memo[mk] = out
|
|
680
|
+
return out
|
|
681
|
+
|
|
682
|
+
def _read_test_strings(self, ctx, c, names) -> list[str]:
|
|
683
|
+
out = []
|
|
684
|
+
with self._lock:
|
|
685
|
+
tests = self._memo.get(("tests", str(ctx.root)))
|
|
686
|
+
if tests is None:
|
|
687
|
+
from ...discover import list_files
|
|
688
|
+
from ...discover.base import is_test_path
|
|
689
|
+
ext = {"python": ".py", "rust": ".rs", "go": ".go", "java": ".java", "typescript": ".ts"}.get(c.get("language") or "", "")
|
|
690
|
+
tests = self._memo[("tests", str(ctx.root))] = [f for f in list_files(Path(ctx.root)) if is_test_path(f)
|
|
691
|
+
and (not ext or f.endswith(ext) or ext == ".ts" and f.endswith((".js", ".tsx")))]
|
|
692
|
+
for rel in tests[:400]:
|
|
693
|
+
try:
|
|
694
|
+
text = (Path(ctx.root) / rel).read_text(errors="replace")
|
|
695
|
+
except OSError:
|
|
696
|
+
continue
|
|
697
|
+
if not any(n in text for n in names):
|
|
698
|
+
continue
|
|
699
|
+
for m in re.finditer(r"\"((?:[^\"\\\n]|\\.){1,120})\"|'((?:[^'\\\n]|\\.){1,120})'", text):
|
|
700
|
+
out.append(m.group(1) or m.group(2))
|
|
701
|
+
if len(out) >= 300:
|
|
702
|
+
return out
|
|
703
|
+
return out
|
|
704
|
+
|
|
705
|
+
def _bounded_count(self, ctx, c, st, eng, cache):
|
|
706
|
+
flavor = harness.ENGINES[c["engine"]]["flavor"]
|
|
707
|
+
parsed = syntax.parse(c["pattern"], flavor, c["flags"])
|
|
708
|
+
rng = random.Random(st["seed"])
|
|
709
|
+
fams = syntax.scan_families(parsed) or [{"prefix": "", "pump": syntax.generate(parsed, rng) + "\n", "suffix": ""}]
|
|
710
|
+
if flavor != "rust":
|
|
711
|
+
# a count or a yes/no read from the list of every match: text where the pattern matches often
|
|
712
|
+
fams = [{"prefix": "", "pump": (syntax.generate(parsed, random.Random(st["seed"] + 1), max_rep=2) or "x") + " ", "suffix": ""}] + fams[:2]
|
|
713
|
+
version = eng.version(c["engine"])
|
|
714
|
+
take = int(c["take"])
|
|
715
|
+
best = None
|
|
716
|
+
for fam in fams:
|
|
717
|
+
b = M.grow(eng, c["engine"], c["pattern"], c["flags"], "count", fam, st, cache, version=version)
|
|
718
|
+
a = M.grow(eng, c["engine"], c["pattern"], c["flags"], "count", fam, st, cache, take=take, version=version)
|
|
719
|
+
pb = self._stated(b, st)
|
|
720
|
+
if pb and (best is None or pb[1] > best[2][1]):
|
|
721
|
+
best = (fam, b, pb, a)
|
|
722
|
+
if best is None:
|
|
723
|
+
return {"outcome": outcome(self.name, "not_judged", "sandbox_could_not_run")}
|
|
724
|
+
fam, b, pb, a = best
|
|
725
|
+
pa = M.at(a, pb[0])
|
|
726
|
+
corpus = syntax.corpus(parsed, rng, st["corpus_size"], families=fams)
|
|
727
|
+
same = M.same_matches(eng, c["engine"], c["pattern"], c["pattern"], c["flags"], "count", corpus, st, take_before=None, take_after=take,
|
|
728
|
+
cmp=lambda x, y: min(int(x), take) == int(y))
|
|
729
|
+
unit_kb = pb[0] >= 4096
|
|
730
|
+
runtime = self._runtime(eng, c["engine"], st)
|
|
731
|
+
scale = {"name": "input size", "unit": "KB" if unit_kb else "characters", "points": [round(x[0] / 1024, 2) if unit_kb else x[0] for x in b["points"]][-12:],
|
|
732
|
+
"at": round(pb[0] / 1024, 2) if unit_kb else pb[0]}
|
|
733
|
+
ms = [kmeasure("time_at_size", "ms", pb[1], pa[1] if pa else None, spread_before=(pb[2], pb[3]), spread_after=(pa[2], pa[3]) if pa else None,
|
|
734
|
+
runs=pb[4]), kmeasure("growth_slope", "", b["fit"].get("slope"), a["fit"].get("slope"), verdict=False)]
|
|
735
|
+
pr = proof(source="sandbox", measures=ms, runtime=runtime, scale=scale,
|
|
736
|
+
same=sameness("same_matches", same["held"], compared=same["compared"], differed=same["differed"],
|
|
737
|
+
basis=f"the comparison sees min(count, {take}): {same['compared']:,} generated strings"),
|
|
738
|
+
series=[self._series(b, "count every match", unit_kb), self._series(a, f"first {take}", unit_kb)],
|
|
739
|
+
inputs={"family": f"lines of {_short(fam['pump'], 30)!r}", "typical": "generated from the pattern", "observed": "none"})
|
|
740
|
+
use = c.get("use") or ""
|
|
741
|
+
fix = {"change": "bounded_count", "before": use, "after": self._bounded_text(c, use, take)}
|
|
742
|
+
gate = st["slow_ms"] if flavor == "rust" else st["min_gain_ms"]
|
|
743
|
+
base = {"before_ms": pb[1], "order": b["fit"]["order"], "slow": pb[1] >= gate, "family": fam, "at_len": pb[0], "issue": "bounded_count"}
|
|
744
|
+
if flavor != "rust" and pa and pb[1] - pa[1] < st["min_gain_ms"]:
|
|
745
|
+
return {**base, "slow": False, "outcome": outcome(self.name, "nothing_to_gain", "already_cheap_measured",
|
|
746
|
+
evidence={"saved_ms": round(pb[1] - pa[1], 4)}), "proof": pr}
|
|
747
|
+
if pb[1] < gate:
|
|
748
|
+
return {**base, "outcome": outcome(self.name, "nothing_to_gain", "already_cheap_measured", evidence={"time_ms": round(pb[1], 3)}), "proof": pr}
|
|
749
|
+
if same["held"] is False:
|
|
750
|
+
return {**base, "outcome": outcome(self.name, "blocked", "fix_results_differ"), "proof": pr, "fix": fix}
|
|
751
|
+
if pa and M.gain_beyond_spread(pb, pa):
|
|
752
|
+
return {**base, "outcome": outcome(self.name, "fixed", "verified", evidence={"take": take}), "proof": pr, "fix": fix}
|
|
753
|
+
return {**base, "outcome": outcome(self.name, "blocked", "no_gain_measured"), "proof": pr, "fix": fix}
|
|
754
|
+
|
|
755
|
+
@staticmethod
|
|
756
|
+
def _bounded_text(c, use: str, take: int) -> str:
|
|
757
|
+
"""The call that stops at the first `take` matches, in the site's language."""
|
|
758
|
+
if c.get("engine", "").startswith("rust"):
|
|
759
|
+
return use.replace(".count()", f".take({take}).count()", 1)
|
|
760
|
+
if c.get("engine") in PY_ENGINES:
|
|
761
|
+
m = re.search(r"(\b[\w.\]\)]+)\.findall\(", use) or re.search(r"\bre\.findall\(", use)
|
|
762
|
+
if "len(" not in use:
|
|
763
|
+
return re.sub(r"\.findall\(", ".search(", use, count=1) + " # the first match decides; search() stops there"
|
|
764
|
+
return ("import itertools\n\n" + re.sub(r"len\((.*?)\.findall\((.*)\)\)", rf"sum(1 for _ in itertools.islice(\1.finditer(\2), {take}))",
|
|
765
|
+
use, count=1) + f" # the first {take} matches decide") if m else use
|
|
766
|
+
return ("function countUpTo(re, s, n) { let k = 0; for (const _ of s.matchAll(re)) if (++k >= n) break; return k; }\n\n"
|
|
767
|
+
+ re.sub(r"\(\s*([\w.$\[\]]+)\.match\((/.*?/\w*)\)\s*\|\|\s*\[\]\s*\)\.length", rf"countUpTo(\2, \1, {take})", use, count=1)
|
|
768
|
+
+ f" // the first {take} matches decide")
|
|
769
|
+
|
|
770
|
+
def _compile(self, ctx, c, st, eng, cache):
|
|
771
|
+
if c.get("pattern") is None:
|
|
772
|
+
return {"outcome": outcome(self.name, "not_judged", "regex.pattern_not_read", evidence={"why": "built at run time"})}
|
|
773
|
+
flavor = harness.ENGINES[c["engine"]]["flavor"]
|
|
774
|
+
try:
|
|
775
|
+
parsed = syntax.parse(c["pattern"], flavor, c["flags"])
|
|
776
|
+
sample = syntax.generate(parsed, random.Random(st["seed"]))
|
|
777
|
+
except (syntax.Unsupported, ValueError, IndexError, OverflowError):
|
|
778
|
+
sample = ""
|
|
779
|
+
k = M.Cache.key("compile", harness.HARNESS_VERSION, c["engine"], eng.version(c["engine"]), c["pattern"], c["flags"], c["mode"], sample)
|
|
780
|
+
got = cache.get(k)
|
|
781
|
+
if got is None:
|
|
782
|
+
got = M.compile_cost(eng, c["engine"], c["pattern"], c["flags"], c["mode"], sample, st) or {}
|
|
783
|
+
cache.put(k, got)
|
|
784
|
+
if not got.get("per_call_compiled_each_ms"):
|
|
785
|
+
return {"outcome": outcome(self.name, "not_judged", "sandbox_could_not_run", evidence={"error": str(got.get("error") or "")[:80]})}
|
|
786
|
+
b, a = got["per_call_compiled_each_ms"], got["per_call_precompiled_ms"]
|
|
787
|
+
bm, am = sorted(b)[len(b) // 2], sorted(a)[len(a) // 2]
|
|
788
|
+
ms = [kmeasure("time_per_call", "ms", bm, am, spread_before=(min(b), max(b)), spread_after=(min(a), max(a)), runs=len(b)),
|
|
789
|
+
kmeasure("compile_ms", "ms", got.get("compile_ms"), None, verdict=False)]
|
|
790
|
+
pr = proof(source="sandbox", measures=ms, runtime=self._runtime(eng, c["engine"], st),
|
|
791
|
+
same=sameness("same_matches", True, basis="the same pattern, compiled once"),
|
|
792
|
+
schedule={"calls": st["compile_calls"], "in_loop": "yes" if c.get("compiled") == "loop" else "no"},
|
|
793
|
+
inputs={"family": "one string generated from the pattern", "typical": _short(sample, 30), "observed": "none"})
|
|
794
|
+
name = c.get("name") or "re"
|
|
795
|
+
fix = {"change": "hoist_compile", "before": c.get("use") or c["pattern"],
|
|
796
|
+
"after": {"rust": f"static {(name or 'pattern').upper()}_RE: std::sync::LazyLock<Regex> =\n"
|
|
797
|
+
f" std::sync::LazyLock::new(|| Regex::new(r#\"{c['pattern']}\"#).unwrap()); // compiled once",
|
|
798
|
+
"rust-fancy": f"static {(name or 'pattern').upper()}_RE: std::sync::LazyLock<fancy_regex::Regex> =\n"
|
|
799
|
+
f" std::sync::LazyLock::new(|| fancy_regex::Regex::new(r#\"{c['pattern']}\"#).unwrap()); // compiled once",
|
|
800
|
+
"go": f"var {name}Re = regexp.MustCompile(`{c['pattern']}`) // package level, compiled once",
|
|
801
|
+
"java": f"private static final Pattern {name.upper() or 'P'}_RE = Pattern.compile({json.dumps(c['pattern'])});",
|
|
802
|
+
"node": f"const {name}Re = new RegExp({json.dumps(c['pattern'])}, {json.dumps(c['flags'])}); // module level"}.get(c["engine"], "")}
|
|
803
|
+
base = {"before_ms": bm, "slow": bm - am >= st.get("compile_min_ms", 0.01), "issue": "compile_per_call"}
|
|
804
|
+
if bm - am < float((ctx.settings or {}).get("compile_min_ms", 0.01)) or not (max(a) < min(b)):
|
|
805
|
+
return {**base, "outcome": outcome(self.name, "nothing_to_gain", "already_cheap_measured", evidence={"saved_ms": round(bm - am, 5)}), "proof": pr}
|
|
806
|
+
return {**base, "outcome": outcome(self.name, "fixed", "verified"), "proof": pr, "fix": fix}
|
|
807
|
+
|
|
808
|
+
def _unicode(self, ctx, c, st, eng, cache):
|
|
809
|
+
rng = random.Random(st["seed"])
|
|
810
|
+
pats = []
|
|
811
|
+
for p, f in c["patterns"]:
|
|
812
|
+
try:
|
|
813
|
+
parsed = syntax.parse(p, "rust", f)
|
|
814
|
+
except (syntax.Unsupported, ValueError, IndexError, OverflowError):
|
|
815
|
+
continue
|
|
816
|
+
iss = [i for i in syntax.analyse(parsed) if i.code == "unicode_boundary"]
|
|
817
|
+
if iss:
|
|
818
|
+
pats.append((p, f, parsed, syntax.rewrites(parsed, iss[0])[0].pattern))
|
|
819
|
+
if not pats:
|
|
820
|
+
return {"outcome": outcome(self.name, "nothing_to_gain", "regex.linear_on_engine")}
|
|
821
|
+
size = st["typical_bytes"]
|
|
822
|
+
ascii_text = syntax.typical_text([x[2] for x in pats], rng, size)
|
|
823
|
+
one = ascii_text + "é"
|
|
824
|
+
accented = syntax.typical_text([x[2] for x in pats], random.Random(st["seed"] + 3), size).replace("e ", "é ")
|
|
825
|
+
version = eng.version("rust")
|
|
826
|
+
|
|
827
|
+
def t(pattern, flags, text):
|
|
828
|
+
k = M.Cache.key("utime", harness.HARNESS_VERSION, version, pattern, flags, len(text), hash(text) & 0xffffffff, st["runs"])
|
|
829
|
+
got = cache.get(k)
|
|
830
|
+
if got is None:
|
|
831
|
+
r = M.time_inputs(eng, "rust", pattern, flags, "count", [text], st)
|
|
832
|
+
got = r["points"][0] if r["points"] else None
|
|
833
|
+
cache.put(k, got)
|
|
834
|
+
return got
|
|
835
|
+
sums = {"b": [0.0, 0.0, 0.0], "a": [0.0, 0.0, 0.0], "ab": 0.0, "aa": 0.0}
|
|
836
|
+
held, differ, compared = [], [], 0
|
|
837
|
+
diff_compared = 0
|
|
838
|
+
for p, f, parsed, after in pats:
|
|
839
|
+
corpus = syntax.corpus(parsed, rng, max(200, st["corpus_size"] // 4), extra=["café au lait", "naïve x", "über", "x é y", "日本 word"])
|
|
840
|
+
same = M.same_matches(eng, "rust", p, after, f, "all", corpus, st)
|
|
841
|
+
if not same["held"]:
|
|
842
|
+
differ.append((p, after, same))
|
|
843
|
+
diff_compared += same["compared"]
|
|
844
|
+
continue
|
|
845
|
+
b, a = t(p, f, one), t(after, f, one)
|
|
846
|
+
if not b or not a:
|
|
847
|
+
continue
|
|
848
|
+
held.append((p, after))
|
|
849
|
+
compared += same["compared"]
|
|
850
|
+
for i in range(3):
|
|
851
|
+
sums["b"][i] += b[1 + i]
|
|
852
|
+
sums["a"][i] += a[1 + i]
|
|
853
|
+
ab, aa = t(p, f, ascii_text), t(after, f, ascii_text)
|
|
854
|
+
sums["ab"] += ab[1] if ab else 0
|
|
855
|
+
sums["aa"] += aa[1] if aa else 0
|
|
856
|
+
b, a = sums["b"], sums["a"]
|
|
857
|
+
ms = [kmeasure("table_ms", "ms", b[0], a[0], spread_before=(b[1], b[2]), spread_after=(a[1], a[2]), runs=st["runs"]),
|
|
858
|
+
kmeasure("ascii_table_ms", "ms", sums["ab"], sums["aa"], verdict=False)]
|
|
859
|
+
pr = proof(source="sandbox", measures=ms, runtime=self._runtime(eng, "rust", st),
|
|
860
|
+
scale={"name": "text size", "unit": "KB", "points": [round(size / 1024)], "at": round(size / 1024)},
|
|
861
|
+
# the fix rewrites only the patterns that kept every match; the others stay as they are
|
|
862
|
+
same=sameness("same_matches", True, compared=compared, differed=0,
|
|
863
|
+
basis=f"{len(held)} of {len(pats)} patterns rewritten; {len(differ)} match differently and stay")
|
|
864
|
+
if held else sameness("same_matches", False, compared=diff_compared, differed=sum(x[2]["differed"] for x in differ),
|
|
865
|
+
basis=f"all {len(pats)} patterns match differently on accented text"),
|
|
866
|
+
inputs={"family": f"{round(size / 1024)} KB of ASCII text and one 'é' at the end", "typical": "pure ASCII (shown, not judged)",
|
|
867
|
+
"observed": "none"})
|
|
868
|
+
base = {"before_ms": b[0], "slow": True, "issue": "unicode_boundary", "members": len(pats), "held": len(held), "differ": len(differ)}
|
|
869
|
+
fix = {"change": "ascii_word_boundary", "before": "\\b", "after": "(?-u:\\b)"}
|
|
870
|
+
if not held:
|
|
871
|
+
d = differ[0]
|
|
872
|
+
return {**base, "outcome": outcome(self.name, "blocked", "regex.rewrite_matches_differently", evidence={"patterns": len(differ)}),
|
|
873
|
+
"proof": pr, "fix": {"change": "ascii_word_boundary", "before": d[0], "after": d[1]}}
|
|
874
|
+
if not (a[2] < b[1]) or b[0] - a[0] < float((ctx.settings or {}).get("min_gain_ms", 1.0)):
|
|
875
|
+
return {**base, "outcome": outcome(self.name, "nothing_to_gain" if b[0] < st["slow_ms"] else "blocked",
|
|
876
|
+
"already_cheap_measured" if b[0] < st["slow_ms"] else "no_gain_measured"), "proof": pr}
|
|
877
|
+
return {**base, "outcome": outcome(self.name, "fixed", "verified", evidence={"patterns": len(held), "differ": len(differ)}),
|
|
878
|
+
"proof": pr, "fix": fix}
|
|
879
|
+
|
|
880
|
+
# --- call shapes: a table of patterns, one pattern per word, a keyword test ---------------------------------------------
|
|
881
|
+
def _shape_timed(self, eng, engine, cache, st, op: dict, variant: str, mode: str, texts: list[str]) -> dict:
|
|
882
|
+
k = M.Cache.key("shape", harness.HARNESS_VERSION, engine, eng.version(engine), op, variant, mode, [len(t) for t in texts],
|
|
883
|
+
hash("".join(texts)) & 0xffffffff, st["runs"])
|
|
884
|
+
got = cache.get(k)
|
|
885
|
+
if got is None:
|
|
886
|
+
got = M.time_inputs(eng, engine, "", "", mode, texts, st, op={**op, "variant": variant})
|
|
887
|
+
cache.put(k, got)
|
|
888
|
+
return got
|
|
889
|
+
|
|
890
|
+
def _shape_verdict(self, ctx, c, st, eng, cache, *, op, variants, mode, texts, corpus, measure_name, sizes, plants, change_of,
|
|
891
|
+
fix_of, basis_of, extra=None):
|
|
892
|
+
"""Time the code's shape (`plain`) and each variant on ordinary text at `sizes`; a variant is a fix when every
|
|
893
|
+
result is the same on the corpus and the texts, and it saves at least `min_gain_ms` beyond the spread at the
|
|
894
|
+
largest size."""
|
|
895
|
+
engine = c["engine"]
|
|
896
|
+
before = self._shape_timed(eng, engine, cache, st, op, "plain", mode, texts)
|
|
897
|
+
if not before["points"]:
|
|
898
|
+
return {"outcome": outcome(self.name, "not_judged", "sandbox_could_not_run", evidence={"error": str(before.get("error") or "")[:80]})}
|
|
899
|
+
pb = before["points"][-1]
|
|
900
|
+
best, differ, tried = None, None, []
|
|
901
|
+
for v in variants:
|
|
902
|
+
after = self._shape_timed(eng, engine, cache, st, op, v, mode, texts)
|
|
903
|
+
pa = after["points"][-1] if len(after["points"]) == len(before["points"]) else None
|
|
904
|
+
gain = pa is not None and M.gain_beyond_spread(pb, pa) and pb[1] - pa[1] >= st["min_gain_ms"]
|
|
905
|
+
tried.append((v, after, pa))
|
|
906
|
+
if not gain:
|
|
907
|
+
continue
|
|
908
|
+
same = M.same_matches(eng, engine, "", "", "", mode, corpus + texts, st, op_before={**op, "variant": "plain"},
|
|
909
|
+
op_after={**op, "variant": v})
|
|
910
|
+
if same["held"] is False:
|
|
911
|
+
differ = differ or (v, after, pa, same)
|
|
912
|
+
continue
|
|
913
|
+
if same["held"] and (best is None or pa[1] < best[2][1]):
|
|
914
|
+
best = (v, after, pa, same)
|
|
915
|
+
unit = "KB"
|
|
916
|
+
scale = {"name": "text size", "unit": unit, "points": [round(n / 1024, 2) for n in sizes], "at": round(sizes[-1] / 1024, 2)}
|
|
917
|
+
ser = [{"name": "before", "x_unit": unit, "y_unit": "ms", "points": [[round(q[0] / 1024, 3), round(q[1], 4)] for q in before["points"]]}]
|
|
918
|
+
pick = best or differ or (min((t for t in tried if t[2]), key=lambda t: t[2][1]) if any(t[2] for t in tried) else None)
|
|
919
|
+
pa = pick[2] if pick else None
|
|
920
|
+
ms = [kmeasure(measure_name, "ms", pb[1], pa[1] if pa else None, spread_before=(pb[2], pb[3]),
|
|
921
|
+
spread_after=(pa[2], pa[3]) if pa else None, runs=pb[4])]
|
|
922
|
+
if pick:
|
|
923
|
+
ser.append({"name": "after", "x_unit": unit, "y_unit": "ms", "points": [[round(q[0] / 1024, 3), round(q[1], 4)] for q in pick[1]["points"]]})
|
|
924
|
+
inputs = {"family": f"ordinary prose and code, {plants}", "typical": "generated", "observed": "none"}
|
|
925
|
+
runtime = self._runtime(eng, engine, st)
|
|
926
|
+
base = {"before_ms": pb[1], "slow": pb[1] >= st["min_gain_ms"], "issue": c["check"], **(extra or {})}
|
|
927
|
+
if best:
|
|
928
|
+
v, after, pa, same = best
|
|
929
|
+
pr = proof(source="sandbox", measures=ms, runtime=runtime, scale=scale, series=ser, inputs=inputs,
|
|
930
|
+
same=sameness("same_matches", True, compared=same["compared"], differed=0, basis=basis_of(v, same)))
|
|
931
|
+
return {**base, "outcome": outcome(self.name, "fixed", "verified", evidence={"variant": v}), "proof": pr,
|
|
932
|
+
"fix": fix_of(v), "variant": v}
|
|
933
|
+
if differ:
|
|
934
|
+
v, after, pa, same = differ
|
|
935
|
+
pr = proof(source="sandbox", measures=ms, runtime=runtime, scale=scale, series=ser, inputs=inputs,
|
|
936
|
+
same=sameness("same_matches", False, compared=same["compared"], differed=same["differed"],
|
|
937
|
+
basis=f"differs on {json.dumps(same['example'])[:60]}"))
|
|
938
|
+
return {**base, "outcome": outcome(self.name, "blocked", "regex.rewrite_matches_differently",
|
|
939
|
+
evidence={"differed": same["differed"], "compared": same["compared"]}),
|
|
940
|
+
"proof": pr, "fix": fix_of(v), "differs_on": same["example"], "variant": v}
|
|
941
|
+
pr = proof(source="sandbox", measures=ms, runtime=runtime, scale=scale, series=ser, inputs=inputs)
|
|
942
|
+
reason = "regex.table_no_gain" if pb[1] >= st["min_gain_ms"] else "already_cheap_measured"
|
|
943
|
+
return {**base, "slow": False, "outcome": outcome(self.name, "nothing_to_gain", reason, evidence={"time_ms": round(pb[1], 3)}), "proof": pr}
|
|
944
|
+
|
|
945
|
+
def _table(self, ctx, c, st, eng, cache):
|
|
946
|
+
engine = c["engine"]
|
|
947
|
+
flavor = harness.ENGINES[engine]["flavor"]
|
|
948
|
+
mode = c["mode"] if c["mode"] in ("search", "all", "bool", "match", "full") else "search"
|
|
949
|
+
pats, parsed_ok = [], []
|
|
950
|
+
for pat, fl, line, _e in c.get("members") or []:
|
|
951
|
+
try:
|
|
952
|
+
pp = syntax.parse(pat, flavor, fl)
|
|
953
|
+
except (syntax.Unsupported, ValueError, IndexError, OverflowError, RecursionError):
|
|
954
|
+
pats.append({"pattern": pat, "flags": fl, "literals": None, "ci": False, "fold": False})
|
|
955
|
+
continue
|
|
956
|
+
parsed_ok.append(pp)
|
|
957
|
+
lits, ci = syntax.required_literals(pp, st["literal_min"])
|
|
958
|
+
pats.append({"pattern": pat, "flags": fl, "literals": sorted(lits) if lits else None, "ci": bool(lits) and ci,
|
|
959
|
+
"fold": engine == "python" and syntax.fold_eligible(pat, "python", fl)})
|
|
960
|
+
with_lit = sum(1 for p in pats if p["literals"])
|
|
961
|
+
with_fold = sum(1 for p in pats if p["fold"])
|
|
962
|
+
variants = (["prefilter"] if with_lit else []) + (["fold"] if with_fold else [])
|
|
963
|
+
extra = {"prefilter": {"of": len(pats), "with_literal": with_lit, "folded": with_fold, "ci": sum(1 for p in pats if p["ci"]),
|
|
964
|
+
"literals": [p["literals"][0] for p in pats if p["literals"]][:8], "table": c.get("table")}}
|
|
965
|
+
if not variants:
|
|
966
|
+
return {"outcome": outcome(self.name, "nothing_to_gain", "regex.no_required_literal", evidence={"patterns": len(pats)}), **extra}
|
|
967
|
+
sizes = sorted(st["table_sizes"])
|
|
968
|
+
texts = [syntax.ordinary_text(parsed_ok, random.Random(st["seed"] + i), n, st["plant_every"]) for i, n in enumerate(sizes)]
|
|
969
|
+
rng = random.Random(st["seed"])
|
|
970
|
+
per = max(8, st["corpus_size"] // max(1, len(parsed_ok)))
|
|
971
|
+
corp = []
|
|
972
|
+
for pp in parsed_ok:
|
|
973
|
+
corp += syntax.corpus(pp, rng, per)
|
|
974
|
+
corp = list(dict.fromkeys(corp))[:st["corpus_size"] * 2]
|
|
975
|
+
corp = corp + syntax.class_variants(corp, syntax.alphabet_classes(parsed_ok[:64]), st["class_strings"] // 4)
|
|
976
|
+
op = {"op": "table", "patterns": pats, "mode": mode}
|
|
977
|
+
name, lang = c.get("table") or "PATTERNS", c.get("language")
|
|
978
|
+
|
|
979
|
+
def fix_of(v):
|
|
980
|
+
if v == "prefilter":
|
|
981
|
+
return {"change": "required_literal_prefilter", "before": c.get("use") or "", "after": self._prefilter_code(pats, name, lang)}
|
|
982
|
+
return {"change": "fold_once", "before": c.get("use") or "", "after": self._fold_code(pats, name)}
|
|
983
|
+
|
|
984
|
+
def basis_of(v, same):
|
|
985
|
+
if v == "prefilter":
|
|
986
|
+
return f"by construction (no literal, no match); {same['compared']:,} strings, each pattern's matches compared"[:120]
|
|
987
|
+
return f"{same['compared']:,} strings with spans compared per pattern, folded text keeps every span"[:120]
|
|
988
|
+
return self._shape_verdict(ctx, c, st, eng, cache, op=op, variants=variants, mode=mode, texts=texts, corpus=corp,
|
|
989
|
+
measure_name="table_text_ms", sizes=sizes, plants=f"one match planted every {st['plant_every']:,} characters",
|
|
990
|
+
change_of=None, fix_of=fix_of, basis_of=basis_of, extra=extra)
|
|
991
|
+
|
|
992
|
+
@staticmethod
|
|
993
|
+
def _prefilter_code(pats, name, lang) -> str:
|
|
994
|
+
rows = [(tuple(p["literals"]) if p["literals"] else None, p["ci"]) for p in pats]
|
|
995
|
+
if lang == "go":
|
|
996
|
+
body = ",\n".join("\t" + ("nil" if lits is None else "{" + ", ".join(json.dumps(x) for x in lits) + "}")
|
|
997
|
+
+ (" // (?i)" if ci else "") for lits, ci in rows)
|
|
998
|
+
return (f"// per rule of {name}, in order: literals one of which every match contains (read from the pattern); nil: always run\n"
|
|
999
|
+
f"var {name}Required = [][]string{{\n{body},\n}}\n\n"
|
|
1000
|
+
"// the text (?i) literals are looked for in: Go folds k with the Kelvin sign and s with the long s\n"
|
|
1001
|
+
"folded := strings.ToLower(strings.NewReplacer(\"\\u017f\", \"s\", \"\\u212a\", \"k\").Replace(text))\n"
|
|
1002
|
+
f"for i, r := range {name} {{\n"
|
|
1003
|
+
f"\tif lits := {name}Required[i]; lits != nil {{\n\t\thit := false\n"
|
|
1004
|
+
"\t\tfor _, x := range lits {\n\t\t\tif strings.Contains(text, x) || strings.Contains(folded, x) {\n"
|
|
1005
|
+
"\t\t\t\thit = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !hit {\n\t\t\tcontinue // this rule cannot match\n\t\t}\n\t}\n"
|
|
1006
|
+
"\t// … the loop body as it is …\n}")
|
|
1007
|
+
body = ",\n".join(" " + ("None" if lits is None else repr(lits)) + (" # case-insensitive" if ci else "") for lits, ci in rows)
|
|
1008
|
+
return (f"# per pattern of {name}, in order: literals one of which every match contains (read from the pattern by CodeCop);\n"
|
|
1009
|
+
f"# None: the pattern has none and always runs\n_{name.upper()}_REQUIRED = [\n{body},\n]\n\n"
|
|
1010
|
+
"# the text case-insensitive literals are looked for in (the characters lower() leaves alone mapped first)\n"
|
|
1011
|
+
"folded = text.replace(\"\\u0131\", \"i\").replace(\"\\u017f\", \"s\").replace(\"\\u212a\", \"k\").lower()\n"
|
|
1012
|
+
f"for i, <the loop's names> in enumerate({name}):\n"
|
|
1013
|
+
f" lits = _{name.upper()}_REQUIRED[i]\n"
|
|
1014
|
+
" if lits and not any(x in text or x in folded for x in lits):\n"
|
|
1015
|
+
" continue # this pattern cannot match\n"
|
|
1016
|
+
" # … the loop body as it is …")
|
|
1017
|
+
|
|
1018
|
+
@staticmethod
|
|
1019
|
+
def _fold_code(pats, name) -> str:
|
|
1020
|
+
return ("def _fold(text):\n \"\"\"lower() per character, spans unchanged (the four characters lower() does not bring to ASCII first).\"\"\"\n"
|
|
1021
|
+
" for a, b in ((\"\\u0130\", \"i\"), (\"\\u0131\", \"i\"), (\"\\u017f\", \"s\"), (\"\\u212a\", \"k\")):\n"
|
|
1022
|
+
" text = text.replace(a, b)\n return text.lower()\n\n"
|
|
1023
|
+
f"# compile the {sum(1 for p in pats if p['fold'])} case-insensitive patterns of {name} WITHOUT re.I and run them on the text folded once:\n"
|
|
1024
|
+
"folded = _fold(text)\n"
|
|
1025
|
+
f"for p in {name}: # those patterns: p.search(folded) in place of p.search(text)\n"
|
|
1026
|
+
" m = p.search(folded)\n"
|
|
1027
|
+
" # read the matched text from the original: text[m.start():m.end()]")
|
|
1028
|
+
|
|
1029
|
+
def _words(self, ctx, c, st, eng, cache):
|
|
1030
|
+
words, pre, post, flags = c["words"], c.get("pre") or "", c.get("post") or "", c.get("flags") or ""
|
|
1031
|
+
kind = c.get("word_kind") or "sub"
|
|
1032
|
+
ws = [w for w, _ in words]
|
|
1033
|
+
plants = ws + [w.upper() for w in ws] + [w.lower() for w in ws]
|
|
1034
|
+
sizes = sorted(st["table_sizes"])
|
|
1035
|
+
every = max(16, st["plant_every"] // 64)
|
|
1036
|
+
texts = [syntax.ordinary_text([], random.Random(st["seed"] + i), n, every, words=plants) for i, n in enumerate(sizes)]
|
|
1037
|
+
rng = random.Random(st["seed"])
|
|
1038
|
+
corp = list(dict.fromkeys([""] + plants + [f"{a} {b}" for a in ws for b in ws[:6]] + [f"x{w}x" for w in ws] + [f"{w}_" for w in ws]
|
|
1039
|
+
+ [f"({w}), {w}." for w in ws] + [r or "" for _, r in words]
|
|
1040
|
+
+ [" ".join(rng.choice(plants) for _ in range(rng.randint(1, 8))) for _ in range(st["corpus_size"])]))
|
|
1041
|
+
try:
|
|
1042
|
+
pp = syntax.parse(pre + "(?:" + "|".join(ws) + ")" + post, "python", flags)
|
|
1043
|
+
corp += syntax.class_variants(corp[:400], syntax.alphabet_classes([pp]), st["class_strings"] // 4)
|
|
1044
|
+
except (syntax.Unsupported, ValueError, IndexError, OverflowError):
|
|
1045
|
+
pass
|
|
1046
|
+
op = {"op": "words", "pre": pre, "post": post, "flags": flags, "words": words, "kind": kind}
|
|
1047
|
+
order = sorted(words, key=lambda w: -len(w[0]))
|
|
1048
|
+
mod = "regex" if c["engine"] == "python-regex" else "re"
|
|
1049
|
+
flag_txt = (", " + " | ".join(f"{mod}.{syntax.PY_FLAG_NAMES[x]}" for x in flags if x in syntax.PY_FLAG_NAMES)) if flags else ""
|
|
1050
|
+
alt = pre + "(?:" + "|".join(w for w, _ in order) + ")" + post
|
|
1051
|
+
if kind == "sub":
|
|
1052
|
+
key = "m.group().lower()" if "i" in flags else "m.group()"
|
|
1053
|
+
table = {(w.lower() if "i" in flags else w): r for w, r in words}
|
|
1054
|
+
after = (f"_WORDS = {table!r}\n_WORDS_RE = {mod}.compile({alt!r}{flag_txt}) # one alternation, longest first\n\n"
|
|
1055
|
+
f"{c.get('arg') or 'text'} = _WORDS_RE.sub(lambda m: _WORDS[{key}], {c.get('arg') or 'text'}) # in place of the loop")
|
|
1056
|
+
else:
|
|
1057
|
+
after = f"_WORDS_RE = {mod}.compile({alt!r}{flag_txt}) # one alternation, longest first\n\nif _WORDS_RE.search(text): # in place of the loop"
|
|
1058
|
+
|
|
1059
|
+
def basis_of(v, same):
|
|
1060
|
+
return f"{same['compared']:,} strings of the words, their neighbours and case, output compared"[:120]
|
|
1061
|
+
return self._shape_verdict(ctx, c, st, eng, cache, op=op, variants=["alternation"], mode="all", texts=texts, corpus=corp,
|
|
1062
|
+
measure_name="words_ms", sizes=sizes, plants=f"one of the {len(ws)} words every {every:,} characters",
|
|
1063
|
+
change_of=None, fix_of=lambda v: {"change": "one_alternation", "before": c.get("use") or "", "after": after},
|
|
1064
|
+
basis_of=basis_of, extra={"words": {"n": len(ws), "kind": kind, "examples": ws[:6]}})
|
|
1065
|
+
|
|
1066
|
+
def _fold_keywords(self, ctx, c, st, eng, cache):
|
|
1067
|
+
pat, flags = c["pattern"], c.get("flags") or ""
|
|
1068
|
+
parsed = syntax.parse(pat, "python", flags)
|
|
1069
|
+
mode = c["mode"] if c["mode"] in ("search", "bool", "all") else "search"
|
|
1070
|
+
sizes = sorted(st["table_sizes"])
|
|
1071
|
+
# a yes/no test stops at the first keyword: what it costs is the text with none (the usual answer), so none is planted
|
|
1072
|
+
texts = [syntax.ordinary_text([parsed], random.Random(st["seed"] + i), n, 0) for i, n in enumerate(sizes)]
|
|
1073
|
+
rng = random.Random(st["seed"])
|
|
1074
|
+
corp = syntax.corpus(parsed, rng, st["corpus_size"], extra=[k.upper() for k in c["keywords"]] + [k.title() for k in c["keywords"]]
|
|
1075
|
+
+ ["İ", "ı", "ſ", "K", "\u212a"])
|
|
1076
|
+
corp = self._with_classes(corp, [parsed], st)
|
|
1077
|
+
op = {"op": "table", "patterns": [{"pattern": pat, "flags": flags, "literals": None, "fold": True}], "mode": mode}
|
|
1078
|
+
mod = "re"
|
|
1079
|
+
nf = flags.replace("i", "")
|
|
1080
|
+
fl = (", " + " | ".join(f"{mod}.{syntax.PY_FLAG_NAMES[x]}" for x in nf if x in syntax.PY_FLAG_NAMES)) if nf else ""
|
|
1081
|
+
name = c.get("name") or "PATTERN"
|
|
1082
|
+
after = (self._fold_code([{"fold": True}], name).split("\n\n")[0]
|
|
1083
|
+
+ f"\n\n{name}_FOLDED = re.compile({pat!r}{fl}) # the same pattern without re.I\n"
|
|
1084
|
+
f"{name}_FOLDED.search(_fold(text)) # spans are the original text's")
|
|
1085
|
+
|
|
1086
|
+
def basis_of(v, same):
|
|
1087
|
+
return f"{same['compared']:,} strings incl. every folding character, spans compared"[:120]
|
|
1088
|
+
return self._shape_verdict(ctx, c, st, eng, cache, op=op, variants=["fold"], mode=mode, texts=texts, corpus=corp,
|
|
1089
|
+
measure_name="ordinary_ms", sizes=sizes, plants="no keyword in it (a test that finds one stops there)",
|
|
1090
|
+
change_of=None, fix_of=lambda v: {"change": "fold_once", "before": c.get("use") or pat, "after": after},
|
|
1091
|
+
basis_of=basis_of, extra={"keywords": {"n": len(c["keywords"]), "examples": c["keywords"][:6]}})
|
|
1092
|
+
|
|
1093
|
+
def verify(self, ctx, cands):
|
|
1094
|
+
st = M.settings_of(ctx.settings)
|
|
1095
|
+
workers = st["workers"] or 4
|
|
1096
|
+
with ThreadPoolExecutor(max(1, workers)) as ex:
|
|
1097
|
+
judged = list(ex.map(lambda c: (c, self.judge(ctx, c)), cands))
|
|
1098
|
+
out = []
|
|
1099
|
+
for c, j in judged:
|
|
1100
|
+
site = {"file": c.get("file"), "line": c.get("line"), "symbol": c.get("symbol") or ""}
|
|
1101
|
+
o = j["outcome"]
|
|
1102
|
+
state = o["state"]
|
|
1103
|
+
eng_label = harness.ENGINES.get(c.get("engine"), {}).get("label", c.get("engine"))
|
|
1104
|
+
order = j.get('order') or ''
|
|
1105
|
+
title = {"backtracking": (f"{order.capitalize()} backtracking" if order in M.SUPER else "No growth faster than linear" if order in ('linear', 'flat') else "Backtracking"),
|
|
1106
|
+
"bounded_count": "A match count scans to the end for every match",
|
|
1107
|
+
"compile_per_call": "Pattern compiled on every call",
|
|
1108
|
+
"unicode_boundary": f"Unicode word boundary in {c.get('members', 0)} pattern{'' if c.get('members') == 1 else 's'} of {c.get('def_file')}",
|
|
1109
|
+
"unreadable": "Pattern not read",
|
|
1110
|
+
"table": f"{len(c['members']) if isinstance(c.get('members'), list) else 0} patterns run one after another on the same text ({c.get('table')})",
|
|
1111
|
+
"word_loop": f"One pattern per word in a loop, {len(c.get('words') or [])} words",
|
|
1112
|
+
"fold_keywords": "A case-insensitive keyword test"}.get(c["check"], "Regex")
|
|
1113
|
+
if c["check"] == "backtracking" and j.get("issue") == "lookahead_scan" and order in M.SUPER:
|
|
1114
|
+
title = f"{order.capitalize()} lookahead scan"
|
|
1115
|
+
if c.get("pattern") and c["check"] not in ("unicode_boundary", "table", "word_loop"):
|
|
1116
|
+
title += f": {_short(' '.join(c['pattern'].split()), 32)}"
|
|
1117
|
+
sev = "high" if state == "fixed" and (j.get("before_ms") or 0) >= 1000 or j.get("order") == "exponential" and j.get("slow") else \
|
|
1118
|
+
"medium" if j.get("slow") else "low"
|
|
1119
|
+
extra = {"regex": {k: v for k, v in {
|
|
1120
|
+
"check": c["check"], "engine": c.get("engine"), "engine_label": eng_label, "api": c.get("api"), "mode": c.get("mode"),
|
|
1121
|
+
"compiled": c.get("compiled"), "flags": c.get("flags"), "pattern": (c.get("pattern") or "")[:300] if c["check"] not in ("unicode_boundary", "table", "word_loop") else None,
|
|
1122
|
+
"issue": j.get("issue"), "order": j.get("order"),
|
|
1123
|
+
"order_after": (j.get("after_curve") or {}).get("fit", {}).get("order"),
|
|
1124
|
+
"family": {k2: _short(v2, 40) for k2, v2 in (j.get("family") or {}).items()} or None,
|
|
1125
|
+
"bound": c.get("bound") or j.get("bound"), "members": c.get("members"), "held": j.get("held"), "differ": j.get("differ"),
|
|
1126
|
+
"def": f"{c.get('def_file')}:{c.get('def_line')}" if c.get("def_line") else None,
|
|
1127
|
+
"differs_on": _short(j.get("differs_on"), 80) if j.get("differs_on") else None,
|
|
1128
|
+
"flows": c.get("flows"),
|
|
1129
|
+
"fix_kind": ("helper function" if (j.get("fix") or {}).get("change") in HELPER_FIXES else
|
|
1130
|
+
"call shape" if (j.get("fix") or {}).get("change") in ("required_literal_prefilter", "fold_once", "one_alternation",
|
|
1131
|
+
"bounded_count", "hoist_compile") else
|
|
1132
|
+
"pattern" if j.get("fix") else None),
|
|
1133
|
+
"helper": j.get("helper"), "prefilter": j.get("prefilter"), "words": j.get("words"), "keywords": j.get("keywords"),
|
|
1134
|
+
"variant": j.get("variant"), "take": c.get("take")}.items() if v not in (None, "", [])}}
|
|
1135
|
+
out.append(finding(self.name, id=c["id"], title=title, site=site, outcome=o, proof=j.get("proof"), severity=sev,
|
|
1136
|
+
confidence="high" if j.get("proof") and state in ("fixed", "nothing_to_gain") else "medium",
|
|
1137
|
+
summary=str(j.get("why") or "")[:300], fix=j.get("fix"), extra=extra))
|
|
1138
|
+
# what was set aside, for the report and the summary
|
|
1139
|
+
aside: dict = {}
|
|
1140
|
+
for s in ctx.sites():
|
|
1141
|
+
why = self.set_aside(s)
|
|
1142
|
+
if why:
|
|
1143
|
+
aside[why] = aside.get(why, 0) + 1
|
|
1144
|
+
try:
|
|
1145
|
+
p = Path(ctx.out_dir) / "kinds" / "regex-set-aside.json"
|
|
1146
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
1147
|
+
p.write_text(json.dumps({"sites": len(ctx.sites()), "set_aside": aside, "candidates": len(cands),
|
|
1148
|
+
"built_at_run_time": sum(1 for s in ctx.sites() if s.get("pattern") is None)}, indent=1))
|
|
1149
|
+
except OSError:
|
|
1150
|
+
pass
|
|
1151
|
+
return out
|
|
1152
|
+
|
|
1153
|
+
def handoff(self, f):
|
|
1154
|
+
from .. import handoff_text
|
|
1155
|
+
text = handoff_text(f)
|
|
1156
|
+
rx = f.get("regex") or {}
|
|
1157
|
+
add = [f"Engine: {rx.get('engine_label') or rx.get('engine')} ({rx.get('api')}, compiled {rx.get('compiled')})"]
|
|
1158
|
+
if rx.get("bound"):
|
|
1159
|
+
b = rx["bound"]
|
|
1160
|
+
add.append(f"Input bound: {b.get('n')} characters at {b.get('line')} ({b.get('text', '')})")
|
|
1161
|
+
if rx.get("family"):
|
|
1162
|
+
fam = rx["family"]
|
|
1163
|
+
add.append(f"Attack family: {fam.get('prefix')!r} + {fam.get('pump')!r} * n + {fam.get('suffix')!r}")
|
|
1164
|
+
return text + "\n" + "\n".join(add)
|
|
1165
|
+
|
|
1166
|
+
def doctor(self) -> list:
|
|
1167
|
+
return harness.doctor()
|