#6002·pipecat

SarvamTTSService: one failed keepalive ping stops the keepalive for the rest of the session

Author: Bot-Dev-RPACreated Oct 1, 2026Updated Oct 1, 2026
Labelsin-progress

pipecat version

1.11.0, also reproduced on main at 49dea682f (2026-09-30). services/sarvam/tts.py is unchanged in 1.12.0 and main.

Python version

3.14.7

Operating System

Linux (Debian 13, aarch64). websockets 16.0.

Issue description

SarvamTTSService._keepalive_task_handler (tts.py:1144-1149) runs while True: await asyncio.sleep(20); await self._send_keepalive() with no exception handling. _send_keepalive checks state == State.OPEN and then awaits send(), which can still raise, for example ConnectionClosedError when the connection is lost while the ping is being written. The exception ends the task, and nothing starts it again:

  • _connect() (tts.py:1009) creates the keepalive only if not self._keepalive_task, and the finished task is still assigned, so neither run_tts's reconnect nor any other _connect() replaces it.
  • The base-class reconnect (WebsocketService._try_reconnect -> _reconnect_websocket) does not touch it.
  • Only a full _disconnect() + _connect() resets it, for example an interruption while the bot is speaking.

From then on, whenever the bot is silent for 60 s, Sarvam closes the idle socket (its docs: "The WebSocket closes automatically after 60 seconds of inactivity"). The receive loop reconnects each time, so the session keeps closing and reopening the TTS socket once per idle minute, and a reply that starts during one of those windows has to race the reconnect.

pipecat already guards against this elsewhere: WebsocketSTTService._reconnect_websocket restarts its keepalive after a reconnect because "The keepalive task breaks out of its loop on send errors", and DeepgramSTTService._keepalive_handler catches send errors and keeps looping.

Proposed fix: catch and log exceptions from _send_keepalive() inside the loop and keep looping. Optionally also let _connect() replace a finished task (if not self._keepalive_task or self._keepalive_task.done()). With the first change the example below keeps one connection and keeps pinging.

Reproduction steps

  1. Save the script below as repro.py.
  2. pip install "pipecat-ai[sarvam]". No API key or network is needed: a local websocket server stands in for /text-to-speech/ws and, like Sarvam, closes a connection after 60 s without a message.
  3. python repro.py. The first ping's send() raises, as it does when the connection is lost at that moment; every later send works. The bot stays silent. To keep the run short, time is compressed 10x for the keepalive loop's sleep and the fake's idle timeout only, so 30 s of wall clock covers 300 s of session time.

Minimal reproducible example

python
import asyncio
import json

from websockets.asyncio.server import serve
from websockets.exceptions import ConnectionClosed, ConnectionClosedError

import pipecat.services.sarvam.tts as sarvam_tts
from pipecat.services.sarvam.tts import SarvamTTSService
from pipecat.tests.utils import SleepFrame, run_test

# Compress time 10x for the keepalive loop only: its 20 s sleep becomes 2 s,
# and the fake server's 60 s idle timeout becomes 6 s.
SCALE = 10


class _ScaledAsyncio:
    def __getattr__(self, name):
        return getattr(asyncio, name)

    @staticmethod
    async def sleep(delay):
        await asyncio.sleep(delay / SCALE)


sarvam_tts.asyncio = _ScaledAsyncio()

connections = 0
pings = 0


async def fake_sarvam_tts(ws):
    """Local stand-in for /text-to-speech/ws: closes a connection after 60 s
    without a message, as Sarvam does."""
    global connections, pings
    connections += 1
    while True:
        try:
            message = await asyncio.wait_for(ws.recv(), timeout=60 / SCALE)
        except TimeoutError:
            await ws.close(1000, "idle timeout")
            return
        except ConnectionClosed:
            return
        pings += json.loads(message).get("type") == "ping"


async def main():
    async with serve(fake_sarvam_tts, "127.0.0.1", 0) as server:
        port = server.sockets[0].getsockname()[1]
        tts = SarvamTTSService(api_key="test", url=f"ws://127.0.0.1:{port}/ws")

        @tts.event_handler("on_connected")
        async def on_connected(service):
            if connections > 1:
                return
            # The first ping's send fails, as it does when the connection drops
            # while the ping is written. Every later send works.
            send, failed = service._websocket.send, []

            async def send_once_failing(message):
                if not failed and json.loads(message).get("type") == "ping":
                    failed.append(True)
                    raise ConnectionClosedError(None, None)
                await send(message)

            service._websocket.send = send_once_failing

        # The bot stays silent for 30 s, i.e. 300 s of session time.
        await run_test(tts, frames_to_send=[SleepFrame(sleep=30)])
    print("connections:", connections)
    print("pings      :", pings)


asyncio.run(main())

Expected behavior

One failed ping is logged and the next ping 20 s later goes out as usual: one connection for the whole silent stretch, with a ping every 20 s. (Without the injected failure the example prints connections: 1 and pings: 14.)

Actual behavior

connections: 5
pings      : 0

After the failed ping no ping is ever sent again. The fake server closes each idle connection after 60 s (session time) and the service reconnects, four times in 300 s. Near the end tts._keepalive_task is still the finished task.

Logs

bash
ERROR    | pipecat.utils.asyncio.task_manager:run_coroutine:199 - SarvamTTSService#0::_keepalive_task_handler unexpected exception (repro.py:63): no close frame received or sent
WARNING  | pipecat.services.websocket_service:_maybe_try_reconnect:325 - SarvamTTSService#0 connection closed by server
WARNING  | pipecat.services.websocket_service:_try_reconnect:219 - SarvamTTSService#0 reconnecting, attempt 1
INFO     | pipecat.services.websocket_service:_try_reconnect:221 - SarvamTTSService#0 reconnected successfully on attempt 1
... the last three lines repeat once per 60 s of silence

Before you submit

  • I have personally reproduced this issue on the latest Pipecat release (or main).
  • I have searched existing issues for this bug.
  • If AI tools helped write this report, I have verified the behavior myself and will personally answer follow-up questions.