jwadow commited on
Commit ·
da0a4de
1
Parent(s): 079364d
refactor: improve timeout handling and logging in http_client and streaming
Browse files- .env.example +1 -1
- CONTRIBUTORS.md +1 -1
- kiro_gateway/config.py +32 -0
- kiro_gateway/http_client.py +96 -66
- kiro_gateway/streaming.py +14 -4
- main.py +30 -26
- tests/README.md +69 -17
- tests/unit/test_config.py +147 -43
- tests/unit/test_http_client.py +224 -178
- tests/unit/test_streaming.py +322 -2
.env.example
CHANGED
|
@@ -52,7 +52,7 @@ KIRO_CREDS_FILE="~/.aws/sso/cache/kiro-auth-token.json"
|
|
| 52 |
# Timeout for waiting for the first token from the model (in seconds).
|
| 53 |
# If the model doesn't respond within this time, the request will be cancelled and retried.
|
| 54 |
# This helps handle "stuck" requests when the model takes too long to start responding.
|
| 55 |
-
# Default:
|
| 56 |
# Set a lower value (e.g., 5-10) for more aggressive retry behavior.
|
| 57 |
# FIRST_TOKEN_TIMEOUT="15"
|
| 58 |
|
|
|
|
| 52 |
# Timeout for waiting for the first token from the model (in seconds).
|
| 53 |
# If the model doesn't respond within this time, the request will be cancelled and retried.
|
| 54 |
# This helps handle "stuck" requests when the model takes too long to start responding.
|
| 55 |
+
# Default: 15 seconds (recommended for production)
|
| 56 |
# Set a lower value (e.g., 5-10) for more aggressive retry behavior.
|
| 57 |
# FIRST_TOKEN_TIMEOUT="15"
|
| 58 |
|
CONTRIBUTORS.md
CHANGED
|
@@ -4,4 +4,4 @@ Thank you to all the contributors who have helped improve this project!
|
|
| 4 |
|
| 5 |
## Contributors
|
| 6 |
|
| 7 |
-
- [Kartvya69](https://github.com/Kartvya69)
|
|
|
|
| 4 |
|
| 5 |
## Contributors
|
| 6 |
|
| 7 |
+
- [@Kartvya69](https://github.com/Kartvya69) — STREAMING_READ_TIMEOUT feature (#9)
|
kiro_gateway/config.py
CHANGED
|
@@ -295,6 +295,38 @@ def _warn_deprecated_debug_setting():
|
|
| 295 |
"""
|
| 296 |
print(warning_text, file=sys.stderr)
|
| 297 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 298 |
# ==================================================================================================
|
| 299 |
# Application Version
|
| 300 |
# ==================================================================================================
|
|
|
|
| 295 |
"""
|
| 296 |
print(warning_text, file=sys.stderr)
|
| 297 |
|
| 298 |
+
|
| 299 |
+
def _warn_timeout_configuration():
|
| 300 |
+
"""
|
| 301 |
+
Print warning if timeout configuration is suboptimal.
|
| 302 |
+
Called at application startup.
|
| 303 |
+
|
| 304 |
+
FIRST_TOKEN_TIMEOUT should be less than STREAMING_READ_TIMEOUT:
|
| 305 |
+
- FIRST_TOKEN_TIMEOUT: time to wait for model to START responding
|
| 306 |
+
- STREAMING_READ_TIMEOUT: time to wait BETWEEN chunks during streaming
|
| 307 |
+
"""
|
| 308 |
+
if FIRST_TOKEN_TIMEOUT >= STREAMING_READ_TIMEOUT:
|
| 309 |
+
import sys
|
| 310 |
+
YELLOW = "\033[93m"
|
| 311 |
+
RESET = "\033[0m"
|
| 312 |
+
|
| 313 |
+
warning_text = f"""
|
| 314 |
+
{YELLOW}⚠️ WARNING: Suboptimal timeout configuration detected.
|
| 315 |
+
|
| 316 |
+
FIRST_TOKEN_TIMEOUT ({FIRST_TOKEN_TIMEOUT}s) >= STREAMING_READ_TIMEOUT ({STREAMING_READ_TIMEOUT}s)
|
| 317 |
+
|
| 318 |
+
These timeouts serve different purposes:
|
| 319 |
+
- FIRST_TOKEN_TIMEOUT: time to wait for model to START responding (default: 15s)
|
| 320 |
+
- STREAMING_READ_TIMEOUT: time to wait BETWEEN chunks during streaming (default: 300s)
|
| 321 |
+
|
| 322 |
+
Recommendation: FIRST_TOKEN_TIMEOUT should be LESS than STREAMING_READ_TIMEOUT.
|
| 323 |
+
|
| 324 |
+
Example configuration:
|
| 325 |
+
FIRST_TOKEN_TIMEOUT=15
|
| 326 |
+
STREAMING_READ_TIMEOUT=300{RESET}
|
| 327 |
+
"""
|
| 328 |
+
print(warning_text, file=sys.stderr)
|
| 329 |
+
|
| 330 |
# ==================================================================================================
|
| 331 |
# Application Version
|
| 332 |
# ==================================================================================================
|
kiro_gateway/http_client.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
# -*- coding: utf-8 -*-
|
| 2 |
|
| 3 |
# Kiro OpenAI Gateway
|
|
|
|
| 4 |
# Copyright (C) 2025 Jwadow
|
| 5 |
#
|
| 6 |
# This program is free software: you can redistribute it and/or modify
|
|
@@ -17,13 +18,13 @@
|
|
| 17 |
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
| 18 |
|
| 19 |
"""
|
| 20 |
-
HTTP
|
| 21 |
|
| 22 |
-
|
| 23 |
-
- 403:
|
| 24 |
- 429: exponential backoff
|
| 25 |
- 5xx: exponential backoff
|
| 26 |
-
-
|
| 27 |
"""
|
| 28 |
|
| 29 |
import asyncio
|
|
@@ -33,23 +34,23 @@ import httpx
|
|
| 33 |
from fastapi import HTTPException
|
| 34 |
from loguru import logger
|
| 35 |
|
| 36 |
-
from kiro_gateway.config import MAX_RETRIES, BASE_RETRY_DELAY,
|
| 37 |
from kiro_gateway.auth import KiroAuthManager
|
| 38 |
from kiro_gateway.utils import get_kiro_headers
|
| 39 |
|
| 40 |
|
| 41 |
class KiroHttpClient:
|
| 42 |
"""
|
| 43 |
-
HTTP
|
| 44 |
|
| 45 |
-
|
| 46 |
-
- 403:
|
| 47 |
-
- 429:
|
| 48 |
-
- 5xx:
|
| 49 |
-
-
|
| 50 |
Attributes:
|
| 51 |
-
auth_manager:
|
| 52 |
-
client: HTTP
|
| 53 |
|
| 54 |
Example:
|
| 55 |
>>> client = KiroHttpClient(auth_manager)
|
|
@@ -63,43 +64,57 @@ class KiroHttpClient:
|
|
| 63 |
|
| 64 |
def __init__(self, auth_manager: KiroAuthManager):
|
| 65 |
"""
|
| 66 |
-
|
| 67 |
|
| 68 |
Args:
|
| 69 |
-
auth_manager:
|
| 70 |
"""
|
| 71 |
self.auth_manager = auth_manager
|
| 72 |
self.client: Optional[httpx.AsyncClient] = None
|
| 73 |
|
| 74 |
-
async def _get_client(self,
|
| 75 |
"""
|
| 76 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
|
| 78 |
Args:
|
| 79 |
-
|
| 80 |
-
stream: Если True, использует отдельный read timeout для streaming
|
| 81 |
|
| 82 |
Returns:
|
| 83 |
-
|
| 84 |
"""
|
| 85 |
if self.client is None or self.client.is_closed:
|
| 86 |
if stream:
|
| 87 |
-
# For streaming:
|
| 88 |
-
#
|
| 89 |
-
#
|
|
|
|
| 90 |
timeout_config = httpx.Timeout(
|
| 91 |
-
connect=
|
| 92 |
-
read=STREAMING_READ_TIMEOUT,
|
| 93 |
-
write=30.0,
|
| 94 |
-
pool=30.0
|
| 95 |
)
|
|
|
|
| 96 |
else:
|
| 97 |
-
|
|
|
|
|
|
|
|
|
|
| 98 |
self.client = httpx.AsyncClient(timeout=timeout_config, follow_redirects=True)
|
| 99 |
return self.client
|
| 100 |
|
| 101 |
async def close(self) -> None:
|
| 102 |
-
"""
|
| 103 |
if self.client and not self.client.is_closed:
|
| 104 |
await self.client.aclose()
|
| 105 |
|
|
@@ -108,46 +123,42 @@ class KiroHttpClient:
|
|
| 108 |
method: str,
|
| 109 |
url: str,
|
| 110 |
json_data: dict,
|
| 111 |
-
stream: bool = False
|
| 112 |
-
first_token_timeout: float = None
|
| 113 |
) -> httpx.Response:
|
| 114 |
"""
|
| 115 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
- 429: ждёт с exponential backoff (1s, 2s, 4s)
|
| 120 |
-
- 5xx: ждёт с exponential backoff
|
| 121 |
-
- Таймауты: ждёт с exponential backoff (для streaming - retry при first token timeout)
|
| 122 |
|
| 123 |
Args:
|
| 124 |
-
method: HTTP
|
| 125 |
-
url:
|
| 126 |
-
json_data:
|
| 127 |
-
stream:
|
| 128 |
-
first_token_timeout: Таймаут ожидания первого ответа для streaming (секунды).
|
| 129 |
-
Если None, используется FIRST_TOKEN_TIMEOUT из config.
|
| 130 |
|
| 131 |
Returns:
|
| 132 |
-
httpx.Response
|
| 133 |
|
| 134 |
Raises:
|
| 135 |
-
HTTPException:
|
| 136 |
"""
|
| 137 |
-
#
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
max_retries = FIRST_TOKEN_MAX_RETRIES
|
| 141 |
-
else:
|
| 142 |
-
timeout = 300
|
| 143 |
-
max_retries = MAX_RETRIES
|
| 144 |
|
| 145 |
-
client = await self._get_client(
|
| 146 |
last_error = None
|
| 147 |
|
| 148 |
for attempt in range(max_retries):
|
| 149 |
try:
|
| 150 |
-
#
|
| 151 |
token = await self.auth_manager.get_access_token()
|
| 152 |
headers = get_kiro_headers(self.auth_manager, token)
|
| 153 |
|
|
@@ -157,41 +168,60 @@ class KiroHttpClient:
|
|
| 157 |
else:
|
| 158 |
response = await client.request(method, url, json=json_data, headers=headers)
|
| 159 |
|
| 160 |
-
#
|
| 161 |
if response.status_code == 200:
|
| 162 |
return response
|
| 163 |
|
| 164 |
-
# 403 -
|
| 165 |
if response.status_code == 403:
|
| 166 |
logger.warning(f"Received 403, refreshing token (attempt {attempt + 1}/{MAX_RETRIES})")
|
| 167 |
await self.auth_manager.force_refresh()
|
| 168 |
continue
|
| 169 |
|
| 170 |
-
# 429 - rate limit,
|
| 171 |
if response.status_code == 429:
|
| 172 |
delay = BASE_RETRY_DELAY * (2 ** attempt)
|
| 173 |
logger.warning(f"Received 429, waiting {delay}s (attempt {attempt + 1}/{MAX_RETRIES})")
|
| 174 |
await asyncio.sleep(delay)
|
| 175 |
continue
|
| 176 |
|
| 177 |
-
# 5xx -
|
| 178 |
if 500 <= response.status_code < 600:
|
| 179 |
delay = BASE_RETRY_DELAY * (2 ** attempt)
|
| 180 |
logger.warning(f"Received {response.status_code}, waiting {delay}s (attempt {attempt + 1}/{MAX_RETRIES})")
|
| 181 |
await asyncio.sleep(delay)
|
| 182 |
continue
|
| 183 |
|
| 184 |
-
#
|
| 185 |
return response
|
| 186 |
|
| 187 |
except httpx.TimeoutException as e:
|
| 188 |
last_error = e
|
|
|
|
|
|
|
|
|
|
| 189 |
if stream:
|
| 190 |
-
#
|
| 191 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 192 |
else:
|
| 193 |
delay = BASE_RETRY_DELAY * (2 ** attempt)
|
| 194 |
-
logger.warning(
|
|
|
|
|
|
|
| 195 |
await asyncio.sleep(delay)
|
| 196 |
|
| 197 |
except httpx.RequestError as e:
|
|
@@ -200,11 +230,11 @@ class KiroHttpClient:
|
|
| 200 |
logger.warning(f"Request error: {e}, waiting {delay}s (attempt {attempt + 1}/{max_retries})")
|
| 201 |
await asyncio.sleep(delay)
|
| 202 |
|
| 203 |
-
#
|
| 204 |
if stream:
|
| 205 |
raise HTTPException(
|
| 206 |
status_code=504,
|
| 207 |
-
detail=f"
|
| 208 |
)
|
| 209 |
else:
|
| 210 |
raise HTTPException(
|
|
@@ -213,9 +243,9 @@ class KiroHttpClient:
|
|
| 213 |
)
|
| 214 |
|
| 215 |
async def __aenter__(self) -> "KiroHttpClient":
|
| 216 |
-
"""
|
| 217 |
return self
|
| 218 |
|
| 219 |
async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
|
| 220 |
-
"""
|
| 221 |
await self.close()
|
|
|
|
| 1 |
# -*- coding: utf-8 -*-
|
| 2 |
|
| 3 |
# Kiro OpenAI Gateway
|
| 4 |
+
# https://github.com/jwadow/kiro-openai-gateway
|
| 5 |
# Copyright (C) 2025 Jwadow
|
| 6 |
#
|
| 7 |
# This program is free software: you can redistribute it and/or modify
|
|
|
|
| 18 |
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
| 19 |
|
| 20 |
"""
|
| 21 |
+
HTTP client for Kiro API with retry logic support.
|
| 22 |
|
| 23 |
+
Handles:
|
| 24 |
+
- 403: automatic token refresh and retry
|
| 25 |
- 429: exponential backoff
|
| 26 |
- 5xx: exponential backoff
|
| 27 |
+
- Timeouts: exponential backoff
|
| 28 |
"""
|
| 29 |
|
| 30 |
import asyncio
|
|
|
|
| 34 |
from fastapi import HTTPException
|
| 35 |
from loguru import logger
|
| 36 |
|
| 37 |
+
from kiro_gateway.config import MAX_RETRIES, BASE_RETRY_DELAY, FIRST_TOKEN_MAX_RETRIES, STREAMING_READ_TIMEOUT
|
| 38 |
from kiro_gateway.auth import KiroAuthManager
|
| 39 |
from kiro_gateway.utils import get_kiro_headers
|
| 40 |
|
| 41 |
|
| 42 |
class KiroHttpClient:
|
| 43 |
"""
|
| 44 |
+
HTTP client for Kiro API with retry logic support.
|
| 45 |
|
| 46 |
+
Automatically handles errors and retries requests:
|
| 47 |
+
- 403: refreshes token and retries
|
| 48 |
+
- 429: waits with exponential backoff
|
| 49 |
+
- 5xx: waits with exponential backoff
|
| 50 |
+
- Timeouts: waits with exponential backoff
|
| 51 |
Attributes:
|
| 52 |
+
auth_manager: Authentication manager for obtaining tokens
|
| 53 |
+
client: httpx HTTP client
|
| 54 |
|
| 55 |
Example:
|
| 56 |
>>> client = KiroHttpClient(auth_manager)
|
|
|
|
| 64 |
|
| 65 |
def __init__(self, auth_manager: KiroAuthManager):
|
| 66 |
"""
|
| 67 |
+
Initializes the HTTP client.
|
| 68 |
|
| 69 |
Args:
|
| 70 |
+
auth_manager: Authentication manager
|
| 71 |
"""
|
| 72 |
self.auth_manager = auth_manager
|
| 73 |
self.client: Optional[httpx.AsyncClient] = None
|
| 74 |
|
| 75 |
+
async def _get_client(self, stream: bool = False) -> httpx.AsyncClient:
|
| 76 |
"""
|
| 77 |
+
Returns or creates an HTTP client with proper timeouts.
|
| 78 |
+
|
| 79 |
+
httpx timeouts:
|
| 80 |
+
- connect: TCP handshake (DNS + TCP SYN/ACK)
|
| 81 |
+
- read: waiting for data from server between chunks
|
| 82 |
+
- write: sending data to server
|
| 83 |
+
- pool: waiting for free connection from pool
|
| 84 |
+
|
| 85 |
+
IMPORTANT: FIRST_TOKEN_TIMEOUT is NOT used here!
|
| 86 |
+
It is applied in streaming.py via asyncio.wait_for() to control
|
| 87 |
+
the wait time for the first token from the model (retry business logic).
|
| 88 |
|
| 89 |
Args:
|
| 90 |
+
stream: If True, uses STREAMING_READ_TIMEOUT for read
|
|
|
|
| 91 |
|
| 92 |
Returns:
|
| 93 |
+
Active HTTP client
|
| 94 |
"""
|
| 95 |
if self.client is None or self.client.is_closed:
|
| 96 |
if stream:
|
| 97 |
+
# For streaming:
|
| 98 |
+
# - connect: 30 sec (TCP connection, usually < 1 sec)
|
| 99 |
+
# - read: STREAMING_READ_TIMEOUT (300 sec) - model may "think" between chunks
|
| 100 |
+
# - write/pool: standard values
|
| 101 |
timeout_config = httpx.Timeout(
|
| 102 |
+
connect=30.0,
|
| 103 |
+
read=STREAMING_READ_TIMEOUT,
|
| 104 |
+
write=30.0,
|
| 105 |
+
pool=30.0
|
| 106 |
)
|
| 107 |
+
logger.debug(f"Creating streaming HTTP client (read_timeout={STREAMING_READ_TIMEOUT}s)")
|
| 108 |
else:
|
| 109 |
+
# For regular requests: single timeout of 300 sec
|
| 110 |
+
timeout_config = httpx.Timeout(timeout=300.0)
|
| 111 |
+
logger.debug("Creating non-streaming HTTP client (timeout=300s)")
|
| 112 |
+
|
| 113 |
self.client = httpx.AsyncClient(timeout=timeout_config, follow_redirects=True)
|
| 114 |
return self.client
|
| 115 |
|
| 116 |
async def close(self) -> None:
|
| 117 |
+
"""Closes the HTTP client."""
|
| 118 |
if self.client and not self.client.is_closed:
|
| 119 |
await self.client.aclose()
|
| 120 |
|
|
|
|
| 123 |
method: str,
|
| 124 |
url: str,
|
| 125 |
json_data: dict,
|
| 126 |
+
stream: bool = False
|
|
|
|
| 127 |
) -> httpx.Response:
|
| 128 |
"""
|
| 129 |
+
Executes an HTTP request with retry logic.
|
| 130 |
+
|
| 131 |
+
Automatically handles various error types:
|
| 132 |
+
- 403: refreshes token via auth_manager.force_refresh() and retries
|
| 133 |
+
- 429: waits with exponential backoff (1s, 2s, 4s)
|
| 134 |
+
- 5xx: waits with exponential backoff
|
| 135 |
+
- Timeouts: waits with exponential backoff
|
| 136 |
|
| 137 |
+
For streaming, STREAMING_READ_TIMEOUT is used for waiting between chunks.
|
| 138 |
+
First token timeout is controlled separately in streaming.py via asyncio.wait_for().
|
|
|
|
|
|
|
|
|
|
| 139 |
|
| 140 |
Args:
|
| 141 |
+
method: HTTP method (GET, POST, etc.)
|
| 142 |
+
url: Request URL
|
| 143 |
+
json_data: Request body (JSON)
|
| 144 |
+
stream: Use streaming (default False)
|
|
|
|
|
|
|
| 145 |
|
| 146 |
Returns:
|
| 147 |
+
httpx.Response with successful response
|
| 148 |
|
| 149 |
Raises:
|
| 150 |
+
HTTPException: On failure after all attempts (502/504)
|
| 151 |
"""
|
| 152 |
+
# Determine the number of retry attempts
|
| 153 |
+
# FIRST_TOKEN_TIMEOUT is used in streaming.py, not here
|
| 154 |
+
max_retries = FIRST_TOKEN_MAX_RETRIES if stream else MAX_RETRIES
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
|
| 156 |
+
client = await self._get_client(stream=stream)
|
| 157 |
last_error = None
|
| 158 |
|
| 159 |
for attempt in range(max_retries):
|
| 160 |
try:
|
| 161 |
+
# Get current token
|
| 162 |
token = await self.auth_manager.get_access_token()
|
| 163 |
headers = get_kiro_headers(self.auth_manager, token)
|
| 164 |
|
|
|
|
| 168 |
else:
|
| 169 |
response = await client.request(method, url, json=json_data, headers=headers)
|
| 170 |
|
| 171 |
+
# Check status
|
| 172 |
if response.status_code == 200:
|
| 173 |
return response
|
| 174 |
|
| 175 |
+
# 403 - token expired, refresh and retry
|
| 176 |
if response.status_code == 403:
|
| 177 |
logger.warning(f"Received 403, refreshing token (attempt {attempt + 1}/{MAX_RETRIES})")
|
| 178 |
await self.auth_manager.force_refresh()
|
| 179 |
continue
|
| 180 |
|
| 181 |
+
# 429 - rate limit, wait and retry
|
| 182 |
if response.status_code == 429:
|
| 183 |
delay = BASE_RETRY_DELAY * (2 ** attempt)
|
| 184 |
logger.warning(f"Received 429, waiting {delay}s (attempt {attempt + 1}/{MAX_RETRIES})")
|
| 185 |
await asyncio.sleep(delay)
|
| 186 |
continue
|
| 187 |
|
| 188 |
+
# 5xx - server error, wait and retry
|
| 189 |
if 500 <= response.status_code < 600:
|
| 190 |
delay = BASE_RETRY_DELAY * (2 ** attempt)
|
| 191 |
logger.warning(f"Received {response.status_code}, waiting {delay}s (attempt {attempt + 1}/{MAX_RETRIES})")
|
| 192 |
await asyncio.sleep(delay)
|
| 193 |
continue
|
| 194 |
|
| 195 |
+
# Other errors - return as is
|
| 196 |
return response
|
| 197 |
|
| 198 |
except httpx.TimeoutException as e:
|
| 199 |
last_error = e
|
| 200 |
+
# Determine timeout type for logging
|
| 201 |
+
timeout_type = type(e).__name__
|
| 202 |
+
|
| 203 |
if stream:
|
| 204 |
+
# For streaming this could be:
|
| 205 |
+
# - ConnectTimeout: TCP connection issue
|
| 206 |
+
# - ReadTimeout: server not responding (STREAMING_READ_TIMEOUT)
|
| 207 |
+
if isinstance(e, httpx.ConnectTimeout):
|
| 208 |
+
logger.warning(
|
| 209 |
+
f"[{timeout_type}] Connection timeout (attempt {attempt + 1}/{max_retries})"
|
| 210 |
+
)
|
| 211 |
+
elif isinstance(e, httpx.ReadTimeout):
|
| 212 |
+
logger.warning(
|
| 213 |
+
f"[{timeout_type}] Read timeout after {STREAMING_READ_TIMEOUT}s - "
|
| 214 |
+
f"server stopped responding (attempt {attempt + 1}/{max_retries})"
|
| 215 |
+
)
|
| 216 |
+
else:
|
| 217 |
+
logger.warning(
|
| 218 |
+
f"[{timeout_type}] Timeout during streaming (attempt {attempt + 1}/{max_retries})"
|
| 219 |
+
)
|
| 220 |
else:
|
| 221 |
delay = BASE_RETRY_DELAY * (2 ** attempt)
|
| 222 |
+
logger.warning(
|
| 223 |
+
f"[{timeout_type}] Request timeout, waiting {delay}s (attempt {attempt + 1}/{max_retries})"
|
| 224 |
+
)
|
| 225 |
await asyncio.sleep(delay)
|
| 226 |
|
| 227 |
except httpx.RequestError as e:
|
|
|
|
| 230 |
logger.warning(f"Request error: {e}, waiting {delay}s (attempt {attempt + 1}/{max_retries})")
|
| 231 |
await asyncio.sleep(delay)
|
| 232 |
|
| 233 |
+
# All attempts exhausted
|
| 234 |
if stream:
|
| 235 |
raise HTTPException(
|
| 236 |
status_code=504,
|
| 237 |
+
detail=f"Streaming failed after {max_retries} attempts. Last error: {type(last_error).__name__}"
|
| 238 |
)
|
| 239 |
else:
|
| 240 |
raise HTTPException(
|
|
|
|
| 243 |
)
|
| 244 |
|
| 245 |
async def __aenter__(self) -> "KiroHttpClient":
|
| 246 |
+
"""Async context manager support."""
|
| 247 |
return self
|
| 248 |
|
| 249 |
async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
|
| 250 |
+
"""Closes the client when exiting context."""
|
| 251 |
await self.close()
|
kiro_gateway/streaming.py
CHANGED
|
@@ -114,14 +114,18 @@ async def stream_kiro_to_openai_internal(
|
|
| 114 |
# Create iterator for reading bytes
|
| 115 |
byte_iterator = response.aiter_bytes()
|
| 116 |
|
| 117 |
-
# Wait for first chunk with timeout
|
|
|
|
|
|
|
| 118 |
try:
|
|
|
|
| 119 |
first_byte_chunk = await asyncio.wait_for(
|
| 120 |
byte_iterator.__anext__(),
|
| 121 |
timeout=first_token_timeout
|
| 122 |
)
|
|
|
|
| 123 |
except asyncio.TimeoutError:
|
| 124 |
-
logger.warning(f"
|
| 125 |
raise FirstTokenTimeoutError(f"No response within {first_token_timeout} seconds")
|
| 126 |
except StopAsyncIteration:
|
| 127 |
# Empty response - this is normal, just finish
|
|
@@ -473,7 +477,10 @@ async def stream_with_first_token_retry(
|
|
| 473 |
|
| 474 |
except FirstTokenTimeoutError as e:
|
| 475 |
last_error = e
|
| 476 |
-
logger.warning(
|
|
|
|
|
|
|
|
|
|
| 477 |
|
| 478 |
# Close current response if open
|
| 479 |
if response:
|
|
@@ -496,7 +503,10 @@ async def stream_with_first_token_retry(
|
|
| 496 |
raise
|
| 497 |
|
| 498 |
# All attempts exhausted - raise HTTP error
|
| 499 |
-
logger.error(
|
|
|
|
|
|
|
|
|
|
| 500 |
raise HTTPException(
|
| 501 |
status_code=504,
|
| 502 |
detail=f"Model did not respond within {first_token_timeout}s after {max_retries} attempts. Please try again."
|
|
|
|
| 114 |
# Create iterator for reading bytes
|
| 115 |
byte_iterator = response.aiter_bytes()
|
| 116 |
|
| 117 |
+
# Wait for first chunk with timeout (FIRST_TOKEN_TIMEOUT)
|
| 118 |
+
# This is our business logic for detecting "stuck" requests
|
| 119 |
+
# where the model takes too long to start responding
|
| 120 |
try:
|
| 121 |
+
logger.debug(f"Waiting for first token (timeout={first_token_timeout}s)...")
|
| 122 |
first_byte_chunk = await asyncio.wait_for(
|
| 123 |
byte_iterator.__anext__(),
|
| 124 |
timeout=first_token_timeout
|
| 125 |
)
|
| 126 |
+
logger.debug("First token received")
|
| 127 |
except asyncio.TimeoutError:
|
| 128 |
+
logger.warning(f"[FirstTokenTimeout] Model did not respond within {first_token_timeout}s")
|
| 129 |
raise FirstTokenTimeoutError(f"No response within {first_token_timeout} seconds")
|
| 130 |
except StopAsyncIteration:
|
| 131 |
# Empty response - this is normal, just finish
|
|
|
|
| 477 |
|
| 478 |
except FirstTokenTimeoutError as e:
|
| 479 |
last_error = e
|
| 480 |
+
logger.warning(
|
| 481 |
+
f"[FirstTokenTimeout] Attempt {attempt + 1}/{max_retries} failed - "
|
| 482 |
+
f"model did not respond within {first_token_timeout}s"
|
| 483 |
+
)
|
| 484 |
|
| 485 |
# Close current response if open
|
| 486 |
if response:
|
|
|
|
| 503 |
raise
|
| 504 |
|
| 505 |
# All attempts exhausted - raise HTTP error
|
| 506 |
+
logger.error(
|
| 507 |
+
f"[FirstTokenTimeout] All {max_retries} attempts exhausted - "
|
| 508 |
+
f"model never responded within {first_token_timeout}s per attempt"
|
| 509 |
+
)
|
| 510 |
raise HTTPException(
|
| 511 |
status_code=504,
|
| 512 |
detail=f"Model did not respond within {first_token_timeout}s after {max_retries} attempts. Please try again."
|
main.py
CHANGED
|
@@ -48,6 +48,7 @@ from kiro_gateway.config import (
|
|
| 48 |
PROXY_API_KEY,
|
| 49 |
LOG_LEVEL,
|
| 50 |
_warn_deprecated_debug_setting,
|
|
|
|
| 51 |
)
|
| 52 |
from kiro_gateway.auth import KiroAuthManager
|
| 53 |
from kiro_gateway.cache import ModelInfoCache
|
|
@@ -67,20 +68,20 @@ logger.add(
|
|
| 67 |
|
| 68 |
class InterceptHandler(logging.Handler):
|
| 69 |
"""
|
| 70 |
-
|
| 71 |
|
| 72 |
-
|
| 73 |
-
|
| 74 |
"""
|
| 75 |
|
| 76 |
def emit(self, record: logging.LogRecord) -> None:
|
| 77 |
-
#
|
| 78 |
try:
|
| 79 |
level = logger.level(record.levelname).name
|
| 80 |
except ValueError:
|
| 81 |
level = record.levelno
|
| 82 |
|
| 83 |
-
#
|
| 84 |
frame, depth = logging.currentframe(), 2
|
| 85 |
while frame.f_code.co_filename == logging.__file__:
|
| 86 |
frame = frame.f_back
|
|
@@ -91,15 +92,15 @@ class InterceptHandler(logging.Handler):
|
|
| 91 |
|
| 92 |
def setup_logging_intercept():
|
| 93 |
"""
|
| 94 |
-
|
| 95 |
|
| 96 |
-
|
| 97 |
- uvicorn (access logs, error logs)
|
| 98 |
- uvicorn.error
|
| 99 |
- uvicorn.access
|
| 100 |
- fastapi
|
| 101 |
"""
|
| 102 |
-
#
|
| 103 |
loggers_to_intercept = [
|
| 104 |
"uvicorn",
|
| 105 |
"uvicorn.error",
|
|
@@ -113,7 +114,7 @@ def setup_logging_intercept():
|
|
| 113 |
logging_logger.propagate = False
|
| 114 |
|
| 115 |
|
| 116 |
-
#
|
| 117 |
setup_logging_intercept()
|
| 118 |
|
| 119 |
|
|
@@ -207,20 +208,23 @@ validate_configuration()
|
|
| 207 |
# Warn about deprecated DEBUG_LAST_REQUEST if used
|
| 208 |
_warn_deprecated_debug_setting()
|
| 209 |
|
|
|
|
|
|
|
|
|
|
| 210 |
|
| 211 |
# --- Lifespan Manager ---
|
| 212 |
@asynccontextmanager
|
| 213 |
async def lifespan(app: FastAPI):
|
| 214 |
"""
|
| 215 |
-
|
| 216 |
|
| 217 |
-
|
| 218 |
-
- KiroAuthManager
|
| 219 |
-
- ModelInfoCache
|
| 220 |
"""
|
| 221 |
logger.info("Starting application... Creating state managers.")
|
| 222 |
|
| 223 |
-
#
|
| 224 |
app.state.auth_manager = KiroAuthManager(
|
| 225 |
refresh_token=REFRESH_TOKEN,
|
| 226 |
profile_arn=PROFILE_ARN,
|
|
@@ -228,7 +232,7 @@ async def lifespan(app: FastAPI):
|
|
| 228 |
creds_file=KIRO_CREDS_FILE if KIRO_CREDS_FILE else None
|
| 229 |
)
|
| 230 |
|
| 231 |
-
#
|
| 232 |
app.state.model_cache = ModelInfoCache()
|
| 233 |
|
| 234 |
yield
|
|
@@ -236,7 +240,7 @@ async def lifespan(app: FastAPI):
|
|
| 236 |
logger.info("Shutting down application.")
|
| 237 |
|
| 238 |
|
| 239 |
-
# --- FastAPI
|
| 240 |
app = FastAPI(
|
| 241 |
title=APP_TITLE,
|
| 242 |
description=APP_DESCRIPTION,
|
|
@@ -246,28 +250,28 @@ app = FastAPI(
|
|
| 246 |
|
| 247 |
|
| 248 |
# --- CORS Middleware ---
|
| 249 |
-
#
|
| 250 |
-
#
|
| 251 |
app.add_middleware(
|
| 252 |
CORSMiddleware,
|
| 253 |
-
allow_origins=["*"], #
|
| 254 |
allow_credentials=True,
|
| 255 |
-
allow_methods=["*"], #
|
| 256 |
-
allow_headers=["*"], #
|
| 257 |
)
|
| 258 |
|
| 259 |
|
| 260 |
-
# ---
|
| 261 |
app.add_exception_handler(RequestValidationError, validation_exception_handler)
|
| 262 |
|
| 263 |
|
| 264 |
-
# ---
|
| 265 |
app.include_router(router)
|
| 266 |
|
| 267 |
|
| 268 |
# --- Uvicorn log config ---
|
| 269 |
-
#
|
| 270 |
-
#
|
| 271 |
UVICORN_LOG_CONFIG = {
|
| 272 |
"version": 1,
|
| 273 |
"disable_existing_loggers": False,
|
|
@@ -284,7 +288,7 @@ UVICORN_LOG_CONFIG = {
|
|
| 284 |
}
|
| 285 |
|
| 286 |
|
| 287 |
-
# ---
|
| 288 |
if __name__ == "__main__":
|
| 289 |
import uvicorn
|
| 290 |
logger.info("Starting Uvicorn server...")
|
|
|
|
| 48 |
PROXY_API_KEY,
|
| 49 |
LOG_LEVEL,
|
| 50 |
_warn_deprecated_debug_setting,
|
| 51 |
+
_warn_timeout_configuration,
|
| 52 |
)
|
| 53 |
from kiro_gateway.auth import KiroAuthManager
|
| 54 |
from kiro_gateway.cache import ModelInfoCache
|
|
|
|
| 68 |
|
| 69 |
class InterceptHandler(logging.Handler):
|
| 70 |
"""
|
| 71 |
+
Intercepts logs from standard logging and redirects them to loguru.
|
| 72 |
|
| 73 |
+
This allows capturing logs from uvicorn, FastAPI and other libraries
|
| 74 |
+
that use standard logging instead of loguru.
|
| 75 |
"""
|
| 76 |
|
| 77 |
def emit(self, record: logging.LogRecord) -> None:
|
| 78 |
+
# Get the corresponding loguru level
|
| 79 |
try:
|
| 80 |
level = logger.level(record.levelname).name
|
| 81 |
except ValueError:
|
| 82 |
level = record.levelno
|
| 83 |
|
| 84 |
+
# Find the caller frame for correct source display
|
| 85 |
frame, depth = logging.currentframe(), 2
|
| 86 |
while frame.f_code.co_filename == logging.__file__:
|
| 87 |
frame = frame.f_back
|
|
|
|
| 92 |
|
| 93 |
def setup_logging_intercept():
|
| 94 |
"""
|
| 95 |
+
Configures log interception from standard logging to loguru.
|
| 96 |
|
| 97 |
+
Intercepts logs from:
|
| 98 |
- uvicorn (access logs, error logs)
|
| 99 |
- uvicorn.error
|
| 100 |
- uvicorn.access
|
| 101 |
- fastapi
|
| 102 |
"""
|
| 103 |
+
# List of loggers to intercept
|
| 104 |
loggers_to_intercept = [
|
| 105 |
"uvicorn",
|
| 106 |
"uvicorn.error",
|
|
|
|
| 114 |
logging_logger.propagate = False
|
| 115 |
|
| 116 |
|
| 117 |
+
# Configure uvicorn/fastapi log interception
|
| 118 |
setup_logging_intercept()
|
| 119 |
|
| 120 |
|
|
|
|
| 208 |
# Warn about deprecated DEBUG_LAST_REQUEST if used
|
| 209 |
_warn_deprecated_debug_setting()
|
| 210 |
|
| 211 |
+
# Warn about suboptimal timeout configuration
|
| 212 |
+
_warn_timeout_configuration()
|
| 213 |
+
|
| 214 |
|
| 215 |
# --- Lifespan Manager ---
|
| 216 |
@asynccontextmanager
|
| 217 |
async def lifespan(app: FastAPI):
|
| 218 |
"""
|
| 219 |
+
Manages the application lifecycle.
|
| 220 |
|
| 221 |
+
Creates and initializes:
|
| 222 |
+
- KiroAuthManager for token management
|
| 223 |
+
- ModelInfoCache for model caching
|
| 224 |
"""
|
| 225 |
logger.info("Starting application... Creating state managers.")
|
| 226 |
|
| 227 |
+
# Create AuthManager
|
| 228 |
app.state.auth_manager = KiroAuthManager(
|
| 229 |
refresh_token=REFRESH_TOKEN,
|
| 230 |
profile_arn=PROFILE_ARN,
|
|
|
|
| 232 |
creds_file=KIRO_CREDS_FILE if KIRO_CREDS_FILE else None
|
| 233 |
)
|
| 234 |
|
| 235 |
+
# Create model cache
|
| 236 |
app.state.model_cache = ModelInfoCache()
|
| 237 |
|
| 238 |
yield
|
|
|
|
| 240 |
logger.info("Shutting down application.")
|
| 241 |
|
| 242 |
|
| 243 |
+
# --- FastAPI Application ---
|
| 244 |
app = FastAPI(
|
| 245 |
title=APP_TITLE,
|
| 246 |
description=APP_DESCRIPTION,
|
|
|
|
| 250 |
|
| 251 |
|
| 252 |
# --- CORS Middleware ---
|
| 253 |
+
# Allow CORS for all origins to support browser clients
|
| 254 |
+
# and tools that send preflight OPTIONS requests
|
| 255 |
app.add_middleware(
|
| 256 |
CORSMiddleware,
|
| 257 |
+
allow_origins=["*"], # Allow all origins
|
| 258 |
allow_credentials=True,
|
| 259 |
+
allow_methods=["*"], # Allow all methods (GET, POST, OPTIONS, etc.)
|
| 260 |
+
allow_headers=["*"], # Allow all headers
|
| 261 |
)
|
| 262 |
|
| 263 |
|
| 264 |
+
# --- Validation Error Handler Registration ---
|
| 265 |
app.add_exception_handler(RequestValidationError, validation_exception_handler)
|
| 266 |
|
| 267 |
|
| 268 |
+
# --- Route Registration ---
|
| 269 |
app.include_router(router)
|
| 270 |
|
| 271 |
|
| 272 |
# --- Uvicorn log config ---
|
| 273 |
+
# Minimal configuration for redirecting uvicorn logs to loguru.
|
| 274 |
+
# Uses InterceptHandler which intercepts logs and passes them to loguru.
|
| 275 |
UVICORN_LOG_CONFIG = {
|
| 276 |
"version": 1,
|
| 277 |
"disable_existing_loggers": False,
|
|
|
|
| 288 |
}
|
| 289 |
|
| 290 |
|
| 291 |
+
# --- Entry Point ---
|
| 292 |
if __name__ == "__main__":
|
| 293 |
import uvicorn
|
| 294 |
logger.info("Starting Uvicorn server...")
|
tests/README.md
CHANGED
|
@@ -338,7 +338,7 @@ Unit tests for **ModelInfoCache** (model metadata cache). **23 tests.**
|
|
| 338 |
|
| 339 |
### `tests/unit/test_config.py`
|
| 340 |
|
| 341 |
-
Unit tests for **configuration module** (loading settings from environment variables). **
|
| 342 |
|
| 343 |
#### `TestLogLevelConfig`
|
| 344 |
|
|
@@ -384,6 +384,26 @@ Tests for TOOL_DESCRIPTION_MAX_LENGTH configuration.
|
|
| 384 |
- **What it does**: Verifies that 0 disables the feature
|
| 385 |
- **Purpose**: Ensure TOOL_DESCRIPTION_MAX_LENGTH=0 works
|
| 386 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 387 |
---
|
| 388 |
|
| 389 |
### `tests/unit/test_debug_logger.py`
|
|
@@ -1077,7 +1097,7 @@ Integration tests for tokenizer.
|
|
| 1077 |
|
| 1078 |
### `tests/unit/test_streaming.py`
|
| 1079 |
|
| 1080 |
-
Unit tests for **streaming module** (Kiro to OpenAI format stream conversion). **
|
| 1081 |
|
| 1082 |
#### `TestStreamingToolCallsIndex`
|
| 1083 |
|
|
@@ -1153,12 +1173,40 @@ Tests for error handling in streaming module (bug #8 fix).
|
|
| 1153 |
|
| 1154 |
#### `TestFirstTokenTimeoutError`
|
| 1155 |
|
| 1156 |
-
Tests for FirstTokenTimeoutError.
|
| 1157 |
|
| 1158 |
- **`test_first_token_timeout_not_caught_by_general_handler()`**:
|
| 1159 |
- **What it does**: Verifies that FirstTokenTimeoutError is propagated for retry
|
| 1160 |
- **Purpose**: Ensure first token timeout is not handled as regular error
|
| 1161 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1162 |
---
|
| 1163 |
|
| 1164 |
### `tests/unit/test_http_client.py`
|
|
@@ -1203,13 +1251,13 @@ Unit tests for **KiroHttpClient** (HTTP client with retry logic). **29 tests.**
|
|
| 1203 |
|
| 1204 |
- **`test_backoff_delay_increases_exponentially()`**: Verifies exponential delay increase
|
| 1205 |
|
| 1206 |
-
#### `
|
| 1207 |
|
| 1208 |
-
|
| 1209 |
|
| 1210 |
-
- **`
|
| 1211 |
-
- **What it does**: Verifies that streaming requests use
|
| 1212 |
-
- **Purpose**: Ensure
|
| 1213 |
|
| 1214 |
- **`test_streaming_uses_first_token_max_retries()`**:
|
| 1215 |
- **What it does**: Verifies that streaming requests use FIRST_TOKEN_MAX_RETRIES
|
|
@@ -1217,19 +1265,23 @@ Unit tests for **KiroHttpClient** (HTTP client with retry logic). **29 tests.**
|
|
| 1217 |
|
| 1218 |
- **`test_streaming_timeout_retry_without_delay()`**:
|
| 1219 |
- **What it does**: Verifies that streaming timeout retry happens without delay
|
| 1220 |
-
- **Purpose**: Ensure no exponential backoff on
|
| 1221 |
|
| 1222 |
- **`test_non_streaming_uses_default_timeout()`**:
|
| 1223 |
-
- **What it does**: Verifies that non-streaming requests use 300
|
| 1224 |
-
- **Purpose**: Ensure
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1225 |
|
| 1226 |
-
- **`
|
| 1227 |
-
- **What it does**: Verifies
|
| 1228 |
-
- **Purpose**: Ensure
|
| 1229 |
|
| 1230 |
-
- **`
|
| 1231 |
-
- **What it does**: Verifies that streaming timeout returns 504
|
| 1232 |
-
- **Purpose**: Ensure 504 Gateway Timeout
|
| 1233 |
|
| 1234 |
- **`test_non_streaming_timeout_returns_502()`**:
|
| 1235 |
- **What it does**: Verifies that non-streaming timeout returns 502
|
|
|
|
| 338 |
|
| 339 |
### `tests/unit/test_config.py`
|
| 340 |
|
| 341 |
+
Unit tests for **configuration module** (loading settings from environment variables). **13 tests.**
|
| 342 |
|
| 343 |
#### `TestLogLevelConfig`
|
| 344 |
|
|
|
|
| 384 |
- **What it does**: Verifies that 0 disables the feature
|
| 385 |
- **Purpose**: Ensure TOOL_DESCRIPTION_MAX_LENGTH=0 works
|
| 386 |
|
| 387 |
+
#### `TestTimeoutConfigurationWarning`
|
| 388 |
+
|
| 389 |
+
Tests for `_warn_timeout_configuration()` function.
|
| 390 |
+
|
| 391 |
+
- **`test_no_warning_when_first_token_less_than_streaming()`**:
|
| 392 |
+
- **What it does**: Verifies no warning when FIRST_TOKEN_TIMEOUT < STREAMING_READ_TIMEOUT
|
| 393 |
+
- **Purpose**: Ensure correct configuration doesn't trigger warning
|
| 394 |
+
|
| 395 |
+
- **`test_warning_when_first_token_equals_streaming()`**:
|
| 396 |
+
- **What it does**: Verifies warning when FIRST_TOKEN_TIMEOUT == STREAMING_READ_TIMEOUT
|
| 397 |
+
- **Purpose**: Ensure equal timeouts trigger warning
|
| 398 |
+
|
| 399 |
+
- **`test_warning_when_first_token_greater_than_streaming()`**:
|
| 400 |
+
- **What it does**: Verifies warning when FIRST_TOKEN_TIMEOUT > STREAMING_READ_TIMEOUT
|
| 401 |
+
- **Purpose**: Ensure suboptimal configuration triggers warning with timeout values
|
| 402 |
+
|
| 403 |
+
- **`test_warning_contains_recommendation()`**:
|
| 404 |
+
- **What it does**: Verifies warning contains recommendation text
|
| 405 |
+
- **Purpose**: Ensure user gets helpful information about correct configuration
|
| 406 |
+
|
| 407 |
---
|
| 408 |
|
| 409 |
### `tests/unit/test_debug_logger.py`
|
|
|
|
| 1097 |
|
| 1098 |
### `tests/unit/test_streaming.py`
|
| 1099 |
|
| 1100 |
+
Unit tests for **streaming module** (Kiro to OpenAI format stream conversion). **23 tests.**
|
| 1101 |
|
| 1102 |
#### `TestStreamingToolCallsIndex`
|
| 1103 |
|
|
|
|
| 1173 |
|
| 1174 |
#### `TestFirstTokenTimeoutError`
|
| 1175 |
|
| 1176 |
+
Tests for FirstTokenTimeoutError and first token timeout logging.
|
| 1177 |
|
| 1178 |
- **`test_first_token_timeout_not_caught_by_general_handler()`**:
|
| 1179 |
- **What it does**: Verifies that FirstTokenTimeoutError is propagated for retry
|
| 1180 |
- **Purpose**: Ensure first token timeout is not handled as regular error
|
| 1181 |
|
| 1182 |
+
- **`test_first_token_timeout_logged_with_correct_format()`**:
|
| 1183 |
+
- **What it does**: Verifies that first token timeout is logged with [FirstTokenTimeout] prefix
|
| 1184 |
+
- **Purpose**: Ensure consistent logging format for first token timeout
|
| 1185 |
+
|
| 1186 |
+
- **`test_first_token_timeout_includes_timeout_value()`**:
|
| 1187 |
+
- **What it does**: Verifies that first token timeout log includes the timeout value
|
| 1188 |
+
- **Purpose**: Ensure timeout value is visible in logs for debugging
|
| 1189 |
+
|
| 1190 |
+
- **`test_first_token_received_logged_on_success()`**:
|
| 1191 |
+
- **What it does**: Verifies that successful first token receipt is logged
|
| 1192 |
+
- **Purpose**: Ensure debug log shows when first token is received
|
| 1193 |
+
|
| 1194 |
+
#### `TestStreamWithFirstTokenRetry`
|
| 1195 |
+
|
| 1196 |
+
Tests for stream_with_first_token_retry function.
|
| 1197 |
+
|
| 1198 |
+
- **`test_retry_on_first_token_timeout()`**:
|
| 1199 |
+
- **What it does**: Verifies that request is retried on first token timeout
|
| 1200 |
+
- **Purpose**: Ensure retry logic works for first token timeout
|
| 1201 |
+
|
| 1202 |
+
- **`test_all_retries_exhausted_raises_504()`**:
|
| 1203 |
+
- **What it does**: Verifies that 504 is raised after all retries exhausted
|
| 1204 |
+
- **Purpose**: Ensure proper error handling when model never responds
|
| 1205 |
+
|
| 1206 |
+
- **`test_retry_logs_attempt_number()`**:
|
| 1207 |
+
- **What it does**: Verifies that retry attempts are logged with attempt number
|
| 1208 |
+
- **Purpose**: Ensure logs show which attempt failed (e.g., "1/3", "2/3", "3/3")
|
| 1209 |
+
|
| 1210 |
---
|
| 1211 |
|
| 1212 |
### `tests/unit/test_http_client.py`
|
|
|
|
| 1251 |
|
| 1252 |
- **`test_backoff_delay_increases_exponentially()`**: Verifies exponential delay increase
|
| 1253 |
|
| 1254 |
+
#### `TestKiroHttpClientStreamingTimeout`
|
| 1255 |
|
| 1256 |
+
Tests for streaming timeout logic (httpx timeouts, not FIRST_TOKEN_TIMEOUT).
|
| 1257 |
|
| 1258 |
+
- **`test_streaming_uses_streaming_read_timeout()`**:
|
| 1259 |
+
- **What it does**: Verifies that streaming requests use STREAMING_READ_TIMEOUT for read timeout
|
| 1260 |
+
- **Purpose**: Ensure httpx.Timeout is configured with connect=30s and read=STREAMING_READ_TIMEOUT
|
| 1261 |
|
| 1262 |
- **`test_streaming_uses_first_token_max_retries()`**:
|
| 1263 |
- **What it does**: Verifies that streaming requests use FIRST_TOKEN_MAX_RETRIES
|
|
|
|
| 1265 |
|
| 1266 |
- **`test_streaming_timeout_retry_without_delay()`**:
|
| 1267 |
- **What it does**: Verifies that streaming timeout retry happens without delay
|
| 1268 |
+
- **Purpose**: Ensure no exponential backoff on streaming timeout
|
| 1269 |
|
| 1270 |
- **`test_non_streaming_uses_default_timeout()`**:
|
| 1271 |
+
- **What it does**: Verifies that non-streaming requests use httpx.Timeout(timeout=300)
|
| 1272 |
+
- **Purpose**: Ensure unified 300s timeout for all operations in non-streaming mode
|
| 1273 |
+
|
| 1274 |
+
- **`test_connect_timeout_logged_correctly()`**:
|
| 1275 |
+
- **What it does**: Verifies that ConnectTimeout is logged with [ConnectTimeout] prefix
|
| 1276 |
+
- **Purpose**: Ensure timeout type is visible in logs for debugging
|
| 1277 |
|
| 1278 |
+
- **`test_read_timeout_logged_correctly()`**:
|
| 1279 |
+
- **What it does**: Verifies that ReadTimeout is logged with [ReadTimeout] prefix and STREAMING_READ_TIMEOUT value
|
| 1280 |
+
- **Purpose**: Ensure timeout type and value are visible in logs
|
| 1281 |
|
| 1282 |
+
- **`test_streaming_timeout_returns_504_with_error_type()`**:
|
| 1283 |
+
- **What it does**: Verifies that streaming timeout returns 504 with error type in detail
|
| 1284 |
+
- **Purpose**: Ensure 504 Gateway Timeout includes error type (e.g., "ReadTimeout")
|
| 1285 |
|
| 1286 |
- **`test_non_streaming_timeout_returns_502()`**:
|
| 1287 |
- **What it does**: Verifies that non-streaming timeout returns 502
|
tests/unit/test_config.py
CHANGED
|
@@ -1,8 +1,8 @@
|
|
| 1 |
# -*- coding: utf-8 -*-
|
| 2 |
|
| 3 |
"""
|
| 4 |
-
Unit
|
| 5 |
-
|
| 6 |
"""
|
| 7 |
|
| 8 |
import pytest
|
|
@@ -11,49 +11,49 @@ from unittest.mock import patch
|
|
| 11 |
|
| 12 |
|
| 13 |
class TestLogLevelConfig:
|
| 14 |
-
"""
|
| 15 |
|
| 16 |
def test_default_log_level_is_info(self):
|
| 17 |
"""
|
| 18 |
-
|
| 19 |
-
|
| 20 |
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
"""
|
| 25 |
-
print("
|
| 26 |
|
| 27 |
-
#
|
| 28 |
original_getenv = os.getenv
|
| 29 |
|
| 30 |
def mock_getenv(key, default=None):
|
| 31 |
if key == "LOG_LEVEL":
|
| 32 |
-
print(f"os.getenv('{key}') -> None (
|
| 33 |
-
return default #
|
| 34 |
return original_getenv(key, default)
|
| 35 |
|
| 36 |
with patch.object(os, 'getenv', side_effect=mock_getenv):
|
| 37 |
-
#
|
| 38 |
import importlib
|
| 39 |
import kiro_gateway.config as config_module
|
| 40 |
importlib.reload(config_module)
|
| 41 |
|
| 42 |
print(f"LOG_LEVEL: {config_module.LOG_LEVEL}")
|
| 43 |
-
print(f"
|
| 44 |
assert config_module.LOG_LEVEL == "INFO"
|
| 45 |
|
| 46 |
-
#
|
| 47 |
import importlib
|
| 48 |
import kiro_gateway.config as config_module
|
| 49 |
importlib.reload(config_module)
|
| 50 |
|
| 51 |
def test_log_level_from_environment(self):
|
| 52 |
"""
|
| 53 |
-
|
| 54 |
-
|
| 55 |
"""
|
| 56 |
-
print("
|
| 57 |
|
| 58 |
with patch.dict(os.environ, {"LOG_LEVEL": "DEBUG"}):
|
| 59 |
import importlib
|
|
@@ -61,15 +61,15 @@ class TestLogLevelConfig:
|
|
| 61 |
importlib.reload(config_module)
|
| 62 |
|
| 63 |
print(f"LOG_LEVEL: {config_module.LOG_LEVEL}")
|
| 64 |
-
print(f"
|
| 65 |
assert config_module.LOG_LEVEL == "DEBUG"
|
| 66 |
|
| 67 |
def test_log_level_uppercase_conversion(self):
|
| 68 |
"""
|
| 69 |
-
|
| 70 |
-
|
| 71 |
"""
|
| 72 |
-
print("
|
| 73 |
|
| 74 |
with patch.dict(os.environ, {"LOG_LEVEL": "warning"}):
|
| 75 |
import importlib
|
|
@@ -77,15 +77,15 @@ class TestLogLevelConfig:
|
|
| 77 |
importlib.reload(config_module)
|
| 78 |
|
| 79 |
print(f"LOG_LEVEL: {config_module.LOG_LEVEL}")
|
| 80 |
-
print(f"
|
| 81 |
assert config_module.LOG_LEVEL == "WARNING"
|
| 82 |
|
| 83 |
def test_log_level_trace(self):
|
| 84 |
"""
|
| 85 |
-
|
| 86 |
-
|
| 87 |
"""
|
| 88 |
-
print("
|
| 89 |
|
| 90 |
with patch.dict(os.environ, {"LOG_LEVEL": "TRACE"}):
|
| 91 |
import importlib
|
|
@@ -97,10 +97,10 @@ class TestLogLevelConfig:
|
|
| 97 |
|
| 98 |
def test_log_level_error(self):
|
| 99 |
"""
|
| 100 |
-
|
| 101 |
-
|
| 102 |
"""
|
| 103 |
-
print("
|
| 104 |
|
| 105 |
with patch.dict(os.environ, {"LOG_LEVEL": "ERROR"}):
|
| 106 |
import importlib
|
|
@@ -112,10 +112,10 @@ class TestLogLevelConfig:
|
|
| 112 |
|
| 113 |
def test_log_level_critical(self):
|
| 114 |
"""
|
| 115 |
-
|
| 116 |
-
|
| 117 |
"""
|
| 118 |
-
print("
|
| 119 |
|
| 120 |
with patch.dict(os.environ, {"LOG_LEVEL": "CRITICAL"}):
|
| 121 |
import importlib
|
|
@@ -127,14 +127,14 @@ class TestLogLevelConfig:
|
|
| 127 |
|
| 128 |
|
| 129 |
class TestToolDescriptionMaxLengthConfig:
|
| 130 |
-
"""
|
| 131 |
|
| 132 |
def test_default_tool_description_max_length(self):
|
| 133 |
"""
|
| 134 |
-
|
| 135 |
-
|
| 136 |
"""
|
| 137 |
-
print("
|
| 138 |
|
| 139 |
with patch.dict(os.environ, {}, clear=False):
|
| 140 |
if "TOOL_DESCRIPTION_MAX_LENGTH" in os.environ:
|
|
@@ -149,10 +149,10 @@ class TestToolDescriptionMaxLengthConfig:
|
|
| 149 |
|
| 150 |
def test_tool_description_max_length_from_environment(self):
|
| 151 |
"""
|
| 152 |
-
|
| 153 |
-
|
| 154 |
"""
|
| 155 |
-
print("
|
| 156 |
|
| 157 |
with patch.dict(os.environ, {"TOOL_DESCRIPTION_MAX_LENGTH": "5000"}):
|
| 158 |
import importlib
|
|
@@ -164,10 +164,10 @@ class TestToolDescriptionMaxLengthConfig:
|
|
| 164 |
|
| 165 |
def test_tool_description_max_length_zero_disables(self):
|
| 166 |
"""
|
| 167 |
-
|
| 168 |
-
|
| 169 |
"""
|
| 170 |
-
print("
|
| 171 |
|
| 172 |
with patch.dict(os.environ, {"TOOL_DESCRIPTION_MAX_LENGTH": "0"}):
|
| 173 |
import importlib
|
|
@@ -175,4 +175,108 @@ class TestToolDescriptionMaxLengthConfig:
|
|
| 175 |
importlib.reload(config_module)
|
| 176 |
|
| 177 |
print(f"TOOL_DESCRIPTION_MAX_LENGTH: {config_module.TOOL_DESCRIPTION_MAX_LENGTH}")
|
| 178 |
-
assert config_module.TOOL_DESCRIPTION_MAX_LENGTH == 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
# -*- coding: utf-8 -*-
|
| 2 |
|
| 3 |
"""
|
| 4 |
+
Unit tests for the configuration module.
|
| 5 |
+
Verifies loading settings from environment variables.
|
| 6 |
"""
|
| 7 |
|
| 8 |
import pytest
|
|
|
|
| 11 |
|
| 12 |
|
| 13 |
class TestLogLevelConfig:
|
| 14 |
+
"""Tests for LOG_LEVEL configuration."""
|
| 15 |
|
| 16 |
def test_default_log_level_is_info(self):
|
| 17 |
"""
|
| 18 |
+
What it does: Verifies that LOG_LEVEL defaults to INFO.
|
| 19 |
+
Purpose: Ensure that INFO is used when no environment variable is set.
|
| 20 |
|
| 21 |
+
Note: This test verifies the config.py code logic, not the actual
|
| 22 |
+
value from the .env file. We mock os.getenv to simulate
|
| 23 |
+
the absence of the environment variable.
|
| 24 |
"""
|
| 25 |
+
print("Setup: Mocking os.getenv for LOG_LEVEL...")
|
| 26 |
|
| 27 |
+
# Create a mock that returns None for LOG_LEVEL (simulating missing variable)
|
| 28 |
original_getenv = os.getenv
|
| 29 |
|
| 30 |
def mock_getenv(key, default=None):
|
| 31 |
if key == "LOG_LEVEL":
|
| 32 |
+
print(f"os.getenv('{key}') -> None (mocked)")
|
| 33 |
+
return default # Return default, simulating missing variable
|
| 34 |
return original_getenv(key, default)
|
| 35 |
|
| 36 |
with patch.object(os, 'getenv', side_effect=mock_getenv):
|
| 37 |
+
# Reload config module with mocked getenv
|
| 38 |
import importlib
|
| 39 |
import kiro_gateway.config as config_module
|
| 40 |
importlib.reload(config_module)
|
| 41 |
|
| 42 |
print(f"LOG_LEVEL: {config_module.LOG_LEVEL}")
|
| 43 |
+
print(f"Comparing: Expected 'INFO', Got '{config_module.LOG_LEVEL}'")
|
| 44 |
assert config_module.LOG_LEVEL == "INFO"
|
| 45 |
|
| 46 |
+
# Restore module with real values
|
| 47 |
import importlib
|
| 48 |
import kiro_gateway.config as config_module
|
| 49 |
importlib.reload(config_module)
|
| 50 |
|
| 51 |
def test_log_level_from_environment(self):
|
| 52 |
"""
|
| 53 |
+
What it does: Verifies loading LOG_LEVEL from environment variable.
|
| 54 |
+
Purpose: Ensure that the value from environment is used.
|
| 55 |
"""
|
| 56 |
+
print("Setup: Setting LOG_LEVEL=DEBUG...")
|
| 57 |
|
| 58 |
with patch.dict(os.environ, {"LOG_LEVEL": "DEBUG"}):
|
| 59 |
import importlib
|
|
|
|
| 61 |
importlib.reload(config_module)
|
| 62 |
|
| 63 |
print(f"LOG_LEVEL: {config_module.LOG_LEVEL}")
|
| 64 |
+
print(f"Comparing: Expected 'DEBUG', Got '{config_module.LOG_LEVEL}'")
|
| 65 |
assert config_module.LOG_LEVEL == "DEBUG"
|
| 66 |
|
| 67 |
def test_log_level_uppercase_conversion(self):
|
| 68 |
"""
|
| 69 |
+
What it does: Verifies LOG_LEVEL conversion to uppercase.
|
| 70 |
+
Purpose: Ensure that lowercase value is converted to uppercase.
|
| 71 |
"""
|
| 72 |
+
print("Setup: Setting LOG_LEVEL=warning (lowercase)...")
|
| 73 |
|
| 74 |
with patch.dict(os.environ, {"LOG_LEVEL": "warning"}):
|
| 75 |
import importlib
|
|
|
|
| 77 |
importlib.reload(config_module)
|
| 78 |
|
| 79 |
print(f"LOG_LEVEL: {config_module.LOG_LEVEL}")
|
| 80 |
+
print(f"Comparing: Expected 'WARNING', Got '{config_module.LOG_LEVEL}'")
|
| 81 |
assert config_module.LOG_LEVEL == "WARNING"
|
| 82 |
|
| 83 |
def test_log_level_trace(self):
|
| 84 |
"""
|
| 85 |
+
What it does: Verifies setting LOG_LEVEL=TRACE.
|
| 86 |
+
Purpose: Ensure that TRACE level is supported.
|
| 87 |
"""
|
| 88 |
+
print("Setup: Setting LOG_LEVEL=TRACE...")
|
| 89 |
|
| 90 |
with patch.dict(os.environ, {"LOG_LEVEL": "TRACE"}):
|
| 91 |
import importlib
|
|
|
|
| 97 |
|
| 98 |
def test_log_level_error(self):
|
| 99 |
"""
|
| 100 |
+
What it does: Verifies setting LOG_LEVEL=ERROR.
|
| 101 |
+
Purpose: Ensure that ERROR level is supported.
|
| 102 |
"""
|
| 103 |
+
print("Setup: Setting LOG_LEVEL=ERROR...")
|
| 104 |
|
| 105 |
with patch.dict(os.environ, {"LOG_LEVEL": "ERROR"}):
|
| 106 |
import importlib
|
|
|
|
| 112 |
|
| 113 |
def test_log_level_critical(self):
|
| 114 |
"""
|
| 115 |
+
What it does: Verifies setting LOG_LEVEL=CRITICAL.
|
| 116 |
+
Purpose: Ensure that CRITICAL level is supported.
|
| 117 |
"""
|
| 118 |
+
print("Setup: Setting LOG_LEVEL=CRITICAL...")
|
| 119 |
|
| 120 |
with patch.dict(os.environ, {"LOG_LEVEL": "CRITICAL"}):
|
| 121 |
import importlib
|
|
|
|
| 127 |
|
| 128 |
|
| 129 |
class TestToolDescriptionMaxLengthConfig:
|
| 130 |
+
"""Tests for TOOL_DESCRIPTION_MAX_LENGTH configuration."""
|
| 131 |
|
| 132 |
def test_default_tool_description_max_length(self):
|
| 133 |
"""
|
| 134 |
+
What it does: Verifies the default value for TOOL_DESCRIPTION_MAX_LENGTH.
|
| 135 |
+
Purpose: Ensure that 10000 is used by default.
|
| 136 |
"""
|
| 137 |
+
print("Setup: Removing TOOL_DESCRIPTION_MAX_LENGTH from environment...")
|
| 138 |
|
| 139 |
with patch.dict(os.environ, {}, clear=False):
|
| 140 |
if "TOOL_DESCRIPTION_MAX_LENGTH" in os.environ:
|
|
|
|
| 149 |
|
| 150 |
def test_tool_description_max_length_from_environment(self):
|
| 151 |
"""
|
| 152 |
+
What it does: Verifies loading TOOL_DESCRIPTION_MAX_LENGTH from environment.
|
| 153 |
+
Purpose: Ensure that the value from environment is used.
|
| 154 |
"""
|
| 155 |
+
print("Setup: Setting TOOL_DESCRIPTION_MAX_LENGTH=5000...")
|
| 156 |
|
| 157 |
with patch.dict(os.environ, {"TOOL_DESCRIPTION_MAX_LENGTH": "5000"}):
|
| 158 |
import importlib
|
|
|
|
| 164 |
|
| 165 |
def test_tool_description_max_length_zero_disables(self):
|
| 166 |
"""
|
| 167 |
+
What it does: Verifies that 0 disables the feature.
|
| 168 |
+
Purpose: Ensure that TOOL_DESCRIPTION_MAX_LENGTH=0 works.
|
| 169 |
"""
|
| 170 |
+
print("Setup: Setting TOOL_DESCRIPTION_MAX_LENGTH=0...")
|
| 171 |
|
| 172 |
with patch.dict(os.environ, {"TOOL_DESCRIPTION_MAX_LENGTH": "0"}):
|
| 173 |
import importlib
|
|
|
|
| 175 |
importlib.reload(config_module)
|
| 176 |
|
| 177 |
print(f"TOOL_DESCRIPTION_MAX_LENGTH: {config_module.TOOL_DESCRIPTION_MAX_LENGTH}")
|
| 178 |
+
assert config_module.TOOL_DESCRIPTION_MAX_LENGTH == 0
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
class TestTimeoutConfigurationWarning:
|
| 182 |
+
"""Tests for _warn_timeout_configuration() function."""
|
| 183 |
+
|
| 184 |
+
def test_no_warning_when_first_token_less_than_streaming(self, capsys):
|
| 185 |
+
"""
|
| 186 |
+
What it does: Verifies that warning is NOT shown with correct configuration.
|
| 187 |
+
Purpose: Ensure that no warning when FIRST_TOKEN_TIMEOUT < STREAMING_READ_TIMEOUT.
|
| 188 |
+
"""
|
| 189 |
+
print("Setup: FIRST_TOKEN_TIMEOUT=15, STREAMING_READ_TIMEOUT=300...")
|
| 190 |
+
|
| 191 |
+
with patch.dict(os.environ, {
|
| 192 |
+
"FIRST_TOKEN_TIMEOUT": "15",
|
| 193 |
+
"STREAMING_READ_TIMEOUT": "300"
|
| 194 |
+
}):
|
| 195 |
+
import importlib
|
| 196 |
+
import kiro_gateway.config as config_module
|
| 197 |
+
importlib.reload(config_module)
|
| 198 |
+
|
| 199 |
+
# Call the warning function
|
| 200 |
+
config_module._warn_timeout_configuration()
|
| 201 |
+
|
| 202 |
+
captured = capsys.readouterr()
|
| 203 |
+
print(f"Captured stderr: {captured.err}")
|
| 204 |
+
|
| 205 |
+
# Warning should NOT be shown
|
| 206 |
+
assert "WARNING" not in captured.err
|
| 207 |
+
assert "Suboptimal timeout configuration" not in captured.err
|
| 208 |
+
|
| 209 |
+
def test_warning_when_first_token_equals_streaming(self, capsys):
|
| 210 |
+
"""
|
| 211 |
+
What it does: Verifies that warning is shown when timeouts are equal.
|
| 212 |
+
Purpose: Ensure that warning when FIRST_TOKEN_TIMEOUT == STREAMING_READ_TIMEOUT.
|
| 213 |
+
"""
|
| 214 |
+
print("Setup: FIRST_TOKEN_TIMEOUT=300, STREAMING_READ_TIMEOUT=300...")
|
| 215 |
+
|
| 216 |
+
with patch.dict(os.environ, {
|
| 217 |
+
"FIRST_TOKEN_TIMEOUT": "300",
|
| 218 |
+
"STREAMING_READ_TIMEOUT": "300"
|
| 219 |
+
}):
|
| 220 |
+
import importlib
|
| 221 |
+
import kiro_gateway.config as config_module
|
| 222 |
+
importlib.reload(config_module)
|
| 223 |
+
|
| 224 |
+
# Call the warning function
|
| 225 |
+
config_module._warn_timeout_configuration()
|
| 226 |
+
|
| 227 |
+
captured = capsys.readouterr()
|
| 228 |
+
print(f"Captured stderr: {captured.err}")
|
| 229 |
+
|
| 230 |
+
# Warning SHOULD be shown
|
| 231 |
+
assert "WARNING" in captured.err or "Suboptimal timeout configuration" in captured.err
|
| 232 |
+
|
| 233 |
+
def test_warning_when_first_token_greater_than_streaming(self, capsys):
|
| 234 |
+
"""
|
| 235 |
+
What it does: Verifies that warning is shown when FIRST_TOKEN > STREAMING.
|
| 236 |
+
Purpose: Ensure that warning when FIRST_TOKEN_TIMEOUT > STREAMING_READ_TIMEOUT.
|
| 237 |
+
"""
|
| 238 |
+
print("Setup: FIRST_TOKEN_TIMEOUT=500, STREAMING_READ_TIMEOUT=300...")
|
| 239 |
+
|
| 240 |
+
with patch.dict(os.environ, {
|
| 241 |
+
"FIRST_TOKEN_TIMEOUT": "500",
|
| 242 |
+
"STREAMING_READ_TIMEOUT": "300"
|
| 243 |
+
}):
|
| 244 |
+
import importlib
|
| 245 |
+
import kiro_gateway.config as config_module
|
| 246 |
+
importlib.reload(config_module)
|
| 247 |
+
|
| 248 |
+
# Call the warning function
|
| 249 |
+
config_module._warn_timeout_configuration()
|
| 250 |
+
|
| 251 |
+
captured = capsys.readouterr()
|
| 252 |
+
print(f"Captured stderr: {captured.err}")
|
| 253 |
+
|
| 254 |
+
# Warning SHOULD be shown
|
| 255 |
+
assert "WARNING" in captured.err or "Suboptimal timeout configuration" in captured.err
|
| 256 |
+
# Verify that timeout values are mentioned in warning
|
| 257 |
+
assert "500" in captured.err
|
| 258 |
+
assert "300" in captured.err
|
| 259 |
+
|
| 260 |
+
def test_warning_contains_recommendation(self, capsys):
|
| 261 |
+
"""
|
| 262 |
+
What it does: Verifies that warning contains a recommendation.
|
| 263 |
+
Purpose: Ensure that user receives useful information.
|
| 264 |
+
"""
|
| 265 |
+
print("Setup: FIRST_TOKEN_TIMEOUT=400, STREAMING_READ_TIMEOUT=300...")
|
| 266 |
+
|
| 267 |
+
with patch.dict(os.environ, {
|
| 268 |
+
"FIRST_TOKEN_TIMEOUT": "400",
|
| 269 |
+
"STREAMING_READ_TIMEOUT": "300"
|
| 270 |
+
}):
|
| 271 |
+
import importlib
|
| 272 |
+
import kiro_gateway.config as config_module
|
| 273 |
+
importlib.reload(config_module)
|
| 274 |
+
|
| 275 |
+
# Call the warning function
|
| 276 |
+
config_module._warn_timeout_configuration()
|
| 277 |
+
|
| 278 |
+
captured = capsys.readouterr()
|
| 279 |
+
print(f"Captured stderr: {captured.err}")
|
| 280 |
+
|
| 281 |
+
# Warning should contain recommendation
|
| 282 |
+
assert "Recommendation" in captured.err or "LESS than" in captured.err
|
tests/unit/test_http_client.py
CHANGED
|
@@ -1,8 +1,8 @@
|
|
| 1 |
# -*- coding: utf-8 -*-
|
| 2 |
|
| 3 |
"""
|
| 4 |
-
Unit
|
| 5 |
-
|
| 6 |
"""
|
| 7 |
|
| 8 |
import asyncio
|
|
@@ -15,12 +15,12 @@ from fastapi import HTTPException
|
|
| 15 |
|
| 16 |
from kiro_gateway.http_client import KiroHttpClient
|
| 17 |
from kiro_gateway.auth import KiroAuthManager
|
| 18 |
-
from kiro_gateway.config import MAX_RETRIES, BASE_RETRY_DELAY,
|
| 19 |
|
| 20 |
|
| 21 |
@pytest.fixture
|
| 22 |
def mock_auth_manager_for_http():
|
| 23 |
-
"""
|
| 24 |
manager = Mock(spec=KiroAuthManager)
|
| 25 |
manager.get_access_token = AsyncMock(return_value="test_access_token")
|
| 26 |
manager.force_refresh = AsyncMock(return_value="new_access_token")
|
|
@@ -30,44 +30,44 @@ def mock_auth_manager_for_http():
|
|
| 30 |
|
| 31 |
|
| 32 |
class TestKiroHttpClientInitialization:
|
| 33 |
-
"""
|
| 34 |
|
| 35 |
def test_initialization_stores_auth_manager(self, mock_auth_manager_for_http):
|
| 36 |
"""
|
| 37 |
-
|
| 38 |
-
|
| 39 |
"""
|
| 40 |
-
print("
|
| 41 |
client = KiroHttpClient(mock_auth_manager_for_http)
|
| 42 |
|
| 43 |
-
print("
|
| 44 |
assert client.auth_manager is mock_auth_manager_for_http
|
| 45 |
|
| 46 |
def test_initialization_client_is_none(self, mock_auth_manager_for_http):
|
| 47 |
"""
|
| 48 |
-
|
| 49 |
-
|
| 50 |
"""
|
| 51 |
-
print("
|
| 52 |
client = KiroHttpClient(mock_auth_manager_for_http)
|
| 53 |
|
| 54 |
-
print("
|
| 55 |
assert client.client is None
|
| 56 |
|
| 57 |
|
| 58 |
class TestKiroHttpClientGetClient:
|
| 59 |
-
"""
|
| 60 |
|
| 61 |
@pytest.mark.asyncio
|
| 62 |
async def test_get_client_creates_new_client(self, mock_auth_manager_for_http):
|
| 63 |
"""
|
| 64 |
-
|
| 65 |
-
|
| 66 |
"""
|
| 67 |
-
print("
|
| 68 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 69 |
|
| 70 |
-
print("
|
| 71 |
with patch('kiro_gateway.http_client.httpx.AsyncClient') as mock_async_client:
|
| 72 |
mock_instance = AsyncMock()
|
| 73 |
mock_instance.is_closed = False
|
|
@@ -75,43 +75,43 @@ class TestKiroHttpClientGetClient:
|
|
| 75 |
|
| 76 |
client = await http_client._get_client()
|
| 77 |
|
| 78 |
-
print("
|
| 79 |
mock_async_client.assert_called_once()
|
| 80 |
assert client is mock_instance
|
| 81 |
|
| 82 |
@pytest.mark.asyncio
|
| 83 |
async def test_get_client_reuses_existing_client(self, mock_auth_manager_for_http):
|
| 84 |
"""
|
| 85 |
-
|
| 86 |
-
|
| 87 |
"""
|
| 88 |
-
print("
|
| 89 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 90 |
|
| 91 |
mock_existing = AsyncMock()
|
| 92 |
mock_existing.is_closed = False
|
| 93 |
http_client.client = mock_existing
|
| 94 |
|
| 95 |
-
print("
|
| 96 |
client = await http_client._get_client()
|
| 97 |
|
| 98 |
-
print("
|
| 99 |
assert client is mock_existing
|
| 100 |
|
| 101 |
@pytest.mark.asyncio
|
| 102 |
async def test_get_client_recreates_closed_client(self, mock_auth_manager_for_http):
|
| 103 |
"""
|
| 104 |
-
|
| 105 |
-
|
| 106 |
"""
|
| 107 |
-
print("
|
| 108 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 109 |
|
| 110 |
mock_closed = AsyncMock()
|
| 111 |
mock_closed.is_closed = True
|
| 112 |
http_client.client = mock_closed
|
| 113 |
|
| 114 |
-
print("
|
| 115 |
with patch('kiro_gateway.http_client.httpx.AsyncClient') as mock_async_client:
|
| 116 |
mock_new = AsyncMock()
|
| 117 |
mock_new.is_closed = False
|
|
@@ -119,21 +119,21 @@ class TestKiroHttpClientGetClient:
|
|
| 119 |
|
| 120 |
client = await http_client._get_client()
|
| 121 |
|
| 122 |
-
print("
|
| 123 |
mock_async_client.assert_called_once()
|
| 124 |
assert client is mock_new
|
| 125 |
|
| 126 |
|
| 127 |
class TestKiroHttpClientClose:
|
| 128 |
-
"""
|
| 129 |
|
| 130 |
@pytest.mark.asyncio
|
| 131 |
async def test_close_closes_client(self, mock_auth_manager_for_http):
|
| 132 |
"""
|
| 133 |
-
|
| 134 |
-
|
| 135 |
"""
|
| 136 |
-
print("
|
| 137 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 138 |
|
| 139 |
mock_client = AsyncMock()
|
|
@@ -141,56 +141,56 @@ class TestKiroHttpClientClose:
|
|
| 141 |
mock_client.aclose = AsyncMock()
|
| 142 |
http_client.client = mock_client
|
| 143 |
|
| 144 |
-
print("
|
| 145 |
await http_client.close()
|
| 146 |
|
| 147 |
-
print("
|
| 148 |
mock_client.aclose.assert_called_once()
|
| 149 |
|
| 150 |
@pytest.mark.asyncio
|
| 151 |
async def test_close_does_nothing_for_none_client(self, mock_auth_manager_for_http):
|
| 152 |
"""
|
| 153 |
-
|
| 154 |
-
|
| 155 |
"""
|
| 156 |
-
print("
|
| 157 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 158 |
|
| 159 |
-
print("
|
| 160 |
-
await http_client.close() #
|
| 161 |
|
| 162 |
-
print("
|
| 163 |
|
| 164 |
@pytest.mark.asyncio
|
| 165 |
async def test_close_does_nothing_for_closed_client(self, mock_auth_manager_for_http):
|
| 166 |
"""
|
| 167 |
-
|
| 168 |
-
|
| 169 |
"""
|
| 170 |
-
print("
|
| 171 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 172 |
|
| 173 |
mock_client = AsyncMock()
|
| 174 |
mock_client.is_closed = True
|
| 175 |
http_client.client = mock_client
|
| 176 |
|
| 177 |
-
print("
|
| 178 |
await http_client.close()
|
| 179 |
|
| 180 |
-
print("
|
| 181 |
mock_client.aclose.assert_not_called()
|
| 182 |
|
| 183 |
|
| 184 |
class TestKiroHttpClientRequestWithRetry:
|
| 185 |
-
"""
|
| 186 |
|
| 187 |
@pytest.mark.asyncio
|
| 188 |
async def test_successful_request_returns_response(self, mock_auth_manager_for_http):
|
| 189 |
"""
|
| 190 |
-
|
| 191 |
-
|
| 192 |
"""
|
| 193 |
-
print("
|
| 194 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 195 |
|
| 196 |
mock_response = AsyncMock()
|
|
@@ -200,7 +200,7 @@ class TestKiroHttpClientRequestWithRetry:
|
|
| 200 |
mock_client.is_closed = False
|
| 201 |
mock_client.request = AsyncMock(return_value=mock_response)
|
| 202 |
|
| 203 |
-
print("
|
| 204 |
with patch.object(http_client, '_get_client', return_value=mock_client):
|
| 205 |
with patch('kiro_gateway.http_client.get_kiro_headers', return_value={}):
|
| 206 |
response = await http_client.request_with_retry(
|
|
@@ -209,17 +209,17 @@ class TestKiroHttpClientRequestWithRetry:
|
|
| 209 |
{"data": "value"}
|
| 210 |
)
|
| 211 |
|
| 212 |
-
print("
|
| 213 |
assert response.status_code == 200
|
| 214 |
mock_client.request.assert_called_once()
|
| 215 |
|
| 216 |
@pytest.mark.asyncio
|
| 217 |
async def test_403_triggers_token_refresh(self, mock_auth_manager_for_http):
|
| 218 |
"""
|
| 219 |
-
|
| 220 |
-
|
| 221 |
"""
|
| 222 |
-
print("
|
| 223 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 224 |
|
| 225 |
mock_response_403 = AsyncMock()
|
|
@@ -232,7 +232,7 @@ class TestKiroHttpClientRequestWithRetry:
|
|
| 232 |
mock_client.is_closed = False
|
| 233 |
mock_client.request = AsyncMock(side_effect=[mock_response_403, mock_response_200])
|
| 234 |
|
| 235 |
-
print("
|
| 236 |
with patch.object(http_client, '_get_client', return_value=mock_client):
|
| 237 |
with patch('kiro_gateway.http_client.get_kiro_headers', return_value={}):
|
| 238 |
response = await http_client.request_with_retry(
|
|
@@ -241,17 +241,17 @@ class TestKiroHttpClientRequestWithRetry:
|
|
| 241 |
{"data": "value"}
|
| 242 |
)
|
| 243 |
|
| 244 |
-
print("
|
| 245 |
mock_auth_manager_for_http.force_refresh.assert_called_once()
|
| 246 |
assert response.status_code == 200
|
| 247 |
|
| 248 |
@pytest.mark.asyncio
|
| 249 |
async def test_429_triggers_backoff(self, mock_auth_manager_for_http):
|
| 250 |
"""
|
| 251 |
-
|
| 252 |
-
|
| 253 |
"""
|
| 254 |
-
print("
|
| 255 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 256 |
|
| 257 |
mock_response_429 = AsyncMock()
|
|
@@ -264,7 +264,7 @@ class TestKiroHttpClientRequestWithRetry:
|
|
| 264 |
mock_client.is_closed = False
|
| 265 |
mock_client.request = AsyncMock(side_effect=[mock_response_429, mock_response_200])
|
| 266 |
|
| 267 |
-
print("
|
| 268 |
with patch.object(http_client, '_get_client', return_value=mock_client):
|
| 269 |
with patch('kiro_gateway.http_client.get_kiro_headers', return_value={}):
|
| 270 |
with patch('kiro_gateway.http_client.asyncio.sleep', new_callable=AsyncMock) as mock_sleep:
|
|
@@ -274,17 +274,17 @@ class TestKiroHttpClientRequestWithRetry:
|
|
| 274 |
{"data": "value"}
|
| 275 |
)
|
| 276 |
|
| 277 |
-
print("
|
| 278 |
mock_sleep.assert_called_once()
|
| 279 |
assert response.status_code == 200
|
| 280 |
|
| 281 |
@pytest.mark.asyncio
|
| 282 |
async def test_5xx_triggers_backoff(self, mock_auth_manager_for_http):
|
| 283 |
"""
|
| 284 |
-
|
| 285 |
-
|
| 286 |
"""
|
| 287 |
-
print("
|
| 288 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 289 |
|
| 290 |
mock_response_500 = AsyncMock()
|
|
@@ -297,7 +297,7 @@ class TestKiroHttpClientRequestWithRetry:
|
|
| 297 |
mock_client.is_closed = False
|
| 298 |
mock_client.request = AsyncMock(side_effect=[mock_response_500, mock_response_200])
|
| 299 |
|
| 300 |
-
print("
|
| 301 |
with patch.object(http_client, '_get_client', return_value=mock_client):
|
| 302 |
with patch('kiro_gateway.http_client.get_kiro_headers', return_value={}):
|
| 303 |
with patch('kiro_gateway.http_client.asyncio.sleep', new_callable=AsyncMock) as mock_sleep:
|
|
@@ -307,17 +307,17 @@ class TestKiroHttpClientRequestWithRetry:
|
|
| 307 |
{"data": "value"}
|
| 308 |
)
|
| 309 |
|
| 310 |
-
print("
|
| 311 |
mock_sleep.assert_called_once()
|
| 312 |
assert response.status_code == 200
|
| 313 |
|
| 314 |
@pytest.mark.asyncio
|
| 315 |
async def test_timeout_triggers_backoff(self, mock_auth_manager_for_http):
|
| 316 |
"""
|
| 317 |
-
|
| 318 |
-
|
| 319 |
"""
|
| 320 |
-
print("
|
| 321 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 322 |
|
| 323 |
mock_response_200 = AsyncMock()
|
|
@@ -330,7 +330,7 @@ class TestKiroHttpClientRequestWithRetry:
|
|
| 330 |
mock_response_200
|
| 331 |
])
|
| 332 |
|
| 333 |
-
print("
|
| 334 |
with patch.object(http_client, '_get_client', return_value=mock_client):
|
| 335 |
with patch('kiro_gateway.http_client.get_kiro_headers', return_value={}):
|
| 336 |
with patch('kiro_gateway.http_client.asyncio.sleep', new_callable=AsyncMock) as mock_sleep:
|
|
@@ -340,17 +340,17 @@ class TestKiroHttpClientRequestWithRetry:
|
|
| 340 |
{"data": "value"}
|
| 341 |
)
|
| 342 |
|
| 343 |
-
print("
|
| 344 |
mock_sleep.assert_called_once()
|
| 345 |
assert response.status_code == 200
|
| 346 |
|
| 347 |
@pytest.mark.asyncio
|
| 348 |
async def test_request_error_triggers_backoff(self, mock_auth_manager_for_http):
|
| 349 |
"""
|
| 350 |
-
|
| 351 |
-
|
| 352 |
"""
|
| 353 |
-
print("
|
| 354 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 355 |
|
| 356 |
mock_response_200 = AsyncMock()
|
|
@@ -363,7 +363,7 @@ class TestKiroHttpClientRequestWithRetry:
|
|
| 363 |
mock_response_200
|
| 364 |
])
|
| 365 |
|
| 366 |
-
print("
|
| 367 |
with patch.object(http_client, '_get_client', return_value=mock_client):
|
| 368 |
with patch('kiro_gateway.http_client.get_kiro_headers', return_value={}):
|
| 369 |
with patch('kiro_gateway.http_client.asyncio.sleep', new_callable=AsyncMock) as mock_sleep:
|
|
@@ -373,24 +373,24 @@ class TestKiroHttpClientRequestWithRetry:
|
|
| 373 |
{"data": "value"}
|
| 374 |
)
|
| 375 |
|
| 376 |
-
print("
|
| 377 |
mock_sleep.assert_called_once()
|
| 378 |
assert response.status_code == 200
|
| 379 |
|
| 380 |
@pytest.mark.asyncio
|
| 381 |
async def test_max_retries_exceeded_raises_502(self, mock_auth_manager_for_http):
|
| 382 |
"""
|
| 383 |
-
|
| 384 |
-
|
| 385 |
"""
|
| 386 |
-
print("
|
| 387 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 388 |
|
| 389 |
mock_client = AsyncMock()
|
| 390 |
mock_client.is_closed = False
|
| 391 |
mock_client.request = AsyncMock(side_effect=httpx.TimeoutException("Timeout"))
|
| 392 |
|
| 393 |
-
print("
|
| 394 |
with patch.object(http_client, '_get_client', return_value=mock_client):
|
| 395 |
with patch('kiro_gateway.http_client.get_kiro_headers', return_value={}):
|
| 396 |
with patch('kiro_gateway.http_client.asyncio.sleep', new_callable=AsyncMock):
|
|
@@ -401,17 +401,17 @@ class TestKiroHttpClientRequestWithRetry:
|
|
| 401 |
{"data": "value"}
|
| 402 |
)
|
| 403 |
|
| 404 |
-
print(f"
|
| 405 |
assert exc_info.value.status_code == 502
|
| 406 |
assert str(MAX_RETRIES) in exc_info.value.detail
|
| 407 |
|
| 408 |
@pytest.mark.asyncio
|
| 409 |
async def test_other_status_codes_returned_as_is(self, mock_auth_manager_for_http):
|
| 410 |
"""
|
| 411 |
-
|
| 412 |
-
|
| 413 |
"""
|
| 414 |
-
print("
|
| 415 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 416 |
|
| 417 |
mock_response = AsyncMock()
|
|
@@ -421,7 +421,7 @@ class TestKiroHttpClientRequestWithRetry:
|
|
| 421 |
mock_client.is_closed = False
|
| 422 |
mock_client.request = AsyncMock(return_value=mock_response)
|
| 423 |
|
| 424 |
-
print("
|
| 425 |
with patch.object(http_client, '_get_client', return_value=mock_client):
|
| 426 |
with patch('kiro_gateway.http_client.get_kiro_headers', return_value={}):
|
| 427 |
response = await http_client.request_with_retry(
|
|
@@ -430,17 +430,17 @@ class TestKiroHttpClientRequestWithRetry:
|
|
| 430 |
{"data": "value"}
|
| 431 |
)
|
| 432 |
|
| 433 |
-
print("
|
| 434 |
assert response.status_code == 400
|
| 435 |
mock_client.request.assert_called_once()
|
| 436 |
|
| 437 |
@pytest.mark.asyncio
|
| 438 |
async def test_streaming_request_uses_send(self, mock_auth_manager_for_http):
|
| 439 |
"""
|
| 440 |
-
|
| 441 |
-
|
| 442 |
"""
|
| 443 |
-
print("
|
| 444 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 445 |
|
| 446 |
mock_response = AsyncMock()
|
|
@@ -453,7 +453,7 @@ class TestKiroHttpClientRequestWithRetry:
|
|
| 453 |
mock_client.build_request = Mock(return_value=mock_request)
|
| 454 |
mock_client.send = AsyncMock(return_value=mock_response)
|
| 455 |
|
| 456 |
-
print("
|
| 457 |
with patch.object(http_client, '_get_client', return_value=mock_client):
|
| 458 |
with patch('kiro_gateway.http_client.get_kiro_headers', return_value={}):
|
| 459 |
response = await http_client.request_with_retry(
|
|
@@ -463,37 +463,37 @@ class TestKiroHttpClientRequestWithRetry:
|
|
| 463 |
stream=True
|
| 464 |
)
|
| 465 |
|
| 466 |
-
print("
|
| 467 |
mock_client.build_request.assert_called_once()
|
| 468 |
mock_client.send.assert_called_once_with(mock_request, stream=True)
|
| 469 |
assert response.status_code == 200
|
| 470 |
|
| 471 |
|
| 472 |
class TestKiroHttpClientContextManager:
|
| 473 |
-
"""
|
| 474 |
|
| 475 |
@pytest.mark.asyncio
|
| 476 |
async def test_context_manager_returns_self(self, mock_auth_manager_for_http):
|
| 477 |
"""
|
| 478 |
-
|
| 479 |
-
|
| 480 |
"""
|
| 481 |
-
print("
|
| 482 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 483 |
|
| 484 |
-
print("
|
| 485 |
result = await http_client.__aenter__()
|
| 486 |
|
| 487 |
-
print("
|
| 488 |
assert result is http_client
|
| 489 |
|
| 490 |
@pytest.mark.asyncio
|
| 491 |
async def test_context_manager_closes_on_exit(self, mock_auth_manager_for_http):
|
| 492 |
"""
|
| 493 |
-
|
| 494 |
-
|
| 495 |
"""
|
| 496 |
-
print("
|
| 497 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 498 |
|
| 499 |
mock_client = AsyncMock()
|
|
@@ -501,23 +501,23 @@ class TestKiroHttpClientContextManager:
|
|
| 501 |
mock_client.aclose = AsyncMock()
|
| 502 |
http_client.client = mock_client
|
| 503 |
|
| 504 |
-
print("
|
| 505 |
await http_client.__aexit__(None, None, None)
|
| 506 |
|
| 507 |
-
print("
|
| 508 |
mock_client.aclose.assert_called_once()
|
| 509 |
|
| 510 |
|
| 511 |
class TestKiroHttpClientExponentialBackoff:
|
| 512 |
-
"""
|
| 513 |
|
| 514 |
@pytest.mark.asyncio
|
| 515 |
async def test_backoff_delay_increases_exponentially(self, mock_auth_manager_for_http):
|
| 516 |
"""
|
| 517 |
-
|
| 518 |
-
|
| 519 |
"""
|
| 520 |
-
print("
|
| 521 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 522 |
|
| 523 |
mock_response_429 = AsyncMock()
|
|
@@ -528,7 +528,7 @@ class TestKiroHttpClientExponentialBackoff:
|
|
| 528 |
|
| 529 |
mock_client = AsyncMock()
|
| 530 |
mock_client.is_closed = False
|
| 531 |
-
#
|
| 532 |
mock_client.request = AsyncMock(side_effect=[
|
| 533 |
mock_response_429,
|
| 534 |
mock_response_429,
|
|
@@ -540,7 +540,7 @@ class TestKiroHttpClientExponentialBackoff:
|
|
| 540 |
async def capture_sleep(delay):
|
| 541 |
sleep_delays.append(delay)
|
| 542 |
|
| 543 |
-
print("
|
| 544 |
with patch.object(http_client, '_get_client', return_value=mock_client):
|
| 545 |
with patch('kiro_gateway.http_client.get_kiro_headers', return_value={}):
|
| 546 |
with patch('kiro_gateway.http_client.asyncio.sleep', side_effect=capture_sleep):
|
|
@@ -550,23 +550,23 @@ class TestKiroHttpClientExponentialBackoff:
|
|
| 550 |
{"data": "value"}
|
| 551 |
)
|
| 552 |
|
| 553 |
-
print(f"
|
| 554 |
-
print(f"
|
| 555 |
assert len(sleep_delays) == 2
|
| 556 |
assert sleep_delays[0] == BASE_RETRY_DELAY * (2 ** 0) # 1.0
|
| 557 |
assert sleep_delays[1] == BASE_RETRY_DELAY * (2 ** 1) # 2.0
|
| 558 |
|
| 559 |
|
| 560 |
-
class
|
| 561 |
-
"""
|
| 562 |
|
| 563 |
@pytest.mark.asyncio
|
| 564 |
-
async def
|
| 565 |
"""
|
| 566 |
-
|
| 567 |
-
|
| 568 |
"""
|
| 569 |
-
print("
|
| 570 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 571 |
|
| 572 |
mock_response = AsyncMock()
|
|
@@ -579,7 +579,7 @@ class TestKiroHttpClientFirstTokenTimeout:
|
|
| 579 |
mock_client.build_request = Mock(return_value=mock_request)
|
| 580 |
mock_client.send = AsyncMock(return_value=mock_response)
|
| 581 |
|
| 582 |
-
print("
|
| 583 |
with patch('kiro_gateway.http_client.httpx.AsyncClient') as mock_async_client:
|
| 584 |
mock_async_client.return_value = mock_client
|
| 585 |
|
|
@@ -591,22 +591,24 @@ class TestKiroHttpClientFirstTokenTimeout:
|
|
| 591 |
stream=True
|
| 592 |
)
|
| 593 |
|
| 594 |
-
print("
|
| 595 |
-
# For streaming, we use httpx.Timeout with connect=FIRST_TOKEN_TIMEOUT and read=STREAMING_READ_TIMEOUT
|
| 596 |
call_args = mock_async_client.call_args
|
| 597 |
timeout_arg = call_args.kwargs.get('timeout')
|
| 598 |
assert timeout_arg is not None, f"timeout not found in call_args: {call_args}"
|
| 599 |
-
|
|
|
|
|
|
|
|
|
|
| 600 |
assert call_args.kwargs.get('follow_redirects') == True
|
| 601 |
assert response.status_code == 200
|
| 602 |
|
| 603 |
@pytest.mark.asyncio
|
| 604 |
async def test_streaming_uses_first_token_max_retries(self, mock_auth_manager_for_http):
|
| 605 |
"""
|
| 606 |
-
|
| 607 |
-
|
| 608 |
"""
|
| 609 |
-
print("
|
| 610 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 611 |
|
| 612 |
mock_request = Mock()
|
|
@@ -616,7 +618,7 @@ class TestKiroHttpClientFirstTokenTimeout:
|
|
| 616 |
mock_client.build_request = Mock(return_value=mock_request)
|
| 617 |
mock_client.send = AsyncMock(side_effect=httpx.TimeoutException("Timeout"))
|
| 618 |
|
| 619 |
-
print("
|
| 620 |
with patch('kiro_gateway.http_client.httpx.AsyncClient', return_value=mock_client):
|
| 621 |
with patch('kiro_gateway.http_client.get_kiro_headers', return_value={}):
|
| 622 |
with pytest.raises(HTTPException) as exc_info:
|
|
@@ -627,20 +629,20 @@ class TestKiroHttpClientFirstTokenTimeout:
|
|
| 627 |
stream=True
|
| 628 |
)
|
| 629 |
|
| 630 |
-
print(f"
|
| 631 |
assert exc_info.value.status_code == 504
|
| 632 |
assert str(FIRST_TOKEN_MAX_RETRIES) in exc_info.value.detail
|
| 633 |
|
| 634 |
-
print(f"
|
| 635 |
assert mock_client.send.call_count == FIRST_TOKEN_MAX_RETRIES
|
| 636 |
|
| 637 |
@pytest.mark.asyncio
|
| 638 |
async def test_streaming_timeout_retry_without_delay(self, mock_auth_manager_for_http):
|
| 639 |
"""
|
| 640 |
-
|
| 641 |
-
|
| 642 |
"""
|
| 643 |
-
print("
|
| 644 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 645 |
|
| 646 |
mock_response = AsyncMock()
|
|
@@ -651,7 +653,7 @@ class TestKiroHttpClientFirstTokenTimeout:
|
|
| 651 |
mock_client = AsyncMock()
|
| 652 |
mock_client.is_closed = False
|
| 653 |
mock_client.build_request = Mock(return_value=mock_request)
|
| 654 |
-
#
|
| 655 |
mock_client.send = AsyncMock(side_effect=[
|
| 656 |
httpx.TimeoutException("Timeout"),
|
| 657 |
mock_response
|
|
@@ -663,7 +665,7 @@ class TestKiroHttpClientFirstTokenTimeout:
|
|
| 663 |
nonlocal sleep_called
|
| 664 |
sleep_called = True
|
| 665 |
|
| 666 |
-
print("
|
| 667 |
with patch('kiro_gateway.http_client.httpx.AsyncClient', return_value=mock_client):
|
| 668 |
with patch('kiro_gateway.http_client.get_kiro_headers', return_value={}):
|
| 669 |
with patch('kiro_gateway.http_client.asyncio.sleep', side_effect=capture_sleep):
|
|
@@ -674,17 +676,17 @@ class TestKiroHttpClientFirstTokenTimeout:
|
|
| 674 |
stream=True
|
| 675 |
)
|
| 676 |
|
| 677 |
-
print("
|
| 678 |
assert not sleep_called
|
| 679 |
assert response.status_code == 200
|
| 680 |
-
|
| 681 |
@pytest.mark.asyncio
|
| 682 |
async def test_non_streaming_uses_default_timeout(self, mock_auth_manager_for_http):
|
| 683 |
"""
|
| 684 |
-
|
| 685 |
-
|
| 686 |
"""
|
| 687 |
-
print("
|
| 688 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 689 |
|
| 690 |
mock_response = AsyncMock()
|
|
@@ -694,7 +696,7 @@ class TestKiroHttpClientFirstTokenTimeout:
|
|
| 694 |
mock_client.is_closed = False
|
| 695 |
mock_client.request = AsyncMock(return_value=mock_response)
|
| 696 |
|
| 697 |
-
print("
|
| 698 |
with patch('kiro_gateway.http_client.httpx.AsyncClient') as mock_async_client:
|
| 699 |
mock_async_client.return_value = mock_client
|
| 700 |
|
|
@@ -706,17 +708,23 @@ class TestKiroHttpClientFirstTokenTimeout:
|
|
| 706 |
stream=False
|
| 707 |
)
|
| 708 |
|
| 709 |
-
print("
|
| 710 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 711 |
assert response.status_code == 200
|
| 712 |
|
| 713 |
@pytest.mark.asyncio
|
| 714 |
-
async def
|
| 715 |
"""
|
| 716 |
-
|
| 717 |
-
|
| 718 |
"""
|
| 719 |
-
print("
|
| 720 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 721 |
|
| 722 |
mock_response = AsyncMock()
|
|
@@ -727,39 +735,75 @@ class TestKiroHttpClientFirstTokenTimeout:
|
|
| 727 |
mock_client = AsyncMock()
|
| 728 |
mock_client.is_closed = False
|
| 729 |
mock_client.build_request = Mock(return_value=mock_request)
|
| 730 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 731 |
|
| 732 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 733 |
|
| 734 |
-
|
| 735 |
-
|
| 736 |
-
|
| 737 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 738 |
with patch('kiro_gateway.http_client.get_kiro_headers', return_value={}):
|
| 739 |
-
|
| 740 |
-
|
| 741 |
-
|
| 742 |
-
|
| 743 |
-
|
| 744 |
-
|
| 745 |
-
|
| 746 |
|
| 747 |
-
print(
|
| 748 |
-
|
| 749 |
-
|
| 750 |
-
|
| 751 |
-
assert timeout_arg is not None, f"timeout not found in call_args: {call_args}"
|
| 752 |
-
assert timeout_arg.connect == custom_timeout
|
| 753 |
-
assert call_args.kwargs.get('follow_redirects') == True
|
| 754 |
assert response.status_code == 200
|
| 755 |
|
| 756 |
@pytest.mark.asyncio
|
| 757 |
-
async def
|
| 758 |
"""
|
| 759 |
-
|
| 760 |
-
|
| 761 |
"""
|
| 762 |
-
print("
|
| 763 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 764 |
|
| 765 |
mock_request = Mock()
|
|
@@ -767,9 +811,9 @@ class TestKiroHttpClientFirstTokenTimeout:
|
|
| 767 |
mock_client = AsyncMock()
|
| 768 |
mock_client.is_closed = False
|
| 769 |
mock_client.build_request = Mock(return_value=mock_request)
|
| 770 |
-
mock_client.send = AsyncMock(side_effect=httpx.
|
| 771 |
|
| 772 |
-
print("
|
| 773 |
with patch('kiro_gateway.http_client.httpx.AsyncClient', return_value=mock_client):
|
| 774 |
with patch('kiro_gateway.http_client.get_kiro_headers', return_value={}):
|
| 775 |
with pytest.raises(HTTPException) as exc_info:
|
|
@@ -780,25 +824,27 @@ class TestKiroHttpClientFirstTokenTimeout:
|
|
| 780 |
stream=True
|
| 781 |
)
|
| 782 |
|
| 783 |
-
print("
|
|
|
|
| 784 |
assert exc_info.value.status_code == 504
|
| 785 |
-
|
| 786 |
-
assert "
|
|
|
|
| 787 |
|
| 788 |
@pytest.mark.asyncio
|
| 789 |
async def test_non_streaming_timeout_returns_502(self, mock_auth_manager_for_http):
|
| 790 |
"""
|
| 791 |
-
|
| 792 |
-
|
| 793 |
"""
|
| 794 |
-
print("
|
| 795 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 796 |
|
| 797 |
mock_client = AsyncMock()
|
| 798 |
mock_client.is_closed = False
|
| 799 |
mock_client.request = AsyncMock(side_effect=httpx.TimeoutException("Timeout"))
|
| 800 |
|
| 801 |
-
print("
|
| 802 |
with patch('kiro_gateway.http_client.httpx.AsyncClient', return_value=mock_client):
|
| 803 |
with patch('kiro_gateway.http_client.get_kiro_headers', return_value={}):
|
| 804 |
with patch('kiro_gateway.http_client.asyncio.sleep', new_callable=AsyncMock):
|
|
@@ -810,5 +856,5 @@ class TestKiroHttpClientFirstTokenTimeout:
|
|
| 810 |
stream=False
|
| 811 |
)
|
| 812 |
|
| 813 |
-
print("
|
| 814 |
assert exc_info.value.status_code == 502
|
|
|
|
| 1 |
# -*- coding: utf-8 -*-
|
| 2 |
|
| 3 |
"""
|
| 4 |
+
Unit tests for KiroHttpClient.
|
| 5 |
+
Tests retry logic, error handling, and HTTP client management.
|
| 6 |
"""
|
| 7 |
|
| 8 |
import asyncio
|
|
|
|
| 15 |
|
| 16 |
from kiro_gateway.http_client import KiroHttpClient
|
| 17 |
from kiro_gateway.auth import KiroAuthManager
|
| 18 |
+
from kiro_gateway.config import MAX_RETRIES, BASE_RETRY_DELAY, FIRST_TOKEN_MAX_RETRIES, STREAMING_READ_TIMEOUT
|
| 19 |
|
| 20 |
|
| 21 |
@pytest.fixture
|
| 22 |
def mock_auth_manager_for_http():
|
| 23 |
+
"""Creates a mocked KiroAuthManager for HTTP client tests."""
|
| 24 |
manager = Mock(spec=KiroAuthManager)
|
| 25 |
manager.get_access_token = AsyncMock(return_value="test_access_token")
|
| 26 |
manager.force_refresh = AsyncMock(return_value="new_access_token")
|
|
|
|
| 30 |
|
| 31 |
|
| 32 |
class TestKiroHttpClientInitialization:
|
| 33 |
+
"""Tests for KiroHttpClient initialization."""
|
| 34 |
|
| 35 |
def test_initialization_stores_auth_manager(self, mock_auth_manager_for_http):
|
| 36 |
"""
|
| 37 |
+
What it does: Verifies auth_manager is stored during initialization.
|
| 38 |
+
Purpose: Ensure auth_manager is available for obtaining tokens.
|
| 39 |
"""
|
| 40 |
+
print("Setup: Creating KiroHttpClient...")
|
| 41 |
client = KiroHttpClient(mock_auth_manager_for_http)
|
| 42 |
|
| 43 |
+
print("Verification: auth_manager is stored...")
|
| 44 |
assert client.auth_manager is mock_auth_manager_for_http
|
| 45 |
|
| 46 |
def test_initialization_client_is_none(self, mock_auth_manager_for_http):
|
| 47 |
"""
|
| 48 |
+
What it does: Verifies that HTTP client is initially None.
|
| 49 |
+
Purpose: Ensure lazy initialization.
|
| 50 |
"""
|
| 51 |
+
print("Setup: Creating KiroHttpClient...")
|
| 52 |
client = KiroHttpClient(mock_auth_manager_for_http)
|
| 53 |
|
| 54 |
+
print("Verification: client is initially None...")
|
| 55 |
assert client.client is None
|
| 56 |
|
| 57 |
|
| 58 |
class TestKiroHttpClientGetClient:
|
| 59 |
+
"""Tests for _get_client method."""
|
| 60 |
|
| 61 |
@pytest.mark.asyncio
|
| 62 |
async def test_get_client_creates_new_client(self, mock_auth_manager_for_http):
|
| 63 |
"""
|
| 64 |
+
What it does: Verifies creation of a new HTTP client.
|
| 65 |
+
Purpose: Ensure client is created on first call.
|
| 66 |
"""
|
| 67 |
+
print("Setup: Creating KiroHttpClient...")
|
| 68 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 69 |
|
| 70 |
+
print("Action: Getting client...")
|
| 71 |
with patch('kiro_gateway.http_client.httpx.AsyncClient') as mock_async_client:
|
| 72 |
mock_instance = AsyncMock()
|
| 73 |
mock_instance.is_closed = False
|
|
|
|
| 75 |
|
| 76 |
client = await http_client._get_client()
|
| 77 |
|
| 78 |
+
print("Verification: Client created...")
|
| 79 |
mock_async_client.assert_called_once()
|
| 80 |
assert client is mock_instance
|
| 81 |
|
| 82 |
@pytest.mark.asyncio
|
| 83 |
async def test_get_client_reuses_existing_client(self, mock_auth_manager_for_http):
|
| 84 |
"""
|
| 85 |
+
What it does: Verifies reuse of existing client.
|
| 86 |
+
Purpose: Ensure client is not recreated unnecessarily.
|
| 87 |
"""
|
| 88 |
+
print("Setup: Creating KiroHttpClient with existing client...")
|
| 89 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 90 |
|
| 91 |
mock_existing = AsyncMock()
|
| 92 |
mock_existing.is_closed = False
|
| 93 |
http_client.client = mock_existing
|
| 94 |
|
| 95 |
+
print("Action: Getting client...")
|
| 96 |
client = await http_client._get_client()
|
| 97 |
|
| 98 |
+
print("Verification: Existing client returned...")
|
| 99 |
assert client is mock_existing
|
| 100 |
|
| 101 |
@pytest.mark.asyncio
|
| 102 |
async def test_get_client_recreates_closed_client(self, mock_auth_manager_for_http):
|
| 103 |
"""
|
| 104 |
+
What it does: Verifies recreation of closed client.
|
| 105 |
+
Purpose: Ensure closed client is replaced with a new one.
|
| 106 |
"""
|
| 107 |
+
print("Setup: Creating KiroHttpClient with closed client...")
|
| 108 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 109 |
|
| 110 |
mock_closed = AsyncMock()
|
| 111 |
mock_closed.is_closed = True
|
| 112 |
http_client.client = mock_closed
|
| 113 |
|
| 114 |
+
print("Action: Getting client...")
|
| 115 |
with patch('kiro_gateway.http_client.httpx.AsyncClient') as mock_async_client:
|
| 116 |
mock_new = AsyncMock()
|
| 117 |
mock_new.is_closed = False
|
|
|
|
| 119 |
|
| 120 |
client = await http_client._get_client()
|
| 121 |
|
| 122 |
+
print("Verification: New client created...")
|
| 123 |
mock_async_client.assert_called_once()
|
| 124 |
assert client is mock_new
|
| 125 |
|
| 126 |
|
| 127 |
class TestKiroHttpClientClose:
|
| 128 |
+
"""Tests for close method."""
|
| 129 |
|
| 130 |
@pytest.mark.asyncio
|
| 131 |
async def test_close_closes_client(self, mock_auth_manager_for_http):
|
| 132 |
"""
|
| 133 |
+
What it does: Verifies HTTP client closure.
|
| 134 |
+
Purpose: Ensure aclose() is called.
|
| 135 |
"""
|
| 136 |
+
print("Setup: Creating KiroHttpClient with client...")
|
| 137 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 138 |
|
| 139 |
mock_client = AsyncMock()
|
|
|
|
| 141 |
mock_client.aclose = AsyncMock()
|
| 142 |
http_client.client = mock_client
|
| 143 |
|
| 144 |
+
print("Action: Closing client...")
|
| 145 |
await http_client.close()
|
| 146 |
|
| 147 |
+
print("Verification: aclose() called...")
|
| 148 |
mock_client.aclose.assert_called_once()
|
| 149 |
|
| 150 |
@pytest.mark.asyncio
|
| 151 |
async def test_close_does_nothing_for_none_client(self, mock_auth_manager_for_http):
|
| 152 |
"""
|
| 153 |
+
What it does: Verifies that close() doesn't fail for None client.
|
| 154 |
+
Purpose: Ensure safe close() call without client.
|
| 155 |
"""
|
| 156 |
+
print("Setup: Creating KiroHttpClient without client...")
|
| 157 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 158 |
|
| 159 |
+
print("Action: Closing client...")
|
| 160 |
+
await http_client.close() # Should not raise an error
|
| 161 |
|
| 162 |
+
print("Verification: No errors...")
|
| 163 |
|
| 164 |
@pytest.mark.asyncio
|
| 165 |
async def test_close_does_nothing_for_closed_client(self, mock_auth_manager_for_http):
|
| 166 |
"""
|
| 167 |
+
What it does: Verifies that close() doesn't fail for closed client.
|
| 168 |
+
Purpose: Ensure safe repeated close() call.
|
| 169 |
"""
|
| 170 |
+
print("Setup: Creating KiroHttpClient with closed client...")
|
| 171 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 172 |
|
| 173 |
mock_client = AsyncMock()
|
| 174 |
mock_client.is_closed = True
|
| 175 |
http_client.client = mock_client
|
| 176 |
|
| 177 |
+
print("Action: Closing client...")
|
| 178 |
await http_client.close()
|
| 179 |
|
| 180 |
+
print("Verification: aclose() NOT called...")
|
| 181 |
mock_client.aclose.assert_not_called()
|
| 182 |
|
| 183 |
|
| 184 |
class TestKiroHttpClientRequestWithRetry:
|
| 185 |
+
"""Tests for request_with_retry method."""
|
| 186 |
|
| 187 |
@pytest.mark.asyncio
|
| 188 |
async def test_successful_request_returns_response(self, mock_auth_manager_for_http):
|
| 189 |
"""
|
| 190 |
+
What it does: Verifies successful request.
|
| 191 |
+
Purpose: Ensure 200 response is returned immediately.
|
| 192 |
"""
|
| 193 |
+
print("Setup: Creating KiroHttpClient...")
|
| 194 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 195 |
|
| 196 |
mock_response = AsyncMock()
|
|
|
|
| 200 |
mock_client.is_closed = False
|
| 201 |
mock_client.request = AsyncMock(return_value=mock_response)
|
| 202 |
|
| 203 |
+
print("Action: Executing request...")
|
| 204 |
with patch.object(http_client, '_get_client', return_value=mock_client):
|
| 205 |
with patch('kiro_gateway.http_client.get_kiro_headers', return_value={}):
|
| 206 |
response = await http_client.request_with_retry(
|
|
|
|
| 209 |
{"data": "value"}
|
| 210 |
)
|
| 211 |
|
| 212 |
+
print("Verification: Response received...")
|
| 213 |
assert response.status_code == 200
|
| 214 |
mock_client.request.assert_called_once()
|
| 215 |
|
| 216 |
@pytest.mark.asyncio
|
| 217 |
async def test_403_triggers_token_refresh(self, mock_auth_manager_for_http):
|
| 218 |
"""
|
| 219 |
+
What it does: Verifies token refresh on 403.
|
| 220 |
+
Purpose: Ensure force_refresh() is called on 403.
|
| 221 |
"""
|
| 222 |
+
print("Setup: Creating KiroHttpClient...")
|
| 223 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 224 |
|
| 225 |
mock_response_403 = AsyncMock()
|
|
|
|
| 232 |
mock_client.is_closed = False
|
| 233 |
mock_client.request = AsyncMock(side_effect=[mock_response_403, mock_response_200])
|
| 234 |
|
| 235 |
+
print("Action: Executing request...")
|
| 236 |
with patch.object(http_client, '_get_client', return_value=mock_client):
|
| 237 |
with patch('kiro_gateway.http_client.get_kiro_headers', return_value={}):
|
| 238 |
response = await http_client.request_with_retry(
|
|
|
|
| 241 |
{"data": "value"}
|
| 242 |
)
|
| 243 |
|
| 244 |
+
print("Verification: force_refresh() called...")
|
| 245 |
mock_auth_manager_for_http.force_refresh.assert_called_once()
|
| 246 |
assert response.status_code == 200
|
| 247 |
|
| 248 |
@pytest.mark.asyncio
|
| 249 |
async def test_429_triggers_backoff(self, mock_auth_manager_for_http):
|
| 250 |
"""
|
| 251 |
+
What it does: Verifies exponential backoff on 429.
|
| 252 |
+
Purpose: Ensure request is retried after delay.
|
| 253 |
"""
|
| 254 |
+
print("Setup: Creating KiroHttpClient...")
|
| 255 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 256 |
|
| 257 |
mock_response_429 = AsyncMock()
|
|
|
|
| 264 |
mock_client.is_closed = False
|
| 265 |
mock_client.request = AsyncMock(side_effect=[mock_response_429, mock_response_200])
|
| 266 |
|
| 267 |
+
print("Action: Executing request...")
|
| 268 |
with patch.object(http_client, '_get_client', return_value=mock_client):
|
| 269 |
with patch('kiro_gateway.http_client.get_kiro_headers', return_value={}):
|
| 270 |
with patch('kiro_gateway.http_client.asyncio.sleep', new_callable=AsyncMock) as mock_sleep:
|
|
|
|
| 274 |
{"data": "value"}
|
| 275 |
)
|
| 276 |
|
| 277 |
+
print("Verification: sleep() called for backoff...")
|
| 278 |
mock_sleep.assert_called_once()
|
| 279 |
assert response.status_code == 200
|
| 280 |
|
| 281 |
@pytest.mark.asyncio
|
| 282 |
async def test_5xx_triggers_backoff(self, mock_auth_manager_for_http):
|
| 283 |
"""
|
| 284 |
+
What it does: Verifies exponential backoff on 5xx.
|
| 285 |
+
Purpose: Ensure server errors are handled with retry.
|
| 286 |
"""
|
| 287 |
+
print("Setup: Creating KiroHttpClient...")
|
| 288 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 289 |
|
| 290 |
mock_response_500 = AsyncMock()
|
|
|
|
| 297 |
mock_client.is_closed = False
|
| 298 |
mock_client.request = AsyncMock(side_effect=[mock_response_500, mock_response_200])
|
| 299 |
|
| 300 |
+
print("Action: Executing request...")
|
| 301 |
with patch.object(http_client, '_get_client', return_value=mock_client):
|
| 302 |
with patch('kiro_gateway.http_client.get_kiro_headers', return_value={}):
|
| 303 |
with patch('kiro_gateway.http_client.asyncio.sleep', new_callable=AsyncMock) as mock_sleep:
|
|
|
|
| 307 |
{"data": "value"}
|
| 308 |
)
|
| 309 |
|
| 310 |
+
print("Verification: sleep() called for backoff...")
|
| 311 |
mock_sleep.assert_called_once()
|
| 312 |
assert response.status_code == 200
|
| 313 |
|
| 314 |
@pytest.mark.asyncio
|
| 315 |
async def test_timeout_triggers_backoff(self, mock_auth_manager_for_http):
|
| 316 |
"""
|
| 317 |
+
What it does: Verifies exponential backoff on timeout.
|
| 318 |
+
Purpose: Ensure timeouts are handled with retry.
|
| 319 |
"""
|
| 320 |
+
print("Setup: Creating KiroHttpClient...")
|
| 321 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 322 |
|
| 323 |
mock_response_200 = AsyncMock()
|
|
|
|
| 330 |
mock_response_200
|
| 331 |
])
|
| 332 |
|
| 333 |
+
print("Action: Executing request...")
|
| 334 |
with patch.object(http_client, '_get_client', return_value=mock_client):
|
| 335 |
with patch('kiro_gateway.http_client.get_kiro_headers', return_value={}):
|
| 336 |
with patch('kiro_gateway.http_client.asyncio.sleep', new_callable=AsyncMock) as mock_sleep:
|
|
|
|
| 340 |
{"data": "value"}
|
| 341 |
)
|
| 342 |
|
| 343 |
+
print("Verification: sleep() called for backoff...")
|
| 344 |
mock_sleep.assert_called_once()
|
| 345 |
assert response.status_code == 200
|
| 346 |
|
| 347 |
@pytest.mark.asyncio
|
| 348 |
async def test_request_error_triggers_backoff(self, mock_auth_manager_for_http):
|
| 349 |
"""
|
| 350 |
+
What it does: Verifies exponential backoff on request error.
|
| 351 |
+
Purpose: Ensure network errors are handled with retry.
|
| 352 |
"""
|
| 353 |
+
print("Setup: Creating KiroHttpClient...")
|
| 354 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 355 |
|
| 356 |
mock_response_200 = AsyncMock()
|
|
|
|
| 363 |
mock_response_200
|
| 364 |
])
|
| 365 |
|
| 366 |
+
print("Action: Executing request...")
|
| 367 |
with patch.object(http_client, '_get_client', return_value=mock_client):
|
| 368 |
with patch('kiro_gateway.http_client.get_kiro_headers', return_value={}):
|
| 369 |
with patch('kiro_gateway.http_client.asyncio.sleep', new_callable=AsyncMock) as mock_sleep:
|
|
|
|
| 373 |
{"data": "value"}
|
| 374 |
)
|
| 375 |
|
| 376 |
+
print("Verification: sleep() called for backoff...")
|
| 377 |
mock_sleep.assert_called_once()
|
| 378 |
assert response.status_code == 200
|
| 379 |
|
| 380 |
@pytest.mark.asyncio
|
| 381 |
async def test_max_retries_exceeded_raises_502(self, mock_auth_manager_for_http):
|
| 382 |
"""
|
| 383 |
+
What it does: Verifies HTTPException is raised after exhausting retries.
|
| 384 |
+
Purpose: Ensure 502 is raised after MAX_RETRIES.
|
| 385 |
"""
|
| 386 |
+
print("Setup: Creating KiroHttpClient...")
|
| 387 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 388 |
|
| 389 |
mock_client = AsyncMock()
|
| 390 |
mock_client.is_closed = False
|
| 391 |
mock_client.request = AsyncMock(side_effect=httpx.TimeoutException("Timeout"))
|
| 392 |
|
| 393 |
+
print("Action: Executing request...")
|
| 394 |
with patch.object(http_client, '_get_client', return_value=mock_client):
|
| 395 |
with patch('kiro_gateway.http_client.get_kiro_headers', return_value={}):
|
| 396 |
with patch('kiro_gateway.http_client.asyncio.sleep', new_callable=AsyncMock):
|
|
|
|
| 401 |
{"data": "value"}
|
| 402 |
)
|
| 403 |
|
| 404 |
+
print(f"Verification: HTTPException with code 502...")
|
| 405 |
assert exc_info.value.status_code == 502
|
| 406 |
assert str(MAX_RETRIES) in exc_info.value.detail
|
| 407 |
|
| 408 |
@pytest.mark.asyncio
|
| 409 |
async def test_other_status_codes_returned_as_is(self, mock_auth_manager_for_http):
|
| 410 |
"""
|
| 411 |
+
What it does: Verifies other status codes are returned without retry.
|
| 412 |
+
Purpose: Ensure 400, 404, etc. are returned immediately.
|
| 413 |
"""
|
| 414 |
+
print("Setup: Creating KiroHttpClient...")
|
| 415 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 416 |
|
| 417 |
mock_response = AsyncMock()
|
|
|
|
| 421 |
mock_client.is_closed = False
|
| 422 |
mock_client.request = AsyncMock(return_value=mock_response)
|
| 423 |
|
| 424 |
+
print("Action: Executing request...")
|
| 425 |
with patch.object(http_client, '_get_client', return_value=mock_client):
|
| 426 |
with patch('kiro_gateway.http_client.get_kiro_headers', return_value={}):
|
| 427 |
response = await http_client.request_with_retry(
|
|
|
|
| 430 |
{"data": "value"}
|
| 431 |
)
|
| 432 |
|
| 433 |
+
print("Verification: 400 response returned without retry...")
|
| 434 |
assert response.status_code == 400
|
| 435 |
mock_client.request.assert_called_once()
|
| 436 |
|
| 437 |
@pytest.mark.asyncio
|
| 438 |
async def test_streaming_request_uses_send(self, mock_auth_manager_for_http):
|
| 439 |
"""
|
| 440 |
+
What it does: Verifies send() is used for streaming.
|
| 441 |
+
Purpose: Ensure stream=True uses build_request + send.
|
| 442 |
"""
|
| 443 |
+
print("Setup: Creating KiroHttpClient...")
|
| 444 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 445 |
|
| 446 |
mock_response = AsyncMock()
|
|
|
|
| 453 |
mock_client.build_request = Mock(return_value=mock_request)
|
| 454 |
mock_client.send = AsyncMock(return_value=mock_response)
|
| 455 |
|
| 456 |
+
print("Action: Executing streaming request...")
|
| 457 |
with patch.object(http_client, '_get_client', return_value=mock_client):
|
| 458 |
with patch('kiro_gateway.http_client.get_kiro_headers', return_value={}):
|
| 459 |
response = await http_client.request_with_retry(
|
|
|
|
| 463 |
stream=True
|
| 464 |
)
|
| 465 |
|
| 466 |
+
print("Verification: build_request and send called...")
|
| 467 |
mock_client.build_request.assert_called_once()
|
| 468 |
mock_client.send.assert_called_once_with(mock_request, stream=True)
|
| 469 |
assert response.status_code == 200
|
| 470 |
|
| 471 |
|
| 472 |
class TestKiroHttpClientContextManager:
|
| 473 |
+
"""Tests for async context manager."""
|
| 474 |
|
| 475 |
@pytest.mark.asyncio
|
| 476 |
async def test_context_manager_returns_self(self, mock_auth_manager_for_http):
|
| 477 |
"""
|
| 478 |
+
What it does: Verifies that __aenter__ returns self.
|
| 479 |
+
Purpose: Ensure correct async with behavior.
|
| 480 |
"""
|
| 481 |
+
print("Setup: Creating KiroHttpClient...")
|
| 482 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 483 |
|
| 484 |
+
print("Action: Entering context...")
|
| 485 |
result = await http_client.__aenter__()
|
| 486 |
|
| 487 |
+
print("Verification: self returned...")
|
| 488 |
assert result is http_client
|
| 489 |
|
| 490 |
@pytest.mark.asyncio
|
| 491 |
async def test_context_manager_closes_on_exit(self, mock_auth_manager_for_http):
|
| 492 |
"""
|
| 493 |
+
What it does: Verifies client closure on context exit.
|
| 494 |
+
Purpose: Ensure close() is called in __aexit__.
|
| 495 |
"""
|
| 496 |
+
print("Setup: Creating KiroHttpClient...")
|
| 497 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 498 |
|
| 499 |
mock_client = AsyncMock()
|
|
|
|
| 501 |
mock_client.aclose = AsyncMock()
|
| 502 |
http_client.client = mock_client
|
| 503 |
|
| 504 |
+
print("Action: Exiting context...")
|
| 505 |
await http_client.__aexit__(None, None, None)
|
| 506 |
|
| 507 |
+
print("Verification: aclose() called...")
|
| 508 |
mock_client.aclose.assert_called_once()
|
| 509 |
|
| 510 |
|
| 511 |
class TestKiroHttpClientExponentialBackoff:
|
| 512 |
+
"""Tests for exponential backoff logic."""
|
| 513 |
|
| 514 |
@pytest.mark.asyncio
|
| 515 |
async def test_backoff_delay_increases_exponentially(self, mock_auth_manager_for_http):
|
| 516 |
"""
|
| 517 |
+
What it does: Verifies exponential delay increase.
|
| 518 |
+
Purpose: Ensure delay = BASE_RETRY_DELAY * (2 ** attempt).
|
| 519 |
"""
|
| 520 |
+
print("Setup: Creating KiroHttpClient...")
|
| 521 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 522 |
|
| 523 |
mock_response_429 = AsyncMock()
|
|
|
|
| 528 |
|
| 529 |
mock_client = AsyncMock()
|
| 530 |
mock_client.is_closed = False
|
| 531 |
+
# 2 errors 429, then success (to verify 2 backoff delays)
|
| 532 |
mock_client.request = AsyncMock(side_effect=[
|
| 533 |
mock_response_429,
|
| 534 |
mock_response_429,
|
|
|
|
| 540 |
async def capture_sleep(delay):
|
| 541 |
sleep_delays.append(delay)
|
| 542 |
|
| 543 |
+
print("Action: Executing request with multiple retries...")
|
| 544 |
with patch.object(http_client, '_get_client', return_value=mock_client):
|
| 545 |
with patch('kiro_gateway.http_client.get_kiro_headers', return_value={}):
|
| 546 |
with patch('kiro_gateway.http_client.asyncio.sleep', side_effect=capture_sleep):
|
|
|
|
| 550 |
{"data": "value"}
|
| 551 |
)
|
| 552 |
|
| 553 |
+
print(f"Verification: Delays increase exponentially...")
|
| 554 |
+
print(f"Delays: {sleep_delays}")
|
| 555 |
assert len(sleep_delays) == 2
|
| 556 |
assert sleep_delays[0] == BASE_RETRY_DELAY * (2 ** 0) # 1.0
|
| 557 |
assert sleep_delays[1] == BASE_RETRY_DELAY * (2 ** 1) # 2.0
|
| 558 |
|
| 559 |
|
| 560 |
+
class TestKiroHttpClientStreamingTimeout:
|
| 561 |
+
"""Tests for streaming request timeout logic."""
|
| 562 |
|
| 563 |
@pytest.mark.asyncio
|
| 564 |
+
async def test_streaming_uses_streaming_read_timeout(self, mock_auth_manager_for_http):
|
| 565 |
"""
|
| 566 |
+
What it does: Verifies that streaming requests use STREAMING_READ_TIMEOUT.
|
| 567 |
+
Purpose: Ensure stream=True uses httpx.Timeout with correct values.
|
| 568 |
"""
|
| 569 |
+
print("Setup: Creating KiroHttpClient...")
|
| 570 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 571 |
|
| 572 |
mock_response = AsyncMock()
|
|
|
|
| 579 |
mock_client.build_request = Mock(return_value=mock_request)
|
| 580 |
mock_client.send = AsyncMock(return_value=mock_response)
|
| 581 |
|
| 582 |
+
print("Action: Executing streaming request...")
|
| 583 |
with patch('kiro_gateway.http_client.httpx.AsyncClient') as mock_async_client:
|
| 584 |
mock_async_client.return_value = mock_client
|
| 585 |
|
|
|
|
| 591 |
stream=True
|
| 592 |
)
|
| 593 |
|
| 594 |
+
print("Verification: AsyncClient created with httpx.Timeout for streaming...")
|
|
|
|
| 595 |
call_args = mock_async_client.call_args
|
| 596 |
timeout_arg = call_args.kwargs.get('timeout')
|
| 597 |
assert timeout_arg is not None, f"timeout not found in call_args: {call_args}"
|
| 598 |
+
print(f"Comparing connect: Expected 30.0, Got {timeout_arg.connect}")
|
| 599 |
+
assert timeout_arg.connect == 30.0, f"Expected connect=30.0, got {timeout_arg.connect}"
|
| 600 |
+
print(f"Comparing read: Expected {STREAMING_READ_TIMEOUT}, Got {timeout_arg.read}")
|
| 601 |
+
assert timeout_arg.read == STREAMING_READ_TIMEOUT, f"Expected read={STREAMING_READ_TIMEOUT}, got {timeout_arg.read}"
|
| 602 |
assert call_args.kwargs.get('follow_redirects') == True
|
| 603 |
assert response.status_code == 200
|
| 604 |
|
| 605 |
@pytest.mark.asyncio
|
| 606 |
async def test_streaming_uses_first_token_max_retries(self, mock_auth_manager_for_http):
|
| 607 |
"""
|
| 608 |
+
What it does: Verifies that streaming requests use FIRST_TOKEN_MAX_RETRIES.
|
| 609 |
+
Purpose: Ensure stream=True uses separate retry counter.
|
| 610 |
"""
|
| 611 |
+
print("Setup: Creating KiroHttpClient...")
|
| 612 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 613 |
|
| 614 |
mock_request = Mock()
|
|
|
|
| 618 |
mock_client.build_request = Mock(return_value=mock_request)
|
| 619 |
mock_client.send = AsyncMock(side_effect=httpx.TimeoutException("Timeout"))
|
| 620 |
|
| 621 |
+
print("Action: Executing streaming request with timeouts...")
|
| 622 |
with patch('kiro_gateway.http_client.httpx.AsyncClient', return_value=mock_client):
|
| 623 |
with patch('kiro_gateway.http_client.get_kiro_headers', return_value={}):
|
| 624 |
with pytest.raises(HTTPException) as exc_info:
|
|
|
|
| 629 |
stream=True
|
| 630 |
)
|
| 631 |
|
| 632 |
+
print(f"Verification: HTTPException with code 504...")
|
| 633 |
assert exc_info.value.status_code == 504
|
| 634 |
assert str(FIRST_TOKEN_MAX_RETRIES) in exc_info.value.detail
|
| 635 |
|
| 636 |
+
print(f"Verification: Attempt count = FIRST_TOKEN_MAX_RETRIES ({FIRST_TOKEN_MAX_RETRIES})...")
|
| 637 |
assert mock_client.send.call_count == FIRST_TOKEN_MAX_RETRIES
|
| 638 |
|
| 639 |
@pytest.mark.asyncio
|
| 640 |
async def test_streaming_timeout_retry_without_delay(self, mock_auth_manager_for_http):
|
| 641 |
"""
|
| 642 |
+
What it does: Verifies that streaming timeout retry happens without delay.
|
| 643 |
+
Purpose: Ensure no exponential backoff on first token timeout.
|
| 644 |
"""
|
| 645 |
+
print("Setup: Creating KiroHttpClient...")
|
| 646 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 647 |
|
| 648 |
mock_response = AsyncMock()
|
|
|
|
| 653 |
mock_client = AsyncMock()
|
| 654 |
mock_client.is_closed = False
|
| 655 |
mock_client.build_request = Mock(return_value=mock_request)
|
| 656 |
+
# First timeout, then success
|
| 657 |
mock_client.send = AsyncMock(side_effect=[
|
| 658 |
httpx.TimeoutException("Timeout"),
|
| 659 |
mock_response
|
|
|
|
| 665 |
nonlocal sleep_called
|
| 666 |
sleep_called = True
|
| 667 |
|
| 668 |
+
print("Action: Executing streaming request with one timeout...")
|
| 669 |
with patch('kiro_gateway.http_client.httpx.AsyncClient', return_value=mock_client):
|
| 670 |
with patch('kiro_gateway.http_client.get_kiro_headers', return_value={}):
|
| 671 |
with patch('kiro_gateway.http_client.asyncio.sleep', side_effect=capture_sleep):
|
|
|
|
| 676 |
stream=True
|
| 677 |
)
|
| 678 |
|
| 679 |
+
print("Verification: sleep() NOT called for streaming timeout...")
|
| 680 |
assert not sleep_called
|
| 681 |
assert response.status_code == 200
|
| 682 |
+
|
| 683 |
@pytest.mark.asyncio
|
| 684 |
async def test_non_streaming_uses_default_timeout(self, mock_auth_manager_for_http):
|
| 685 |
"""
|
| 686 |
+
What it does: Verifies that non-streaming requests use 300 seconds.
|
| 687 |
+
Purpose: Ensure stream=False uses unified httpx.Timeout.
|
| 688 |
"""
|
| 689 |
+
print("Setup: Creating KiroHttpClient...")
|
| 690 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 691 |
|
| 692 |
mock_response = AsyncMock()
|
|
|
|
| 696 |
mock_client.is_closed = False
|
| 697 |
mock_client.request = AsyncMock(return_value=mock_response)
|
| 698 |
|
| 699 |
+
print("Action: Executing non-streaming request...")
|
| 700 |
with patch('kiro_gateway.http_client.httpx.AsyncClient') as mock_async_client:
|
| 701 |
mock_async_client.return_value = mock_client
|
| 702 |
|
|
|
|
| 708 |
stream=False
|
| 709 |
)
|
| 710 |
|
| 711 |
+
print("Verification: AsyncClient created with httpx.Timeout(timeout=300)...")
|
| 712 |
+
call_args = mock_async_client.call_args
|
| 713 |
+
timeout_arg = call_args.kwargs.get('timeout')
|
| 714 |
+
assert timeout_arg is not None, f"timeout not found in call_args: {call_args}"
|
| 715 |
+
# httpx.Timeout(timeout=300) sets all timeouts to 300
|
| 716 |
+
print(f"Comparing timeout: Expected 300.0 for all, Got connect={timeout_arg.connect}")
|
| 717 |
+
assert timeout_arg.connect == 300.0
|
| 718 |
+
assert timeout_arg.read == 300.0
|
| 719 |
assert response.status_code == 200
|
| 720 |
|
| 721 |
@pytest.mark.asyncio
|
| 722 |
+
async def test_connect_timeout_logged_correctly(self, mock_auth_manager_for_http):
|
| 723 |
"""
|
| 724 |
+
What it does: Verifies ConnectTimeout logging.
|
| 725 |
+
Purpose: Ensure ConnectTimeout is logged with correct type.
|
| 726 |
"""
|
| 727 |
+
print("Setup: Creating KiroHttpClient...")
|
| 728 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 729 |
|
| 730 |
mock_response = AsyncMock()
|
|
|
|
| 735 |
mock_client = AsyncMock()
|
| 736 |
mock_client.is_closed = False
|
| 737 |
mock_client.build_request = Mock(return_value=mock_request)
|
| 738 |
+
# First ConnectTimeout, then success
|
| 739 |
+
mock_client.send = AsyncMock(side_effect=[
|
| 740 |
+
httpx.ConnectTimeout("Connection timeout"),
|
| 741 |
+
mock_response
|
| 742 |
+
])
|
| 743 |
+
|
| 744 |
+
print("Action: Executing streaming request with ConnectTimeout...")
|
| 745 |
+
with patch('kiro_gateway.http_client.httpx.AsyncClient', return_value=mock_client):
|
| 746 |
+
with patch('kiro_gateway.http_client.get_kiro_headers', return_value={}):
|
| 747 |
+
with patch('kiro_gateway.http_client.logger') as mock_logger:
|
| 748 |
+
response = await http_client.request_with_retry(
|
| 749 |
+
"POST",
|
| 750 |
+
"https://api.example.com/test",
|
| 751 |
+
{"data": "value"},
|
| 752 |
+
stream=True
|
| 753 |
+
)
|
| 754 |
|
| 755 |
+
print("Verification: logger.warning called with [ConnectTimeout]...")
|
| 756 |
+
warning_calls = [str(call) for call in mock_logger.warning.call_args_list]
|
| 757 |
+
assert any("ConnectTimeout" in call for call in warning_calls), f"ConnectTimeout not found in: {warning_calls}"
|
| 758 |
+
assert response.status_code == 200
|
| 759 |
+
|
| 760 |
+
@pytest.mark.asyncio
|
| 761 |
+
async def test_read_timeout_logged_correctly(self, mock_auth_manager_for_http):
|
| 762 |
+
"""
|
| 763 |
+
What it does: Verifies ReadTimeout logging.
|
| 764 |
+
Purpose: Ensure ReadTimeout is logged with STREAMING_READ_TIMEOUT.
|
| 765 |
+
"""
|
| 766 |
+
print("Setup: Creating KiroHttpClient...")
|
| 767 |
+
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 768 |
|
| 769 |
+
mock_response = AsyncMock()
|
| 770 |
+
mock_response.status_code = 200
|
| 771 |
+
|
| 772 |
+
mock_request = Mock()
|
| 773 |
+
|
| 774 |
+
mock_client = AsyncMock()
|
| 775 |
+
mock_client.is_closed = False
|
| 776 |
+
mock_client.build_request = Mock(return_value=mock_request)
|
| 777 |
+
# First ReadTimeout, then success
|
| 778 |
+
mock_client.send = AsyncMock(side_effect=[
|
| 779 |
+
httpx.ReadTimeout("Read timeout"),
|
| 780 |
+
mock_response
|
| 781 |
+
])
|
| 782 |
+
|
| 783 |
+
print("Action: Executing streaming request with ReadTimeout...")
|
| 784 |
+
with patch('kiro_gateway.http_client.httpx.AsyncClient', return_value=mock_client):
|
| 785 |
with patch('kiro_gateway.http_client.get_kiro_headers', return_value={}):
|
| 786 |
+
with patch('kiro_gateway.http_client.logger') as mock_logger:
|
| 787 |
+
response = await http_client.request_with_retry(
|
| 788 |
+
"POST",
|
| 789 |
+
"https://api.example.com/test",
|
| 790 |
+
{"data": "value"},
|
| 791 |
+
stream=True
|
| 792 |
+
)
|
| 793 |
|
| 794 |
+
print("Verification: logger.warning called with [ReadTimeout] and STREAMING_READ_TIMEOUT...")
|
| 795 |
+
warning_calls = [str(call) for call in mock_logger.warning.call_args_list]
|
| 796 |
+
assert any("ReadTimeout" in call for call in warning_calls), f"ReadTimeout not found in: {warning_calls}"
|
| 797 |
+
assert any(str(STREAMING_READ_TIMEOUT) in call for call in warning_calls), f"STREAMING_READ_TIMEOUT not found in: {warning_calls}"
|
|
|
|
|
|
|
|
|
|
| 798 |
assert response.status_code == 200
|
| 799 |
|
| 800 |
@pytest.mark.asyncio
|
| 801 |
+
async def test_streaming_timeout_returns_504_with_error_type(self, mock_auth_manager_for_http):
|
| 802 |
"""
|
| 803 |
+
What it does: Verifies that streaming timeout returns 504 with error type.
|
| 804 |
+
Purpose: Ensure 504 is returned with error info after exhausting retries.
|
| 805 |
"""
|
| 806 |
+
print("Setup: Creating KiroHttpClient...")
|
| 807 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 808 |
|
| 809 |
mock_request = Mock()
|
|
|
|
| 811 |
mock_client = AsyncMock()
|
| 812 |
mock_client.is_closed = False
|
| 813 |
mock_client.build_request = Mock(return_value=mock_request)
|
| 814 |
+
mock_client.send = AsyncMock(side_effect=httpx.ReadTimeout("Timeout"))
|
| 815 |
|
| 816 |
+
print("Action: Executing streaming request with persistent timeouts...")
|
| 817 |
with patch('kiro_gateway.http_client.httpx.AsyncClient', return_value=mock_client):
|
| 818 |
with patch('kiro_gateway.http_client.get_kiro_headers', return_value={}):
|
| 819 |
with pytest.raises(HTTPException) as exc_info:
|
|
|
|
| 824 |
stream=True
|
| 825 |
)
|
| 826 |
|
| 827 |
+
print("Verification: HTTPException with code 504 and error type...")
|
| 828 |
+
print(f"Comparing status_code: Expected 504, Got {exc_info.value.status_code}")
|
| 829 |
assert exc_info.value.status_code == 504
|
| 830 |
+
print(f"Comparing detail: Expected 'ReadTimeout' in '{exc_info.value.detail}'")
|
| 831 |
+
assert "ReadTimeout" in exc_info.value.detail
|
| 832 |
+
assert "Streaming failed" in exc_info.value.detail
|
| 833 |
|
| 834 |
@pytest.mark.asyncio
|
| 835 |
async def test_non_streaming_timeout_returns_502(self, mock_auth_manager_for_http):
|
| 836 |
"""
|
| 837 |
+
What it does: Verifies that non-streaming timeout returns 502.
|
| 838 |
+
Purpose: Ensure non-streaming uses legacy logic with 502.
|
| 839 |
"""
|
| 840 |
+
print("Setup: Creating KiroHttpClient...")
|
| 841 |
http_client = KiroHttpClient(mock_auth_manager_for_http)
|
| 842 |
|
| 843 |
mock_client = AsyncMock()
|
| 844 |
mock_client.is_closed = False
|
| 845 |
mock_client.request = AsyncMock(side_effect=httpx.TimeoutException("Timeout"))
|
| 846 |
|
| 847 |
+
print("Action: Executing non-streaming request with persistent timeouts...")
|
| 848 |
with patch('kiro_gateway.http_client.httpx.AsyncClient', return_value=mock_client):
|
| 849 |
with patch('kiro_gateway.http_client.get_kiro_headers', return_value={}):
|
| 850 |
with patch('kiro_gateway.http_client.asyncio.sleep', new_callable=AsyncMock):
|
|
|
|
| 856 |
stream=False
|
| 857 |
)
|
| 858 |
|
| 859 |
+
print("Verification: HTTPException with code 502...")
|
| 860 |
assert exc_info.value.status_code == 502
|
tests/unit/test_streaming.py
CHANGED
|
@@ -728,7 +728,7 @@ class TestStreamingErrorHandling:
|
|
| 728 |
|
| 729 |
|
| 730 |
class TestFirstTokenTimeoutError:
|
| 731 |
-
"""Tests for FirstTokenTimeoutError."""
|
| 732 |
|
| 733 |
@pytest.mark.asyncio
|
| 734 |
async def test_first_token_timeout_not_caught_by_general_handler(self, mock_http_client, mock_model_cache, mock_auth_manager):
|
|
@@ -771,4 +771,324 @@ class TestFirstTokenTimeoutError:
|
|
| 771 |
|
| 772 |
# Verify response was closed
|
| 773 |
mock_response.aclose.assert_called()
|
| 774 |
-
print("✓ response.aclose() was called")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 728 |
|
| 729 |
|
| 730 |
class TestFirstTokenTimeoutError:
|
| 731 |
+
"""Tests for FirstTokenTimeoutError and first token timeout logging."""
|
| 732 |
|
| 733 |
@pytest.mark.asyncio
|
| 734 |
async def test_first_token_timeout_not_caught_by_general_handler(self, mock_http_client, mock_model_cache, mock_auth_manager):
|
|
|
|
| 771 |
|
| 772 |
# Verify response was closed
|
| 773 |
mock_response.aclose.assert_called()
|
| 774 |
+
print("✓ response.aclose() was called")
|
| 775 |
+
|
| 776 |
+
@pytest.mark.asyncio
|
| 777 |
+
async def test_first_token_timeout_logged_with_correct_format(self, mock_http_client, mock_model_cache, mock_auth_manager):
|
| 778 |
+
"""
|
| 779 |
+
What it does: Verifies that first token timeout is logged with [FirstTokenTimeout] prefix.
|
| 780 |
+
Goal: Ensure consistent logging format for first token timeout.
|
| 781 |
+
"""
|
| 782 |
+
import asyncio
|
| 783 |
+
from kiro_gateway.streaming import FirstTokenTimeoutError, stream_kiro_to_openai_internal
|
| 784 |
+
|
| 785 |
+
print("Setup: Mock response with timeout...")
|
| 786 |
+
|
| 787 |
+
mock_response = AsyncMock()
|
| 788 |
+
mock_response.status_code = 200
|
| 789 |
+
mock_response.aclose = AsyncMock()
|
| 790 |
+
|
| 791 |
+
async def mock_aiter_bytes():
|
| 792 |
+
yield b'{"content":"test"}'
|
| 793 |
+
|
| 794 |
+
mock_response.aiter_bytes = mock_aiter_bytes
|
| 795 |
+
|
| 796 |
+
async def mock_wait_for_timeout(*args, **kwargs):
|
| 797 |
+
raise asyncio.TimeoutError()
|
| 798 |
+
|
| 799 |
+
print("Action: Running streaming with timeout and checking logs...")
|
| 800 |
+
|
| 801 |
+
with patch('kiro_gateway.streaming.asyncio.wait_for', side_effect=mock_wait_for_timeout):
|
| 802 |
+
with patch('kiro_gateway.streaming.logger') as mock_logger:
|
| 803 |
+
try:
|
| 804 |
+
async for chunk in stream_kiro_to_openai_internal(
|
| 805 |
+
mock_http_client, mock_response, "test-model",
|
| 806 |
+
mock_model_cache, mock_auth_manager,
|
| 807 |
+
first_token_timeout=15
|
| 808 |
+
):
|
| 809 |
+
pass
|
| 810 |
+
except FirstTokenTimeoutError:
|
| 811 |
+
pass
|
| 812 |
+
|
| 813 |
+
print("Check: logger.warning should be called with [FirstTokenTimeout]...")
|
| 814 |
+
warning_calls = [str(call) for call in mock_logger.warning.call_args_list]
|
| 815 |
+
print(f"Warning calls: {warning_calls}")
|
| 816 |
+
|
| 817 |
+
assert any("FirstTokenTimeout" in call for call in warning_calls), \
|
| 818 |
+
f"[FirstTokenTimeout] not found in warning logs: {warning_calls}"
|
| 819 |
+
print("✓ [FirstTokenTimeout] prefix found in logs")
|
| 820 |
+
|
| 821 |
+
@pytest.mark.asyncio
|
| 822 |
+
async def test_first_token_timeout_includes_timeout_value(self, mock_http_client, mock_model_cache, mock_auth_manager):
|
| 823 |
+
"""
|
| 824 |
+
What it does: Verifies that first token timeout log includes the timeout value.
|
| 825 |
+
Goal: Ensure timeout value is visible in logs for debugging.
|
| 826 |
+
"""
|
| 827 |
+
import asyncio
|
| 828 |
+
from kiro_gateway.streaming import FirstTokenTimeoutError, stream_kiro_to_openai_internal
|
| 829 |
+
|
| 830 |
+
print("Setup: Mock response with timeout...")
|
| 831 |
+
|
| 832 |
+
mock_response = AsyncMock()
|
| 833 |
+
mock_response.status_code = 200
|
| 834 |
+
mock_response.aclose = AsyncMock()
|
| 835 |
+
|
| 836 |
+
async def mock_aiter_bytes():
|
| 837 |
+
yield b'{"content":"test"}'
|
| 838 |
+
|
| 839 |
+
mock_response.aiter_bytes = mock_aiter_bytes
|
| 840 |
+
|
| 841 |
+
async def mock_wait_for_timeout(*args, **kwargs):
|
| 842 |
+
raise asyncio.TimeoutError()
|
| 843 |
+
|
| 844 |
+
custom_timeout = 25.0
|
| 845 |
+
|
| 846 |
+
print(f"Action: Running streaming with custom timeout={custom_timeout}...")
|
| 847 |
+
|
| 848 |
+
with patch('kiro_gateway.streaming.asyncio.wait_for', side_effect=mock_wait_for_timeout):
|
| 849 |
+
with patch('kiro_gateway.streaming.logger') as mock_logger:
|
| 850 |
+
try:
|
| 851 |
+
async for chunk in stream_kiro_to_openai_internal(
|
| 852 |
+
mock_http_client, mock_response, "test-model",
|
| 853 |
+
mock_model_cache, mock_auth_manager,
|
| 854 |
+
first_token_timeout=custom_timeout
|
| 855 |
+
):
|
| 856 |
+
pass
|
| 857 |
+
except FirstTokenTimeoutError:
|
| 858 |
+
pass
|
| 859 |
+
|
| 860 |
+
print("Check: logger.warning should include timeout value...")
|
| 861 |
+
warning_calls = [str(call) for call in mock_logger.warning.call_args_list]
|
| 862 |
+
print(f"Warning calls: {warning_calls}")
|
| 863 |
+
|
| 864 |
+
assert any(str(custom_timeout) in call for call in warning_calls), \
|
| 865 |
+
f"Timeout value {custom_timeout} not found in warning logs: {warning_calls}"
|
| 866 |
+
print(f"✓ Timeout value {custom_timeout} found in logs")
|
| 867 |
+
|
| 868 |
+
@pytest.mark.asyncio
|
| 869 |
+
async def test_first_token_received_logged_on_success(self, mock_http_client, mock_model_cache, mock_auth_manager):
|
| 870 |
+
"""
|
| 871 |
+
What it does: Verifies that successful first token receipt is logged.
|
| 872 |
+
Goal: Ensure debug log shows when first token is received.
|
| 873 |
+
"""
|
| 874 |
+
from kiro_gateway.streaming import stream_kiro_to_openai_internal
|
| 875 |
+
|
| 876 |
+
print("Setup: Mock response with successful first token...")
|
| 877 |
+
|
| 878 |
+
mock_response = AsyncMock()
|
| 879 |
+
mock_response.status_code = 200
|
| 880 |
+
mock_response.aclose = AsyncMock()
|
| 881 |
+
|
| 882 |
+
async def mock_aiter_bytes():
|
| 883 |
+
yield b'{"content":"Hello"}'
|
| 884 |
+
|
| 885 |
+
mock_response.aiter_bytes = mock_aiter_bytes
|
| 886 |
+
|
| 887 |
+
mock_parser = MagicMock()
|
| 888 |
+
mock_parser.feed.return_value = [{"type": "content", "data": "Hello"}]
|
| 889 |
+
mock_parser.get_tool_calls.return_value = []
|
| 890 |
+
|
| 891 |
+
print("Action: Running streaming and checking debug logs...")
|
| 892 |
+
|
| 893 |
+
with patch('kiro_gateway.streaming.AwsEventStreamParser', return_value=mock_parser):
|
| 894 |
+
with patch('kiro_gateway.streaming.parse_bracket_tool_calls', return_value=[]):
|
| 895 |
+
with patch('kiro_gateway.streaming.logger') as mock_logger:
|
| 896 |
+
chunks = []
|
| 897 |
+
async for chunk in stream_kiro_to_openai_internal(
|
| 898 |
+
mock_http_client, mock_response, "test-model",
|
| 899 |
+
mock_model_cache, mock_auth_manager,
|
| 900 |
+
first_token_timeout=15
|
| 901 |
+
):
|
| 902 |
+
chunks.append(chunk)
|
| 903 |
+
|
| 904 |
+
print(f"Received {len(chunks)} chunks")
|
| 905 |
+
print("Check: logger.debug should be called with 'First token received'...")
|
| 906 |
+
debug_calls = [str(call) for call in mock_logger.debug.call_args_list]
|
| 907 |
+
print(f"Debug calls: {debug_calls}")
|
| 908 |
+
|
| 909 |
+
assert any("First token received" in call for call in debug_calls), \
|
| 910 |
+
f"'First token received' not found in debug logs: {debug_calls}"
|
| 911 |
+
print("✓ 'First token received' found in debug logs")
|
| 912 |
+
|
| 913 |
+
|
| 914 |
+
class TestStreamWithFirstTokenRetry:
|
| 915 |
+
"""Tests for stream_with_first_token_retry function."""
|
| 916 |
+
|
| 917 |
+
@pytest.mark.asyncio
|
| 918 |
+
async def test_retry_on_first_token_timeout(self, mock_http_client, mock_model_cache, mock_auth_manager):
|
| 919 |
+
"""
|
| 920 |
+
What it does: Verifies that request is retried on first token timeout.
|
| 921 |
+
Goal: Ensure retry logic works for first token timeout.
|
| 922 |
+
"""
|
| 923 |
+
import asyncio
|
| 924 |
+
from kiro_gateway.streaming import stream_with_first_token_retry, FirstTokenTimeoutError
|
| 925 |
+
|
| 926 |
+
print("Setup: Mock make_request that succeeds on second attempt...")
|
| 927 |
+
|
| 928 |
+
mock_response_success = AsyncMock()
|
| 929 |
+
mock_response_success.status_code = 200
|
| 930 |
+
mock_response_success.aclose = AsyncMock()
|
| 931 |
+
|
| 932 |
+
async def mock_aiter_bytes_success():
|
| 933 |
+
yield b'{"content":"Success"}'
|
| 934 |
+
|
| 935 |
+
mock_response_success.aiter_bytes = mock_aiter_bytes_success
|
| 936 |
+
|
| 937 |
+
call_count = 0
|
| 938 |
+
|
| 939 |
+
async def mock_make_request():
|
| 940 |
+
nonlocal call_count
|
| 941 |
+
call_count += 1
|
| 942 |
+
print(f"make_request called (attempt {call_count})")
|
| 943 |
+
return mock_response_success
|
| 944 |
+
|
| 945 |
+
mock_parser = MagicMock()
|
| 946 |
+
mock_parser.feed.return_value = [{"type": "content", "data": "Success"}]
|
| 947 |
+
mock_parser.get_tool_calls.return_value = []
|
| 948 |
+
|
| 949 |
+
# First call raises timeout, second succeeds
|
| 950 |
+
timeout_raised = False
|
| 951 |
+
|
| 952 |
+
async def mock_wait_for_with_retry(coro, timeout):
|
| 953 |
+
nonlocal timeout_raised
|
| 954 |
+
if not timeout_raised:
|
| 955 |
+
timeout_raised = True
|
| 956 |
+
raise asyncio.TimeoutError()
|
| 957 |
+
return await coro
|
| 958 |
+
|
| 959 |
+
print("Action: Running stream_with_first_token_retry...")
|
| 960 |
+
|
| 961 |
+
with patch('kiro_gateway.streaming.AwsEventStreamParser', return_value=mock_parser):
|
| 962 |
+
with patch('kiro_gateway.streaming.parse_bracket_tool_calls', return_value=[]):
|
| 963 |
+
with patch('kiro_gateway.streaming.asyncio.wait_for', side_effect=mock_wait_for_with_retry):
|
| 964 |
+
chunks = []
|
| 965 |
+
async for chunk in stream_with_first_token_retry(
|
| 966 |
+
mock_make_request,
|
| 967 |
+
mock_http_client,
|
| 968 |
+
"test-model",
|
| 969 |
+
mock_model_cache,
|
| 970 |
+
mock_auth_manager,
|
| 971 |
+
max_retries=3,
|
| 972 |
+
first_token_timeout=15
|
| 973 |
+
):
|
| 974 |
+
chunks.append(chunk)
|
| 975 |
+
|
| 976 |
+
print(f"Received {len(chunks)} chunks")
|
| 977 |
+
print(f"make_request was called {call_count} times")
|
| 978 |
+
|
| 979 |
+
assert call_count == 2, f"Expected 2 calls (1 timeout + 1 success), got {call_count}"
|
| 980 |
+
assert len(chunks) > 0, "Should receive chunks after retry"
|
| 981 |
+
print("✓ Retry logic worked correctly")
|
| 982 |
+
|
| 983 |
+
@pytest.mark.asyncio
|
| 984 |
+
async def test_all_retries_exhausted_raises_504(self, mock_http_client, mock_model_cache, mock_auth_manager):
|
| 985 |
+
"""
|
| 986 |
+
What it does: Verifies that 504 is raised after all retries exhausted.
|
| 987 |
+
Goal: Ensure proper error handling when model never responds.
|
| 988 |
+
"""
|
| 989 |
+
import asyncio
|
| 990 |
+
from fastapi import HTTPException
|
| 991 |
+
from kiro_gateway.streaming import stream_with_first_token_retry
|
| 992 |
+
|
| 993 |
+
print("Setup: Mock make_request that always times out...")
|
| 994 |
+
|
| 995 |
+
mock_response = AsyncMock()
|
| 996 |
+
mock_response.status_code = 200
|
| 997 |
+
mock_response.aclose = AsyncMock()
|
| 998 |
+
|
| 999 |
+
async def mock_aiter_bytes():
|
| 1000 |
+
yield b'{"content":"test"}'
|
| 1001 |
+
|
| 1002 |
+
mock_response.aiter_bytes = mock_aiter_bytes
|
| 1003 |
+
|
| 1004 |
+
call_count = 0
|
| 1005 |
+
|
| 1006 |
+
async def mock_make_request():
|
| 1007 |
+
nonlocal call_count
|
| 1008 |
+
call_count += 1
|
| 1009 |
+
print(f"make_request called (attempt {call_count})")
|
| 1010 |
+
return mock_response
|
| 1011 |
+
|
| 1012 |
+
async def mock_wait_for_always_timeout(*args, **kwargs):
|
| 1013 |
+
raise asyncio.TimeoutError()
|
| 1014 |
+
|
| 1015 |
+
max_retries = 3
|
| 1016 |
+
|
| 1017 |
+
print(f"Action: Running stream_with_first_token_retry with max_retries={max_retries}...")
|
| 1018 |
+
|
| 1019 |
+
with patch('kiro_gateway.streaming.asyncio.wait_for', side_effect=mock_wait_for_always_timeout):
|
| 1020 |
+
with pytest.raises(HTTPException) as exc_info:
|
| 1021 |
+
async for chunk in stream_with_first_token_retry(
|
| 1022 |
+
mock_make_request,
|
| 1023 |
+
mock_http_client,
|
| 1024 |
+
"test-model",
|
| 1025 |
+
mock_model_cache,
|
| 1026 |
+
mock_auth_manager,
|
| 1027 |
+
max_retries=max_retries,
|
| 1028 |
+
first_token_timeout=15
|
| 1029 |
+
):
|
| 1030 |
+
pass
|
| 1031 |
+
|
| 1032 |
+
print(f"Caught HTTPException: {exc_info.value.status_code} - {exc_info.value.detail}")
|
| 1033 |
+
print(f"make_request was called {call_count} times")
|
| 1034 |
+
|
| 1035 |
+
print(f"Сравниваем status_code: Ожидалось 504, Получено {exc_info.value.status_code}")
|
| 1036 |
+
assert exc_info.value.status_code == 504
|
| 1037 |
+
print(f"Сравниваем call_count: Ожидалось {max_retries}, Получено {call_count}")
|
| 1038 |
+
assert call_count == max_retries
|
| 1039 |
+
assert "15" in exc_info.value.detail, "Timeout value should be in error message"
|
| 1040 |
+
print("✓ 504 raised after all retries exhausted")
|
| 1041 |
+
|
| 1042 |
+
@pytest.mark.asyncio
|
| 1043 |
+
async def test_retry_logs_attempt_number(self, mock_http_client, mock_model_cache, mock_auth_manager):
|
| 1044 |
+
"""
|
| 1045 |
+
What it does: Verifies that retry attempts are logged with attempt number.
|
| 1046 |
+
Goal: Ensure logs show which attempt failed.
|
| 1047 |
+
"""
|
| 1048 |
+
import asyncio
|
| 1049 |
+
from fastapi import HTTPException
|
| 1050 |
+
from kiro_gateway.streaming import stream_with_first_token_retry
|
| 1051 |
+
|
| 1052 |
+
print("Setup: Mock make_request that always times out...")
|
| 1053 |
+
|
| 1054 |
+
mock_response = AsyncMock()
|
| 1055 |
+
mock_response.status_code = 200
|
| 1056 |
+
mock_response.aclose = AsyncMock()
|
| 1057 |
+
|
| 1058 |
+
async def mock_aiter_bytes():
|
| 1059 |
+
yield b'{"content":"test"}'
|
| 1060 |
+
|
| 1061 |
+
mock_response.aiter_bytes = mock_aiter_bytes
|
| 1062 |
+
|
| 1063 |
+
async def mock_make_request():
|
| 1064 |
+
return mock_response
|
| 1065 |
+
|
| 1066 |
+
async def mock_wait_for_always_timeout(*args, **kwargs):
|
| 1067 |
+
raise asyncio.TimeoutError()
|
| 1068 |
+
|
| 1069 |
+
print("Action: Running stream_with_first_token_retry and checking logs...")
|
| 1070 |
+
|
| 1071 |
+
with patch('kiro_gateway.streaming.asyncio.wait_for', side_effect=mock_wait_for_always_timeout):
|
| 1072 |
+
with patch('kiro_gateway.streaming.logger') as mock_logger:
|
| 1073 |
+
try:
|
| 1074 |
+
async for chunk in stream_with_first_token_retry(
|
| 1075 |
+
mock_make_request,
|
| 1076 |
+
mock_http_client,
|
| 1077 |
+
"test-model",
|
| 1078 |
+
mock_model_cache,
|
| 1079 |
+
mock_auth_manager,
|
| 1080 |
+
max_retries=3,
|
| 1081 |
+
first_token_timeout=15
|
| 1082 |
+
):
|
| 1083 |
+
pass
|
| 1084 |
+
except HTTPException:
|
| 1085 |
+
pass
|
| 1086 |
+
|
| 1087 |
+
print("Check: logger.warning should include attempt numbers...")
|
| 1088 |
+
warning_calls = [str(call) for call in mock_logger.warning.call_args_list]
|
| 1089 |
+
print(f"Warning calls: {warning_calls}")
|
| 1090 |
+
|
| 1091 |
+
# Should have warnings for attempts 1/3, 2/3, 3/3
|
| 1092 |
+
assert any("1/3" in call or "2/3" in call or "3/3" in call for call in warning_calls), \
|
| 1093 |
+
f"Attempt numbers not found in warning logs: {warning_calls}"
|
| 1094 |
+
print("✓ Attempt numbers found in logs")
|