Skip to content

Use Claude Code, Codex, VSCode, Pi, and OpenCode (and 6 other harnesses) for free (1.3B+ free tokens) from your terminal, app, IDE, or phone, and now from the browser with native browser sessions (multi-harness + multi-model) like OpenClaw (voice supported + ToS friendly)

Python

Removed all signal handler logic

Alishahryar142a833245ff1
diff --git a/api/app.py b/api/app.py
index 9734d9e0..2180807d 100644
--- a/api/app.py
+++ b/api/app.py
@@ -2,7 +2,6 @@
import asyncio
import os
-import signal
# Opt-in to future behavior for python-telegram-bot
os.environ["PTB_TIMEDELTA"] = "1"
@@ -17,8 +16,6 @@ from .dependencies import cleanup_provider
from providers.exceptions import ProviderError
from config.settings import get_settings
-from utils.signal_handlers import install_chained_signal_handlers
-
# Configure logging (atomic - only on true fresh start)
_settings = get_settings()
LOG_FILE = _settings.log_file
@@ -50,9 +47,6 @@ async def _best_effort(
"""Run a shutdown step with timeout; never raise to callers."""
try:
await asyncio.wait_for(awaitable, timeout=timeout_s)
- except asyncio.CancelledError:
- # Shutdown tasks may be cancelled; treat as a successful "best effort".
- return
except asyncio.TimeoutError:
logger.warning(f"Shutdown step timed out: {name} ({timeout_s}s)")
except Exception as e:
@@ -70,86 +64,6 @@ async def lifespan(app: FastAPI):
message_handler = None
cli_manager = None
- # Ctrl+C shutdown assist: chain SIGINT/SIGTERM to trigger early cleanup.
- shutdown_event = asyncio.Event()
- # Keep a plain counter because asyncio.Event state may lag behind
- # call_soon_threadsafe when signals arrive back-to-back.
- signal_count = {"n": 0}
- loop = asyncio.get_running_loop()
-
- def _on_signal(signum: int, _frame) -> None:
- signal_count["n"] += 1
- logger.warning(
- f"Signal received: {signum} (count={signal_count['n']}); requesting shutdown"
- )
- # On Windows + uvicorn, shutdown can hang indefinitely when
- # timeout_graceful_shutdown is None and there are stuck connections/tasks.
- # A second signal should always force termination.
- if signal_count["n"] >= 2:
- logger.error("Second shutdown signal; forcing exit")
- try:
- from cli.process_registry import kill_all_best_effort
-
- kill_all_best_effort()
- finally:
- os._exit(130)
- try:
- loop.call_soon_threadsafe(shutdown_event.set)
- except Exception:
- # Best-effort fallback; should still be safe if we're already on-loop.
- shutdown_event.set()
-
- signals = [signal.SIGINT, signal.SIGTERM]
- if hasattr(signal, "SIGBREAK"):
- # Windows Ctrl+Break.
- signals.append(signal.SIGBREAK)
-
- restore_signal_handlers = install_chained_signal_handlers(
- signals=signals,
- handler=_on_signal,
- )
- logger.info(f"Installed shutdown signal handlers: {[int(s) for s in signals]}")
-
- async def _early_shutdown_worker() -> None:
- await shutdown_event.wait()
- logger.warning("Early shutdown: running best-effort cleanup steps")
- try:
- from cli.process_registry import kill_all_best_effort
-
- kill_all_best_effort()
- except Exception:
- pass
-
- # Try to stop the Telegram poller quickly; lifespan cleanup will also run.
- mp = getattr(app.state, "messaging_platform", None)
- cm = getattr(app.state, "cli_manager", None)
- mh = getattr(app.state, "message_handler", None)
- if mp:
- await _best_effort(
- "early.messaging_platform.stop", mp.stop(), timeout_s=2.0
- )
- if mh:
- await _best_effort(
- "early.message_handler.stop_all_tasks",
- mh.stop_all_tasks(),
- timeout_s=2.0,
- )
- if cm:
- await _best_effort(
- "early.cli_manager.stop_all", cm.stop_all(), timeout_s=2.0
- )
- try:
- from messaging.limiter import MessagingRateLimiter
-
- await _best_effort(
- "early.MessagingRateLimiter.shutdown_instance",
- MessagingRateLimiter.shutdown_instance(),
- timeout_s=2.0,
- )
- except Exception:
- pass
-
- early_shutdown_task = asyncio.create_task(_early_shutdown_worker())
try:
# Use the messaging factory to create the right platform
@@ -266,17 +180,6 @@ async def lifespan(app: FastAPI):
# Limiter may never have been imported/initialized.
pass
- # Stop the early-shutdown worker and restore signal handlers.
- try:
- early_shutdown_task.cancel()
- await _best_effort("early_shutdown_task", early_shutdown_task, timeout_s=1.0)
- except Exception:
- pass
- try:
- restore_signal_handlers()
- except Exception:
- pass
-
logger.info("Server shut down cleanly")
diff --git a/server.py b/server.py
index 1f0b17f7..68e1f3c8 100644
--- a/server.py
+++ b/server.py
@@ -16,7 +16,7 @@ if __name__ == "__main__":
settings = get_settings()
try:
- # Avoid hanging forever on Ctrl+C when there are stuck connections/tasks.
+ # timeout_graceful_shutdown ensures uvicorn doesn't hang on task cleanup.
uvicorn.run(
app,
host=settings.host,
@@ -25,5 +25,5 @@ if __name__ == "__main__":
timeout_graceful_shutdown=5,
)
finally:
- # Safety net for Ctrl+C cases where lifespan shutdown doesn't fully run.
+ # Safety net: cleanup subprocesses if lifespan shutdown doesn't fully run.
kill_all_best_effort()
diff --git a/tests/test_signal_handlers.py b/tests/test_signal_handlers.py
deleted file mode 100644
index d8b6c248..00000000
--- a/tests/test_signal_handlers.py
+++ /dev/null
@@ -1,33 +0,0 @@
-import signal
-
-from utils.signal_handlers import install_chained_signal_handlers
-
-
-def test_install_chained_signal_handlers_calls_prev_and_new_handler():
- calls = []
-
- def prev(signum, frame):
- calls.append(("prev", signum))
-
- old = signal.getsignal(signal.SIGINT)
- signal.signal(signal.SIGINT, prev)
-
- try:
-
- def ours(signum, frame):
- calls.append(("ours", signum))
-
- restore = install_chained_signal_handlers(signals=[signal.SIGINT], handler=ours)
-
- try:
- h = signal.getsignal(signal.SIGINT)
- assert callable(h)
- # Call the installed handler directly (don't actually raise SIGINT).
- h(signal.SIGINT, None) # type: ignore[misc]
- finally:
- restore()
-
- finally:
- signal.signal(signal.SIGINT, old)
-
- assert calls == [("ours", signal.SIGINT), ("prev", signal.SIGINT)]
diff --git a/utils/signal_handlers.py b/utils/signal_handlers.py
deleted file mode 100644
index f9d9ac4c..00000000
--- a/utils/signal_handlers.py
+++ /dev/null
@@ -1,57 +0,0 @@
-"""Signal handler helpers.
-
-We run under asyncio + uvicorn on Windows. Ctrl+C (SIGINT) is normally handled by
-uvicorn, but some background tasks (Telegram polling, subprocesses) may keep the
-process alive longer than expected. These helpers let us *chain* our own handler
-without breaking any existing handler already installed by uvicorn.
-"""
-
-from __future__ import annotations
-
-import signal
-import threading
-from types import FrameType
-from typing import Any, Callable, Dict, Iterable, Optional
-
-
-def _call_prev(prev: Any, signum: int, frame: Optional[FrameType]) -> None:
- if not callable(prev):
- return
- try:
- prev(signum, frame)
- except TypeError:
- # Some handlers only accept (signum).
- prev(signum) # type: ignore[misc]
-
-
-def install_chained_signal_handlers(
- *,
- signals: Iterable[int],
- handler: Callable[[int, Optional[FrameType]], None],
-) -> Callable[[], None]:
- """Install `handler` for each signal, while preserving any existing handler.
-
- Returns a restore() function that puts the previous handlers back.
- """
- # `signal.signal(...)` only works in the main thread. During tests (FastAPI
- # TestClient), lifespan runs in a worker thread, so we must no-op.
- if threading.current_thread() is not threading.main_thread():
- return lambda: None
-
- previous: Dict[int, Any] = {}
-
- for sig in signals:
- prev = signal.getsignal(sig)
- previous[sig] = prev
-
- def _wrapped(signum: int, frame: Optional[FrameType], _prev=prev) -> None:
- handler(signum, frame)
- _call_prev(_prev, signum, frame)
-
- signal.signal(sig, _wrapped)
-
- def restore() -> None:
- for sig, prev in previous.items():
- signal.signal(sig, prev) # type: ignore[arg-type]
-
- return restore