fix(file-ops): native rg runner honours deadline and /stop while rg is silent
The first version checked the deadline only after a line arrived, so an rg that produced nothing for 60 s (huge tree, no hits yet) pinned the caller past the timeout and ignored the interrupt flag that the shell path honours via _wait_for_process. Drain on a daemon thread; the waiter owns deadline (124) and interrupt (130) and kills the process group, so no rg or child survives the return. Probe: silent 10 s process, timeout=2 → 2.0 s / 124; interrupt at 0.5 s → 0.5 s / 130; zero stray processes afterwards.
This commit is contained in:
@@ -69,6 +69,29 @@ def test_native_search_never_touches_the_shell_and_matches_shell_results(tree, m
|
||||
assert not [c for c in calls if "pipefail" in c or c.startswith("test -e")], case
|
||||
|
||||
|
||||
def test_native_runner_honours_deadline_and_interrupt_while_rg_is_silent(tree, monkeypatch):
|
||||
"""A search producing no output must still stop at the deadline / on /stop
|
||||
(the shell path gets this from ``_wait_for_process``)."""
|
||||
import threading
|
||||
import time
|
||||
|
||||
from tools import interrupt
|
||||
|
||||
ops = _ops(tree, [])
|
||||
started = time.monotonic()
|
||||
result = ops._run_rg_native(["sh", "-c", "'sleep 30'"], 5, timeout=1)
|
||||
assert result.exit_code == 124 and time.monotonic() - started < 5
|
||||
|
||||
tid = threading.get_ident()
|
||||
threading.Timer(0.3, lambda: interrupt.set_interrupt(True, tid)).start()
|
||||
try:
|
||||
started = time.monotonic()
|
||||
result = ops._run_rg_native(["sh", "-c", "'sleep 30'"], 5, timeout=30)
|
||||
finally:
|
||||
interrupt.set_interrupt(False, tid)
|
||||
assert result.exit_code == 130 and time.monotonic() - started < 5
|
||||
|
||||
|
||||
def test_kill_switch_routes_search_back_to_the_shell(tree, monkeypatch):
|
||||
monkeypatch.setenv("HERMES_NATIVE_FILE_READ", "0")
|
||||
calls = []
|
||||
|
||||
@@ -4,10 +4,12 @@
|
||||
(no I/O).
|
||||
"""
|
||||
|
||||
import contextlib
|
||||
import os
|
||||
import posixpath
|
||||
import re
|
||||
import shlex
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
@@ -335,10 +337,11 @@ class SearchMixin:
|
||||
two bash spawns. ``shlex.split`` undoes the escaping the builders apply for
|
||||
the shell path, so both transports see identical arguments. Exit code and
|
||||
stdout follow the shell contract (rg 0/1/2; 124 on timeout with partial
|
||||
output), so ``_parse_search_output`` is shared. Once the bound is reached rg
|
||||
is killed like ``head`` closing the pipe would. ``merge_stderr`` mirrors the
|
||||
shell path's stderr handling: merged for content search (diagnostics feed
|
||||
the error message), discarded (``2>/dev/null``) for file lists and probes."""
|
||||
output; 130 on interrupt), so ``_parse_search_output`` is shared. Once the
|
||||
bound is reached rg is killed like ``head`` closing the pipe would.
|
||||
``merge_stderr`` mirrors the shell path's stderr handling: merged for content
|
||||
search (diagnostics feed the error message), discarded (``2>/dev/null``) for
|
||||
file lists and probes."""
|
||||
from tools.environments.local import _make_run_env
|
||||
cwd = getattr(self.env, "cwd", None) or self.cwd
|
||||
args = shlex.split(" ".join(argv))
|
||||
@@ -349,35 +352,47 @@ class SearchMixin:
|
||||
start_new_session=True)
|
||||
except OSError as exc:
|
||||
return ExecuteResult(stdout=f"rg: {exc}", exit_code=2)
|
||||
|
||||
# Drain on a thread so a silent rg (huge tree, no hits yet) cannot pin the
|
||||
# caller past the deadline or past a /stop; the waiter below owns both.
|
||||
lines: List[bytes] = []
|
||||
deadline = time.monotonic() + timeout
|
||||
timed_out = False
|
||||
bounded = False
|
||||
try:
|
||||
bounded = threading.Event()
|
||||
|
||||
def _drain() -> None:
|
||||
for raw in proc.stdout:
|
||||
lines.append(raw)
|
||||
if len(lines) >= fetch_limit:
|
||||
bounded = True
|
||||
bounded.set()
|
||||
break
|
||||
if time.monotonic() > deadline:
|
||||
timed_out = True
|
||||
break
|
||||
if bounded or timed_out:
|
||||
proc.kill()
|
||||
try:
|
||||
proc.wait(timeout=max(0.1, deadline - time.monotonic()))
|
||||
except subprocess.TimeoutExpired:
|
||||
proc.kill()
|
||||
proc.wait()
|
||||
timed_out = True
|
||||
finally:
|
||||
proc.stdout.close()
|
||||
|
||||
drainer = threading.Thread(target=_drain, daemon=True)
|
||||
drainer.start()
|
||||
deadline = time.monotonic() + timeout
|
||||
exit_code: Optional[int] = None
|
||||
while True:
|
||||
drainer.join(0.05)
|
||||
if not drainer.is_alive() or bounded.is_set():
|
||||
break
|
||||
if tool_interrupt.is_interrupted():
|
||||
exit_code = 130
|
||||
break
|
||||
if time.monotonic() > deadline:
|
||||
exit_code = 124
|
||||
break
|
||||
if proc.poll() is None:
|
||||
with contextlib.suppress(ProcessLookupError, PermissionError):
|
||||
os.killpg(proc.pid, signal.SIGKILL)
|
||||
proc.wait()
|
||||
drainer.join()
|
||||
proc.stdout.close()
|
||||
stdout = b"".join(lines).decode("utf-8", errors="replace")
|
||||
if timed_out:
|
||||
if exit_code == 124:
|
||||
return ExecuteResult(stdout=stdout + f"\n[Command timed out after {timeout}s]", exit_code=124)
|
||||
if exit_code == 130:
|
||||
return ExecuteResult(stdout=stdout + "\n[Command interrupted]", exit_code=130)
|
||||
# A killed-at-bound rg reports a signal (negative returncode); head would have
|
||||
# left the pipeline at 0 unless rg itself already failed.
|
||||
return ExecuteResult(stdout=stdout, exit_code=0 if bounded else proc.returncode)
|
||||
return ExecuteResult(stdout=stdout, exit_code=0 if bounded.is_set() else proc.returncode)
|
||||
|
||||
def _quote_executable(self, executable: str) -> str:
|
||||
"""Quote an executable without leaking controller path semantics."""
|
||||
|
||||
Reference in New Issue
Block a user