irsmith 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.
- irsmith/__init__.py +1 -0
- irsmith/__main__.py +3 -0
- irsmith/app.py +64 -0
- irsmith/bisect/__init__.py +0 -0
- irsmith/bisect/driver.py +264 -0
- irsmith/bisect/git.py +198 -0
- irsmith/config.py +240 -0
- irsmith/errors.py +19 -0
- irsmith/jobs.py +123 -0
- irsmith/limits_exec.py +50 -0
- irsmith/models.py +290 -0
- irsmith/oracle/__init__.py +0 -0
- irsmith/oracle/__main__.py +18 -0
- irsmith/oracle/spec.py +94 -0
- irsmith/pipeline/__init__.py +0 -0
- irsmith/pipeline/diff.py +40 -0
- irsmith/pipeline/dumps.py +62 -0
- irsmith/pipeline/passes.py +82 -0
- irsmith/pipeline/run.py +58 -0
- irsmith/proc.py +313 -0
- irsmith/py.typed +0 -0
- irsmith/reduce/__init__.py +1 -0
- irsmith/reduce/driver.py +139 -0
- irsmith/server.py +211 -0
- irsmith/signature/__init__.py +4 -0
- irsmith/signature/normalize.py +91 -0
- irsmith/signature/parse.py +112 -0
- irsmith/store.py +185 -0
- irsmith/triage/__init__.py +0 -0
- irsmith/triage/github.py +147 -0
- irsmith/triage/search.py +200 -0
- irsmith-0.1.0.dist-info/METADATA +140 -0
- irsmith-0.1.0.dist-info/RECORD +37 -0
- irsmith-0.1.0.dist-info/WHEEL +4 -0
- irsmith-0.1.0.dist-info/entry_points.txt +2 -0
- irsmith-0.1.0.dist-info/licenses/LICENSE-APACHE +176 -0
- irsmith-0.1.0.dist-info/licenses/LICENSE-MIT +21 -0
irsmith/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
irsmith/__main__.py
ADDED
irsmith/app.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Shared server state and the helpers every tool uses to start a child."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from dataclasses import dataclass, replace
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
import anyio
|
|
10
|
+
|
|
11
|
+
from .config import Config, Toolchain
|
|
12
|
+
from .jobs import JobManager
|
|
13
|
+
from .errors import IrsmithError
|
|
14
|
+
from .proc import GroupRegistry, RunResult, run
|
|
15
|
+
from .store import JobDir, Store
|
|
16
|
+
|
|
17
|
+
_PASS_THROUGH = ("PATH", "HOME", "LANG")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def child_env(config: Config, job: JobDir, toolchain: Toolchain | None, extra: dict[str, str] | None = None) -> dict[str, str]:
|
|
21
|
+
"""An allowlisted environment: no tokens or other ambient secrets reach the child."""
|
|
22
|
+
env = {k: v for k, v in os.environ.items() if k in _PASS_THROUGH or k.startswith("CCACHE_")}
|
|
23
|
+
env |= {"LC_ALL": "C", "TMPDIR": str(job.tmp), "LLVM_DISABLE_CRASH_REPORT": "1"}
|
|
24
|
+
if toolchain and "llvm-symbolizer" in toolchain.tools:
|
|
25
|
+
env["LLVM_SYMBOLIZER_PATH"] = str(toolchain.tools["llvm-symbolizer"])
|
|
26
|
+
return env | config.env | (extra or {})
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def substitute(argv: list[str], values: dict[str, str]) -> list[str]:
|
|
30
|
+
out = []
|
|
31
|
+
for arg in argv:
|
|
32
|
+
for key, value in values.items():
|
|
33
|
+
arg = arg.replace("{" + key + "}", value)
|
|
34
|
+
out.append(arg)
|
|
35
|
+
return out
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def existing_file(path: str) -> Path:
|
|
39
|
+
p = Path(path).expanduser()
|
|
40
|
+
if not p.is_file():
|
|
41
|
+
raise IrsmithError("invalid_argument", f"input file {path!r} does not exist")
|
|
42
|
+
return p.resolve()
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass
|
|
46
|
+
class App:
|
|
47
|
+
config: Config
|
|
48
|
+
store: Store
|
|
49
|
+
registry: GroupRegistry | None
|
|
50
|
+
light: anyio.Semaphore
|
|
51
|
+
jobs: JobManager | None = None
|
|
52
|
+
|
|
53
|
+
async def run_tool(self, job: JobDir, argv: list[str], *, toolchain: Toolchain | None, name: str,
|
|
54
|
+
timeout_s: float | None = None, env: dict[str, str] | None = None) -> RunResult:
|
|
55
|
+
limits = self.config.limits if timeout_s is None else replace(self.config.limits, timeout_s=timeout_s)
|
|
56
|
+
return await run(
|
|
57
|
+
argv,
|
|
58
|
+
cwd=job.path,
|
|
59
|
+
env=child_env(self.config, job, toolchain, env),
|
|
60
|
+
limits=limits,
|
|
61
|
+
stdout=job.file(f"{name}.stdout"),
|
|
62
|
+
stderr=job.file(f"{name}.stderr"),
|
|
63
|
+
registry=self.registry,
|
|
64
|
+
)
|
|
File without changes
|
irsmith/bisect/driver.py
ADDED
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
"""The `bisect` tool: find the commit that introduced (or fixed) a crash, using the user's own build.
|
|
2
|
+
|
|
3
|
+
Refuses to start on a dirty tree, during another bisect, rebase or merge, or
|
|
4
|
+
with a build that is not Ninja. Bisects with `git bisect --no-checkout` and
|
|
5
|
+
checks out each commit itself, after checking that the tree is still clean.
|
|
6
|
+
Whatever happens, HEAD and the branch are restored at the end.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import math
|
|
12
|
+
import os
|
|
13
|
+
import shutil
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Literal
|
|
17
|
+
|
|
18
|
+
import anyio
|
|
19
|
+
|
|
20
|
+
from ..app import App, existing_file, substitute
|
|
21
|
+
from ..config import Toolchain
|
|
22
|
+
from ..errors import IrsmithError
|
|
23
|
+
from ..jobs import Job
|
|
24
|
+
from ..models import BisectOracle, BisectResult, BisectStep, CommitInfo, CrashReport
|
|
25
|
+
from ..oracle.spec import REJECT, classify
|
|
26
|
+
from ..proc import RunResult
|
|
27
|
+
from ..signature import signature_key, to_signature
|
|
28
|
+
from .git import Git, Head, RepoLock
|
|
29
|
+
|
|
30
|
+
Outcome = Literal["bad", "good", "skip"]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass
|
|
34
|
+
class Bisection:
|
|
35
|
+
"""What the search found. Kept apart from the restore, which runs whatever happens."""
|
|
36
|
+
|
|
37
|
+
old: str
|
|
38
|
+
new: str
|
|
39
|
+
estimated_steps: int
|
|
40
|
+
steps: list[BisectStep] = field(default_factory=list)
|
|
41
|
+
found: str | None = None
|
|
42
|
+
candidates: list[str] = field(default_factory=list)
|
|
43
|
+
report: CrashReport | None = None
|
|
44
|
+
notes: list[str] = field(default_factory=list)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _toolchain(app: App, name: str) -> Toolchain:
|
|
48
|
+
chain = next((t for t in app.config.toolchains if t.name == name), None)
|
|
49
|
+
if chain is None:
|
|
50
|
+
raise IrsmithError("tool_not_found", f"no toolchain named {name!r}", hint="run doctor to list toolchains")
|
|
51
|
+
if chain.build_dir is None or chain.source_dir is None:
|
|
52
|
+
raise IrsmithError("unsupported_input", f"toolchain {name!r} has no CMake build dir with a source dir",
|
|
53
|
+
hint="bisect needs a toolchain configured with build_dir")
|
|
54
|
+
if chain.generator != "Ninja":
|
|
55
|
+
raise IrsmithError("unsupported_input", f"the build in {chain.build_dir} uses {chain.generator!r}, not Ninja",
|
|
56
|
+
hint="bisect drives ninja. Configure a build with cmake -G Ninja.")
|
|
57
|
+
return chain
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class _Run:
|
|
61
|
+
def __init__(self, app: App, job: Job, chain: Toolchain, command: list[str], input: Path, oracle: BisectOracle,
|
|
62
|
+
find: str, targets: list[str], max_build_s: float, git: Git):
|
|
63
|
+
self.app, self.job, self.chain, self.oracle, self.git = app, job, chain, oracle, git
|
|
64
|
+
self.find, self.targets, self.max_build_s = find, targets, max_build_s
|
|
65
|
+
self.make = chain.make_program or Path(shutil.which("ninja") or "ninja")
|
|
66
|
+
work = job.dir
|
|
67
|
+
values = {"input": str(input), "out": str(work.file("out")), "tmp": str(work.tmp)}
|
|
68
|
+
template = oracle.custom_command if oracle.kind == "custom" else command
|
|
69
|
+
assert template
|
|
70
|
+
self.argv = [template[0], *substitute(template[1:], values)]
|
|
71
|
+
self.env: dict[str, str] = {"LLVM_DISABLE_SYMBOLIZATION": "1"}
|
|
72
|
+
self.expect: str | None = None
|
|
73
|
+
self.report: CrashReport | None = None
|
|
74
|
+
self.built_other = False
|
|
75
|
+
self.count = 0
|
|
76
|
+
self.fraction: float | None = None
|
|
77
|
+
|
|
78
|
+
def exe(self) -> Path:
|
|
79
|
+
built = self.chain.bin / self.argv[0]
|
|
80
|
+
if built.exists() or self.oracle.kind != "custom":
|
|
81
|
+
return built
|
|
82
|
+
return self.app.config.resolve(self.argv[0])[1]
|
|
83
|
+
|
|
84
|
+
async def build(self, name: str) -> RunResult:
|
|
85
|
+
argv = [str(self.make), "-C", str(self.chain.build_dir), "-l", str(os.cpu_count() or 4), *self.targets]
|
|
86
|
+
return await self.app.run_tool(self.job.dir, argv, toolchain=None, name=name, timeout_s=self.max_build_s)
|
|
87
|
+
|
|
88
|
+
async def check(self) -> tuple[RunResult, CrashReport]:
|
|
89
|
+
result = await self.app.run_tool(self.job.dir, [str(self.exe()), *self.argv[1:]], toolchain=self.chain,
|
|
90
|
+
name=f"step{self.count}", env=self.env)
|
|
91
|
+
return result, classify(result)
|
|
92
|
+
|
|
93
|
+
def judge(self, result: RunResult, report: CrashReport) -> tuple[Outcome, str | None]:
|
|
94
|
+
if result.timed_out or result.oom_killed:
|
|
95
|
+
return "skip", report.kind
|
|
96
|
+
if self.oracle.kind == "custom":
|
|
97
|
+
return ("bad" if result.exit_code == 0 else "good"), None
|
|
98
|
+
if self.oracle.kind == "exit_nonzero":
|
|
99
|
+
return ("good" if result.exit_code == 0 else "bad"), None
|
|
100
|
+
if report.kind == "clean":
|
|
101
|
+
return "good", None
|
|
102
|
+
if report.kind in REJECT:
|
|
103
|
+
return "skip", report.kind
|
|
104
|
+
if self.expect is None or signature_key(report, self.oracle.match) == self.expect:
|
|
105
|
+
return "bad", None
|
|
106
|
+
return "skip", "other_signature"
|
|
107
|
+
|
|
108
|
+
async def test(self, sha: str, head: Head) -> BisectStep:
|
|
109
|
+
"""Check out, build and test one commit."""
|
|
110
|
+
self.count += 1
|
|
111
|
+
if changes := await self.git.changes():
|
|
112
|
+
here = await self.git.head()
|
|
113
|
+
switch = f"git switch {head.branch}" if head.branch else f"git switch --detach {head.sha[:12]}"
|
|
114
|
+
raise IrsmithError(
|
|
115
|
+
"dirty_tree", f"the working tree changed during the bisect: {changes.splitlines()[0].strip()}",
|
|
116
|
+
hint=f"irsmith stopped without checking anything out. HEAD is at {here.label} with your changes. "
|
|
117
|
+
f"It started from {head.label}: commit or stash the changes, then {switch}.")
|
|
118
|
+
if (await self.git.head()).sha != sha:
|
|
119
|
+
await self.git.switch(sha, detach=True)
|
|
120
|
+
self.built_other |= sha != head.sha
|
|
121
|
+
self.job.report("building", self.fraction, f"step {self.count}: {sha[:12]}")
|
|
122
|
+
build = await self.build(f"build{self.count}")
|
|
123
|
+
build_s = round(build.duration_s, 1)
|
|
124
|
+
if build.timed_out:
|
|
125
|
+
return BisectStep(sha=sha[:12], build_s=build_s, outcome="skip", reason="build_timeout")
|
|
126
|
+
if build.exit_code != 0:
|
|
127
|
+
return BisectStep(sha=sha[:12], build_s=build_s, outcome="skip", reason="build_failed")
|
|
128
|
+
self.job.report("testing", self.fraction, f"step {self.count}: {sha[:12]}")
|
|
129
|
+
result, report = await self.check()
|
|
130
|
+
if self.oracle.kind == "crash" and self.expect is None:
|
|
131
|
+
if report.message is None and report.kind not in ("clean", "timeout", "oom"):
|
|
132
|
+
self.env = {} # the key will use frames, so symbolize them
|
|
133
|
+
result, report = await self.check()
|
|
134
|
+
self.report = report
|
|
135
|
+
outcome, reason = self.judge(result, report)
|
|
136
|
+
return BisectStep(sha=sha[:12], build_s=build_s, outcome=outcome, reason=reason)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
async def _search(run: _Run, head: Head, bad: str, old: str, new: str, max_steps: int, estimated: int) -> Bisection:
|
|
140
|
+
git, found = run.git, Bisection(old=old, new=new, estimated_steps=estimated)
|
|
141
|
+
|
|
142
|
+
endpoint = await run.test(bad, head)
|
|
143
|
+
found.steps.append(endpoint)
|
|
144
|
+
if endpoint.outcome != "bad":
|
|
145
|
+
raise IrsmithError("not_reproducible", f"the bug does not show at bad ({bad[:12]}): the step was "
|
|
146
|
+
f"{endpoint.outcome}{' (' + endpoint.reason + ')' if endpoint.reason else ''}",
|
|
147
|
+
hint=f"see {run.job.dir.handle('build1.stdout')} and {run.job.dir.handle('step1.stderr')}")
|
|
148
|
+
if run.oracle.kind == "crash":
|
|
149
|
+
found.report = run.report
|
|
150
|
+
run.expect = signature_key(run.report, run.oracle.match)
|
|
151
|
+
|
|
152
|
+
await git.run("bisect", "start", "--term-old=old", "--term-new=new", "--no-checkout", new, old)
|
|
153
|
+
while True:
|
|
154
|
+
first_new, remaining, untested = await git.bisect_range()
|
|
155
|
+
if not untested:
|
|
156
|
+
if remaining == [first_new]:
|
|
157
|
+
found.found = first_new
|
|
158
|
+
else:
|
|
159
|
+
found.candidates = [sha[:12] for sha in remaining]
|
|
160
|
+
return found
|
|
161
|
+
if len(found.steps) > max_steps:
|
|
162
|
+
found.notes.append(f"stopped after max_steps={max_steps}: the change is after {found.old[:12]} "
|
|
163
|
+
f"and at or before {found.new[:12]}")
|
|
164
|
+
return found
|
|
165
|
+
sha = await git.out("rev-parse", "BISECT_HEAD")
|
|
166
|
+
run.fraction = round(min(1.0, (len(found.steps) - 1) / max(estimated, 1)), 2)
|
|
167
|
+
step = await run.test(sha, head)
|
|
168
|
+
found.steps.append(step)
|
|
169
|
+
term = "skip" if step.outcome == "skip" else ("new" if (step.outcome == "bad") == (run.find == "regression") else "old")
|
|
170
|
+
if term == "new":
|
|
171
|
+
found.new = sha
|
|
172
|
+
elif term == "old":
|
|
173
|
+
found.old = sha
|
|
174
|
+
code, out = await git.run("bisect", term, sha, check=False)
|
|
175
|
+
if code != 0 and sha in (await git.bisect_range())[2]:
|
|
176
|
+
raise IrsmithError("internal", f"git bisect {term} failed: {(out.splitlines() or [''])[-1]}")
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
async def _commit_info(git: Git, sha: str) -> CommitInfo:
|
|
180
|
+
full, subject, author, date = (await git.out("show", "-s", "--format=%H%n%s%n%an%n%as", sha)).splitlines()[:4]
|
|
181
|
+
return CommitInfo(sha=full, subject=subject, author=author, date=date)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
async def bisect(app: App, job: Job, *, toolchain: str, good: str, bad: str, command: list[str], input: str,
|
|
185
|
+
oracle: BisectOracle, find: Literal["regression", "fix"], targets: list[str] | None,
|
|
186
|
+
max_build_s: float, max_steps: int, restore_build: bool) -> BisectResult:
|
|
187
|
+
chain = _toolchain(app, toolchain)
|
|
188
|
+
template = oracle.custom_command if oracle.kind == "custom" else command
|
|
189
|
+
if not template or not any("{input}" in arg for arg in template):
|
|
190
|
+
raise IrsmithError("invalid_argument", "the command must contain {input} where the input file goes")
|
|
191
|
+
if not command or any("/" in name for name in [command[0], *(targets or [])]):
|
|
192
|
+
raise IrsmithError("invalid_argument", "command[0] and targets must be tool names such as opt, not paths")
|
|
193
|
+
path = existing_file(input)
|
|
194
|
+
source = job.dir.file(f"input{path.suffix}")
|
|
195
|
+
shutil.copyfile(path, source) # checkouts must not change the input
|
|
196
|
+
|
|
197
|
+
assert chain.source_dir is not None
|
|
198
|
+
git = Git(Path(await Git(chain.source_dir).out("rev-parse", "--show-toplevel")))
|
|
199
|
+
lock = RepoLock(app.config.state_dir, git.repo)
|
|
200
|
+
if not lock.acquire():
|
|
201
|
+
raise IrsmithError("bisect_in_progress", f"another irsmith bisect is running in {git.repo}",
|
|
202
|
+
hint="wait for it or cancel it with job_cancel")
|
|
203
|
+
try:
|
|
204
|
+
notes = [note] if (note := await lock.recover(git)) else []
|
|
205
|
+
if what := await git.in_progress():
|
|
206
|
+
raise IrsmithError("bisect_in_progress" if what == "a bisect" else "dirty_tree",
|
|
207
|
+
f"{what} is in progress in {git.repo}", hint="finish or abort it first")
|
|
208
|
+
if changes := await git.changes():
|
|
209
|
+
raise IrsmithError("dirty_tree", f"{git.repo} has uncommitted changes: {changes.splitlines()[0].strip()}",
|
|
210
|
+
hint="commit or stash them first. Untracked files are fine.")
|
|
211
|
+
good_sha, bad_sha = await git.commit(good), await git.commit(bad)
|
|
212
|
+
old, new = (good_sha, bad_sha) if find == "regression" else (bad_sha, good_sha)
|
|
213
|
+
if old == new or not await git.is_ancestor(old, new):
|
|
214
|
+
first, second = ("good", "bad") if find == "regression" else ("bad", "good")
|
|
215
|
+
raise IrsmithError("invalid_argument", f"{first} must be an ancestor of {second} when find={find}")
|
|
216
|
+
count = int(await git.out("rev-list", "--count", f"{old}..{new}"))
|
|
217
|
+
estimated = math.ceil(math.log2(count)) if count > 1 else 0
|
|
218
|
+
job.report("starting", 0.0, f"{count} commits to search, about {estimated} steps")
|
|
219
|
+
|
|
220
|
+
head = await git.head()
|
|
221
|
+
lock.save(head, job.dir.id)
|
|
222
|
+
run = _Run(app, job, chain, command, source, oracle, find, targets or [command[0]], max_build_s, git)
|
|
223
|
+
interrupted = False
|
|
224
|
+
try:
|
|
225
|
+
found = await _search(run, head, bad_sha, old, new, max_steps, estimated)
|
|
226
|
+
except BaseException as e:
|
|
227
|
+
interrupted = isinstance(e, anyio.get_cancelled_exc_class())
|
|
228
|
+
raise
|
|
229
|
+
finally:
|
|
230
|
+
with anyio.CancelScope(shield=True):
|
|
231
|
+
code, log = await git.run("bisect", "log", check=False)
|
|
232
|
+
if code == 0:
|
|
233
|
+
job.dir.file("bisect.log").write_text(log + "\n")
|
|
234
|
+
why = await git.restore(head)
|
|
235
|
+
lock.clear()
|
|
236
|
+
rebuilt = False
|
|
237
|
+
if why is None and run.built_other and restore_build and not interrupted:
|
|
238
|
+
job.report("rebuilding", message=f"{head.label} at {head.sha[:12]}")
|
|
239
|
+
rebuilt = (await run.build("rebuild")).exit_code == 0
|
|
240
|
+
state = f"HEAD restored to {head.label}" if why is None else f"HEAD not restored: {why}"
|
|
241
|
+
job.report("finished", 1.0, state + ("" if rebuilt or not run.built_other else ", build dir not rebuilt"))
|
|
242
|
+
finally:
|
|
243
|
+
lock.release()
|
|
244
|
+
|
|
245
|
+
if why:
|
|
246
|
+
notes.append(f"HEAD not restored to {head.label}: {why}")
|
|
247
|
+
if run.built_other and not rebuilt:
|
|
248
|
+
notes.append(f"the build dir holds binaries from another commit. Rebuild {head.label} before using them.")
|
|
249
|
+
commit = await _commit_info(git, found.found) if found.found else None
|
|
250
|
+
return BisectResult(
|
|
251
|
+
find=find,
|
|
252
|
+
first_bad=commit if find == "regression" else None,
|
|
253
|
+
first_good=commit if find == "fix" else None,
|
|
254
|
+
candidates=found.candidates,
|
|
255
|
+
signature=to_signature(found.report) if found.report else None,
|
|
256
|
+
estimated_steps=estimated,
|
|
257
|
+
steps=found.steps,
|
|
258
|
+
skipped=[s.sha for s in found.steps if s.outcome == "skip"],
|
|
259
|
+
head=head.label,
|
|
260
|
+
restored_head=why is None,
|
|
261
|
+
build_dir_rebuilt=rebuilt,
|
|
262
|
+
notes=notes + found.notes,
|
|
263
|
+
artifacts={"log": job.dir.handle("bisect.log")} if job.dir.file("bisect.log").exists() else {},
|
|
264
|
+
)
|
irsmith/bisect/git.py
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
"""Git access for bisect: refusal checks, HEAD restore, and the per-repository lock and session file.
|
|
2
|
+
|
|
3
|
+
Every git command runs shielded from cancellation, so a cancelled job never
|
|
4
|
+
kills git halfway through a checkout and leaves index.lock behind.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import fcntl
|
|
10
|
+
import hashlib
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import time
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
import anyio
|
|
18
|
+
|
|
19
|
+
from ..errors import IrsmithError
|
|
20
|
+
|
|
21
|
+
GIT_TIMEOUT_S = 600
|
|
22
|
+
_ENV = ("PATH", "HOME", "LANG")
|
|
23
|
+
_IN_PROGRESS = (("BISECT_START", "a bisect"), ("rebase-merge", "a rebase"), ("rebase-apply", "a rebase or am"),
|
|
24
|
+
("MERGE_HEAD", "a merge"), ("CHERRY_PICK_HEAD", "a cherry-pick"), ("REVERT_HEAD", "a revert"))
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True)
|
|
28
|
+
class Head:
|
|
29
|
+
branch: str | None
|
|
30
|
+
sha: str
|
|
31
|
+
|
|
32
|
+
@property
|
|
33
|
+
def label(self) -> str:
|
|
34
|
+
return self.branch or self.sha[:12]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class Git:
|
|
38
|
+
def __init__(self, repo: Path):
|
|
39
|
+
self.repo = repo
|
|
40
|
+
self.env = {k: v for k, v in os.environ.items() if k in _ENV} | {"LC_ALL": "C", "GIT_TERMINAL_PROMPT": "0"}
|
|
41
|
+
|
|
42
|
+
async def run(self, *args: str, check: bool = True) -> tuple[int, str]:
|
|
43
|
+
"""Run git and return (exit code, stdout plus stderr)."""
|
|
44
|
+
with anyio.CancelScope(shield=True):
|
|
45
|
+
with anyio.fail_after(GIT_TIMEOUT_S):
|
|
46
|
+
result = await anyio.run_process(["git", "-C", str(self.repo), *args], env=self.env, check=False)
|
|
47
|
+
out = (result.stdout + result.stderr).decode(errors="replace").strip()
|
|
48
|
+
if check and result.returncode != 0:
|
|
49
|
+
last = (out.splitlines() or ["no output"])[-1]
|
|
50
|
+
raise IrsmithError("internal", f"git {' '.join(args[:2])} failed: {last}")
|
|
51
|
+
return result.returncode, out
|
|
52
|
+
|
|
53
|
+
async def out(self, *args: str) -> str:
|
|
54
|
+
return (await self.run(*args))[1]
|
|
55
|
+
|
|
56
|
+
async def git_dir(self) -> Path:
|
|
57
|
+
return Path(await self.out("rev-parse", "--absolute-git-dir"))
|
|
58
|
+
|
|
59
|
+
async def head(self) -> Head:
|
|
60
|
+
code, ref = await self.run("symbolic-ref", "-q", "--short", "HEAD", check=False)
|
|
61
|
+
return Head(branch=ref if code == 0 else None, sha=await self.out("rev-parse", "HEAD"))
|
|
62
|
+
|
|
63
|
+
async def changes(self) -> str:
|
|
64
|
+
return await self.out("status", "--porcelain", "--untracked-files=no")
|
|
65
|
+
|
|
66
|
+
async def in_progress(self) -> str | None:
|
|
67
|
+
git_dir = await self.git_dir()
|
|
68
|
+
return next((what for name, what in _IN_PROGRESS if (git_dir / name).exists()), None)
|
|
69
|
+
|
|
70
|
+
async def commit(self, rev: str) -> str:
|
|
71
|
+
code, sha = await self.run("rev-parse", "--verify", "--quiet", f"{rev}^{{commit}}", check=False)
|
|
72
|
+
if code != 0:
|
|
73
|
+
raise IrsmithError("invalid_argument", f"{rev!r} is not a commit in {self.repo}")
|
|
74
|
+
return sha
|
|
75
|
+
|
|
76
|
+
async def bisect_range(self) -> tuple[str, list[str], list[str]]:
|
|
77
|
+
"""Read the bisect state from its refs: the current new commit, the commits that may
|
|
78
|
+
still be the first new one (new included), and those of them not yet tested.
|
|
79
|
+
|
|
80
|
+
Reading refs/bisect/ instead of `git bisect` messages keeps this independent of the
|
|
81
|
+
git version and its wording.
|
|
82
|
+
"""
|
|
83
|
+
new, olds, skips = "", [], set()
|
|
84
|
+
for line in (await self.out("for-each-ref", "--format=%(refname) %(objectname)", "refs/bisect/")).splitlines():
|
|
85
|
+
ref, sha = line.split()
|
|
86
|
+
if ref == "refs/bisect/new":
|
|
87
|
+
new = sha
|
|
88
|
+
elif ref.startswith("refs/bisect/old-"):
|
|
89
|
+
olds.append(sha)
|
|
90
|
+
elif ref.startswith("refs/bisect/skip-"):
|
|
91
|
+
skips.add(sha)
|
|
92
|
+
remaining = (await self.out("rev-list", new, "--not", *olds)).splitlines()
|
|
93
|
+
return new, remaining, [sha for sha in remaining if sha != new and sha not in skips]
|
|
94
|
+
|
|
95
|
+
async def is_ancestor(self, old: str, new: str) -> bool:
|
|
96
|
+
return (await self.run("merge-base", "--is-ancestor", old, new, check=False))[0] == 0
|
|
97
|
+
|
|
98
|
+
async def switch(self, target: str, *, detach: bool) -> None:
|
|
99
|
+
if detach:
|
|
100
|
+
await self.run("switch", "-q", "--detach", target)
|
|
101
|
+
else:
|
|
102
|
+
await self.run("switch", "-q", "--no-guess", target)
|
|
103
|
+
if (self.repo / ".gitmodules").exists():
|
|
104
|
+
await self.run("submodule", "update", "-q")
|
|
105
|
+
|
|
106
|
+
async def restore(self, head: Head) -> str | None:
|
|
107
|
+
"""End irsmith's bisect and put HEAD back. Returns why HEAD was left alone, or None when it is restored.
|
|
108
|
+
|
|
109
|
+
The bisect runs with --no-checkout, so `git bisect reset` only removes
|
|
110
|
+
the bisect state and never touches the working tree.
|
|
111
|
+
"""
|
|
112
|
+
if (await self.git_dir() / "BISECT_START").exists():
|
|
113
|
+
await self.run("bisect", "reset")
|
|
114
|
+
if await self.changes():
|
|
115
|
+
return "the working tree has changes"
|
|
116
|
+
if await self.head() != head:
|
|
117
|
+
await self.switch(head.branch or head.sha, detach=head.branch is None)
|
|
118
|
+
now = await self.head()
|
|
119
|
+
return None if now == head else f"HEAD is {now.label} after the restore, not {head.label}"
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class RepoLock:
|
|
123
|
+
"""One bisect per repository, across servers: a flock plus a session file a later server can restore from."""
|
|
124
|
+
|
|
125
|
+
def __init__(self, state_dir: Path, repo: Path):
|
|
126
|
+
self.repo = repo
|
|
127
|
+
key = hashlib.sha1(str(repo.resolve()).encode()).hexdigest()[:12]
|
|
128
|
+
directory = state_dir / "bisect"
|
|
129
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
130
|
+
self.lock_path = directory / f"{key}.lock"
|
|
131
|
+
self.session = directory / f"{key}.json"
|
|
132
|
+
self.fd: int | None = None
|
|
133
|
+
|
|
134
|
+
def acquire(self) -> bool:
|
|
135
|
+
fd = os.open(self.lock_path, os.O_CREAT | os.O_RDWR, 0o600)
|
|
136
|
+
try:
|
|
137
|
+
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
138
|
+
except BlockingIOError:
|
|
139
|
+
os.close(fd)
|
|
140
|
+
return False
|
|
141
|
+
self.fd = fd
|
|
142
|
+
return True
|
|
143
|
+
|
|
144
|
+
def release(self) -> None:
|
|
145
|
+
if self.fd is not None:
|
|
146
|
+
os.close(self.fd)
|
|
147
|
+
self.fd = None
|
|
148
|
+
|
|
149
|
+
def save(self, head: Head, job: str) -> None:
|
|
150
|
+
data = {"repo": str(self.repo), "branch": head.branch, "sha": head.sha, "job": job, "time": time.time()}
|
|
151
|
+
self.session.write_text(json.dumps(data))
|
|
152
|
+
|
|
153
|
+
def clear(self) -> None:
|
|
154
|
+
self.session.unlink(missing_ok=True)
|
|
155
|
+
|
|
156
|
+
async def recover(self, git: Git) -> str | None:
|
|
157
|
+
"""Restore HEAD for a bisect whose server died. Call with the lock held."""
|
|
158
|
+
try:
|
|
159
|
+
data = json.loads(self.session.read_text())
|
|
160
|
+
except (OSError, ValueError):
|
|
161
|
+
self.clear()
|
|
162
|
+
return None
|
|
163
|
+
head = Head(branch=data["branch"], sha=data["sha"])
|
|
164
|
+
start = await git.git_dir() / "BISECT_START"
|
|
165
|
+
if not start.exists() or start.read_text().strip() not in (head.branch, head.sha):
|
|
166
|
+
self.clear() # not our bisect any more: the user has moved on
|
|
167
|
+
return None
|
|
168
|
+
why = await git.restore(head)
|
|
169
|
+
self.clear()
|
|
170
|
+
if why:
|
|
171
|
+
return f"an interrupted irsmith bisect was cleaned up, but HEAD was not restored to {head.label}: {why}"
|
|
172
|
+
return f"restored {head.label} after an interrupted irsmith bisect"
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
async def recover_sessions(state_dir: Path) -> list[str]:
|
|
176
|
+
"""Restore repositories left mid-bisect by servers that died. Run at startup."""
|
|
177
|
+
notes = []
|
|
178
|
+
directory = state_dir / "bisect"
|
|
179
|
+
for session in sorted(directory.glob("*.json")) if directory.is_dir() else []:
|
|
180
|
+
try:
|
|
181
|
+
repo = Path(json.loads(session.read_text())["repo"])
|
|
182
|
+
except (OSError, ValueError, KeyError):
|
|
183
|
+
session.unlink(missing_ok=True)
|
|
184
|
+
continue
|
|
185
|
+
if not repo.is_dir():
|
|
186
|
+
session.unlink(missing_ok=True)
|
|
187
|
+
continue
|
|
188
|
+
lock = RepoLock(state_dir, repo)
|
|
189
|
+
if not lock.acquire():
|
|
190
|
+
continue
|
|
191
|
+
try:
|
|
192
|
+
if note := await lock.recover(Git(repo)):
|
|
193
|
+
notes.append(note)
|
|
194
|
+
except IrsmithError as e:
|
|
195
|
+
notes.append(f"{repo}: {e.info.message}")
|
|
196
|
+
finally:
|
|
197
|
+
lock.release()
|
|
198
|
+
return notes
|