Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

fix(tests): retry owned_redis on a port already served in the target namespace (#46019)

devin-ai-integration[bot]c94e9a1adbc1
diff --git a/tests/integration/_support/redis_process.py b/tests/integration/_support/redis_process.py
index 7966d105302..e5258fbda02 100644
--- a/tests/integration/_support/redis_process.py
+++ b/tests/integration/_support/redis_process.py
@@ -5,7 +5,7 @@ import socket
import subprocess
import time
import uuid
-from collections.abc import Iterator
+from collections.abc import Callable, Iterator
from contextlib import contextmanager
from dataclasses import dataclass
from pathlib import Path
@@ -14,6 +14,19 @@ from typing import Final, TextIO
from redis import Redis
from redis.exceptions import ConnectionError as RedisConnectionError
+PORT_ATTEMPTS: Final = 5
+
+
+@dataclass(frozen=True, slots=True)
+class PortUnavailable:
+ reason: str
+
+
+def free_loopback_port() -> int:
+ with socket.socket() as reservation:
+ reservation.bind(("127.0.0.1", 0))
+ return reservation.getsockname()[1]
+
@dataclass
class OwnedRedis:
@@ -32,21 +45,54 @@ class OwnedRedis:
except RedisConnectionError:
return False
+ def owned_pid(self) -> int | None:
+ assert self.process is not None
+ if self.command[0] != "docker":
+ return self.process.pid
+ result: Final = subprocess.run(
+ ["docker", "exec", "redis-cache", "cat", self.pid_file],
+ capture_output=True,
+ text=True,
+ timeout=2,
+ )
+ if result.returncode != 0:
+ return None
+ return int(result.stdout)
+
def start(self) -> None:
+ unavailable: Final = self.try_start()
+ assert unavailable is None, unavailable.reason
+
+ def try_start(self) -> PortUnavailable | None:
assert self.process is None
- assert not self.serves(), f"Another Redis already serves {self.host}:{self.port} before the owned one starts"
- self.process = subprocess.Popen(self.command, stdout=self.log, stderr=subprocess.STDOUT, start_new_session=True)
+ if self.serves():
+ return PortUnavailable(f"Another Redis already serves {self.host}:{self.port} before the owned one starts")
+ process: Final = subprocess.Popen(
+ self.command, stdout=self.log, stderr=subprocess.STDOUT, start_new_session=True
+ )
+ self.process = process
deadline: Final = time.monotonic() + 8
with Redis(host=self.host, port=self.port, socket_connect_timeout=0.2, socket_timeout=0.2) as client:
while True:
- assert self.process.poll() is None, "Owned Redis exited before readiness"
+ code: Final = process.poll()
+ if code is not None:
+ self.process = None
+ return PortUnavailable(
+ f"Owned Redis exited with code {code} before readiness on {self.host}:{self.port}"
+ )
try:
if client.ping():
actual: Final = int(client.info("server")["process_id"])
- expected: Final = self.process.pid if self.command[0] != "docker" else int(subprocess.check_output(["docker", "exec", "redis-cache", "cat", self.pid_file], timeout=2))
- assert actual == expected, "Redis readiness reached a different process"
- self.server_pid = actual
- return
+ expected: Final = self.owned_pid()
+ if actual == expected:
+ self.server_pid = actual
+ return None
+ try:
+ process.wait(timeout=max(deadline - time.monotonic(), 0))
+ except subprocess.TimeoutExpired as error:
+ raise AssertionError("Redis readiness reached a different process") from error
+ self.process = None
+ return PortUnavailable(f"A different Redis answered on {self.host}:{self.port} during startup")
except RedisConnectionError:
pass
assert time.monotonic() < deadline, "Owned Redis readiness deadline exceeded"
@@ -59,7 +105,9 @@ class OwnedRedis:
try:
if self.process.poll() is None:
with Redis(host=self.host, port=self.port, socket_connect_timeout=1, socket_timeout=1) as client:
- assert int(client.info("server")["process_id"]) == self.server_pid, "Redis ownership changed before shutdown"
+ assert int(client.info("server")["process_id"]) == self.server_pid, (
+ "Redis ownership changed before shutdown"
+ )
client.shutdown(nosave=True)
except Exception as error:
failure = error
@@ -85,32 +133,84 @@ class OwnedRedis:
self.process.send_signal(action)
return
pid: Final = int(subprocess.check_output(["docker", "exec", "redis-cache", "cat", self.pid_file], timeout=2))
- command: Final = subprocess.check_output(["docker", "exec", "redis-cache", "cat", f"/proc/{pid}/cmdline"], timeout=2)
+ command: Final = subprocess.check_output(
+ ["docker", "exec", "redis-cache", "cat", f"/proc/{pid}/cmdline"], timeout=2
+ )
assert self.pid_file.encode() in command, "Redis process ownership changed"
subprocess.run(["docker", "exec", "redis-cache", "kill", f"-{int(action)}", str(pid)], check=True, timeout=2)
@contextmanager
-def owned_redis(directory: Path) -> Iterator[OwnedRedis]:
+def _started(
+ build: Callable[[int], OwnedRedis],
+ choose_port: Callable[[], int],
+ attempts: int,
+ log_name: str,
+) -> Iterator[OwnedRedis]:
+ server: Final = build(choose_port())
+ try:
+ unavailable: Final = server.try_start()
+ if unavailable is None:
+ yield server
+ return
+ assert attempts > 1, (
+ f"Owned Redis found no usable port after {PORT_ATTEMPTS} attempts: {unavailable.reason} (log {log_name})"
+ )
+ with _started(build, choose_port, attempts - 1, log_name) as started:
+ yield started
+ finally:
+ if server.process is not None:
+ server.stop()
+
+
+@contextmanager
+def owned_redis(directory: Path, choose_port: Callable[[], int] = free_loopback_port) -> Iterator[OwnedRedis]:
binary: Final = shutil.which("redis-server")
- with socket.socket() as reservation:
- reservation.bind(("127.0.0.1", 0))
- port: Final = reservation.getsockname()[1]
if binary:
- host = "127.0.0.1"
- prefix = (binary,)
+ host: Final = "127.0.0.1"
+ prefix: Final = (binary,)
else:
- host = subprocess.check_output(["docker", "inspect", "--format", "{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}", "redis-cache"], text=True).strip()
+ host: Final = subprocess.check_output(
+ [
+ "docker",
+ "inspect",
+ "--format",
+ "{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}",
+ "redis-cache",
+ ],
+ text=True,
+ ).strip()
assert host, "CircleCI owned Redis container has no address"
- prefix = ("docker", "exec", "redis-cache", "redis-server")
+ prefix: Final = ("docker", "exec", "redis-cache", "redis-server")
output: Final = Path(os.environ.get("INTEGRATION_RESULTS_DIR", str(directory)))
output.mkdir(parents=True, exist_ok=True)
+ directory.mkdir(parents=True, exist_ok=True)
with (output / f"owned-redis-{uuid.uuid4().hex}.log").open("w") as log:
- pid_file: Final = str(directory / "owned-redis.pid") if binary else f"/tmp/integration-redis-{uuid.uuid4().hex}.pid"
- server: Final = OwnedRedis(host, port, (*prefix, "--port", str(port), "--set-proc-title", "no", "--pidfile", pid_file, "--bind", "0.0.0.0" if not binary else "127.0.0.1", "--protected-mode", "no", "--save", "", "--appendonly", "no"), log, pid_file)
- try:
- server.start()
+
+ def build(port: int) -> OwnedRedis:
+ pid_file: Final = (
+ str(directory / f"owned-redis-{port}.pid")
+ if binary
+ else f"/tmp/integration-redis-{uuid.uuid4().hex}.pid"
+ )
+ command: Final = (
+ *prefix,
+ "--port",
+ str(port),
+ "--set-proc-title",
+ "no",
+ "--pidfile",
+ pid_file,
+ "--bind",
+ "0.0.0.0" if not binary else "127.0.0.1",
+ "--protected-mode",
+ "no",
+ "--save",
+ "",
+ "--appendonly",
+ "no",
+ )
+ return OwnedRedis(host, port, command, log, pid_file)
+
+ with _started(build, choose_port, PORT_ATTEMPTS, log.name) as server:
yield server
- finally:
- if server.process is not None:
- server.stop()
diff --git a/tests/integration/sdk/test_owned_redis_ports.py b/tests/integration/sdk/test_owned_redis_ports.py
new file mode 100644
index 00000000000..0212329b7b7
--- /dev/null
+++ b/tests/integration/sdk/test_owned_redis_ports.py
@@ -0,0 +1,56 @@
+from __future__ import annotations
+
+import re
+from itertools import chain
+from pathlib import Path
+from typing import Final
+
+import pytest
+from integration._support.redis_process import PORT_ATTEMPTS, free_loopback_port, owned_redis
+from redis import Redis
+
+
+def _redis_pid(host: str, port: int) -> int:
+ with Redis(host=host, port=port) as client:
+ return int(client.info("server")["process_id"])
+
+
+def test_owned_redis_moves_off_a_port_another_owned_redis_already_serves(tmp_path: Path) -> None:
+ with owned_redis(tmp_path / "first") as first:
+ candidates: Final = chain((first.port,), iter(free_loopback_port, None))
+ with owned_redis(tmp_path / "second", lambda: next(candidates)) as second:
+ assert second.port != first.port
+ assert first.serves()
+ assert second.serves()
+ assert second.server_pid != first.server_pid
+ assert _redis_pid(second.host, second.port) == second.server_pid
+ assert _redis_pid(first.host, first.port) == first.server_pid
+ assert not second.serves()
+ assert first.serves()
+
+
+def test_owned_redis_restart_refuses_a_port_another_redis_took_while_it_was_down(tmp_path: Path) -> None:
+ with owned_redis(tmp_path / "first") as first:
+ first.stop()
+ with owned_redis(tmp_path / "squatter", lambda: first.port) as squatter:
+ with pytest.raises(
+ AssertionError, match=f"Another Redis already serves {re.escape(first.host)}:{first.port}"
+ ):
+ first.start()
+ assert first.process is None
+ assert _redis_pid(squatter.host, squatter.port) == squatter.server_pid
+
+
+def test_owned_redis_gives_up_with_the_last_cause_after_a_bounded_number_of_ports(tmp_path: Path) -> None:
+ with owned_redis(tmp_path / "first") as first:
+ ports: Final = iter((first.port,) * PORT_ATTEMPTS)
+ with pytest.raises(
+ AssertionError,
+ match=(
+ f"after {PORT_ATTEMPTS} attempts: Another Redis already serves {re.escape(first.host)}:{first.port}"
+ ),
+ ):
+ with owned_redis(tmp_path / "second", lambda: next(ports)):
+ pytest.fail("Owned Redis unexpectedly reused a port already serving Redis")
+ assert next(ports, None) is None
+ assert first.serves()