⚡️ Speed up function _auth_error_to_http by 18% in PR #10702 (pluggable-auth-service)#11632
Closed
codeflash-ai[bot] wants to merge 186 commits into
Closed
⚡️ Speed up function _auth_error_to_http by 18% in PR #10702 (pluggable-auth-service)#11632codeflash-ai[bot] wants to merge 186 commits into
_auth_error_to_http by 18% in PR #10702 (pluggable-auth-service)#11632codeflash-ai[bot] wants to merge 186 commits into
Conversation
…ager for pluggable service discovery - Added `register_service` decorator to allow services to self-register with the ServiceManager. - Enhanced `ServiceManager` to support multiple service discovery mechanisms, including decorator-based registration, config files, and entry points. - Implemented methods for direct service class registration and plugin discovery from various sources, improving flexibility and extensibility of service management.
- Introduced VariableService class to handle environment variables with in-memory caching. - Added methods for getting, setting, deleting, and listing variables. - Included logging for service initialization and variable operations. - Created an __init__.py file to expose VariableService in the package namespace.
…teardown - Updated LocalStorageService to inherit from both StorageService and Service for improved functionality. - Added a name attribute for service identification. - Implemented an async teardown method for future extensibility, even though no cleanup is currently needed. - Refactored the constructor to ensure proper initialization of both parent classes.
…l logging functionality - Added `BaseTelemetryService` as an abstract base class defining the interface for telemetry services. - Introduced `TelemetryService`, a lightweight implementation that logs telemetry events without sending data. - Created `__init__.py` to expose the telemetry service in the package namespace. - Ensured robust async methods for logging various telemetry events and handling exceptions.
- Added `BaseTracingService` as an abstract base class defining the interface for tracing services. - Implemented `TracingService`, a lightweight version that logs trace events without external integrations. - Included async methods for starting and ending traces, tracing components, and managing logs and outputs. - Enhanced documentation for clarity on method usage and parameters.
- Introduced a new test suite for validating the functionality of the @register_service decorator. - Implemented tests for various service types including LocalStorageService, TelemetryService, and TracingService. - Verified behavior for service registration with and without overrides, ensuring correct service management. - Included tests for custom service implementations and preservation of class functionality. - Enhanced overall test coverage for the service registration mechanism.
- Introduced a suite of unit tests covering edge cases for service registration, lifecycle management, and dependency resolution. - Implemented integration tests to validate service loading from configuration files and environment variables. - Enhanced test coverage for various service types including LocalStorageService, TelemetryService, and VariableService. - Verified behavior for service registration with and without overrides, ensuring correct service management. - Ensured robust handling of error conditions and edge cases in service creation and configuration parsing.
- Introduced comprehensive unit tests for LocalStorageService, TelemetryService, TracingService, and VariableService. - Implemented integration tests to validate the interaction between minimal services. - Ensured robust coverage for file operations, service readiness, and exception handling. - Enhanced documentation within tests for clarity on functionality and expected behavior.
…ection - Revised the documentation to highlight the advantages of the pluggable service system. - Replaced the migration guide with a detailed overview of features such as automatic discovery, lazy instantiation, dependency injection, and lifecycle management. - Clarified examples of service registration and improved overall documentation for better understanding.
During rebase, the teardown method was added in two locations (lines 57 and 220). Removed the duplicate at line 57, keeping the one at the end of the class (line 220) which is the more appropriate location for cleanup methods.
…changes - Add MockSessionService fixtures to test files that use ServiceManager - Update LocalStorageService test instantiation to use mock session and settings services - Fix service count assertions to account for MockSessionService in fixtures - Remove duplicate class-level clean_manager fixtures in test_edge_cases.py These changes fix test failures caused by LocalStorageService requiring session_service and settings_service parameters instead of just data_dir.
- Fixed Diamond Inheritance in LocalStorageService - Added Circular Dependency Detection in _create_service_from_class - Fixed StorageService.teardown to Have Default Implementation
- The aiofile library uses native async I/O (libaio) which fails with EAGAIN (SystemError: 11, 'Resource temporarily unavailable') in containerized environments like GitHub Actions runners. - Switch to aiofiles which uses thread pool executors, providing reliable async file I/O across all environments including containers.
The discover_plugins() method had a TOCTOU (time-of-check to time-of-use) race condition. Since get() uses a keyed lock (per service name), multiple threads requesting different services could concurrently see _plugins_discovered=False and trigger duplicate plugin discovery. Wrap discover_plugins() with self._lock to ensure thread-safe access to the _plugins_discovered flag and prevent concurrent discovery execution.
…ager for pluggable service discovery - Added `register_service` decorator to allow services to self-register with the ServiceManager. - Enhanced `ServiceManager` to support multiple service discovery mechanisms, including decorator-based registration, config files, and entry points. - Implemented methods for direct service class registration and plugin discovery from various sources, improving flexibility and extensibility of service management.
…teardown - Updated LocalStorageService to inherit from both StorageService and Service for improved functionality. - Added a name attribute for service identification. - Implemented an async teardown method for future extensibility, even though no cleanup is currently needed. - Refactored the constructor to ensure proper initialization of both parent classes.
… and add auth service retrieval function
Consolidate all authentication methods into the AuthService class to
enable pluggable authentication implementations. The utils module now
contains thin wrappers that delegate to the registered auth service.
This allows alternative auth implementations (e.g., OIDC) to be
registered via the pluggable services system while maintaining
backward compatibility with existing code that imports from utils.
Changes:
- Move all auth logic (token creation, user validation, API key
security, password hashing, encryption) to AuthService
- Refactor utils.py to delegate to get_auth_service()
- Update function signatures to remove settings_service parameter
(now obtained from the service internally)
…vice parameter - Changed function to retrieve current user from access token instead of JWT. - Updated AuthServiceFactory to specify SettingsService type in create method. - Removed settings_service dependency from encryption and decryption functions, simplifying the code. This refactor enhances the clarity and maintainability of the authentication logic.
- Introduced comprehensive unit tests for AuthService, covering token creation, user validation, and authentication methods. - Added tests for pluggable authentication, ensuring correct delegation to registered services. - Enhanced test coverage for user authentication scenarios, including active/inactive user checks and token validation. These additions improve the reliability and maintainability of the authentication system.
…ai/langflow into pluggable-auth-service
…ai/langflow into pluggable-auth-service
…ai/langflow into pluggable-auth-service
…ai/langflow into pluggable-auth-service
…ai/langflow into pluggable-auth-service
The optimized code achieves an **18% speedup** by addressing two key performance bottlenecks in exception type checking and attribute lookups: ## Key Optimizations **1. Faster Exception Type Checking (`isinstance` → `type()` with frozenset)** The original code uses `isinstance(e, (MissingCredentialsError, InvalidCredentialsError, InsufficientPermissionsError))`, which performs a linear O(n) search through the tuple of types. The optimized version replaces this with `type(e) in _FORBIDDEN_EXCEPTIONS` where `_FORBIDDEN_EXCEPTIONS` is a pre-computed `frozenset`. This provides O(1) average-case membership testing. From the line profiler results, the `isinstance` check took **17.8% + 6.9% + 7.7% = 32.4%** of total time in the original version, while the optimized `type(e) in _FORBIDDEN_EXCEPTIONS` check takes only **11.5%** - a **65% reduction** in type-checking overhead. **2. Cached Status Code Lookups** The original code performs attribute lookups (`status.HTTP_403_FORBIDDEN`, `status.HTTP_401_UNAUTHORIZED`) on every function call. The optimized version caches these as module-level constants `_STATUS_FORBIDDEN` and `_STATUS_UNAUTHORIZED`, eliminating repeated attribute lookups. While the line profiler shows the primary gains come from the type checking optimization, this caching contributes to the overall speedup by reducing attribute access overhead in the `HTTPException` construction. ## Why This Matters This function is likely in a **hot path** for authentication flows, being called on every authentication error. The test suite demonstrates this with: - Large-scale tests processing **500-600 exceptions** consecutively - Mixed error type scenarios alternating between 401/403 responses - High-frequency authentication checking patterns The optimization particularly excels for: - **High-volume authentication scenarios** (as shown in `test_many_different_*` tests) - **Mixed error types** (as demonstrated in `test_mixed_error_types_large_scale`) - **Repeated authentication failures** in production systems The 18% speedup means that in systems processing thousands of authentication errors per second, this optimization can meaningfully reduce response latency and CPU utilization in the authentication middleware layer.
Codecov Report❌ Patch coverage is ❌ Your project status has failed because the head coverage (42.10%) is below the target coverage (60.00%). You can increase the head coverage or adjust the target coverage. Additional details and impacted files@@ Coverage Diff @@
## main #11632 +/- ##
==========================================
- Coverage 35.02% 32.97% -2.06%
==========================================
Files 1515 1512 -3
Lines 72567 72144 -423
Branches 10934 10644 -290
==========================================
- Hits 25418 23786 -1632
- Misses 45755 47027 +1272
+ Partials 1394 1331 -63
Flags with carried forward coverage won't be shown. Click here to find out more.
🚀 New features to boost your workflow:
|
Contributor
|
Closing: removing CodeFlash integration. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
⚡️ This pull request contains optimizations for PR #10702
If you approve this dependent PR, these changes will be merged into the original PR branch
pluggable-auth-service.📄 18% (0.18x) speedup for
_auth_error_to_httpinsrc/backend/base/langflow/services/auth/utils.py⏱️ Runtime :
551 microseconds→465 microseconds(best of125runs)📝 Explanation and details
The optimized code achieves an 18% speedup by addressing two key performance bottlenecks in exception type checking and attribute lookups:
Key Optimizations
1. Faster Exception Type Checking (
isinstance→type()with frozenset)The original code uses
isinstance(e, (MissingCredentialsError, InvalidCredentialsError, InsufficientPermissionsError)), which performs a linear O(n) search through the tuple of types. The optimized version replaces this withtype(e) in _FORBIDDEN_EXCEPTIONSwhere_FORBIDDEN_EXCEPTIONSis a pre-computedfrozenset. This provides O(1) average-case membership testing.From the line profiler results, the
isinstancecheck took 17.8% + 6.9% + 7.7% = 32.4% of total time in the original version, while the optimizedtype(e) in _FORBIDDEN_EXCEPTIONScheck takes only 11.5% - a 65% reduction in type-checking overhead.2. Cached Status Code Lookups
The original code performs attribute lookups (
status.HTTP_403_FORBIDDEN,status.HTTP_401_UNAUTHORIZED) on every function call. The optimized version caches these as module-level constants_STATUS_FORBIDDENand_STATUS_UNAUTHORIZED, eliminating repeated attribute lookups. While the line profiler shows the primary gains come from the type checking optimization, this caching contributes to the overall speedup by reducing attribute access overhead in theHTTPExceptionconstruction.Why This Matters
This function is likely in a hot path for authentication flows, being called on every authentication error. The test suite demonstrates this with:
The optimization particularly excels for:
test_many_different_*tests)test_mixed_error_types_large_scale)The 18% speedup means that in systems processing thousands of authentication errors per second, this optimization can meaningfully reduce response latency and CPU utilization in the authentication middleware layer.
✅ Correctness verification report:
🌀 Click to see Generated Regression Tests
To edit these changes
git checkout codeflash/optimize-pr10702-2026-02-06T17.23.30and push.