fix(search): close admission cancellation race

This commit is contained in:
Royalaid
2026-08-28 19:48:13 -07:00
committed by kshitij
parent 9e47ac17bd
commit 4e5499c62e
4 changed files with 127 additions and 2 deletions
+42
View File
@@ -62,6 +62,48 @@ class TestInterruptModule:
assert other_tid in _interrupted_threads # other thread untouched
_interrupted_threads.discard(other_tid)
def test_run_if_not_interrupted_skips_callback_when_already_interrupted(self):
from tools.interrupt import run_if_not_interrupted, set_interrupt
callbacks = []
set_interrupt(True)
try:
assert run_if_not_interrupted(lambda: callbacks.append("claimed")) is False
finally:
set_interrupt(False)
assert callbacks == []
def test_run_if_not_interrupted_orders_callback_before_concurrent_interrupt(self):
from tools.interrupt import run_if_not_interrupted, set_interrupt
setter_started = threading.Event()
interrupt_published = threading.Event()
callback_observations = []
setters = []
def publish_interrupt():
setter_started.set()
set_interrupt(True)
interrupt_published.set()
def callback():
setter = threading.Thread(target=publish_interrupt)
setters.append(setter)
setter.start()
assert setter_started.wait(5)
callback_observations.append(interrupt_published.is_set())
assert run_if_not_interrupted(callback) is True
setter = setters[0]
setter.join(5)
try:
assert not setter.is_alive()
assert callback_observations == [False]
assert interrupt_published.is_set()
finally:
set_interrupt(False)
# ---------------------------------------------------------------------------
# Unit tests: pre-tool interrupt check
@@ -192,6 +192,68 @@ def test_interrupted_waiter_returns_without_dispatch_or_late_dispatch(monkeypatc
release_holder.set()
def test_interrupt_published_after_final_sample_prevents_filename_dispatch(monkeypatch):
sampled_clear = threading.Event()
resume_acquire = threading.Event()
worker_tid = []
dispatches = []
def scan(self, pattern, path, limit, offset, order, rg_executable=None):
dispatches.append(threading.get_ident())
return SearchResult(files=[str(path)], total_count=1)
operations = _operations(RemoteEnvironment(), scan)
original_is_interrupted = __import__(
"tools.interrupt", fromlist=["is_interrupted"]
).is_interrupted
def pause_after_clear_sample():
interrupted = original_is_interrupted()
if not interrupted and threading.get_ident() == worker_tid[0]:
sampled_clear.set()
assert resume_acquire.wait(5)
return interrupted
monkeypatch.setattr(
"tools.file_operations.tool_interrupt.is_interrupted",
pause_after_clear_sample,
)
def run_search():
worker_tid.append(threading.get_ident())
return operations._search_files("*.py", "/repo", 50, 0)
with ThreadPoolExecutor(max_workers=1) as pool:
future = pool.submit(run_search)
assert sampled_clear.wait(5)
set_interrupt(True, worker_tid[0])
resume_acquire.set()
try:
result = future.result(timeout=5)
finally:
set_interrupt(False, worker_tid[0])
resume_acquire.set()
assert "interrupted" in (result.error or "").lower()
assert dispatches == []
assert _ACTIVE_FILENAME_SEARCH_ROOTS == set()
def test_empty_filename_roots_are_rejected_before_engine_resolution():
def scan(self, pattern, path, limit, offset, order, rg_executable=None):
raise AssertionError("filename engine dispatched")
operations = _operations(RemoteEnvironment(), scan)
operations._resolve_command = lambda command: (_ for _ in ()).throw(
AssertionError(f"engine resolution attempted: {command}")
)
result = operations._search_files("*.py", [], 50, 0)
assert "at least one search root" in (result.error or "").lower()
assert _ACTIVE_FILENAME_SEARCH_ROOTS == set()
@pytest.mark.parametrize("raised", [Exception, KeyboardInterrupt, SystemExit, BaseException])
def test_admission_releases_after_every_base_exception_path(raised):
attempts = 0
+7 -2
View File
@@ -123,8 +123,9 @@ def _acquire_filename_search_roots(
return False
if tool_interrupt.is_interrupted():
return False
_ACTIVE_FILENAME_SEARCH_ROOTS.update(keys)
return True
return tool_interrupt.run_if_not_interrupted(
lambda: _ACTIVE_FILENAME_SEARCH_ROOTS.update(keys)
)
def _release_filename_search_roots(
@@ -3770,6 +3771,10 @@ class ShellFileOperations(FileOperations):
search_pattern = pattern.split('/')[-1]
roots = [path] if isinstance(path, str) else path
if not roots:
return SearchResult(
error="File search requires at least one search root in 'path'."
)
# Prefer ripgrep: bounded parallel traversal with ignore semantics.
# Resolve the engine and exact-order capability before admission so a
+16
View File
@@ -17,6 +17,7 @@ Usage in tools:
import logging
import os
import threading
from collections.abc import Callable
logger = logging.getLogger(__name__)
@@ -95,6 +96,21 @@ def is_thread_interrupted(thread_id: int | None) -> bool:
return thread_id in _interrupted_threads
def run_if_not_interrupted(callback: Callable[[], None]) -> bool:
"""Run a state transition atomically with current-thread interruption.
Returns ``False`` without calling ``callback`` when the current thread is
already interrupted. The callback runs under the interrupt lock and must
not block or re-enter any interrupt API.
"""
tid = threading.current_thread().ident
with _lock:
if tid in _interrupted_threads:
return False
callback()
return True
def get_interrupt_reason() -> str | None:
"""Return the user-safe interrupt cause for the current thread, if known."""
tid = threading.current_thread().ident