File size: 4,539 Bytes
b2941bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
"""Parallel row-validation harness, shared by every entry.

Generalized from chartforge/render_check.py, whose ProcessPoolExecutor driver was always
generic while only its inner check was chart-specific.

THE RULE THIS MODULE EXISTS TO ENFORCE: **the gate imports the released scorer**, it does
not reimplement it. If the scorer's semantics change, the gate changes with it, so a row
can never pass generation-time validation and then fail evaluation-time scoring. Every
entry passes its own `check_fn`, and every `check_fn` must call into that entry's real
scorer rather than a lookalike.

A `check_fn` takes whatever tuple the entry finds convenient, whose first element is the
row id, and returns `(row_id, ok, reason)`. Reasons are formatted `"bucket: detail"` so
`drop_reasons()` aggregates them for free.

    from common.exec_gate import check_many, drop_reasons
    verdicts = check_many(items, my_check, workers=8)
    kept = [i for i in items if verdicts[i[0]][0]]
    print(drop_reasons(verdicts))
"""
from __future__ import annotations

import json
import subprocess
import sys
import tempfile
from collections import Counter
from concurrent.futures import ProcessPoolExecutor, as_completed
from pathlib import Path
from typing import Callable, Sequence

TIMEOUT_S = 8

CheckFn = Callable[[tuple], tuple[str, bool, str]]


def check_many(items: Sequence[tuple], check_fn: CheckFn, workers: int = 8,
               progress_every: int = 2000) -> dict[str, tuple[bool, str]]:
    """Validate rows in parallel. Execution is CPU-bound, so processes beat threads.

    check_fn must be a module-level function (picklable), not a lambda or closure.
    """
    results: dict[str, tuple[bool, str]] = {}
    with ProcessPoolExecutor(max_workers=workers) as pool:
        futs = {pool.submit(check_fn, it): it[0] for it in items}
        done = 0
        for fut in as_completed(futs):
            rid, ok, why = fut.result()
            results[rid] = (ok, why)
            done += 1
            if progress_every and done % progress_every == 0:
                kept = sum(1 for v in results.values() if v[0])
                print(f"  checked {done}/{len(items)}  kept {kept}", flush=True)
    return results


def drop_reasons(verdicts: dict[str, tuple[bool, str]]) -> dict[str, int]:
    """Aggregate failures by the bucket prefix before the first colon."""
    return dict(Counter(why.split(":")[0] for ok, why in verdicts.values() if not ok
                        ).most_common())


def run_python(code: str, marker: str = "__RESULT__", timeout: int = TIMEOUT_S,
               preamble: str = "") -> object | None:
    """Execute code in a subprocess and return the JSON printed after `marker`.

    Used by entries that score by executing generated code. The subprocess is the
    isolation boundary: a row that hangs or segfaults costs one worker, not the run.
    """
    script = (preamble + "\n" + code) if preamble else code
    path = None
    try:
        with tempfile.NamedTemporaryFile("w", suffix=".py", delete=False) as f:
            f.write(script)
            path = f.name
        out = subprocess.run([sys.executable, path], capture_output=True,
                             text=True, timeout=timeout)
        for line in out.stdout.splitlines():
            if line.startswith(marker):
                return json.loads(line[len(marker):])
        return None
    except Exception:
        return None
    finally:
        if path:
            try:
                Path(path).unlink(missing_ok=True)
            except Exception:
                pass


def _echo_check(item: tuple) -> tuple[str, bool, str]:
    """Module-level so the selftest can pickle it."""
    rid, value = item
    if value < 0:
        return rid, False, "negative: value below zero"
    if value == 0:
        return rid, False, "zero: value is zero"
    return rid, True, "ok"


def _selftest() -> None:
    items = [("a", 1), ("b", -1), ("c", 0), ("d", 5), ("e", -2)]
    v = check_many(items, _echo_check, workers=2, progress_every=0)
    assert len(v) == 5
    assert [k for k in v if v[k][0]] == ["a", "d"] or set(k for k in v if v[k][0]) == {"a", "d"}
    assert drop_reasons(v) == {"negative": 2, "zero": 1}, drop_reasons(v)

    assert run_python('print("__RESULT__" + __import__("json").dumps([1,2]))') == [1, 2]
    assert run_python('raise SystemExit(1)') is None
    assert run_python('import time; time.sleep(30)', timeout=2) is None
    print("exec_gate selftest: 5/5 OK")


if __name__ == "__main__":
    _selftest()