File size: 5,974 Bytes
cb0011e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
"""Generate negative-control prediction files for SWE-DockerLess.

Three controls, each of which must score 0/4:

  empty.jsonl    every prediction is an empty patch
  cross.jsonl    each instance receives another instance's gold patch
  partial.jsonl  a plausible but incomplete fix: the gold patch with one of the
                 bugs reintroduced (or, for semverlite, only one of its two
                 files fixed)

Run with:  python tools/make_controls.py
"""

import json
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
REPOS = ROOT / "repos"
FIXED = ROOT / "fixed"
OUTDIR = ROOT / "predictions"
DATASET = ROOT / "SWE-DockerLess.jsonl"

GIT_FLAGS = [
    "-c", "core.autocrlf=false",
    "-c", "core.safecrlf=false",
    "-c", "user.name=control",
    "-c", "user.email=control@example.invalid",
    "-c", "commit.gpgsign=false",
]


def git(args, cwd):
    proc = subprocess.run(
        ["git"] + GIT_FLAGS + args, cwd=str(cwd), capture_output=True, text=True, encoding="utf-8"
    )
    if proc.returncode != 0:
        raise RuntimeError("git %s failed: %s %s" % (args, proc.stdout, proc.stderr))
    return proc


def read_tree(root):
    files = {}
    for path in sorted(Path(root).rglob("*")):
        if path.is_dir() or ".git" in path.parts:
            continue
        files[path.relative_to(root).as_posix()] = path.read_text(encoding="utf-8")
    return files


def write_tree(files, dest):
    for rel, content in files.items():
        path = Path(dest) / rel
        path.parent.mkdir(parents=True, exist_ok=True)
        with open(path, "w", encoding="utf-8", newline="\n") as handle:
            handle.write(content)


def diff_with_overrides(name, overrides):
    """Return a unified diff that turns the base repo into base+overrides."""
    with tempfile.TemporaryDirectory(prefix="swedl-ctl-") as tmp:
        work = Path(tmp) / "w"
        work.mkdir()
        write_tree(read_tree(REPOS / name), work)
        git(["init", "-q", "-b", "main"], work)
        git(["add", "-A"], work)
        git(["commit", "-q", "-m", "base"], work)
        write_tree(overrides, work)
        return git(["diff", "--no-color"], work).stdout


def main():
    OUTDIR.mkdir(exist_ok=True)
    rows = [json.loads(line) for line in open(DATASET, encoding="utf-8") if line.strip()]
    ids = [row["instance_id"] for row in rows]

    # --- control 1: empty patches ----------------------------------------
    with open(OUTDIR / "empty.jsonl", "w", encoding="utf-8", newline="\n") as handle:
        for row in rows:
            handle.write(
                json.dumps(
                    {
                        "instance_id": row["instance_id"],
                        "model_name_or_path": "control-empty",
                        "model_patch": "",
                    }
                )
                + "\n"
            )

    # --- control 2: cross-instance gold patches ---------------------------
    with open(OUTDIR / "cross.jsonl", "w", encoding="utf-8", newline="\n") as handle:
        for index, row in enumerate(rows):
            other = rows[(index + 1) % len(rows)]
            handle.write(
                json.dumps(
                    {
                        "instance_id": row["instance_id"],
                        "model_name_or_path": "control-cross",
                        "model_patch": other["patch"],
                    }
                )
                + "\n"
            )

    # --- control 3: plausible but incomplete fixes ------------------------
    partial = {}

    # miniconf: cycle detection kept, but the $$ escape dropped again
    config = read_tree(FIXED / "miniconf")["miniconf/config.py"]
    broken_escape = config.replace(
        '            if text.startswith("$$", index):\n'
        '                out.append("$")\n'
        "                index += 2\n"
        "                continue\n",
        "",
    )
    assert broken_escape != config, "miniconf control replacement did not apply"
    partial["swedl__miniconf-1"] = diff_with_overrides(
        "miniconf", {"miniconf/config.py": broken_escape}
    )

    # ttlcache: len() fixed, but reads still do not refresh recency
    cache = read_tree(FIXED / "ttlcache")["ttlcache/cache.py"]
    broken_recency = cache.replace("        self._data.move_to_end(key)\n", "")
    assert broken_recency != cache, "ttlcache control replacement did not apply"
    partial["swedl__ttlcache-1"] = diff_with_overrides(
        "ttlcache", {"ttlcache/cache.py": broken_recency}
    )

    # cronlite: Sunday alias fixed, but `<value>/<step>` still collapses
    fields = read_tree(FIXED / "cronlite")["cronlite/fields.py"]
    broken_step = fields.replace(
        "                start = self._check(int(base))\n                stop = self.maximum\n",
        "                start = self._check(int(base))\n                stop = start\n",
    )
    assert broken_step != fields, "cronlite control replacement did not apply"
    partial["swedl__cronlite-1"] = diff_with_overrides(
        "cronlite", {"cronlite/fields.py": broken_step}
    )

    # semverlite: precedence fixed, range gating left out
    version = read_tree(FIXED / "semverlite")["semverlite/version.py"]
    partial["swedl__semverlite-1"] = diff_with_overrides(
        "semverlite", {"semverlite/version.py": version}
    )

    with open(OUTDIR / "partial.jsonl", "w", encoding="utf-8", newline="\n") as handle:
        for instance_id in ids:
            handle.write(
                json.dumps(
                    {
                        "instance_id": instance_id,
                        "model_name_or_path": "control-partial",
                        "model_patch": partial[instance_id],
                    }
                )
                + "\n"
            )

    print("wrote controls for %d instances -> %s" % (len(ids), OUTDIR))


if __name__ == "__main__":
    main()