From 303f62db063b00028a4489c3ec1994a701035cc0 Mon Sep 17 00:00:00 2001 From: Chris Hagglund Date: Fri, 20 Nov 2026 12:11:13 -0600 Subject: [PATCH 1/2] test: show that concurrent 401s each fetch a new token After a failover every in-flight request gets 401 INVALID_TOKEN at once. Each one calls force_refresh_auth_token, which fetches a new token without a lock, so N rejected requests fetch N tokens. The async client has the same race when N coroutines make their first call together. The tests are marked xfail(strict=True) until the fix lands: - 20 rejected requests (sync): 21 token fetches, expected 2 - 20 rejected requests (async): 21 token fetches, expected 2 - 20 first calls (async): 20 token fetches, expected 1 Co-Authored-By: Claude Opus 5.5 --- tests/unit/api_client/test_token_refresh.py | 136 ++++++++++++++++++++ 1 file changed, 136 insertions(+) create mode 100644 tests/unit/api_client/test_token_refresh.py diff --git a/tests/unit/api_client/test_token_refresh.py b/tests/unit/api_client/test_token_refresh.py new file mode 100644 index 000000000..94e93dfb1 --- /dev/null +++ b/tests/unit/api_client/test_token_refresh.py @@ -0,0 +1,136 @@ +import asyncio +import threading +import time +import unittest +from concurrent.futures import ThreadPoolExecutor + +import httpx +import pytest + +from conductor.client.configuration.configuration import Configuration +from conductor.client.configuration.settings.authentication_settings import AuthenticationSettings +from conductor.client.http.api_client import ApiClient +from conductor.client.http.async_api_client import AsyncApiClient +from conductor.client.http.async_rest import AsyncRESTClientObject + +SERVER_URL = 'http://server/api' +INVALID_TOKEN = {'error': 'INVALID_TOKEN', 'message': 'Not a valid token'} +N = 20 + + +def _configuration(): + return Configuration( + server_api_url=SERVER_URL, + authentication_settings=AuthenticationSettings(key_id='key', key_secret='secret'), + ) + + +def _is_token_request(request): + return request.url.path.endswith('/token') + + +class TestTokenRefresh(unittest.TestCase): + """After a failover every in-flight request is rejected at once; together they must fetch one new token.""" + + def _run(self, coro): + loop = asyncio.new_event_loop() + try: + return loop.run_until_complete(coro) + finally: + loop.close() + + @pytest.mark.xfail(strict=True, reason='each rejected request fetches its own token') + def test_concurrent_rejections_fetch_one_new_token(self): + issued = [] + rejected = [] + failed_over = threading.Event() + all_rejected = threading.Barrier(N, timeout=5) + lock = threading.Lock() + + def handler(request): + if _is_token_request(request): + # Hold the fetch open so the other requests' refreshes overlap it. + time.sleep(0.05) + with lock: + issued.append(None) + return httpx.Response(200, json={'token': f't{len(issued)}'}) + if failed_over.is_set() and request.headers.get('X-Authorization') == 't1': + with lock: + rejected.append(None) + try: + all_rejected.wait() + except threading.BrokenBarrierError: + pass + return httpx.Response(401, json=INVALID_TOKEN) + return httpx.Response(200, json={}) + + configuration = _configuration() + configuration.http_connection = httpx.Client(transport=httpx.MockTransport(handler)) + client = ApiClient(configuration) # fetches t1 + failed_over.set() + + with ThreadPoolExecutor(max_workers=N) as pool: + futures = [pool.submit(client.call_api, '/thing', 'GET', _return_http_data_only=True) for _ in range(N)] + for future in futures: + future.result() + + self.assertEqual(N, len(rejected)) + self.assertEqual(2, len(issued)) # t1 before the failover, t2 shared by every retry + + @pytest.mark.xfail(strict=True, reason='each rejected request fetches its own token') + def test_concurrent_rejections_fetch_one_new_token_async(self): + issued = [] + rejected = [] + state = {'failed_over': False} + + async def scenario(): + all_rejected = asyncio.Event() + + async def handler(request): + if _is_token_request(request): + await asyncio.sleep(0.05) + issued.append(None) + return httpx.Response(200, json={'token': f't{len(issued)}'}) + if state['failed_over'] and request.headers.get('X-Authorization') == 't1': + rejected.append(None) + if len(rejected) == N: + all_rejected.set() + try: + await asyncio.wait_for(all_rejected.wait(), timeout=5) + except asyncio.TimeoutError: + pass + return httpx.Response(401, json=INVALID_TOKEN) + return httpx.Response(200, json={}) + + client = AsyncApiClient(_configuration()) + client.async_rest_client = AsyncRESTClientObject( + connection=httpx.AsyncClient(transport=httpx.MockTransport(handler))) + await client.call_api('/thing', 'GET', _return_http_data_only=True) # fetches t1 + state['failed_over'] = True + await asyncio.gather(*(client.call_api('/thing', 'GET', _return_http_data_only=True) for _ in range(N))) + + self._run(scenario()) + + self.assertEqual(N, len(rejected)) + self.assertEqual(2, len(issued)) # t1 before the failover, t2 shared by every retry + + @pytest.mark.xfail(strict=True, reason='each first call fetches its own token') + def test_concurrent_first_calls_fetch_one_token_async(self): + issued = [] + + async def scenario(): + async def handler(request): + if _is_token_request(request): + await asyncio.sleep(0.05) + issued.append(None) + return httpx.Response(200, json={'token': f't{len(issued)}'}) + return httpx.Response(200, json={}) + + client = AsyncApiClient(_configuration()) + client.async_rest_client = AsyncRESTClientObject( + connection=httpx.AsyncClient(transport=httpx.MockTransport(handler))) + await asyncio.gather(*(client.call_api('/thing', 'GET', _return_http_data_only=True) for _ in range(N))) + + self._run(scenario()) + + self.assertEqual(1, len(issued)) From ccf415ea7cb9d3b42563da2d3f5260930984c0ed Mon Sep 17 00:00:00 2001 From: Chris Hagglund Date: Fri, 20 Nov 2026 12:14:25 -0600 Subject: [PATCH 2/2] fix: fetch one new token when concurrent requests are rejected On a 401 with EXPIRED_TOKEN or INVALID_TOKEN, the client now passes the token the request carried to __refresh_auth_token_if_stale. Under a lock, it fetches a new token only if the cache still holds the rejected one; otherwise another thread or coroutine already replaced it, and the request retries with the cached token. The TTL renewal (sync and async) and the async client's first token fetch now check again under the same lock, so callers that need a new token together fetch it once. Each worker process still has its own client and token; this change only removes duplicate fetches within one process. Removes the xfail markers from the tests added in the previous commit. Co-Authored-By: Claude Opus 5.5 --- src/conductor/client/http/api_client.py | 54 ++++++++++++---- src/conductor/client/http/async_api_client.py | 64 +++++++++++++------ tests/unit/api_client/test_token_refresh.py | 4 -- 3 files changed, 86 insertions(+), 36 deletions(-) diff --git a/src/conductor/client/http/api_client.py b/src/conductor/client/http/api_client.py index c753da008..fef632403 100644 --- a/src/conductor/client/http/api_client.py +++ b/src/conductor/client/http/api_client.py @@ -7,6 +7,7 @@ import os import re import tempfile +import threading import time from typing import Dict, Optional, TYPE_CHECKING import uuid @@ -68,6 +69,9 @@ def __init__( self._token_refresh_failures = 0 self._last_token_refresh_attempt = 0 self._max_token_refresh_failures = 5 # Stop after 5 consecutive failures + # Serializes token renewal so threads that need a new token together fetch it once. + # RLock because the token fetch itself goes through call_api. + self._token_lock = threading.RLock() # Metrics collector for API request tracking self.metrics_collector = metrics_collector @@ -95,7 +99,7 @@ def __call_api( logger.info( f'Authentication token is {token_status}, renewing token... (request: {method} {resource_path})') # if the token has expired or is invalid, lets refresh the token - success = self.__force_refresh_auth_token() + success = self.__refresh_auth_token_if_stale(getattr(ae, 'rejected_token', None)) if success: logger.debug('Authentication token successfully renewed') # and now retry the same request @@ -176,13 +180,18 @@ def __call_api_no_retry( url = self.configuration.host + resource_path # perform request and return response - response_data = self.request( - method, url, query_params=query_params, headers=header_params, - post_params=post_params, body=body, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - metric_uri=metric_uri, - metric_context=metric_context) + try: + response_data = self.request( + method, url, query_params=query_params, headers=header_params, + post_params=post_params, body=body, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + metric_uri=metric_uri, + metric_context=metric_context) + except AuthorizationException as ae: + # The token this request carried, so a refresh can tell whether another thread already replaced it. + ae.rejected_token = auth_headers['header']['X-Authorization'] if auth_headers else None + raise return_data = response_data if _preload_content: @@ -793,12 +802,15 @@ def __get_authentication_headers(self): time_since_last_update = now - self.configuration.token_update_time if time_since_last_update > self.configuration.auth_token_ttl_msec: - # time to refresh the token - skip backoff for legitimate renewal - logger.info('Authentication token TTL expired, renewing token...') - token = self.__get_new_token(skip_backoff=True) - self.configuration.update_token(token) - if token: - logger.debug('Authentication token successfully renewed') + with self._token_lock: + # Threads that found the token expired together queue here; only the first renews it. + if now - self.configuration.token_update_time > self.configuration.auth_token_ttl_msec: + # time to refresh the token - skip backoff for legitimate renewal + logger.info('Authentication token TTL expired, renewing token...') + token = self.__get_new_token(skip_backoff=True) + self.configuration.update_token(token) + if token: + logger.debug('Authentication token successfully renewed') return { 'header': { @@ -840,6 +852,20 @@ def __force_refresh_auth_token(self) -> bool: """Deprecated: Use force_refresh_auth_token() instead""" return self.force_refresh_auth_token() + def __refresh_auth_token_if_stale(self, stale_token) -> bool: + """ + Replaces stale_token, the token the server rejected, unless another thread already has. + After a failover every in-flight request is rejected at once, and they should share one new token. + """ + if stale_token is None: + # The request carried no token (such as /token itself), so there is nothing to compare. + return self.__force_refresh_auth_token() + with self._token_lock: + current = self.configuration.AUTH_TOKEN + if current is not None and current != stale_token: + return True + return self.__force_refresh_auth_token() + def __get_new_token(self, skip_backoff: bool = False) -> str: """ Get a new authentication token from the server. diff --git a/src/conductor/client/http/async_api_client.py b/src/conductor/client/http/async_api_client.py index 543ec026d..4d1d2855e 100644 --- a/src/conductor/client/http/async_api_client.py +++ b/src/conductor/client/http/async_api_client.py @@ -1,5 +1,6 @@ from __future__ import annotations +import asyncio import base64 import datetime import logging @@ -70,6 +71,8 @@ def __init__( self._token_refresh_failures = 0 self._last_token_refresh_attempt = 0 self._max_token_refresh_failures = 5 # Stop after 5 consecutive failures + # Serializes token renewal so coroutines that need a new token together fetch it once. + self._token_lock = asyncio.Lock() # Metrics collector for API request tracking self.metrics_collector = metrics_collector @@ -106,7 +109,7 @@ async def __call_api( logger.info( f'Authentication token is {token_status}, renewing token... (request: {method} {resource_path})') # if the token has expired or is invalid, lets refresh the token - success = await self.__force_refresh_auth_token() + success = await self.__refresh_auth_token_if_stale(getattr(ae, 'rejected_token', None)) if success: logger.debug('Authentication token successfully renewed') # and now retry the same request @@ -186,12 +189,17 @@ async def __call_api_no_retry( url = self.configuration.host + resource_path # perform request and return response - response_data = await self.request( - method, url, query_params=query_params, headers=header_params, - post_params=post_params, body=body, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - metric_uri=metric_uri) + try: + response_data = await self.request( + method, url, query_params=query_params, headers=header_params, + post_params=post_params, body=body, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + metric_uri=metric_uri) + except AuthorizationException as ae: + # The token this request carried, so a refresh can tell whether another coroutine already replaced it. + ae.rejected_token = auth_headers['header']['X-Authorization'] if auth_headers else None + raise return_data = response_data if _preload_content: @@ -755,11 +763,14 @@ async def __get_authentication_headers(self): if self.configuration.AUTH_TOKEN is None: if self.configuration.authentication_settings is None: return None - # Initial token generation - apply backoff if there were previous failures - logger.debug('No auth token found, requesting initial token...') - token = await self.__get_new_token(skip_backoff=False) - self.configuration.update_token(token) - if not token: + async with self._token_lock: + # Coroutines that start together queue here; only the first fetches the initial token. + if self.configuration.AUTH_TOKEN is None: + # Initial token generation - apply backoff if there were previous failures + logger.debug('No auth token found, requesting initial token...') + token = await self.__get_new_token(skip_backoff=False) + self.configuration.update_token(token) + if not self.configuration.AUTH_TOKEN: # Failed to get initial token return None @@ -767,12 +778,15 @@ async def __get_authentication_headers(self): time_since_last_update = now - self.configuration.token_update_time if time_since_last_update > self.configuration.auth_token_ttl_msec: - # time to refresh the token - skip backoff for legitimate renewal - logger.info('Authentication token TTL expired, renewing token...') - token = await self.__get_new_token(skip_backoff=True) - self.configuration.update_token(token) - if token: - logger.debug('Authentication token successfully renewed') + async with self._token_lock: + # Coroutines that found the token expired together queue here; only the first renews it. + if now - self.configuration.token_update_time > self.configuration.auth_token_ttl_msec: + # time to refresh the token - skip backoff for legitimate renewal + logger.info('Authentication token TTL expired, renewing token...') + token = await self.__get_new_token(skip_backoff=True) + self.configuration.update_token(token) + if token: + logger.debug('Authentication token successfully renewed') return { 'header': { @@ -799,6 +813,20 @@ async def __force_refresh_auth_token(self) -> bool: """Deprecated: Use force_refresh_auth_token() instead""" return await self.force_refresh_auth_token() + async def __refresh_auth_token_if_stale(self, stale_token) -> bool: + """ + Replaces stale_token, the token the server rejected, unless another coroutine already has. + After a failover every in-flight request is rejected at once, and they should share one new token. + """ + if stale_token is None: + # The request carried no token (such as /token itself), so there is nothing to compare. + return await self.__force_refresh_auth_token() + async with self._token_lock: + current = self.configuration.AUTH_TOKEN + if current is not None and current != stale_token: + return True + return await self.__force_refresh_auth_token() + async def __get_new_token(self, skip_backoff: bool = False) -> str: """ Get a new authentication token from the server. diff --git a/tests/unit/api_client/test_token_refresh.py b/tests/unit/api_client/test_token_refresh.py index 94e93dfb1..c8be3b444 100644 --- a/tests/unit/api_client/test_token_refresh.py +++ b/tests/unit/api_client/test_token_refresh.py @@ -5,7 +5,6 @@ from concurrent.futures import ThreadPoolExecutor import httpx -import pytest from conductor.client.configuration.configuration import Configuration from conductor.client.configuration.settings.authentication_settings import AuthenticationSettings @@ -39,7 +38,6 @@ def _run(self, coro): finally: loop.close() - @pytest.mark.xfail(strict=True, reason='each rejected request fetches its own token') def test_concurrent_rejections_fetch_one_new_token(self): issued = [] rejected = [] @@ -77,7 +75,6 @@ def handler(request): self.assertEqual(N, len(rejected)) self.assertEqual(2, len(issued)) # t1 before the failover, t2 shared by every retry - @pytest.mark.xfail(strict=True, reason='each rejected request fetches its own token') def test_concurrent_rejections_fetch_one_new_token_async(self): issued = [] rejected = [] @@ -114,7 +111,6 @@ async def handler(request): self.assertEqual(N, len(rejected)) self.assertEqual(2, len(issued)) # t1 before the failover, t2 shared by every retry - @pytest.mark.xfail(strict=True, reason='each first call fetches its own token') def test_concurrent_first_calls_fetch_one_token_async(self): issued = []