⚡️ Speed up function _is_user_proxy_admin by 22%
#436
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
📄 22% (0.22x) speedup for
_is_user_proxy_admininlitellm/proxy/auth/auth_checks.py⏱️ Runtime :
61.1 microseconds→50.0 microseconds(best of157runs)📝 Explanation and details
The optimization eliminates redundant code and reduces the number of conditional checks by combining early exit conditions and removing duplicate logic blocks.
Key changes:
Combined null checks: The original code checked
user_obj is Noneanduser_obj.user_role is not Noneseparately in multiple places. The optimized version combines these into a single early exit:if user_obj is None or user_obj.user_role is None:Removed duplicate conditional blocks: The original code had two identical
ifstatements checking the same condition (user_obj.user_role == LitellmUserRoles.PROXY_ADMIN.value), which was clearly a copy-paste error.Direct return statement: Instead of multiple conditional branches, the optimized version uses a single direct comparison:
return user_obj.user_role == LitellmUserRoles.PROXY_ADMIN.valueWhy this is faster:
user_obj.user_roleup to 4 times per call, while the optimized version accesses it at most 2 timesPerformance impact in context:
Based on the function references, this function is called in authentication hot paths:
_is_api_route_allowed()calls it for every API request to check admin privileges_return_user_api_key_auth_obj()calls it during user authentication flowsThe 22% speedup is most beneficial for non-admin users with null/invalid roles (27.5% faster as shown in tests), which are likely the majority of cases, making this optimization particularly valuable for high-traffic authentication scenarios.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-_is_user_proxy_admin-mhwu1trband push.