Skip to content
Merged
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
37 changes: 37 additions & 0 deletions modelq/app/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,7 @@ def __init__(
**kwargs,
):
if redis_client:
self._apply_liveness_defaults(redis_client)
self.redis_client = _RedisWithRetry(redis_client)

else:
Expand Down Expand Up @@ -314,6 +315,42 @@ def _should_ignore_sentry_exception(self, exc: Exception) -> bool:
and isinstance(exc, self.sentry_ignore_exceptions)
)

def _apply_liveness_defaults(self, client: Any) -> None:
"""Give a caller-built client the half-open protection of our own pool.

Servers build `Redis(host=..., port=..., password=...)` and pass it in,
which skips `_connect_to_redis()`. With no socket timeout a worker parked
in a blocking pop on a silently dropped connection waits forever: nothing
is raised, so `_RedisWithRetry` never runs, and only a restart gets it
back. TTS and SFX ran this way through the 2026-10 outages.

Only fills what the caller left unset, and leaves anything that is not a
plain TCP pool alone (a unix socket connection refuses keepalive options).
"""
pool = getattr(client, "connection_pool", None)
connection_kwargs = getattr(pool, "connection_kwargs", None)
connection_class = getattr(pool, "connection_class", None)
if not isinstance(connection_kwargs, dict) or not (
isinstance(connection_class, type)
and issubclass(connection_class, redis.connection.Connection)
):
return

defaults = {
"socket_timeout": self.SOCKET_TIMEOUT,
"socket_connect_timeout": self.SOCKET_CONNECT_TIMEOUT,
"health_check_interval": self.HEALTH_CHECK_INTERVAL,
"socket_keepalive_options": _tcp_keepalive_options(),
}
for name, value in defaults.items():
if not connection_kwargs.get(name):
connection_kwargs[name] = value
connection_kwargs["socket_keepalive"] = True

# A connection the caller already opened keeps the settings it was built
# with, so drop those and let the pool build new ones.
pool.reset()

def _connect_to_redis(
self,
host: str,
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "modelq"
version = "1.0.21"
version = "1.0.22"
description = "Celery-like task queue for ML inference."
authors = ["Tanmaypatil123 <tanmay@modelslab.com>"]
readme = "README.md"
Expand Down
74 changes: 74 additions & 0 deletions tests/test_connection_liveness.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@

import fakeredis
import pytest
import redis
import redis.backoff
import redis.retry

from modelq import ModelQ
from modelq.app.base import _tcp_keepalive_options
Expand Down Expand Up @@ -88,6 +91,77 @@ def test_connection_pool_enables_half_open_detection():
assert kwargs["retry_on_timeout"] is True


# redis-py < 7 (what the GPU servers run) leaves these unset; 8.x defaults
# them to 5 s. Spell the old defaults out so the tests mean the same thing on
# whichever redis-py CI installs.
_UNSET = dict(socket_timeout=None, socket_connect_timeout=None, socket_keepalive=None, health_check_interval=0)


def _caller_built_modelq(client):
with patch.object(ModelQ, "register_server"):
return ModelQ(redis_client=client)


def test_caller_built_client_gets_half_open_detection():
"""Servers pass their own Redis(...), which skips _connect_to_redis()."""
client = redis.Redis(host="redis.invalid", port=6379, **_UNSET)

_caller_built_modelq(client)

kwargs = client.connection_pool.connection_kwargs
assert kwargs["socket_timeout"] == ModelQ.SOCKET_TIMEOUT
assert kwargs["socket_connect_timeout"] == ModelQ.SOCKET_CONNECT_TIMEOUT
assert kwargs["health_check_interval"] == ModelQ.HEALTH_CHECK_INTERVAL
assert kwargs["socket_keepalive"] is True


def test_caller_built_client_keeps_its_own_values():
client = redis.Redis(host="redis.invalid", socket_timeout=120, health_check_interval=5)

_caller_built_modelq(client)

kwargs = client.connection_pool.connection_kwargs
assert kwargs["socket_timeout"] == 120
assert kwargs["health_check_interval"] == 5


def test_unix_socket_client_is_left_alone():
client = redis.Redis(unix_socket_path="/tmp/modelq-test.sock")
before = dict(client.connection_pool.connection_kwargs)

_caller_built_modelq(client)

assert client.connection_pool.connection_kwargs == before


def test_blocking_read_on_a_silent_socket_raises_instead_of_parking():
"""The outage itself: the peer accepts, then never answers."""
silent = socket.socket()
silent.bind(("127.0.0.1", 0))
silent.listen(8)
# No client-side retries: redis-py 8 retries a timed-out read 10 times with
# backoff (~28 s), which would outlast the join without proving anything.
no_retry = redis.retry.Retry(redis.backoff.NoBackoff(), 0)
client = redis.Redis(host="127.0.0.1", port=silent.getsockname()[1], retry=no_retry, **_UNSET)
outcome = {}

def read():
try:
client.blpop("ml_tasks", timeout=1)
except redis.exceptions.TimeoutError as exc:
outcome["raised"] = exc

with patch.object(ModelQ, "SOCKET_TIMEOUT", 0.2):
_caller_built_modelq(client)
reader = threading.Thread(target=read, daemon=True)
reader.start()
reader.join(timeout=5)

silent.close()
assert not reader.is_alive(), "the read parked on a silent socket"
assert "raised" in outcome


def test_keepalive_options_are_valid_for_this_platform():
"""Every key must be a real socket constant, or the pool raises at connect."""
options = _tcp_keepalive_options()
Expand Down
Loading