ruby-anything 0.2.1 → 0.2.3

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.
@@ -1,459 +1,459 @@
1
- """PortPilot Python adapter.
2
-
3
- Runs INSIDE the sandbox only. Reads one JSON request on stdin and writes JSON lines
4
- on stdout, one event per line: {"event": "log" | "case" | "unit" | "file" | "done", ...}.
5
-
6
- Commands:
7
- analyze - static analysis with `ast` (never imports the target code)
8
- record - call a function for each case (twice) and capture its behaviour
9
- bench - time each case over N iterations inside this process
10
- """
11
- import ast
12
- import base64
13
- import contextlib
14
- import hashlib
15
- import importlib.util
16
- import inspect
17
- import io
18
- import json
19
- import math
20
- import os
21
- import random
22
- import sys
23
- import tempfile
24
- import time
25
- import tracemalloc
26
-
27
- SRC = os.environ.get("PORTPILOT_SRC", "/work/src")
28
- REAL_STDOUT = sys.stdout
29
-
30
-
31
- def emit(event, **data):
32
- data["event"] = event
33
- REAL_STDOUT.write(json.dumps(data, ensure_ascii=False, allow_nan=False) + "\n")
34
- REAL_STDOUT.flush()
35
-
36
-
37
- # ---------------------------------------------------------------- value codec
38
-
39
- def encode(value):
40
- if value is None or isinstance(value, (bool, str)):
41
- return value
42
- if isinstance(value, int):
43
- return value
44
- if isinstance(value, float):
45
- if math.isnan(value):
46
- return {"$float": "nan"}
47
- if math.isinf(value):
48
- return {"$float": "inf" if value > 0 else "-inf"}
49
- if value == 0.0 and math.copysign(1.0, value) < 0:
50
- return {"$float": "-0.0"}
51
- return value
52
- if isinstance(value, (list, tuple)):
53
- return [encode(v) for v in value]
54
- if isinstance(value, dict):
55
- return {str(k): encode(v) for k, v in value.items()}
56
- if isinstance(value, (bytes, bytearray)):
57
- return {"$bytes": base64.b64encode(bytes(value)).decode()}
58
- if isinstance(value, (set, frozenset)):
59
- items = [encode(v) for v in value]
60
- return {"$set": sorted(items, key=lambda v: json.dumps(v, sort_keys=True))}
61
- return {"$repr": repr(value)[:200]}
62
-
63
-
64
- def decode(value):
65
- if isinstance(value, list):
66
- return [decode(v) for v in value]
67
- if isinstance(value, dict):
68
- if "$float" in value:
69
- special = {"nan": math.nan, "inf": math.inf, "-inf": -math.inf, "-0.0": -0.0}
70
- return special[value["$float"]] if value["$float"] in special else float(value["$float"])
71
- if "$bytes" in value:
72
- return base64.b64decode(value["$bytes"])
73
- if "$set" in value:
74
- return set(decode(v) for v in value["$set"])
75
- return {k: decode(v) for k, v in value.items()}
76
- return value
77
-
78
-
79
- # ---------------------------------------------------------------- analyze
80
-
81
- SIDE_EFFECT_RULES = {
82
- "filesystem": {"open", "os.remove", "os.unlink", "os.makedirs", "os.mkdir", "os.rename", "shutil.rmtree",
83
- "shutil.copy", "shutil.move", "write_text", "write_bytes", "unlink", "mkdir"},
84
- "network": {"urllib.request.urlopen", "urlopen", "requests.get", "requests.post", "requests.request",
85
- "socket.socket", "socket.create_connection", "http.client.HTTPConnection", "httpx.get", "httpx.post"},
86
- "database": {"sqlite3.connect", "psycopg2.connect", "pymysql.connect", "create_engine"},
87
- "process": {"subprocess.run", "subprocess.Popen", "subprocess.call", "os.system", "os.popen"},
88
- "stdout": {"print"},
89
- "nondeterminism": {"time.time", "datetime.now", "datetime.datetime.now", "random.random", "random.randint",
90
- "random.choice", "uuid.uuid4", "os.urandom"},
91
- "environment": {"os.getenv", "os.environ.get"},
92
- }
93
- MODULE_EFFECTS = {"requests": "network", "httpx": "network", "socket": "network", "urllib": "network",
94
- "sqlite3": "database", "psycopg2": "database", "pymysql": "database", "sqlalchemy": "database",
95
- "subprocess": "process", "shutil": "filesystem"}
96
-
97
-
98
- def dotted(node):
99
- if isinstance(node, ast.Name):
100
- return node.id
101
- if isinstance(node, ast.Attribute):
102
- base = dotted(node.value)
103
- return f"{base}.{node.attr}" if base else node.attr
104
- return None
105
-
106
-
107
- def complexity(fn):
108
- score = 1
109
- for node in ast.walk(fn):
110
- if isinstance(node, (ast.If, ast.For, ast.While, ast.AsyncFor, ast.IfExp, ast.ExceptHandler, ast.With,
111
- ast.Assert, ast.comprehension)):
112
- score += 1
113
- elif isinstance(node, ast.BoolOp):
114
- score += len(node.values) - 1
115
- return score
116
-
117
-
118
- def loop_depth(node, depth=0):
119
- best = depth
120
- for child in ast.iter_child_nodes(node):
121
- inc = 1 if isinstance(child, (ast.For, ast.While, ast.AsyncFor, ast.comprehension)) else 0
122
- best = max(best, loop_depth(child, depth + inc))
123
- return best
124
-
125
-
126
- def describe_args(fn):
127
- args = fn.args
128
- params = []
129
- positional = args.posonlyargs + args.args
130
- defaults = [None] * (len(positional) - len(args.defaults)) + list(args.defaults)
131
- for arg, default in zip(positional, defaults):
132
- params.append({"name": arg.arg, "annotation": ast.unparse(arg.annotation) if arg.annotation else None,
133
- "default": ast.unparse(default) if default is not None else None, "kind": "positional"})
134
- if args.vararg:
135
- params.append({"name": args.vararg.arg, "kind": "varargs", "annotation": None, "default": None})
136
- for arg, default in zip(args.kwonlyargs, args.kw_defaults):
137
- params.append({"name": arg.arg, "annotation": ast.unparse(arg.annotation) if arg.annotation else None,
138
- "default": ast.unparse(default) if default is not None else None, "kind": "keyword"})
139
- if args.kwarg:
140
- params.append({"name": args.kwarg.arg, "kind": "kwargs", "annotation": None, "default": None})
141
- return params
142
-
143
-
144
- def analyze(_req):
145
- stdlib = set(getattr(sys, "stdlib_module_names", ()))
146
- py_files = []
147
- for root, dirs, files in os.walk(SRC):
148
- dirs[:] = sorted(d for d in dirs if not d.startswith(".") and d not in {"__pycache__", "venv", ".venv",
149
- "node_modules", "build", "dist"})
150
- for name in sorted(files):
151
- if name.endswith(".py"):
152
- py_files.append(os.path.join(root, name))
153
- local_modules = {os.path.splitext(os.path.relpath(p, SRC))[0].replace(os.sep, ".") for p in py_files}
154
- local_tops = {m.split(".")[0] for m in local_modules}
155
- defined = {}
156
- parsed = []
157
- for path in py_files:
158
- rel = os.path.relpath(path, SRC).replace(os.sep, "/")
159
- with open(path, "rb") as fh:
160
- raw = fh.read()
161
- source = raw.decode("utf-8", "replace")
162
- try:
163
- tree = ast.parse(source, filename=rel)
164
- except SyntaxError as exc:
165
- emit("file", path=rel, loc=source.count("\n") + 1, error=f"SyntaxError: {exc.msg} (line {exc.lineno})")
166
- continue
167
- parsed.append((rel, source, tree))
168
- for node in tree.body:
169
- if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
170
- defined[node.name] = rel
171
- emit("log", message=f"parsed {len(parsed)} of {len(py_files)} python files")
172
-
173
- for rel, source, tree in parsed:
174
- module = os.path.splitext(rel)[0].replace("/", ".")
175
- imports = []
176
- for node in ast.walk(tree):
177
- if isinstance(node, ast.Import):
178
- imports += [a.name for a in node.names]
179
- elif isinstance(node, ast.ImportFrom) and node.module and node.level == 0:
180
- imports.append(node.module)
181
- tops = sorted({i.split(".")[0] for i in imports})
182
- external = [t for t in tops if t not in stdlib and t not in local_tops]
183
- classes = [n.name for n in tree.body if isinstance(n, ast.ClassDef)]
184
- emit("file", path=rel, module=module, loc=source.count("\n") + 1, imports=tops, external=external,
185
- classes=classes, digest="sha256:" + hashlib.sha256(source.encode()).hexdigest())
186
-
187
- targets = [(n, None) for n in tree.body if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))]
188
- for cls in (n for n in tree.body if isinstance(n, ast.ClassDef)):
189
- targets += [(n, cls.name) for n in cls.body if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))]
190
- for fn, owner in targets:
191
- calls = sorted({dotted(n.func) for n in ast.walk(fn) if isinstance(n, ast.Call) and dotted(n.func)})
192
- effects = set()
193
- for call in calls:
194
- for kind, names in SIDE_EFFECT_RULES.items():
195
- if call in names or any(call.endswith("." + n) for n in names if "." not in n and n != "open"):
196
- effects.add(kind)
197
- top = call.split(".")[0]
198
- if top in MODULE_EFFECTS:
199
- effects.add(MODULE_EFFECTS[top])
200
- if any(isinstance(n, ast.Global) for n in ast.walk(fn)):
201
- effects.add("global_state")
202
- fn_source = ast.get_source_segment(source, fn) or ""
203
- depth = loop_depth(fn)
204
- hints = []
205
- if depth >= 2:
206
- hints.append(f"nested loops (depth {depth}): possible O(n^{depth}) path - static hint, not measured")
207
- if "while" in fn_source and "True" in fn_source:
208
- hints.append("unbounded while loop")
209
- emit("unit", file=rel, module=module, name=fn.name, owner=owner,
210
- qualified_name=f"{module}.{owner + '.' if owner else ''}{fn.name}",
211
- kind="method" if owner else "function", is_async=isinstance(fn, ast.AsyncFunctionDef),
212
- line_start=fn.lineno, line_end=fn.end_lineno, params=describe_args(fn),
213
- returns=ast.unparse(fn.returns) if fn.returns else None, docstring=ast.get_docstring(fn),
214
- source=fn_source, digest="sha256:" + hashlib.sha256(fn_source.encode()).hexdigest(),
215
- calls=calls, internal_deps=sorted(c for c in calls if c in defined and c != fn.name),
216
- side_effects=sorted(effects), complexity=complexity(fn), loop_depth=depth, perf_hints=hints,
217
- raise_lines=sorted({n.lineno for n in ast.walk(fn) if isinstance(n, ast.Raise)}),
218
- loc=(fn.end_lineno or fn.lineno) - fn.lineno + 1)
219
- emit("done")
220
-
221
-
222
- # ---------------------------------------------------------------- input generation
223
-
224
- EDGE_POOLS = {
225
- "str": ["", " ", "a", "Hello World", " multiple spaces ", "UPPER lower", "ünïcödé café", "emoji 😀 here",
226
- "-0", "1h30m", "tab\tnew\nline", "x" * 300, "The cat. The dog. A cat!", "!!!"],
227
- "int": [0, 1, -1, 2, 7, 255, 2 ** 31 - 1, -(2 ** 31), 2 ** 63],
228
- "float": [0.0, -0.0, 1.5, -2.25, 1e-9, 1e308, math.nan, math.inf],
229
- "bool": [True, False],
230
- "list": [[], [1], [1, 2, 3], [-1.5, 2.5], ["apple", "avocado", "banana"], [0, 0, 0]],
231
- "None": [None],
232
- }
233
-
234
-
235
- def pool_for(annotation, default):
236
- if annotation:
237
- for key in ("str", "int", "float", "bool", "list"):
238
- if annotation.startswith(key):
239
- return EDGE_POOLS[key]
240
- if isinstance(default, bool):
241
- return EDGE_POOLS["bool"]
242
- for key, typ in (("str", str), ("int", int), ("float", float), ("list", list)):
243
- if isinstance(default, typ):
244
- return EDGE_POOLS[key]
245
- return EDGE_POOLS["str"] + EDGE_POOLS["int"][:4] + EDGE_POOLS["list"][:3] + [None]
246
-
247
-
248
- def random_value(rng, annotation, default):
249
- kind = annotation or (type(default).__name__ if default is not inspect.Parameter.empty else "any")
250
- if kind.startswith("str"):
251
- alphabet = "abcXYZ019 -_.,!é😀\t"
252
- return "".join(rng.choice(alphabet) for _ in range(rng.randint(0, 24)))
253
- if kind.startswith("int"):
254
- return rng.choice([rng.randint(-10, 10), rng.randint(-(2 ** 40), 2 ** 40)])
255
- if kind.startswith("float"):
256
- return rng.choice([rng.uniform(-1e6, 1e6), float(rng.randint(-5, 5)), 0.1 * rng.randint(0, 30)])
257
- if kind.startswith("bool"):
258
- return rng.random() < 0.5
259
- if kind.startswith("list"):
260
- return [rng.choice([rng.randint(-50, 50), rng.uniform(-5, 5)]) for _ in range(rng.randint(0, 6))]
261
- return rng.choice([None, rng.randint(-3, 3), "s"])
262
-
263
-
264
- def generate_cases(fn, count, seed, mode):
265
- rng = random.Random(seed)
266
- sig = inspect.signature(fn)
267
- params = [p for p in sig.parameters.values() if p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD)]
268
- hints = {p.name: (p.annotation if isinstance(p.annotation, str) else getattr(p.annotation, "__name__", None))
269
- if p.annotation is not inspect.Parameter.empty else None for p in params}
270
- seen, cases = set(), []
271
- attempts = 0
272
- while len(cases) < count and attempts < count * 20:
273
- attempts += 1
274
- args = []
275
- for i, p in enumerate(params):
276
- required = p.default is inspect.Parameter.empty
277
- if not required and rng.random() < 0.5:
278
- break
279
- if mode == "fuzz":
280
- args.append(random_value(rng, hints[p.name], p.default))
281
- else:
282
- pool = pool_for(hints[p.name], None if required else p.default)
283
- # Walk the first parameter's pool in order so every edge value is covered once.
284
- args.append(pool[len(cases) % len(pool)] if i == 0 and len(cases) < len(pool) else rng.choice(pool))
285
- key = json.dumps(encode(args), sort_keys=True)
286
- if key in seen:
287
- continue
288
- seen.add(key)
289
- cases.append({"args": encode(args), "kwargs": {}, "origin": "fuzz" if mode == "fuzz" else "generated"})
290
- return cases
291
-
292
-
293
- # ---------------------------------------------------------------- record / bench
294
-
295
- def load_function(module_file, function):
296
- path = os.path.realpath(os.path.join(SRC, module_file))
297
- if not path.startswith(os.path.realpath(SRC) + os.sep):
298
- raise SystemExit("module_file escapes the source root")
299
- sys.path.insert(0, os.path.dirname(path))
300
- sys.path.insert(0, SRC)
301
- spec = importlib.util.spec_from_file_location("pp_target", path)
302
- module = importlib.util.module_from_spec(spec)
303
- with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
304
- spec.loader.exec_module(module)
305
- target = getattr(module, function, None)
306
- if not callable(target):
307
- raise SystemExit(f"{function} is not a callable in {module_file}")
308
- return target
309
-
310
-
311
- def snapshot(root):
312
- effects = []
313
- for base, _dirs, files in os.walk(root):
314
- for name in files:
315
- full = os.path.join(base, name)
316
- with open(full, "rb") as fh:
317
- data = fh.read()
318
- effects.append({"path": os.path.relpath(full, root).replace(os.sep, "/"), "size": len(data),
319
- "sha256": hashlib.sha256(data).hexdigest()})
320
- return sorted(effects, key=lambda e: e["path"])
321
-
322
-
323
- def raise_line(exc, code):
324
- """Line in the target file where the exception left the target code (innermost frame there)."""
325
- if code is None:
326
- return None
327
- line = None
328
- tb = exc.__traceback__
329
- while tb is not None:
330
- if tb.tb_frame.f_code.co_filename == code.co_filename:
331
- line = tb.tb_lineno
332
- tb = tb.tb_next
333
- return line
334
-
335
-
336
- def run_case(fn, case):
337
- args = decode(case.get("args", []))
338
- kwargs = decode(case.get("kwargs", {}))
339
- out, err = io.StringIO(), io.StringIO()
340
- cwd = os.getcwd()
341
- with tempfile.TemporaryDirectory(prefix="pp-case-") as scratch:
342
- os.chdir(scratch)
343
- started = time.perf_counter_ns()
344
- try:
345
- with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
346
- value = fn(*args, **kwargs)
347
- outcome = {"kind": "return", "value": encode(value)}
348
- except Exception as exc: # noqa: BLE001 - recording every exception is the point
349
- outcome = {"kind": "raise", "type": type(exc).__name__, "message": str(exc)}
350
- line = raise_line(exc, getattr(fn, "__code__", None))
351
- if line:
352
- outcome["raise_line"] = line
353
- duration = (time.perf_counter_ns() - started) // 1000
354
- effects = snapshot(scratch)
355
- os.chdir(cwd)
356
- return {"outcome": outcome, "stdout": out.getvalue(), "stderr": err.getvalue(), "effects": effects,
357
- "duration_us": duration}
358
-
359
-
360
- def observable(result):
361
- return json.dumps({k: result[k] for k in ("outcome", "stdout", "stderr", "effects")}, sort_keys=True)
362
-
363
-
364
- PIN_EPOCH = 1767225600 # 2026-01-01T00:00:00Z
365
-
366
-
367
- def pin_clock():
368
- """Freeze the clock at PIN_EPOCH for code imported after this (time, datetime). Opt-in: pin_clock."""
369
- import datetime as _dt
370
- import time as _time
371
-
372
- _time.time = lambda: float(PIN_EPOCH)
373
- _time.time_ns = lambda: PIN_EPOCH * 1_000_000_000
374
- real = _dt.datetime
375
-
376
- class PinnedDatetime(real):
377
- @classmethod
378
- def now(cls, tz=None):
379
- utc = real.fromtimestamp(PIN_EPOCH, _dt.timezone.utc)
380
- return utc.astimezone(tz) if tz else utc.replace(tzinfo=None)
381
-
382
- @classmethod
383
- def utcnow(cls):
384
- return real.fromtimestamp(PIN_EPOCH, _dt.timezone.utc).replace(tzinfo=None)
385
-
386
- @classmethod
387
- def today(cls):
388
- return cls.now()
389
-
390
- class PinnedDate(_dt.date):
391
- @classmethod
392
- def today(cls):
393
- return _dt.date(2026, 1, 1)
394
-
395
- _dt.datetime = PinnedDatetime
396
- _dt.date = PinnedDate
397
-
398
-
399
- def record(req):
400
- pinned = bool(req.get("pin_clock"))
401
- if pinned:
402
- pin_clock()
403
- fn = load_function(req["module_file"], req["function"])
404
- cases = list(req.get("cases", []))
405
- gen = req.get("generate") or {}
406
- if gen.get("count"):
407
- cases += generate_cases(fn, int(gen["count"]), int(gen.get("seed", 0)), gen.get("mode", "edge"))
408
- emit("log", message=f"recording {len(cases)} cases for {req['function']} (python {sys.version.split()[0]})")
409
- emit("plan", total=len(cases), runtime=f"python {sys.version.split()[0]}")
410
- for index, case in enumerate(cases):
411
- if pinned:
412
- random.seed(0)
413
- first = run_case(fn, case)
414
- if pinned:
415
- random.seed(0)
416
- second = run_case(fn, case)
417
- stable = observable(first) == observable(second)
418
- emit("case", index=index, ref=case.get("ref"), origin=case.get("origin", "manual"), args=case.get("args", []),
419
- kwargs=case.get("kwargs", {}), stable=stable, **first)
420
- emit("done")
421
-
422
-
423
- def bench(req):
424
- fn = load_function(req["module_file"], req["function"])
425
- iterations = max(1, min(int(req.get("iterations", 30)), 10000))
426
- emit("plan", total=len(req["cases"]), runtime=f"python {sys.version.split()[0]}")
427
- for case in req["cases"]:
428
- args, kwargs = decode(case.get("args", [])), decode(case.get("kwargs", {}))
429
- samples = []
430
- sink = io.StringIO()
431
- with tempfile.TemporaryDirectory(prefix="pp-bench-") as scratch:
432
- os.chdir(scratch)
433
- tracemalloc.start()
434
- for _ in range(iterations):
435
- started = time.perf_counter_ns()
436
- try:
437
- with contextlib.redirect_stdout(sink):
438
- fn(*args, **kwargs)
439
- except Exception: # noqa: BLE001 - erroring cases are timed too
440
- pass
441
- samples.append(time.perf_counter_ns() - started)
442
- _current, peak = tracemalloc.get_traced_memory()
443
- tracemalloc.stop()
444
- os.chdir("/")
445
- emit("case", ref=case.get("ref"), samples_ns=samples, peak_memory_bytes=peak)
446
- emit("done")
447
-
448
-
449
- def main():
450
- req = json.loads(sys.stdin.read() or "{}")
451
- command = req.get("command")
452
- handlers = {"analyze": analyze, "record": record, "bench": bench}
453
- if command not in handlers:
454
- raise SystemExit(f"unknown command {command!r}")
455
- handlers[command](req)
456
-
457
-
458
- if __name__ == "__main__":
459
- main()
1
+ """PortPilot Python adapter.
2
+
3
+ Runs INSIDE the sandbox only. Reads one JSON request on stdin and writes JSON lines
4
+ on stdout, one event per line: {"event": "log" | "case" | "unit" | "file" | "done", ...}.
5
+
6
+ Commands:
7
+ analyze - static analysis with `ast` (never imports the target code)
8
+ record - call a function for each case (twice) and capture its behaviour
9
+ bench - time each case over N iterations inside this process
10
+ """
11
+ import ast
12
+ import base64
13
+ import contextlib
14
+ import hashlib
15
+ import importlib.util
16
+ import inspect
17
+ import io
18
+ import json
19
+ import math
20
+ import os
21
+ import random
22
+ import sys
23
+ import tempfile
24
+ import time
25
+ import tracemalloc
26
+
27
+ SRC = os.environ.get("PORTPILOT_SRC", "/work/src")
28
+ REAL_STDOUT = sys.stdout
29
+
30
+
31
+ def emit(event, **data):
32
+ data["event"] = event
33
+ REAL_STDOUT.write(json.dumps(data, ensure_ascii=False, allow_nan=False) + "\n")
34
+ REAL_STDOUT.flush()
35
+
36
+
37
+ # ---------------------------------------------------------------- value codec
38
+
39
+ def encode(value):
40
+ if value is None or isinstance(value, (bool, str)):
41
+ return value
42
+ if isinstance(value, int):
43
+ return value
44
+ if isinstance(value, float):
45
+ if math.isnan(value):
46
+ return {"$float": "nan"}
47
+ if math.isinf(value):
48
+ return {"$float": "inf" if value > 0 else "-inf"}
49
+ if value == 0.0 and math.copysign(1.0, value) < 0:
50
+ return {"$float": "-0.0"}
51
+ return value
52
+ if isinstance(value, (list, tuple)):
53
+ return [encode(v) for v in value]
54
+ if isinstance(value, dict):
55
+ return {str(k): encode(v) for k, v in value.items()}
56
+ if isinstance(value, (bytes, bytearray)):
57
+ return {"$bytes": base64.b64encode(bytes(value)).decode()}
58
+ if isinstance(value, (set, frozenset)):
59
+ items = [encode(v) for v in value]
60
+ return {"$set": sorted(items, key=lambda v: json.dumps(v, sort_keys=True))}
61
+ return {"$repr": repr(value)[:200]}
62
+
63
+
64
+ def decode(value):
65
+ if isinstance(value, list):
66
+ return [decode(v) for v in value]
67
+ if isinstance(value, dict):
68
+ if "$float" in value:
69
+ special = {"nan": math.nan, "inf": math.inf, "-inf": -math.inf, "-0.0": -0.0}
70
+ return special[value["$float"]] if value["$float"] in special else float(value["$float"])
71
+ if "$bytes" in value:
72
+ return base64.b64decode(value["$bytes"])
73
+ if "$set" in value:
74
+ return set(decode(v) for v in value["$set"])
75
+ return {k: decode(v) for k, v in value.items()}
76
+ return value
77
+
78
+
79
+ # ---------------------------------------------------------------- analyze
80
+
81
+ SIDE_EFFECT_RULES = {
82
+ "filesystem": {"open", "os.remove", "os.unlink", "os.makedirs", "os.mkdir", "os.rename", "shutil.rmtree",
83
+ "shutil.copy", "shutil.move", "write_text", "write_bytes", "unlink", "mkdir"},
84
+ "network": {"urllib.request.urlopen", "urlopen", "requests.get", "requests.post", "requests.request",
85
+ "socket.socket", "socket.create_connection", "http.client.HTTPConnection", "httpx.get", "httpx.post"},
86
+ "database": {"sqlite3.connect", "psycopg2.connect", "pymysql.connect", "create_engine"},
87
+ "process": {"subprocess.run", "subprocess.Popen", "subprocess.call", "os.system", "os.popen"},
88
+ "stdout": {"print"},
89
+ "nondeterminism": {"time.time", "datetime.now", "datetime.datetime.now", "random.random", "random.randint",
90
+ "random.choice", "uuid.uuid4", "os.urandom"},
91
+ "environment": {"os.getenv", "os.environ.get"},
92
+ }
93
+ MODULE_EFFECTS = {"requests": "network", "httpx": "network", "socket": "network", "urllib": "network",
94
+ "sqlite3": "database", "psycopg2": "database", "pymysql": "database", "sqlalchemy": "database",
95
+ "subprocess": "process", "shutil": "filesystem"}
96
+
97
+
98
+ def dotted(node):
99
+ if isinstance(node, ast.Name):
100
+ return node.id
101
+ if isinstance(node, ast.Attribute):
102
+ base = dotted(node.value)
103
+ return f"{base}.{node.attr}" if base else node.attr
104
+ return None
105
+
106
+
107
+ def complexity(fn):
108
+ score = 1
109
+ for node in ast.walk(fn):
110
+ if isinstance(node, (ast.If, ast.For, ast.While, ast.AsyncFor, ast.IfExp, ast.ExceptHandler, ast.With,
111
+ ast.Assert, ast.comprehension)):
112
+ score += 1
113
+ elif isinstance(node, ast.BoolOp):
114
+ score += len(node.values) - 1
115
+ return score
116
+
117
+
118
+ def loop_depth(node, depth=0):
119
+ best = depth
120
+ for child in ast.iter_child_nodes(node):
121
+ inc = 1 if isinstance(child, (ast.For, ast.While, ast.AsyncFor, ast.comprehension)) else 0
122
+ best = max(best, loop_depth(child, depth + inc))
123
+ return best
124
+
125
+
126
+ def describe_args(fn):
127
+ args = fn.args
128
+ params = []
129
+ positional = args.posonlyargs + args.args
130
+ defaults = [None] * (len(positional) - len(args.defaults)) + list(args.defaults)
131
+ for arg, default in zip(positional, defaults):
132
+ params.append({"name": arg.arg, "annotation": ast.unparse(arg.annotation) if arg.annotation else None,
133
+ "default": ast.unparse(default) if default is not None else None, "kind": "positional"})
134
+ if args.vararg:
135
+ params.append({"name": args.vararg.arg, "kind": "varargs", "annotation": None, "default": None})
136
+ for arg, default in zip(args.kwonlyargs, args.kw_defaults):
137
+ params.append({"name": arg.arg, "annotation": ast.unparse(arg.annotation) if arg.annotation else None,
138
+ "default": ast.unparse(default) if default is not None else None, "kind": "keyword"})
139
+ if args.kwarg:
140
+ params.append({"name": args.kwarg.arg, "kind": "kwargs", "annotation": None, "default": None})
141
+ return params
142
+
143
+
144
+ def analyze(_req):
145
+ stdlib = set(getattr(sys, "stdlib_module_names", ()))
146
+ py_files = []
147
+ for root, dirs, files in os.walk(SRC):
148
+ dirs[:] = sorted(d for d in dirs if not d.startswith(".") and d not in {"__pycache__", "venv", ".venv",
149
+ "node_modules", "build", "dist"})
150
+ for name in sorted(files):
151
+ if name.endswith(".py"):
152
+ py_files.append(os.path.join(root, name))
153
+ local_modules = {os.path.splitext(os.path.relpath(p, SRC))[0].replace(os.sep, ".") for p in py_files}
154
+ local_tops = {m.split(".")[0] for m in local_modules}
155
+ defined = {}
156
+ parsed = []
157
+ for path in py_files:
158
+ rel = os.path.relpath(path, SRC).replace(os.sep, "/")
159
+ with open(path, "rb") as fh:
160
+ raw = fh.read()
161
+ source = raw.decode("utf-8", "replace")
162
+ try:
163
+ tree = ast.parse(source, filename=rel)
164
+ except SyntaxError as exc:
165
+ emit("file", path=rel, loc=source.count("\n") + 1, error=f"SyntaxError: {exc.msg} (line {exc.lineno})")
166
+ continue
167
+ parsed.append((rel, source, tree))
168
+ for node in tree.body:
169
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
170
+ defined[node.name] = rel
171
+ emit("log", message=f"parsed {len(parsed)} of {len(py_files)} python files")
172
+
173
+ for rel, source, tree in parsed:
174
+ module = os.path.splitext(rel)[0].replace("/", ".")
175
+ imports = []
176
+ for node in ast.walk(tree):
177
+ if isinstance(node, ast.Import):
178
+ imports += [a.name for a in node.names]
179
+ elif isinstance(node, ast.ImportFrom) and node.module and node.level == 0:
180
+ imports.append(node.module)
181
+ tops = sorted({i.split(".")[0] for i in imports})
182
+ external = [t for t in tops if t not in stdlib and t not in local_tops]
183
+ classes = [n.name for n in tree.body if isinstance(n, ast.ClassDef)]
184
+ emit("file", path=rel, module=module, loc=source.count("\n") + 1, imports=tops, external=external,
185
+ classes=classes, digest="sha256:" + hashlib.sha256(source.encode()).hexdigest())
186
+
187
+ targets = [(n, None) for n in tree.body if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))]
188
+ for cls in (n for n in tree.body if isinstance(n, ast.ClassDef)):
189
+ targets += [(n, cls.name) for n in cls.body if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))]
190
+ for fn, owner in targets:
191
+ calls = sorted({dotted(n.func) for n in ast.walk(fn) if isinstance(n, ast.Call) and dotted(n.func)})
192
+ effects = set()
193
+ for call in calls:
194
+ for kind, names in SIDE_EFFECT_RULES.items():
195
+ if call in names or any(call.endswith("." + n) for n in names if "." not in n and n != "open"):
196
+ effects.add(kind)
197
+ top = call.split(".")[0]
198
+ if top in MODULE_EFFECTS:
199
+ effects.add(MODULE_EFFECTS[top])
200
+ if any(isinstance(n, ast.Global) for n in ast.walk(fn)):
201
+ effects.add("global_state")
202
+ fn_source = ast.get_source_segment(source, fn) or ""
203
+ depth = loop_depth(fn)
204
+ hints = []
205
+ if depth >= 2:
206
+ hints.append(f"nested loops (depth {depth}): possible O(n^{depth}) path - static hint, not measured")
207
+ if "while" in fn_source and "True" in fn_source:
208
+ hints.append("unbounded while loop")
209
+ emit("unit", file=rel, module=module, name=fn.name, owner=owner,
210
+ qualified_name=f"{module}.{owner + '.' if owner else ''}{fn.name}",
211
+ kind="method" if owner else "function", is_async=isinstance(fn, ast.AsyncFunctionDef),
212
+ line_start=fn.lineno, line_end=fn.end_lineno, params=describe_args(fn),
213
+ returns=ast.unparse(fn.returns) if fn.returns else None, docstring=ast.get_docstring(fn),
214
+ source=fn_source, digest="sha256:" + hashlib.sha256(fn_source.encode()).hexdigest(),
215
+ calls=calls, internal_deps=sorted(c for c in calls if c in defined and c != fn.name),
216
+ side_effects=sorted(effects), complexity=complexity(fn), loop_depth=depth, perf_hints=hints,
217
+ raise_lines=sorted({n.lineno for n in ast.walk(fn) if isinstance(n, ast.Raise)}),
218
+ loc=(fn.end_lineno or fn.lineno) - fn.lineno + 1)
219
+ emit("done")
220
+
221
+
222
+ # ---------------------------------------------------------------- input generation
223
+
224
+ EDGE_POOLS = {
225
+ "str": ["", " ", "a", "Hello World", " multiple spaces ", "UPPER lower", "ünïcödé café", "emoji 😀 here",
226
+ "-0", "1h30m", "tab\tnew\nline", "x" * 300, "The cat. The dog. A cat!", "!!!"],
227
+ "int": [0, 1, -1, 2, 7, 255, 2 ** 31 - 1, -(2 ** 31), 2 ** 63],
228
+ "float": [0.0, -0.0, 1.5, -2.25, 1e-9, 1e308, math.nan, math.inf],
229
+ "bool": [True, False],
230
+ "list": [[], [1], [1, 2, 3], [-1.5, 2.5], ["apple", "avocado", "banana"], [0, 0, 0]],
231
+ "None": [None],
232
+ }
233
+
234
+
235
+ def pool_for(annotation, default):
236
+ if annotation:
237
+ for key in ("str", "int", "float", "bool", "list"):
238
+ if annotation.startswith(key):
239
+ return EDGE_POOLS[key]
240
+ if isinstance(default, bool):
241
+ return EDGE_POOLS["bool"]
242
+ for key, typ in (("str", str), ("int", int), ("float", float), ("list", list)):
243
+ if isinstance(default, typ):
244
+ return EDGE_POOLS[key]
245
+ return EDGE_POOLS["str"] + EDGE_POOLS["int"][:4] + EDGE_POOLS["list"][:3] + [None]
246
+
247
+
248
+ def random_value(rng, annotation, default):
249
+ kind = annotation or (type(default).__name__ if default is not inspect.Parameter.empty else "any")
250
+ if kind.startswith("str"):
251
+ alphabet = "abcXYZ019 -_.,!é😀\t"
252
+ return "".join(rng.choice(alphabet) for _ in range(rng.randint(0, 24)))
253
+ if kind.startswith("int"):
254
+ return rng.choice([rng.randint(-10, 10), rng.randint(-(2 ** 40), 2 ** 40)])
255
+ if kind.startswith("float"):
256
+ return rng.choice([rng.uniform(-1e6, 1e6), float(rng.randint(-5, 5)), 0.1 * rng.randint(0, 30)])
257
+ if kind.startswith("bool"):
258
+ return rng.random() < 0.5
259
+ if kind.startswith("list"):
260
+ return [rng.choice([rng.randint(-50, 50), rng.uniform(-5, 5)]) for _ in range(rng.randint(0, 6))]
261
+ return rng.choice([None, rng.randint(-3, 3), "s"])
262
+
263
+
264
+ def generate_cases(fn, count, seed, mode):
265
+ rng = random.Random(seed)
266
+ sig = inspect.signature(fn)
267
+ params = [p for p in sig.parameters.values() if p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD)]
268
+ hints = {p.name: (p.annotation if isinstance(p.annotation, str) else getattr(p.annotation, "__name__", None))
269
+ if p.annotation is not inspect.Parameter.empty else None for p in params}
270
+ seen, cases = set(), []
271
+ attempts = 0
272
+ while len(cases) < count and attempts < count * 20:
273
+ attempts += 1
274
+ args = []
275
+ for i, p in enumerate(params):
276
+ required = p.default is inspect.Parameter.empty
277
+ if not required and rng.random() < 0.5:
278
+ break
279
+ if mode == "fuzz":
280
+ args.append(random_value(rng, hints[p.name], p.default))
281
+ else:
282
+ pool = pool_for(hints[p.name], None if required else p.default)
283
+ # Walk the first parameter's pool in order so every edge value is covered once.
284
+ args.append(pool[len(cases) % len(pool)] if i == 0 and len(cases) < len(pool) else rng.choice(pool))
285
+ key = json.dumps(encode(args), sort_keys=True)
286
+ if key in seen:
287
+ continue
288
+ seen.add(key)
289
+ cases.append({"args": encode(args), "kwargs": {}, "origin": "fuzz" if mode == "fuzz" else "generated"})
290
+ return cases
291
+
292
+
293
+ # ---------------------------------------------------------------- record / bench
294
+
295
+ def load_function(module_file, function):
296
+ path = os.path.realpath(os.path.join(SRC, module_file))
297
+ if not path.startswith(os.path.realpath(SRC) + os.sep):
298
+ raise SystemExit("module_file escapes the source root")
299
+ sys.path.insert(0, os.path.dirname(path))
300
+ sys.path.insert(0, SRC)
301
+ spec = importlib.util.spec_from_file_location("pp_target", path)
302
+ module = importlib.util.module_from_spec(spec)
303
+ with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
304
+ spec.loader.exec_module(module)
305
+ target = getattr(module, function, None)
306
+ if not callable(target):
307
+ raise SystemExit(f"{function} is not a callable in {module_file}")
308
+ return target
309
+
310
+
311
+ def snapshot(root):
312
+ effects = []
313
+ for base, _dirs, files in os.walk(root):
314
+ for name in files:
315
+ full = os.path.join(base, name)
316
+ with open(full, "rb") as fh:
317
+ data = fh.read()
318
+ effects.append({"path": os.path.relpath(full, root).replace(os.sep, "/"), "size": len(data),
319
+ "sha256": hashlib.sha256(data).hexdigest()})
320
+ return sorted(effects, key=lambda e: e["path"])
321
+
322
+
323
+ def raise_line(exc, code):
324
+ """Line in the target file where the exception left the target code (innermost frame there)."""
325
+ if code is None:
326
+ return None
327
+ line = None
328
+ tb = exc.__traceback__
329
+ while tb is not None:
330
+ if tb.tb_frame.f_code.co_filename == code.co_filename:
331
+ line = tb.tb_lineno
332
+ tb = tb.tb_next
333
+ return line
334
+
335
+
336
+ def run_case(fn, case):
337
+ args = decode(case.get("args", []))
338
+ kwargs = decode(case.get("kwargs", {}))
339
+ out, err = io.StringIO(), io.StringIO()
340
+ cwd = os.getcwd()
341
+ with tempfile.TemporaryDirectory(prefix="pp-case-") as scratch:
342
+ os.chdir(scratch)
343
+ started = time.perf_counter_ns()
344
+ try:
345
+ with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
346
+ value = fn(*args, **kwargs)
347
+ outcome = {"kind": "return", "value": encode(value)}
348
+ except Exception as exc: # noqa: BLE001 - recording every exception is the point
349
+ outcome = {"kind": "raise", "type": type(exc).__name__, "message": str(exc)}
350
+ line = raise_line(exc, getattr(fn, "__code__", None))
351
+ if line:
352
+ outcome["raise_line"] = line
353
+ duration = (time.perf_counter_ns() - started) // 1000
354
+ effects = snapshot(scratch)
355
+ os.chdir(cwd)
356
+ return {"outcome": outcome, "stdout": out.getvalue(), "stderr": err.getvalue(), "effects": effects,
357
+ "duration_us": duration}
358
+
359
+
360
+ def observable(result):
361
+ return json.dumps({k: result[k] for k in ("outcome", "stdout", "stderr", "effects")}, sort_keys=True)
362
+
363
+
364
+ PIN_EPOCH = 1767225600 # 2026-01-01T00:00:00Z
365
+
366
+
367
+ def pin_clock():
368
+ """Freeze the clock at PIN_EPOCH for code imported after this (time, datetime). Opt-in: pin_clock."""
369
+ import datetime as _dt
370
+ import time as _time
371
+
372
+ _time.time = lambda: float(PIN_EPOCH)
373
+ _time.time_ns = lambda: PIN_EPOCH * 1_000_000_000
374
+ real = _dt.datetime
375
+
376
+ class PinnedDatetime(real):
377
+ @classmethod
378
+ def now(cls, tz=None):
379
+ utc = real.fromtimestamp(PIN_EPOCH, _dt.timezone.utc)
380
+ return utc.astimezone(tz) if tz else utc.replace(tzinfo=None)
381
+
382
+ @classmethod
383
+ def utcnow(cls):
384
+ return real.fromtimestamp(PIN_EPOCH, _dt.timezone.utc).replace(tzinfo=None)
385
+
386
+ @classmethod
387
+ def today(cls):
388
+ return cls.now()
389
+
390
+ class PinnedDate(_dt.date):
391
+ @classmethod
392
+ def today(cls):
393
+ return _dt.date(2026, 1, 1)
394
+
395
+ _dt.datetime = PinnedDatetime
396
+ _dt.date = PinnedDate
397
+
398
+
399
+ def record(req):
400
+ pinned = bool(req.get("pin_clock"))
401
+ if pinned:
402
+ pin_clock()
403
+ fn = load_function(req["module_file"], req["function"])
404
+ cases = list(req.get("cases", []))
405
+ gen = req.get("generate") or {}
406
+ if gen.get("count"):
407
+ cases += generate_cases(fn, int(gen["count"]), int(gen.get("seed", 0)), gen.get("mode", "edge"))
408
+ emit("log", message=f"recording {len(cases)} cases for {req['function']} (python {sys.version.split()[0]})")
409
+ emit("plan", total=len(cases), runtime=f"python {sys.version.split()[0]}")
410
+ for index, case in enumerate(cases):
411
+ if pinned:
412
+ random.seed(0)
413
+ first = run_case(fn, case)
414
+ if pinned:
415
+ random.seed(0)
416
+ second = run_case(fn, case)
417
+ stable = observable(first) == observable(second)
418
+ emit("case", index=index, ref=case.get("ref"), origin=case.get("origin", "manual"), args=case.get("args", []),
419
+ kwargs=case.get("kwargs", {}), stable=stable, **first)
420
+ emit("done")
421
+
422
+
423
+ def bench(req):
424
+ fn = load_function(req["module_file"], req["function"])
425
+ iterations = max(1, min(int(req.get("iterations", 30)), 10000))
426
+ emit("plan", total=len(req["cases"]), runtime=f"python {sys.version.split()[0]}")
427
+ for case in req["cases"]:
428
+ args, kwargs = decode(case.get("args", [])), decode(case.get("kwargs", {}))
429
+ samples = []
430
+ sink = io.StringIO()
431
+ with tempfile.TemporaryDirectory(prefix="pp-bench-") as scratch:
432
+ os.chdir(scratch)
433
+ tracemalloc.start()
434
+ for _ in range(iterations):
435
+ started = time.perf_counter_ns()
436
+ try:
437
+ with contextlib.redirect_stdout(sink):
438
+ fn(*args, **kwargs)
439
+ except Exception: # noqa: BLE001 - erroring cases are timed too
440
+ pass
441
+ samples.append(time.perf_counter_ns() - started)
442
+ _current, peak = tracemalloc.get_traced_memory()
443
+ tracemalloc.stop()
444
+ os.chdir("/")
445
+ emit("case", ref=case.get("ref"), samples_ns=samples, peak_memory_bytes=peak)
446
+ emit("done")
447
+
448
+
449
+ def main():
450
+ req = json.loads(sys.stdin.read() or "{}")
451
+ command = req.get("command")
452
+ handlers = {"analyze": analyze, "record": record, "bench": bench}
453
+ if command not in handlers:
454
+ raise SystemExit(f"unknown command {command!r}")
455
+ handlers[command](req)
456
+
457
+
458
+ if __name__ == "__main__":
459
+ main()