Skip to content

Commit 23c939c

Browse files
committed
fix: retry a runner that the system reports busy, and fail only its problem when it cannot start
A binary that cstudy has just copied can be refused with ETXTBSY while another thread forks a child that still holds the copy's write descriptor. Starting a binary written by cstudy now retries on that error, up to 10 attempts with a doubling delay from 10 ms capped at 0.5 s (about 2 s in all); any other error is raised at once. In cstudy verify, a runner that cannot start for one language of a function, design or concurrent problem fails that problem and the run goes on, ending with exit 1 instead of exit 4.
1 parent fde2a89 commit 23c939c

11 files changed

Lines changed: 263 additions & 31 deletions

File tree

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
"""Starting a binary that `cstudy` wrote a moment ago.
2+
3+
`cstudy` copies a built Go or Rust binary into a private folder and starts it at once. The copy is
4+
written by this process while other threads keep starting children (one per language in
5+
`cstudy verify`), and a child forked while the copy is open for writing holds that descriptor until
6+
its own `exec`. Until then the kernel refuses to execute the copy with `ETXTBSY` ("Text file
7+
busy"). The refusal ends within a fraction of a second, so the start is tried again; any other
8+
failure is the caller's at once.
9+
"""
10+
11+
import errno
12+
import time
13+
from collections.abc import Callable
14+
15+
MAX_ATTEMPTS = 10
16+
FIRST_DELAY_SECONDS = 0.01
17+
MAX_DELAY_SECONDS = 0.5
18+
"""The delay doubles from the first to this one: the attempts wait about 2 s in all."""
19+
20+
21+
def start_when_not_busy[T](start: Callable[[], T]) -> T:
22+
"""The result of `start`, which is tried again while it raises `OSError` with `ETXTBSY`, up to
23+
`MAX_ATTEMPTS` times. Raises that error after the last attempt, and any other `OSError` at
24+
once."""
25+
delay = FIRST_DELAY_SECONDS
26+
for _ in range(MAX_ATTEMPTS - 1):
27+
try:
28+
return start()
29+
except OSError as error:
30+
if error.errno != errno.ETXTBSY:
31+
raise
32+
time.sleep(delay)
33+
delay = min(delay * 2, MAX_DELAY_SECONDS)
34+
return start()

‎cli/src/coding_study/adapters/languages/bounded_process.py‎

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
from contextlib import suppress
1414
from pathlib import Path
1515

16+
from coding_study.adapters.busy_binary import start_when_not_busy
1617
from coding_study.adapters.process_environment import inherited_environment
1718
from coding_study.domain.errors import RunnerStartError
1819

@@ -56,15 +57,18 @@ def _execute(
5657
environment: Mapping[str, str] | None,
5758
stderr: int,
5859
) -> "subprocess.CompletedProcess[bytes]":
59-
with subprocess.Popen(
60-
command,
61-
cwd=cwd,
62-
env=inherited_environment() if environment is None else dict(environment),
63-
stdin=subprocess.DEVNULL,
64-
stdout=subprocess.PIPE,
65-
stderr=stderr,
66-
start_new_session=True,
67-
) as process:
60+
started = start_when_not_busy(
61+
lambda: subprocess.Popen(
62+
command,
63+
cwd=cwd,
64+
env=inherited_environment() if environment is None else dict(environment),
65+
stdin=subprocess.DEVNULL,
66+
stdout=subprocess.PIPE,
67+
stderr=stderr,
68+
start_new_session=True,
69+
)
70+
)
71+
with started as process:
6872
try:
6973
output, errors = process.communicate(timeout=self._timeout_seconds)
7074
except subprocess.TimeoutExpired:

‎cli/src/coding_study/adapters/languages/rust/project_suite.py‎

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
from pathlib import Path
2424
from typing import Protocol
2525

26+
from coding_study.adapters.busy_binary import start_when_not_busy
2627
from coding_study.adapters.debug_process import terminated_like_interrupt
2728
from coding_study.adapters.languages.rust.libtest import (
2829
LIBTEST_ERROR,
@@ -296,14 +297,16 @@ def _start(
296297
command: Sequence[str], cwd: Path, *, stdout: object, stderr: object
297298
) -> "subprocess.Popen[bytes]":
298299
try:
299-
return subprocess.Popen(
300-
list(command),
301-
cwd=cwd,
302-
env=_test_environment(inherited_environment()),
303-
stdin=subprocess.DEVNULL,
304-
stdout=stdout, # type: ignore[arg-type]
305-
stderr=stderr, # type: ignore[arg-type]
306-
start_new_session=True,
300+
return start_when_not_busy(
301+
lambda: subprocess.Popen(
302+
list(command),
303+
cwd=cwd,
304+
env=_test_environment(inherited_environment()),
305+
stdin=subprocess.DEVNULL,
306+
stdout=stdout, # type: ignore[arg-type]
307+
stderr=stderr, # type: ignore[arg-type]
308+
start_new_session=True,
309+
)
307310
)
308311
except OSError as error:
309312
raise RunnerStartError(f"cannot run {command[0]}: {error.strerror or error}") from error

‎cli/src/coding_study/adapters/subprocess_runner.py‎

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@
5050
from typing import IO, Protocol, TypeGuard
5151

5252
from coding_study.adapters.bench_progress import BenchProgress
53+
from coding_study.adapters.busy_binary import start_when_not_busy
5354
from coding_study.adapters.debug_process import DebugOutput, terminated_like_interrupt
5455
from coding_study.adapters.process_environment import inherited_environment
5556
from coding_study.adapters.process_liveness import OrphanGuard, kill_processes_started_from
@@ -737,14 +738,16 @@ def _open_stdout(self, streams: ExitStack) -> IO[bytes] | int:
737738
def _start(self, stdout: IO[bytes] | int, stderr: IO[bytes]) -> subprocess.Popen[bytes]:
738739
arguments = ["--request", str(self._files.request), "--out", str(self._files.events)]
739740
try:
740-
process = subprocess.Popen(
741-
[*self._launch.command, *arguments],
742-
cwd=self._launch.cwd,
743-
env=_environment(self._launch),
744-
stdin=subprocess.DEVNULL,
745-
stdout=stdout,
746-
stderr=stderr,
747-
start_new_session=True,
741+
process = start_when_not_busy(
742+
lambda: subprocess.Popen(
743+
[*self._launch.command, *arguments],
744+
cwd=self._launch.cwd,
745+
env=_environment(self._launch),
746+
stdin=subprocess.DEVNULL,
747+
stdout=stdout,
748+
stderr=stderr,
749+
start_new_session=True,
750+
)
748751
)
749752
except OSError as error:
750753
raise RunnerStartError(

‎cli/src/coding_study/application/reference_runs.py‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
from coding_study.domain import layout
1313
from coding_study.domain.buggy_stubs import BUGGY_STUB_APPROACH_ID, buggy_file
1414
from coding_study.domain.comparators import Comparator
15+
from coding_study.domain.errors import RunnerStartError
1516
from coding_study.domain.judging import CaseStatus, RunnableCase, judge, outcome_summary
1617
from coding_study.domain.problem import Language, ProblemMeta
1718
from coding_study.domain.problem_files import SOLUTIONS_DIRECTORY
@@ -97,13 +98,29 @@ def approaches_in(
9798

9899

99100
def per_language[T](
100-
languages: Sequence[Language], work: Callable[[Language], T], jobs: int | None
101+
languages: Sequence[Language],
102+
work: Callable[[Language], T],
103+
jobs: int | None,
104+
not_started: Callable[[Language, RunnerStartError], T],
101105
) -> dict[Language, T]:
102-
"""`work` for every language, at most `jobs` at a time (default: all at once)."""
106+
"""`work` for every language, at most `jobs` at a time (default: all at once). A language
107+
whose runner cannot start gets `not_started` instead, and the others go on."""
108+
109+
def guarded(language: Language) -> T:
110+
try:
111+
return work(language)
112+
except RunnerStartError as error:
113+
return not_started(language, error)
114+
103115
if not languages:
104116
return {}
105117
with ThreadPoolExecutor(max_workers=jobs or len(languages)) as executor:
106-
return dict(zip(languages, executor.map(work, languages), strict=True))
118+
return dict(zip(languages, executor.map(guarded, languages), strict=True))
119+
120+
121+
def failed_to_start(language: Language, error: RunnerStartError) -> LanguageResult:
122+
"""The language's failure when its runner cannot start: the problem fails, the run goes on."""
123+
return LanguageResult(language, problems=(str(error),))
107124

108125

109126
class LanguageVerifier:

‎cli/src/coding_study/application/verify_conformance.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
LanguageResult,
2424
LanguageVerifier,
2525
approaches_in,
26+
failed_to_start,
2627
per_language,
2728
shown,
2829
)
@@ -143,6 +144,7 @@ def verify(self, slug: str) -> FixtureVerification:
143144
split.runnable,
144145
lambda language: run.language(language, expectations),
145146
self._request.jobs,
147+
failed_to_start,
146148
)
147149
skipped = {
148150
language: LanguageResult(language, skipped=split.reasons[language])

‎cli/src/coding_study/application/verify_content.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
LanguageResult,
2828
LanguageVerifier,
2929
approaches_in,
30+
failed_to_start,
3031
per_language,
3132
shown,
3233
)
@@ -472,6 +473,7 @@ def apply(self, verification: ProblemVerification) -> ProblemVerification:
472473
split.runnable,
473474
lambda language: self._language(language, cases, oracle_cases, comparator),
474475
self._request.jobs,
476+
lambda language, error: (failed_to_start(language, error), None),
475477
)
476478
oracle = (
477479
self._oracle(runs, oracle_cases, comparator)
Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
import errno
2+
import os
3+
import shutil
4+
import subprocess
5+
import sys
6+
import threading
7+
import time
8+
from pathlib import Path
9+
10+
import pytest
11+
12+
from coding_study.adapters import busy_binary
13+
from coding_study.adapters.busy_binary import MAX_ATTEMPTS, start_when_not_busy
14+
from coding_study.adapters.languages.bounded_process import BoundedProcess
15+
from coding_study.adapters.languages.rust import project_suite
16+
from coding_study.domain.errors import RunnerStartError
17+
18+
19+
def busy() -> OSError:
20+
return OSError(errno.ETXTBSY, "Text file busy")
21+
22+
23+
@pytest.fixture
24+
def sleeps(monkeypatch) -> list[float]:
25+
waited: list[float] = []
26+
monkeypatch.setattr(busy_binary.time, "sleep", waited.append)
27+
return waited
28+
29+
30+
def failing(errors: list[OSError], result: str = "started"):
31+
attempts: list[int] = []
32+
33+
def start() -> str:
34+
attempts.append(1)
35+
if errors:
36+
raise errors.pop(0)
37+
return result
38+
39+
return start, attempts
40+
41+
42+
def test_a_busy_binary_is_started_once_it_is_free(sleeps):
43+
start, attempts = failing([busy(), busy()])
44+
assert start_when_not_busy(start) == "started"
45+
assert (len(attempts), sleeps) == (3, [0.01, 0.02])
46+
47+
48+
def test_a_binary_that_stays_busy_fails_after_the_last_attempt(sleeps):
49+
start, attempts = failing([busy()] * 20)
50+
with pytest.raises(OSError, match="Text file busy") as raised:
51+
start_when_not_busy(start)
52+
assert raised.value.errno == errno.ETXTBSY
53+
assert len(attempts) == MAX_ATTEMPTS
54+
assert len(sleeps) == MAX_ATTEMPTS - 1
55+
assert max(sleeps) == busy_binary.MAX_DELAY_SECONDS
56+
assert 1.5 < sum(sleeps) < 2.5
57+
58+
59+
def test_any_other_error_is_raised_at_once(sleeps):
60+
start, attempts = failing([OSError(errno.ENOENT, "No such file or directory")])
61+
with pytest.raises(FileNotFoundError):
62+
start_when_not_busy(start)
63+
assert (len(attempts), sleeps) == (1, [])
64+
65+
66+
def test_the_runner_start_retries_a_busy_binary(monkeypatch, sleeps):
67+
started = []
68+
real = subprocess.Popen
69+
70+
def popen(command, **options):
71+
started.append(command)
72+
if len(started) < 3:
73+
raise busy()
74+
return real(command, **options)
75+
76+
monkeypatch.setattr(subprocess, "Popen", popen)
77+
completed = BoundedProcess("build", 10).run([sys.executable, "--version"], Path.cwd(), None)
78+
assert (completed.returncode, len(started)) == (0, 3)
79+
80+
81+
def test_a_rust_test_binary_that_stays_busy_is_a_start_error(monkeypatch, sleeps):
82+
calls = []
83+
84+
def popen(command, **options):
85+
calls.append(command)
86+
raise busy()
87+
88+
monkeypatch.setattr(subprocess, "Popen", popen)
89+
with pytest.raises(RunnerStartError, match="Text file busy"):
90+
project_suite._start(
91+
["./tests"], Path.cwd(), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
92+
)
93+
assert len(calls) == MAX_ATTEMPTS
94+
95+
96+
@pytest.mark.skipif(not sys.platform.startswith("linux"), reason="ETXTBSY is how Linux refuses")
97+
def test_a_binary_held_open_by_a_forked_child_starts_once_the_child_has_executed(tmp_path):
98+
binary = tmp_path / "python-copy"
99+
shutil.copyfile(sys.executable, binary)
100+
binary.chmod(0o755)
101+
forked, announce = os.pipe()
102+
103+
def hold_until_exec() -> None:
104+
os.write(announce, b"x")
105+
time.sleep(0.5)
106+
107+
holder = threading.Thread(
108+
target=subprocess.run,
109+
args=([sys.executable, "--version"],),
110+
kwargs={"preexec_fn": hold_until_exec, "pass_fds": (announce,), "capture_output": True},
111+
)
112+
with binary.open("r+b"):
113+
holder.start()
114+
assert os.read(forked, 1) == b"x"
115+
os.close(forked)
116+
os.close(announce)
117+
# the forked child still holds the copy's write descriptor: executing it fails until it execs
118+
with pytest.raises(OSError, match="Text file busy") as direct:
119+
subprocess.run([str(binary), "--version"], capture_output=True)
120+
assert direct.value.errno == errno.ETXTBSY
121+
process = start_when_not_busy(
122+
lambda: subprocess.Popen([str(binary), "--version"], stdout=subprocess.PIPE)
123+
)
124+
output, _ = process.communicate()
125+
assert (process.returncode, output.startswith(b"Python")) == (0, True)
126+
holder.join()

0 commit comments

Comments
 (0)