File size: 7,449 Bytes
d086025
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
#!/bin/bash
# Harbor verifier: inject the hidden suite, run it, and score against the
# generation-time measured test count. Every path emits reward + metrics.
set -uo pipefail
mkdir -p /logs/verifier
cd "${WORKDIR:-/workspace/repo}"
OUT_FILE=/logs/verifier/test-output.log
: > "$OUT_FILE"
EXPECTED=$(python3 -c 'import json; d=json.load(open("/tests/tests.json")); print(int(d.get("expected_test_count") or d.get("measured_test_count") or 0))' 2>/dev/null || echo 0)
grade_and_exit() {
  local phase="$1" reason="$2" rc="$3"
  python3 /tests/grader.py --output "$OUT_FILE" --return-code "$rc" --expected-count "$EXPECTED" --phase "$phase" --reason "$reason" >/dev/null
  cat /logs/verifier/reward.txt
  exit 0
}
python3 - /tests/test_patch.diff <<'PY' 2>/dev/null || true
import os, sys
try:
    lines = open(sys.argv[1], encoding='utf-8', errors='replace').read().splitlines()
except OSError:
    lines = []
i = 0
while i < len(lines):
    line = lines[i]
    if line.startswith('diff --git a/'):
        rest = line[len('diff --git a/'):]
        split = rest.find(' b/')
        path = rest[:split] if split != -1 else None
        is_new = False
        j = i + 1
        while j < len(lines) and not lines[j].startswith('diff --git '):
            is_new = is_new or lines[j].startswith('new file mode')
            j += 1
        if is_new and path and os.path.isfile(path):
            try:
                os.remove(path)
            except OSError:
                pass
        i = j
        continue
    i += 1
PY
PATCH_APPLIED=0
if git apply --check /tests/test_patch.diff 2>/dev/null; then
  git apply /tests/test_patch.diff 2>/dev/null && PATCH_APPLIED=1
elif git apply --reverse --check /tests/test_patch.diff 2>/dev/null; then
  PATCH_APPLIED=1
elif patch --dry-run -p1 < /tests/test_patch.diff >/dev/null 2>&1; then
  patch -p1 < /tests/test_patch.diff >/dev/null 2>&1 && PATCH_APPLIED=1
fi
if [ "$PATCH_APPLIED" -ne 1 ]; then
  echo 'hidden test patch could not be applied' > "$OUT_FILE"
  grade_and_exit patch hidden-test-patch-failed 1
fi
export PYTHONPATH="$PWD:${PYTHONPATH:-}"
if [ -d /tests/test_assets ]; then
  find /tests/test_assets -mindepth 1 -maxdepth 1 -exec cp -a -t "$PWD" -- {} +
fi
timeout --signal=TERM --kill-after=30s 3300s bash -lc 'exec python3 -c '"'"'import json, os, sys, unittest
from collections import defaultdict

contract = json.loads(sys.argv[1])
limit = int(sys.argv[2])
coverage = None
if os.environ.get('"'"'"'"'"'"'"'"'COVERAGE_FILE'"'"'"'"'"'"'"'"'):
    from coverage import Coverage
    coverage = Coverage(source=['"'"'"'"'"'"'"'"'.'"'"'"'"'"'"'"'"'])
    coverage.start()

class Result(unittest.TextTestResult):
    outcomes = None
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.outcomes = {}
    def record(self, test, outcome):
        identity = '"'"'"'"'"'"'"'"'unittest::'"'"'"'"'"'"'"'"' + test.id()
        self.outcomes[identity] = outcome
        status = {'"'"'"'"'"'"'"'"'passed'"'"'"'"'"'"'"'"': '"'"'"'"'"'"'"'"'PASSED'"'"'"'"'"'"'"'"', '"'"'"'"'"'"'"'"'failed'"'"'"'"'"'"'"'"': '"'"'"'"'"'"'"'"'FAILED'"'"'"'"'"'"'"'"', '"'"'"'"'"'"'"'"'errors'"'"'"'"'"'"'"'"': '"'"'"'"'"'"'"'"'ERROR'"'"'"'"'"'"'"'"', '"'"'"'"'"'"'"'"'skipped'"'"'"'"'"'"'"'"': '"'"'"'"'"'"'"'"'SKIPPED'"'"'"'"'"'"'"'"'}[outcome]
        print('"'"'"'"'"'"'"'"'\n'"'"'"'"'"'"'"'"' + identity + '"'"'"'"'"'"'"'"' '"'"'"'"'"'"'"'"' + status, flush=True)
    def addSuccess(self, test):
        super().addSuccess(test)
        self.record(test, '"'"'"'"'"'"'"'"'passed'"'"'"'"'"'"'"'"')
    def addFailure(self, test, error):
        super().addFailure(test, error)
        self.record(test, '"'"'"'"'"'"'"'"'failed'"'"'"'"'"'"'"'"')
    def addError(self, test, error):
        super().addError(test, error)
        self.record(test, '"'"'"'"'"'"'"'"'errors'"'"'"'"'"'"'"'"')
    def addSkip(self, test, reason):
        super().addSkip(test, reason)
        self.record(test, '"'"'"'"'"'"'"'"'skipped'"'"'"'"'"'"'"'"')
    def addExpectedFailure(self, test, error):
        super().addExpectedFailure(test, error)
        self.record(test, '"'"'"'"'"'"'"'"'skipped'"'"'"'"'"'"'"'"')
    def addUnexpectedSuccess(self, test):
        super().addUnexpectedSuccess(test)
        self.record(test, '"'"'"'"'"'"'"'"'failed'"'"'"'"'"'"'"'"')
    def addSubTest(self, test, subtest, error):
        super().addSubTest(test, subtest, error)
        if error is not None:
            self.record(test, '"'"'"'"'"'"'"'"'failed'"'"'"'"'"'"'"'"' if issubclass(error[0], test.failureException) else '"'"'"'"'"'"'"'"'errors'"'"'"'"'"'"'"'"')

def flatten(suite):
    for item in suite:
        if isinstance(item, unittest.TestSuite):
            yield from flatten(item)
        else:
            yield item

try:
    loader = unittest.TestLoader()
    suite = loader.discover(**contract)
    if loader.errors:
        for error in loader.errors:
            print(error, file=sys.stderr)
        print('"'"'"'"'"'"'"'"'[programgen] test collection failed with exit code 2'"'"'"'"'"'"'"'"', file=sys.stderr)
        raise SystemExit(2)
    tests = list(flatten(suite))
    if len({test.id() for test in tests}) != len(tests):
        raise RuntimeError('"'"'"'"'"'"'"'"'duplicate unittest identities cannot be measured independently'"'"'"'"'"'"'"'"')
    if limit > 0 and len(tests) > limit:
        groups = defaultdict(list)
        for index, test in enumerate(tests):
            groups[type(test).__module__].append(index)
        selected, depth = [], 0
        while len(selected) < limit:
            for indices in groups.values():
                if depth < len(indices):
                    selected.append(indices[depth])
                    if len(selected) == limit:
                        break
            depth += 1
        tests = [tests[index] for index in sorted(selected)]
    result = unittest.TextTestRunner(stream=sys.stdout, verbosity=2, resultclass=Result).run(unittest.TestSuite(tests))
    payload = {name: sorted(identity for identity, value in result.outcomes.items() if value == name)
               for name in ('"'"'"'"'"'"'"'"'passed'"'"'"'"'"'"'"'"', '"'"'"'"'"'"'"'"'failed'"'"'"'"'"'"'"'"', '"'"'"'"'"'"'"'"'errors'"'"'"'"'"'"'"'"', '"'"'"'"'"'"'"'"'skipped'"'"'"'"'"'"'"'"')}
    print('"'"'"'"'"'"'"'"'PROGRAMGEN_UNITTEST_RESULT='"'"'"'"'"'"'"'"' + json.dumps(payload), flush=True)
    print('"'"'"'"'"'"'"'"'%d passed, %d failed, %d errors, %d skipped'"'"'"'"'"'"'"'"' % tuple(len(payload[name]) for name in ('"'"'"'"'"'"'"'"'passed'"'"'"'"'"'"'"'"', '"'"'"'"'"'"'"'"'failed'"'"'"'"'"'"'"'"', '"'"'"'"'"'"'"'"'errors'"'"'"'"'"'"'"'"', '"'"'"'"'"'"'"'"'skipped'"'"'"'"'"'"'"'"')), flush=True)
    measured = sum(len(payload[name]) for name in ('"'"'"'"'"'"'"'"'passed'"'"'"'"'"'"'"'"', '"'"'"'"'"'"'"'"'failed'"'"'"'"'"'"'"'"', '"'"'"'"'"'"'"'"'errors'"'"'"'"'"'"'"'"'))
    raise SystemExit(5 if not measured else 0 if result.wasSuccessful() else 1)
finally:
    if coverage:
        coverage.stop()
        coverage.save()
'"'"' '"'"'{"pattern": "test_*.py", "start_dir": ".", "top_level_dir": null}'"'"' 500' 2>&1 | tail -c 1500000 > "$OUT_FILE"
RC=${PIPESTATUS[0]}
cat "$OUT_FILE"
if [ "$RC" -eq 124 ] || [ "$RC" -eq 137 ]; then
  grade_and_exit tests verifier-timeout "$RC"
fi
python3 /tests/grader.py --output "$OUT_FILE" --return-code "$RC" --expected-count "$EXPECTED" --phase tests >/dev/null
cat /logs/verifier/reward.txt