The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix grace period with better error handling on frontend and as per best practices
Harshit Jainf87b12a2f7d2
diff --git a/docs/my-website/docs/proxy/config_settings.md b/docs/my-website/docs/proxy/config_settings.mdindex 5499e541335..03cf665b3c8 100644--- a/docs/my-website/docs/proxy/config_settings.md+++ b/docs/my-website/docs/proxy/config_settings.md@@ -765,7 +765,7 @@ router_settings:| LITELM_ENVIRONMENT | Environment of LiteLLM Instance, used by logging services. Currently only used by DeepEval.| LITELLM_KEY_ROTATION_ENABLED | Enable auto-key rotation for LiteLLM (boolean). Default is false.| LITELLM_KEY_ROTATION_CHECK_INTERVAL_SECONDS | Interval in seconds for how often to run job that auto-rotates keys. Default is 86400 (24 hours).-| LITELLM_KEY_ROTATION_GRACE_PERIOD_HOURS | Hours to keep old key valid after rotation (e.g. 24, 48, 72). Default is 0 (immediate revoke). Used for scheduled rotations and as fallback when not specified in regenerate request.+| LITELLM_KEY_ROTATION_GRACE_PERIOD | Duration to keep old key valid after rotation (e.g. "24h", "2d"). Default is empty (immediate revoke). Used for scheduled rotations and as fallback when not specified in regenerate request.| LITELLM_LICENSE | License key for LiteLLM usage| LITELLM_LOCAL_MODEL_COST_MAP | Local configuration for model cost mapping in LiteLLM| LITELLM_LOG | Enable detailed logging for LiteLLMdiff --git a/docs/my-website/docs/proxy/virtual_keys.md b/docs/my-website/docs/proxy/virtual_keys.mdindex 31506ea2611..c74aa75ff4a 100644--- a/docs/my-website/docs/proxy/virtual_keys.md+++ b/docs/my-website/docs/proxy/virtual_keys.md@@ -550,12 +550,12 @@ curl 'http://localhost:4000/key/sk-1234/regenerate' \"gpt-4","gpt-3.5-turbo"],- "grace_period_hours": 48+ "grace_period": "48h"}'```-**Grace period (optional)**: Set `grace_period_hours` (e.g. 24, 48, 72) to keep the old key valid for a transitional period. Both old and new keys work until the grace period elapses, enabling seamless cutover without production downtime. Default is 0 (immediate revoke). Can also be set via `LITELLM_KEY_ROTATION_GRACE_PERIOD_HOURS` for scheduled rotations.+**Grace period (optional)**: Set `grace_period` (e.g. `"24h"`, `"2d"`, `"1w"`) to keep the old key valid for a transitional period. Both old and new keys work until the grace period elapses, enabling seamless cutover without production downtime. Omitted or empty = immediate revoke. Can also be set via `LITELLM_KEY_ROTATION_GRACE_PERIOD` env var for scheduled rotations.**Read More**@@ -643,13 +643,13 @@ Set these environment variables when starting the proxy:|----------|-------------|---------|| `LITELLM_KEY_ROTATION_ENABLED` | Enable the rotation worker | `false` || `LITELLM_KEY_ROTATION_CHECK_INTERVAL_SECONDS` | How often to scan for keys to rotate (in seconds) | `86400` (24 hours) |-| `LITELLM_KEY_ROTATION_GRACE_PERIOD_HOURS` | Hours to keep old key valid after rotation (24–72 recommended) | `0` (immediate revoke) |+| `LITELLM_KEY_ROTATION_GRACE_PERIOD` | Duration to keep old key valid after rotation (e.g. `24h`, `2d`) | `""` (immediate revoke) |**Example:**```bashexport LITELLM_KEY_ROTATION_ENABLED=trueexport LITELLM_KEY_ROTATION_CHECK_INTERVAL_SECONDS=3600 # Check every hour-export LITELLM_KEY_ROTATION_GRACE_PERIOD_HOURS=48 # Keep old key valid for 48h during cutover+export LITELLM_KEY_ROTATION_GRACE_PERIOD=48h # Keep old key valid for 48h during cutoverlitellm --config config.yaml```diff --git a/litellm/constants.py b/litellm/constants.pyindex 73713e6a05b..56349505299 100644--- a/litellm/constants.py+++ b/litellm/constants.py@@ -106,9 +106,7 @@ MCP_OAUTH2_TOKEN_CACHE_DEFAULT_TTL = int(# npm/npx needs a writable cache dir; in containers the default (~/.npm)# may not exist or be read-only. /tmp is always writable.MCP_NPM_CACHE_DIR = os.getenv("MCP_NPM_CACHE_DIR", "/tmp/.npm_mcp_cache")-MCP_OAUTH2_TOKEN_CACHE_MIN_TTL = int(- os.getenv("MCP_OAUTH2_TOKEN_CACHE_MIN_TTL", "10")-)+MCP_OAUTH2_TOKEN_CACHE_MIN_TTL = int(os.getenv("MCP_OAUTH2_TOKEN_CACHE_MIN_TTL", "10"))LITELLM_UI_ALLOW_HEADERS = ["x-litellm-semantic-filter",@@ -225,9 +223,7 @@ REDIS_DAILY_TAG_SPEND_UPDATE_BUFFER_KEY = "litellm_daily_tag_spend_update_bufferMAX_REDIS_BUFFER_DEQUEUE_COUNT = int(os.getenv("MAX_REDIS_BUFFER_DEQUEUE_COUNT", 100))MAX_SIZE_IN_MEMORY_QUEUE = int(os.getenv("MAX_SIZE_IN_MEMORY_QUEUE", 2000))# Bounds asyncio.Queue() instances (log queues, spend update queues, etc.) to prevent unbounded memory growth-LITELLM_ASYNCIO_QUEUE_MAXSIZE = int(- os.getenv("LITELLM_ASYNCIO_QUEUE_MAXSIZE", 1000)-)+LITELLM_ASYNCIO_QUEUE_MAXSIZE = int(os.getenv("LITELLM_ASYNCIO_QUEUE_MAXSIZE", 1000))MAX_IN_MEMORY_QUEUE_FLUSH_COUNT = int(os.getenv("MAX_IN_MEMORY_QUEUE_FLUSH_COUNT", 1000))@@ -349,7 +345,9 @@ MAX_SIZE_PER_ITEM_IN_MEMORY_CACHE_IN_KB = int(DEFAULT_MAX_TOKENS_FOR_TRITON = int(os.getenv("DEFAULT_MAX_TOKENS_FOR_TRITON", 2000))#### Networking settings ####request_timeout: float = float(os.getenv("REQUEST_TIMEOUT", 6000)) # time in seconds-DEFAULT_A2A_AGENT_TIMEOUT: float = float(os.getenv("DEFAULT_A2A_AGENT_TIMEOUT", 6000)) # 10 minutes+DEFAULT_A2A_AGENT_TIMEOUT: float = float(+ os.getenv("DEFAULT_A2A_AGENT_TIMEOUT", 6000)+) # 10 minutes# Patterns that indicate a localhost/internal URL in A2A agent cards that should be# replaced with the original base_url. This is a common misconfiguration where# developers deploy agents with development URLs in their agent cards.@@ -1256,9 +1254,9 @@ LITELLM_KEY_ROTATION_ENABLED = os.getenv("LITELLM_KEY_ROTATION_ENABLED", "false"LITELLM_KEY_ROTATION_CHECK_INTERVAL_SECONDS = int(os.getenv("LITELLM_KEY_ROTATION_CHECK_INTERVAL_SECONDS", 86400)) # 24 hours default-LITELLM_KEY_ROTATION_GRACE_PERIOD_HOURS = int(- os.getenv("LITELLM_KEY_ROTATION_GRACE_PERIOD_HOURS", 0)-) # Hours to keep old key valid after rotation; 0 = immediate revoke (default)+LITELLM_KEY_ROTATION_GRACE_PERIOD: str = os.getenv(+ "LITELLM_KEY_ROTATION_GRACE_PERIOD", ""+) # Duration to keep old key valid after rotation (e.g. "24h", "2d"); empty = immediate revoke (default)UI_SESSION_TOKEN_TEAM_ID = "litellm-dashboard"LITELLM_PROXY_ADMIN_NAME = "default_user_id"diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.pyindex b8c84c7fa2d..fb632dd16d4 100644--- a/litellm/proxy/_types.py+++ b/litellm/proxy/_types.py@@ -854,9 +854,9 @@ class GenerateRequestBase(LiteLLMPydanticObjectBase):allowed_cache_controls: Optional[list] = []config: Optional[dict] = {}permissions: Optional[dict] = {}- model_max_budget: Optional[dict] = (- {}- ) # {"gpt-4": 5.0, "gpt-3.5-turbo": 5.0}, defaults to {}+ model_max_budget: Optional[+ dict+ ] = {} # {"gpt-4": 5.0, "gpt-3.5-turbo": 5.0}, defaults to {}model_config = ConfigDict(protected_namespaces=())model_rpm_limit: Optional[dict] = None@@ -995,9 +995,9 @@ class RegenerateKeyRequest(GenerateKeyRequest):spend: Optional[float] = Nonemetadata: Optional[dict] = Nonenew_master_key: Optional[str] = None- grace_period_hours: Optional[- int- ] = None # Hours to keep old key valid; 0/None = immediate revoke+ grace_period: Optional[+ str+ ] = None # Duration to keep old key valid (e.g. "24h", "2d"); None = immediate revokeclass ResetSpendRequest(LiteLLMPydanticObjectBase):@@ -1409,12 +1409,12 @@ class NewCustomerRequest(BudgetNewRequest):blocked: bool = False # allow/disallow requests for this end-userbudget_id: Optional[str] = None # give either a budget_id or max_budgetspend: Optional[float] = None- allowed_model_region: Optional[AllowedModelRegion] = (- None # require all user requests to use models in this specific region- )- default_model: Optional[str] = (- None # if no equivalent model in allowed region - default all requests to this model- )+ allowed_model_region: Optional[+ AllowedModelRegion+ ] = None # require all user requests to use models in this specific region+ default_model: Optional[+ str+ ] = None # if no equivalent model in allowed region - default all requests to this model@model_validator(mode="before")@classmethod@@ -1436,12 +1436,12 @@ class UpdateCustomerRequest(LiteLLMPydanticObjectBase):blocked: bool = False # allow/disallow requests for this end-usermax_budget: Optional[float] = Nonebudget_id: Optional[str] = None # give either a budget_id or max_budget- allowed_model_region: Optional[AllowedModelRegion] = (- None # require all user requests to use models in this specific region- )- default_model: Optional[str] = (- None # if no equivalent model in allowed region - default all requests to this model- )+ allowed_model_region: Optional[+ AllowedModelRegion+ ] = None # require all user requests to use models in this specific region+ default_model: Optional[+ str+ ] = None # if no equivalent model in allowed region - default all requests to this modelclass DeleteCustomerRequest(LiteLLMPydanticObjectBase):@@ -1530,15 +1530,15 @@ class NewTeamRequest(TeamBase):] = None # raise an error if 'guaranteed_throughput' is set and we're overallocating tpmmodel_tpm_limit: Optional[Dict[str, int]] = None- team_member_budget: Optional[float] = (- None # allow user to set a budget for all team members- )- team_member_rpm_limit: Optional[int] = (- None # allow user to set RPM limit for all team members- )- team_member_tpm_limit: Optional[int] = (- None # allow user to set TPM limit for all team members- )+ team_member_budget: Optional[+ float+ ] = None # allow user to set a budget for all team members+ team_member_rpm_limit: Optional[+ int+ ] = None # allow user to set RPM limit for all team members+ team_member_tpm_limit: Optional[+ int+ ] = None # allow user to set TPM limit for all team membersteam_member_key_duration: Optional[str] = None # e.g. "1d", "1w", "1m"allowed_vector_store_indexes: Optional[List[AllowedVectorStoreIndexItem]] = None@@ -1630,9 +1630,9 @@ class BlockKeyRequest(LiteLLMPydanticObjectBase):class AddTeamCallback(LiteLLMPydanticObjectBase):callback_name: str- callback_type: Optional[Literal["success", "failure", "success_and_failure"]] = (- "success_and_failure"- )+ callback_type: Optional[+ Literal["success", "failure", "success_and_failure"]+ ] = "success_and_failure"callback_vars: Dict[str, str]@model_validator(mode="before")@@ -1964,9 +1964,9 @@ class ConfigList(LiteLLMPydanticObjectBase):stored_in_db: Optional[bool]field_default_value: Anypremium_field: bool = False- nested_fields: Optional[List[FieldDetail]] = (- None # For nested dictionary or Pydantic fields- )+ nested_fields: Optional[+ List[FieldDetail]+ ] = None # For nested dictionary or Pydantic fieldsclass UserHeaderMapping(LiteLLMPydanticObjectBase):@@ -2406,9 +2406,9 @@ class LiteLLM_OrganizationMembershipTable(LiteLLMPydanticObjectBase):budget_id: Optional[str] = Nonecreated_at: datetimeupdated_at: datetime- user: Optional[Any] = (- None # You might want to replace 'Any' with a more specific type if available- )+ user: Optional[+ Any+ ] = None # You might want to replace 'Any' with a more specific type if availablelitellm_budget_table: Optional[LiteLLM_BudgetTable] = Nonemodel_config = ConfigDict(protected_namespaces=())@@ -3384,9 +3384,9 @@ class TeamModelDeleteRequest(BaseModel):# Organization Member Requestsclass OrganizationMemberAddRequest(OrgMemberAddRequest):organization_id: str- max_budget_in_organization: Optional[float] = (- None # Users max budget within the organization- )+ max_budget_in_organization: Optional[+ float+ ] = None # Users max budget within the organizationclass OrganizationMemberDeleteRequest(MemberDeleteRequest):@@ -3604,9 +3604,9 @@ class ProviderBudgetResponse(LiteLLMPydanticObjectBase):Maps provider names to their budget configs."""- providers: Dict[str, ProviderBudgetResponseObject] = (- {}- ) # Dictionary mapping provider names to their budget configurations+ providers: Dict[+ str, ProviderBudgetResponseObject+ ] = {} # Dictionary mapping provider names to their budget configurationsclass ProxyStateVariables(TypedDict):@@ -3749,9 +3749,9 @@ class LiteLLM_JWTAuth(LiteLLMPydanticObjectBase):enforce_rbac: bool = Falseroles_jwt_field: Optional[str] = None # v2 on role mappingsrole_mappings: Optional[List[RoleMapping]] = None- object_id_jwt_field: Optional[str] = (- None # can be either user / team, inferred from the role mapping- )+ object_id_jwt_field: Optional[+ str+ ] = None # can be either user / team, inferred from the role mappingscope_mappings: Optional[List[ScopeMapping]] = Noneenforce_scope_based_access: bool = Falseenforce_team_based_model_access: bool = Falsediff --git a/litellm/proxy/common_utils/key_rotation_manager.py b/litellm/proxy/common_utils/key_rotation_manager.pyindex 7ef26bf07b9..88fd08f6ab4 100644--- a/litellm/proxy/common_utils/key_rotation_manager.py+++ b/litellm/proxy/common_utils/key_rotation_manager.py@@ -10,7 +10,7 @@ from typing import Listfrom litellm._logging import verbose_proxy_loggerfrom litellm.constants import (LITELLM_INTERNAL_JOBS_SERVICE_ACCOUNT_NAME,- LITELLM_KEY_ROTATION_GRACE_PERIOD_HOURS,+ LITELLM_KEY_ROTATION_GRACE_PERIOD,)from litellm.proxy._types import (GenerateKeyResponse,@@ -143,7 +143,7 @@ class KeyRotationManager:regenerate_request = RegenerateKeyRequest(key=key.token or "",key_alias=key.key_alias, # Pass key alias to ensure correct secret is updated in AWS Secrets Manager- grace_period_hours=LITELLM_KEY_ROTATION_GRACE_PERIOD_HOURS,+ grace_period=LITELLM_KEY_ROTATION_GRACE_PERIOD or None,)# Create a system user for key rotationdiff --git a/litellm/proxy/management_endpoints/key_management_endpoints.py b/litellm/proxy/management_endpoints/key_management_endpoints.pyindex f7ad44879bd..e8a1af27978 100644--- a/litellm/proxy/management_endpoints/key_management_endpoints.py+++ b/litellm/proxy/management_endpoints/key_management_endpoints.py@@ -629,7 +629,11 @@ async def _common_key_generation_helper( # noqa: PLR0915# Validate user-provided key formatif data.key is not None and not data.key.startswith("sk-"):- _masked = "{}****{}".format(data.key[:4], data.key[-4:]) if len(data.key) > 8 else "****"+ _masked = (+ "{}****{}".format(data.key[:4], data.key[-4:])+ if len(data.key) > 8+ else "****"+ )raise HTTPException(status_code=400,detail={@@ -1342,7 +1346,7 @@ async def prepare_key_update_data(data_json: dict = data.model_dump(exclude_unset=True)data_json.pop("key", None)data_json.pop("new_key", None)- data_json.pop("grace_period_hours", None) # Request-only param, not a DB column+ data_json.pop("grace_period", None) # Request-only param, not a DB columnif (data.metadata is not Noneand data.metadata.get("service_account_id") is not None@@ -3178,6 +3182,69 @@ def get_new_token(data: Optional[RegenerateKeyRequest]) -> str:return new_token+async def _insert_deprecated_key(+ prisma_client: "PrismaClient",+ old_token_hash: str,+ new_token_hash: str,+ grace_period: Optional[str],+) -> None:+ """+ Insert old key into deprecated table so it remains valid during grace period.++ Uses upsert to handle concurrent rotations gracefully.++ Parameters:+ prisma_client: DB client+ old_token_hash: Hash of the old key being rotated out+ new_token_hash: Hash of the new replacement key+ grace_period: Duration string (e.g. "24h", "2d") or None/empty for immediate revoke+ """+ grace_period_value = grace_period or os.getenv(+ "LITELLM_KEY_ROTATION_GRACE_PERIOD", ""+ )+ if not grace_period_value:+ return++ try:+ grace_seconds = duration_in_seconds(grace_period_value)+ except ValueError:+ verbose_proxy_logger.warning(+ "Invalid grace_period format: %s. Expected format like '24h', '2d'.",+ grace_period_value,+ )+ return++ if grace_seconds <= 0:+ return++ try:+ revoke_at = datetime.now(timezone.utc) + timedelta(seconds=grace_seconds)+ await prisma_client.db.litellm_deprecatedverificationtoken.upsert(+ where={"token": old_token_hash},+ data={+ "create": {+ "token": old_token_hash,+ "active_token_id": new_token_hash,+ "revoke_at": revoke_at,+ },+ "update": {+ "active_token_id": new_token_hash,+ "revoke_at": revoke_at,+ },+ },+ )+ verbose_proxy_logger.debug(+ "Deprecated key retained for %s (revoke_at: %s)",+ grace_period_value,+ revoke_at,+ )+ except Exception as deprecated_err:+ verbose_proxy_logger.warning(+ "Failed to insert deprecated key for grace period: %s",+ deprecated_err,+ )++@router.post("/key/{key:path}/regenerate",tags=["key management"],@@ -3228,7 +3295,7 @@ async def regenerate_key_fn( # noqa: PLR0915- permissions: Optional[dict] - Key-specific permissions- guardrails: Optional[List[str]] - List of active guardrails for the key- blocked: Optional[bool] - Whether the key is blocked- - grace_period_hours: Optional[int] - Hours to keep old key valid after rotation (e.g. 24, 48, 72). 0 or omitted = immediate revoke. Env: LITELLM_KEY_ROTATION_GRACE_PERIOD_HOURS+ - grace_period: Optional[str] - Duration to keep old key valid after rotation (e.g. "24h", "2d"). Omitted = immediate revoke. Env: LITELLM_KEY_ROTATION_GRACE_PERIODReturns:@@ -3369,44 +3436,13 @@ async def regenerate_key_fn( # noqa: PLR0915update_data.update(non_default_values)update_data = prisma_client.jsonify_object(data=update_data)- # If grace period > 0, insert deprecated key so old key remains valid- if data is not None and data.grace_period_hours is not None:- grace_period_hours = data.grace_period_hours- else:- grace_period_hours = int(- os.getenv("LITELLM_KEY_ROTATION_GRACE_PERIOD_HOURS", "0")- )- if grace_period_hours > 0:- try:- revoke_at = datetime.now(timezone.utc) + timedelta(- hours=grace_period_hours- )- # Use upsert to handle concurrent rotations gracefully; avoids- # unique constraint violation if same key is rotated simultaneously- await prisma_client.db.litellm_deprecatedverificationtoken.upsert(- where={"token": hashed_api_key},- data={- "create": {- "token": hashed_api_key,- "active_token_id": new_token_hash,- "revoke_at": revoke_at,- },- "update": {- "active_token_id": new_token_hash,- "revoke_at": revoke_at,- },- },- )- verbose_proxy_logger.debug(- "Deprecated key retained for %s hours (revoke_at: %s)",- grace_period_hours,- revoke_at,- )- except Exception as deprecated_err:- verbose_proxy_logger.warning(- "Failed to insert deprecated key for grace period: %s",- deprecated_err,- )+ # If grace period set, insert deprecated key so old key remains valid+ await _insert_deprecated_key(+ prisma_client=prisma_client,+ old_token_hash=hashed_api_key,+ new_token_hash=new_token_hash,+ grace_period=data.grace_period if data else None,+ )# Update the token in the databaseupdated_token = await prisma_client.db.litellm_verificationtoken.update(diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.pyindex 5fbc003ceb1..528415c891d 100644--- a/litellm/proxy/utils.py+++ b/litellm/proxy/utils.py@@ -1375,11 +1375,11 @@ class ProxyLogging:# Note: user_info is a CallInfo that can represent user/team/org level info. For team budgets,# alert_emails is populated from team_object.metadata.soft_budget_alerting_emails (see auth_checks.py)is_soft_budget_with_alert_emails = (- type == "soft_budget"- and user_info.alert_emails is not None+ type == "soft_budget"+ and user_info.alert_emails is not Noneand len(user_info.alert_emails) > 0)-+if self.alerting is None and not is_soft_budget_with_alert_emails:# do nothing if alerting is not switched on (unless it's a soft_budget alert with team-specific emails)return@@ -1395,10 +1395,9 @@ class ProxyLogging:# 1. "email" is in alerting config, OR# 2. It's a soft_budget alert with team-specific alert_emails (bypasses global alerting config)should_send_email = (- (self.alerting is not None and "email" in self.alerting)- or is_soft_budget_with_alert_emails- )-+ self.alerting is not None and "email" in self.alerting+ ) or is_soft_budget_with_alert_emails+if should_send_email and self.email_logging_instance is not None:await self.email_logging_instance.budget_alerts(type=type,@@ -2032,6 +2031,54 @@ def jsonify_object(data: dict) -> dict:return db_data+# In-memory cache for deprecated key lookups: maps old_token_hash -> (active_token_id, expires_at_ts)+# Avoids a DB query on every auth request for non-deprecated keys.+_deprecated_key_cache: Dict[str, tuple] = {}+_DEPRECATED_KEY_CACHE_TTL_SECONDS = 60+++async def _lookup_deprecated_key(+ db: Any,+ hashed_token: str,+) -> Optional[str]:+ """+ Check if a token exists in the deprecated keys table and is still within its grace period.++ Returns the active_token_id if found and valid, otherwise None.+ Uses an in-memory cache to avoid DB queries on every auth request.+ """+ now = datetime.now(timezone.utc)+ now_ts = now.timestamp()++ # Check cache first+ cached = _deprecated_key_cache.get(hashed_token)+ if cached is not None:+ active_token_id, cache_expires_at_ts = cached+ if now_ts < cache_expires_at_ts:+ return active_token_id+ else:+ _deprecated_key_cache.pop(hashed_token, None)++ try:+ deprecated_row = await db.litellm_deprecatedverificationtoken.find_first(+ where={+ "token": hashed_token,+ "revoke_at": {"gt": now},+ },+ select={"active_token_id": True},+ )+ if deprecated_row and deprecated_row.active_token_id:+ _deprecated_key_cache[hashed_token] = (+ deprecated_row.active_token_id,+ now_ts + _DEPRECATED_KEY_CACHE_TTL_SECONDS,+ )+ return deprecated_row.active_token_id+ except Exception as e:+ verbose_proxy_logger.debug("Deprecated key lookup skipped: %s", e)++ return None++class PrismaClient:spend_log_transactions: List = []_spend_log_transactions_lock = asyncio.Lock()@@ -2665,32 +2712,22 @@ class PrismaClient:)# If not found in main table, check deprecated keys (grace period)- if response is None:- try:- deprecated_row = await self.db.litellm_deprecatedverificationtoken.find_first(- where={- "token": hashed_token,- "revoke_at": {"gt": datetime.now(timezone.utc)},- },- select={"active_token_id": True},+ if response is None and hashed_token is not None:+ active_token_id = await _lookup_deprecated_key(+ db=self.db, hashed_token=hashed_token+ )+ if active_token_id:+ response = await self.get_data(+ token=active_token_id,+ table_name="combined_view",+ query_type="find_unique",+ parent_otel_span=parent_otel_span,+ proxy_logging_obj=proxy_logging_obj,)- if deprecated_row and deprecated_row.active_token_id:- response = await self.get_data(- token=deprecated_row.active_token_id,- table_name="combined_view",- query_type="find_unique",- parent_otel_span=parent_otel_span,- proxy_logging_obj=proxy_logging_obj,+ if response is not None:+ verbose_proxy_logger.debug(+ "Deprecated key used during grace period")- if response is not None:- verbose_proxy_logger.debug(- "Deprecated key used during grace period"- )- except Exception as deprecated_lookup_error:- verbose_proxy_logger.debug(- "Deprecated key lookup skipped: %s",- deprecated_lookup_error,- )if response is not None:if response["team_models"] is None:diff --git a/tests/test_litellm/proxy/common_utils/test_key_rotation_manager.py b/tests/test_litellm/proxy/common_utils/test_key_rotation_manager.pyindex 1f5fab71ef3..002b015d960 100644--- a/tests/test_litellm/proxy/common_utils/test_key_rotation_manager.py+++ b/tests/test_litellm/proxy/common_utils/test_key_rotation_manager.py@@ -248,9 +248,9 @@ class TestKeyRotationManager:assert call_args[1]["where"]["revoke_at"]["lt"] is not None@pytest.mark.asyncio- async def test_rotate_key_passes_grace_period_hours(self):+ async def test_rotate_key_passes_grace_period(self):"""- Test that _rotate_key passes grace_period_hours in RegenerateKeyRequest.+ Test that _rotate_key passes grace_period in RegenerateKeyRequest."""mock_prisma_client = AsyncMock()manager = KeyRotationManager(mock_prisma_client)@@ -281,12 +281,12 @@ class TestKeyRotationManager:new_callable=AsyncMock,):with patch(- "litellm.proxy.common_utils.key_rotation_manager.LITELLM_KEY_ROTATION_GRACE_PERIOD_HOURS",- 48,+ "litellm.proxy.common_utils.key_rotation_manager.LITELLM_KEY_ROTATION_GRACE_PERIOD",+ "48h",):await manager._rotate_key(key_to_rotate)mock_regenerate.assert_called_once()call_args = mock_regenerate.call_argsregenerate_request = call_args[1]["data"]- assert regenerate_request.grace_period_hours == 48+ assert regenerate_request.grace_period == "48h"diff --git a/ui/litellm-dashboard/src/components/organisms/regenerate_key_modal.tsx b/ui/litellm-dashboard/src/components/organisms/regenerate_key_modal.tsxindex 3cea198c62a..2fad101c20f 100644--- a/ui/litellm-dashboard/src/components/organisms/regenerate_key_modal.tsx+++ b/ui/litellm-dashboard/src/components/organisms/regenerate_key_modal.tsx@@ -37,7 +37,7 @@ export function RegenerateKeyModal({ selectedToken, visible, onClose, onKeyUpdattpm_limit: selectedToken.tpm_limit,rpm_limit: selectedToken.rpm_limit,duration: selectedToken.duration || "",- grace_period_hours: 0,+ grace_period: "",});// Initialize the current access token@@ -225,15 +225,21 @@ export function RegenerateKeyModal({ selectedToken, visible, onClose, onKeyUpdat</div>{newExpiryTime && <div className="mt-2 text-sm text-green-600">New expiry: {newExpiryTime}</div>}<Form.Item- name="grace_period_hours"- label="Grace Period (hours)"- tooltip="Keep the old key valid for this many hours after rotation. Both keys work during this period for seamless cutover. 0 = immediate revoke."+ name="grace_period"+ label="Grace Period (eg: 24h, 2d)"+ tooltip="Keep the old key valid for this duration after rotation. Both keys work during this period for seamless cutover. Empty = immediate revoke."className="mt-8"+ rules={[+ {+ pattern: /^(\d+(s|m|h|d|w|mo))?$/,+ message: "Must be a duration like 30s, 30m, 24h, 2d, 1w, or 1mo",+ },+ ]}>- <InputNumber min={0} max={168} placeholder="0 (immediate revoke)" style={{ width: "100%" }} />+ <TextInput placeholder="e.g. 24h, 2d (empty = immediate revoke)" /></Form.Item><div className="mt-2 text-sm text-gray-500">- Recommended: 24-72 hours for production keys to allow seamless client migration.+ Recommended: 24h to 72h for production keys to allow seamless client migration.</div></Form>)}