Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions holmes/core/conversations_worker/worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -859,6 +859,9 @@ def _run_chat_and_publish(

storage = tool_result_storage()
tool_results_dir = storage.__enter__()

cancel_event = threading.Event()

try:
ai = self.config.create_toolcalling_llm(
dal=self.dal,
Expand Down Expand Up @@ -941,6 +944,7 @@ def _run_chat_and_publish(
response_format=chat_request.response_format,
request_context=request_context,
trace_span=trace_span,
cancel_event=cancel_event,
)
stream = stream_with_usage_recording(raw_stream, recorder_state)

Expand Down
4 changes: 4 additions & 0 deletions holmes/core/exceptions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
class LLMInterruptedError(Exception):
"""Raised when the user interrupts an in-progress LLM call (e.g. via Escape key)."""

pass
2 changes: 1 addition & 1 deletion holmes/core/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -351,4 +351,4 @@ class ChatResponse(BaseModel):
tool_calls: Optional[List[ToolCallResult]] = []
follow_up_actions: Optional[List[FollowUpAction]] = []
pending_approvals: Optional[List[PendingToolApproval]] = None
metadata: Optional[Dict[Any, Any]] = None
metadata: Optional[Dict[Any, Any]] = None
21 changes: 13 additions & 8 deletions holmes/core/tool_calling_llm.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,11 +72,7 @@
)
from holmes.utils.tags import parse_messages_tags


class LLMInterruptedError(Exception):
"""Raised when the user interrupts an in-progress LLM call (e.g. via Escape key)."""

pass
from holmes.core.exceptions import LLMInterruptedError # noqa: F401 (re-exported for backwards compat)


# Create a named logger for cost tracking
Expand Down Expand Up @@ -1084,6 +1080,7 @@ def call_stream(

while i < max_steps:
if cancel_event and cancel_event.is_set():
logging.info("call_stream: cancel detected at iteration start (i=%d), aborting", i)
raise LLMInterruptedError()

i += 1
Expand Down Expand Up @@ -1215,6 +1212,7 @@ def call_stream(
raise

if cancel_event and cancel_event.is_set():
logging.info("call_stream: cancel detected after LLM response (iteration %d), aborting", i)
raise LLMInterruptedError()

response_message = full_response.choices[0].message # type: ignore
Expand Down Expand Up @@ -1276,7 +1274,8 @@ def call_stream(
# Extract session approved prefixes from conversation history
session_prefixes = extract_bash_session_prefixes(messages)

with concurrent.futures.ThreadPoolExecutor(max_workers=16) as executor:
executor = concurrent.futures.ThreadPoolExecutor(max_workers=16)
try:
futures = []
for tool_index, t in enumerate(tools_to_call, 1): # type: ignore
tool_number = tool_number_offset + tool_index
Expand All @@ -1299,8 +1298,12 @@ def call_stream(

for future in concurrent.futures.as_completed(futures):
if cancel_event and cancel_event.is_set():
for f in futures:
f.cancel()
logging.info(
"call_stream: cancel detected during tool execution (iteration %d), "
"shutting down executor immediately",
i,
)
executor.shutdown(wait=False, cancel_futures=True)
raise LLMInterruptedError()

tool_call_result: ToolCallResult = future.result()
Expand Down Expand Up @@ -1433,6 +1436,8 @@ def call_stream(
f"Tool list changed - refreshing ({len(tools)} -> {len(new_tools)} tools)"
)
tools = new_tools
finally:
executor.shutdown(wait=False, cancel_futures=True)

raise Exception(
f"Too many LLM calls - exceeded max_steps: {i}/{self.max_steps}"
Expand Down
4 changes: 4 additions & 0 deletions holmes/utils/stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from pydantic import BaseModel, Field

from holmes.common.env_vars import TRACE_TOKEN_USAGE
from holmes.core.exceptions import LLMInterruptedError
from holmes.core.llm import ContextWindowUsage, build_usage_metadata


Expand Down Expand Up @@ -108,6 +109,9 @@ def stream_chat_formatter(
)
else:
yield create_sse_message(message.event.value, message.data)
except LLMInterruptedError:
logging.info("stream_chat_formatter: LLM call interrupted (client disconnected or cancelled)")
return
except Exception as e:
logging.error(f"Error during streaming chat: {e}", exc_info=True)
if _is_rate_limit_error(e):
Expand Down
78 changes: 74 additions & 4 deletions server.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,16 @@

# DO NOT ADD ANY IMPORTS OR CODE ABOVE THIS LINE
# IMPORTING ABOVE MIGHT INITIALIZE AN HTTPS CLIENT THAT DOESN'T TRUST THE CUSTOM CERTIFICATE
import asyncio
import json
import logging
import threading
import time
from datetime import datetime
from pathlib import Path
from typing import List, Optional
from typing import Dict, List, Optional

import anyio.from_thread as _anyio_from_thread
import colorlog
import litellm
from holmes.core.oauth_config import OAuthConfigLookupError, OAuthTokenExchangeError
Expand Down Expand Up @@ -448,6 +450,39 @@ def extract_passthrough_headers(request: Request) -> dict:
return {"headers": passthrough_headers} if passthrough_headers else {}


def _schedule_disconnect_watcher(
request: Request,
cancel_event: threading.Event,
label: str = "",
) -> None:
"""Schedule an async task on the event loop that polls for HTTP client
disconnect and sets cancel_event, capping orphaned-thread lifetime after
the client closes the connection.

No-op when called outside an anyio worker thread (e.g. unit tests).
"""
async def _watch() -> None:
try:
while not cancel_event.is_set():
await asyncio.sleep(0.2)
if await request.is_disconnected():
if not cancel_event.is_set():
cancel_event.set()
logging.info(
"stream %s: HTTP client disconnected, cancelling", label
)
return
except asyncio.CancelledError:
pass

try:
_anyio_from_thread.run_sync(lambda: asyncio.ensure_future(_watch()))
except Exception:
logging.debug(
"Could not schedule disconnect watcher for stream %s", label, exc_info=True
)


def _stream_with_storage_cleanup(storage, stream_generator, req_info):
"""Wrap a stream generator to clean up tool result files after streaming completes."""
try:
Expand All @@ -457,18 +492,35 @@ def _stream_with_storage_cleanup(storage, stream_generator, req_info):
storage.__exit__(None, None, None)


def _stream_with_trace_cleanup(storage, stream_generator, req_info, trace_span):
def _stream_with_trace_cleanup(
storage,
stream_generator,
req_info,
trace_span,
cancel_event: Optional[threading.Event] = None,
):
"""Wrap a stream generator with both storage cleanup and OTel span lifecycle.

The investigation span stays active throughout all yields so that httpx
auto-instrumented calls made during streaming become children of it.
The span is ended in the finally block so it always closes, even on error.
Sets cancel_event on exit so the disconnect watcher task exits promptly.
"""
_start = time.monotonic()
logging.info("Stream request start: %s", req_info)
try:
yield from stream_generator
finally:
logging.info(f"Stream request end: {req_info}")
elapsed = time.monotonic() - _start
was_cancelled = cancel_event is not None and cancel_event.is_set()
logging.info(
"Stream request end: %s (elapsed=%.2fs, cancelled=%s)",
req_info, elapsed, was_cancelled,
)
trace_span.end()
# Signal disconnect watcher (if any) that the stream has ended.
if cancel_event is not None:
cancel_event.set()
storage.__exit__(None, None, None)


Expand Down Expand Up @@ -612,6 +664,17 @@ def chat(chat_request: ChatRequest, http_request: Request):
recorder_state = build_chat_recorder_state(
chat_request, request_ai, dal=dal, is_streaming=True
)

# Create a cancel event so the disconnect watcher can interrupt the LLM loop.
stream_cancel_event = threading.Event()

# Start a background async task that detects HTTP client disconnect
# and sets stream_cancel_event, preventing anyio thread starvation
# when callers repeatedly open and close streaming connections.
_schedule_disconnect_watcher(
http_request, stream_cancel_event, label=req_info
)

recorded_stream = stream_with_usage_recording(
request_ai.call_stream(
msgs=messages,
Expand All @@ -621,6 +684,7 @@ def chat(chat_request: ChatRequest, http_request: Request):
response_format=chat_request.response_format,
request_context=request_context,
trace_span=trace_span,
cancel_event=stream_cancel_event,
),
recorder_state,
)
Expand All @@ -630,7 +694,13 @@ def chat(chat_request: ChatRequest, http_request: Request):
model=chat_request.model or config.model,
)
return StreamingResponse(
_stream_with_trace_cleanup(storage, stream, req_info, trace_span),
_stream_with_trace_cleanup(
storage,
stream,
req_info,
trace_span,
cancel_event=stream_cancel_event,
),
media_type="text/event-stream",
)
else:
Expand Down
67 changes: 66 additions & 1 deletion tests/test_server_endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
from fastapi import Request
from fastapi.testclient import TestClient

from server import app, extract_passthrough_headers
from holmes.core.exceptions import LLMInterruptedError
from holmes.utils.stream import stream_chat_formatter
from server import _stream_with_trace_cleanup, app, extract_passthrough_headers


@pytest.fixture
Expand Down Expand Up @@ -582,3 +584,66 @@ def test_empty_blocked_headers_env(self, monkeypatch):
assert "authorization" in result["headers"]
assert "cookie" in result["headers"]
assert "x-tenant-id" in result["headers"]


def test_stream_chat_formatter_swallows_llm_interrupted_error():
def interrupted_stream():
raise LLMInterruptedError()
yield # pragma: no cover

assert list(stream_chat_formatter(interrupted_stream())) == []


def test_stream_with_trace_cleanup_sets_cancel_event_on_normal_completion():
storage = MagicMock()
trace_span = MagicMock()

def source_stream():
yield "chunk-1"

import threading

cancel_event = threading.Event()

output = list(
_stream_with_trace_cleanup(
storage,
source_stream(),
"req-1",
trace_span,
cancel_event=cancel_event,
)
)

assert output == ["chunk-1"]
assert cancel_event.is_set()
trace_span.end.assert_called_once()
storage.__exit__.assert_called_once_with(None, None, None)


def test_stream_with_trace_cleanup_still_cleans_up_when_stream_errors():
storage = MagicMock()
trace_span = MagicMock()

def source_stream():
yield "before-error"
raise RuntimeError("boom")

import threading

cancel_event = threading.Event()

with pytest.raises(RuntimeError, match="boom"):
list(
_stream_with_trace_cleanup(
storage,
source_stream(),
"req-2",
trace_span,
cancel_event=cancel_event,
)
)

assert cancel_event.is_set()
trace_span.end.assert_called_once()
storage.__exit__.assert_called_once_with(None, None, None)