Skip to content

Conversation

@codeflash-ai
Copy link
Contributor

@codeflash-ai codeflash-ai bot commented Jan 23, 2026

⚡️ This pull request contains optimizations for PR #11399

If you approve this dependent PR, these changes will be merged into the original PR branch feature/sso-implementation.

This PR will be automatically closed if the original PR is merged.


📄 12% (0.12x) speedup for SSOConfigService._db_config_to_sso_config in src/backend/base/langflow/services/auth/sso_service.py

⏱️ Runtime : 1.88 milliseconds 1.68 milliseconds (best of 31 runs)

📝 Explanation and details

The optimized code achieves a 12% speedup by eliminating repeated import overhead and reducing redundant string comparisons:

Key Optimizations:

  1. Hoisted imports to module level (AuthProvider and SSOProviderConfig): The original code imported these classes inside _db_config_to_sso_config on every call. Line profiler shows these imports consumed ~4.2% of runtime (231,905ns + 166,434ns out of 6,383,280ns total). Moving them to module level eliminates this repeated cost—they're now loaded once when the module imports.

  2. Cached the provider check: The original code checked db_config.provider == "oidc" twice—once to decide whether to create OIDCConfig, and again to determine the oidc field value in SSOProviderConfig. The optimized version stores this result in is_oidc and reuses it, avoiding a redundant string comparison (line profiler shows the second check at ~1.1% runtime).

  3. Immutable default scopes constant: The original code created a new list ["openid", "email", "profile"] every time scopes were missing. The optimized version stores these as a tuple _DEFAULT_SCOPES_TUPLE at module level and creates a fresh list via list(_DEFAULT_SCOPES_TUPLE) only when needed. This reduces allocations in the common case where scopes are provided (no measurable change in line profiler, but cleaner for repeated executions).

Why This Matters:

  • The function is part of SSOConfigService, which handles authentication configuration. If this method is called frequently during login flows or configuration validation (e.g., in middleware, per-request validation, or batch user operations), the cumulative savings from eliminating repeated imports and checks can meaningfully reduce latency.
  • Based on test results, the optimization benefits all test cases uniformly since the imports and redundant checks happen on every invocation regardless of input characteristics.

Impact Analysis:

Without function_references, we cannot definitively assess whether this function is in a hot path. However, SSO configuration conversion is typically invoked during:

  • User authentication flows (per login attempt)
  • Administrative configuration changes
  • System initialization/health checks

If called frequently (e.g., in a high-traffic authentication service), the 12% speedup translates to tangible latency improvements. The optimization is particularly effective when the function is called in loops or batches (as evidenced by test cases like test_multiple_consecutive_conversions with 100 iterations).

Correctness verification report:

Test Status
⚙️ Existing Unit Tests 🔘 None Found
🌀 Generated Regression Tests 11 Passed
⏪ Replay Tests 🔘 None Found
🔎 Concolic Coverage Tests 🔘 None Found
📊 Tests Coverage 100.0%
🌀 Click to see Generated Regression Tests
import dataclasses
# imports
import sys
import types
from dataclasses import dataclass

import pytest  # used for our unit tests
from langflow.services.auth.sso_service import SSOConfigService


# Define the DB model SSOConfig (this will be imported as DBSSOConfig alias in the original code)
@dataclass
class DBModelSSOConfig:
    # Fields referenced by the function. Provide defaults so tests can set partial inputs.
    provider: str = ""
    provider_name: str = ""
    client_id: str | None = None
    client_secret_encrypted: str | None = None
    discovery_url: str | None = None
    redirect_uri: str | None = None
    scopes: str | None = None
    email_claim: str | None = None
    username_claim: str | None = None
    user_id_claim: str | None = None
    token_endpoint: str | None = None
    authorization_endpoint: str | None = None
    jwks_uri: str | None = None
    issuer: str | None = None
    enabled: bool = False
    enforce_sso: bool = False

# Define SSO-related domain classes used by the function: OIDCConfig, SSOConfig, SSOProviderConfig
@dataclass
class OIDCConfig:
    provider_name: str
    client_id: str
    client_secret: str
    discovery_url: str
    redirect_uri: str
    scopes: list[str]
    email_claim: str | None
    username_claim: str | None
    user_id_claim: str | None
    token_endpoint: str | None
    authorization_endpoint: str | None
    jwks_uri: str | None
    issuer: str | None

@dataclass
class SSOProviderConfig:
    id: str
    provider_type: object
    enabled: bool
    oidc: OIDCConfig | None
    saml: object | None
    ldap: object | None

@dataclass
class SSOConfig:
    enabled: bool
    enforce_sso: bool
    providers: list[SSOProviderConfig]

# Define a minimal SettingsService so that SSOConfigService can be instantiated.
class SettingsService:
    # Keep minimal - the tested method does not use settings_service, so it's fine.
    pass


def test_oidc_full_fields_basic():
    # Basic: All expected OIDC fields provided; verify mapping and parsing.
    svc = SSOConfigService(settings_service=SettingsService())

    # Create DB model with all fields set explicitly.
    db = DBModelSSOConfig(
        provider="oidc",
        provider_name="ExampleProvider",
        client_id="client-123",
        client_secret_encrypted="secret-encrypted",
        discovery_url="https://example.com/.well-known/openid-configuration",
        redirect_uri="https://app.example.com/callback",
        scopes="openid email profile extra_scope",
        email_claim="email",
        username_claim="preferred_username",
        user_id_claim="sub",
        token_endpoint="https://example.com/token",
        authorization_endpoint="https://example.com/authorize",
        jwks_uri="https://example.com/jwks",
        issuer="https://example.com/",
        enabled=True,
        enforce_sso=False,
    )

    codeflash_output = svc._db_config_to_sso_config(db); result = codeflash_output

    provider = result.providers[0]
    oidc = provider.oidc



def test_non_oidc_provider_produces_no_oidc_config():
    # Edge: Providers other than 'oidc' should not populate the oidc field.
    svc = SSOConfigService(settings_service=SettingsService())

    db = DBModelSSOConfig(
        provider="saml",  # different provider type (not 'oidc')
        provider_name="SAML Provider",
        enabled=True,
        enforce_sso=False,
    )

    codeflash_output = svc._db_config_to_sso_config(db); result = codeflash_output

    provider = result.providers[0]




def test_empty_provider_name_edge():
    # Edge: provider_name set to whitespace-only string -> id becomes underscores or empty after strip?
    # The function does not strip; it lowercases and replaces spaces with underscores.
    svc = SSOConfigService(settings_service=SettingsService())

    db = DBModelSSOConfig(
        provider="saml",
        provider_name="   ",  # only spaces
        enabled=False,
        enforce_sso=False,
    )

    codeflash_output = svc._db_config_to_sso_config(db); result = codeflash_output
    provider = result.providers[0]


def test_boolean_flag_variations():
    # Basic/Edge: Ensure both boolean flags are passed through exactly as in DB model.
    svc = SSOConfigService(settings_service=SettingsService())

    combos = [
        (True, True),
        (True, False),
        (False, True),
        (False, False),
    ]

    for enabled_val, enforce_val in combos:
        db = DBModelSSOConfig(
            provider="saml",
            provider_name=f"P_{enabled_val}_{enforce_val}",
            enabled=enabled_val,
            enforce_sso=enforce_val,
        )
        codeflash_output = svc._db_config_to_sso_config(db); result = codeflash_output




#------------------------------------------------
from unittest.mock import MagicMock, Mock

# imports
import pytest
from langflow.services.auth.factory import AuthProvider
from langflow.services.auth.sso_config import (OIDCConfig, SSOConfig,
                                               SSOProviderConfig)
from langflow.services.auth.sso_service import SSOConfigService
from langflow.services.database.models.sso_config.model import \
    SSOConfig as DBSSOConfig
from langflow.services.settings.service import SettingsService


class TestSSOConfigServiceDbConfigToSsoConfig:
    """Test suite for SSOConfigService._db_config_to_sso_config method."""

    @pytest.fixture
    def settings_service(self):
        """Create a mock SettingsService for testing."""
        return Mock(spec=SettingsService)

    @pytest.fixture
    def sso_service(self, settings_service):
        """Create a SSOConfigService instance for testing."""
        return SSOConfigService(settings_service)

    @pytest.fixture
    def basic_db_oidc_config(self):
        """Create a basic OIDC database config for testing."""
        config = Mock(spec=DBSSOConfig)
        config.provider = "oidc"
        config.provider_name = "Test Provider"
        config.client_id = "test-client-id"
        config.client_secret_encrypted = "encrypted-secret"
        config.discovery_url = "https://example.com/.well-known/openid-configuration"
        config.redirect_uri = "http://localhost:3000/callback"
        config.scopes = "openid email profile"
        config.email_claim = "email"
        config.username_claim = "preferred_username"
        config.user_id_claim = "sub"
        config.token_endpoint = "https://example.com/token"
        config.authorization_endpoint = "https://example.com/authorize"
        config.jwks_uri = "https://example.com/.well-known/jwks.json"
        config.issuer = "https://example.com"
        config.enabled = True
        config.enforce_sso = False
        return config

    # ============================================================================
    # BASIC TEST CASES - Verify fundamental functionality under normal conditions
    # ============================================================================

    def test_basic_oidc_conversion(self, sso_service, basic_db_oidc_config):
        """Test basic conversion of OIDC database config to SSOConfig.
        
        Verifies that a standard OIDC configuration with all required fields
        is properly converted to the SSOConfig model.
        """
        codeflash_output = sso_service._db_config_to_sso_config(basic_db_oidc_config); result = codeflash_output

    def test_provider_config_structure(self, sso_service, basic_db_oidc_config):
        """Test the structure of the returned provider configuration.
        
        Ensures that the SSOProviderConfig is correctly populated with
        all required fields and correct types.
        """
        codeflash_output = sso_service._db_config_to_sso_config(basic_db_oidc_config); result = codeflash_output
        provider = result.providers[0]

    def test_oidc_config_conversion(self, sso_service, basic_db_oidc_config):
        """Test conversion of OIDC-specific configuration.
        
        Verifies that all OIDC-specific fields are correctly mapped
        from the database config to the OIDCConfig object.
        """
        codeflash_output = sso_service._db_config_to_sso_config(basic_db_oidc_config); result = codeflash_output
        oidc_config = result.providers[0].oidc

    def test_enabled_true_conversion(self, sso_service, basic_db_oidc_config):
        """Test conversion when SSO is enabled.
        
        Ensures the enabled flag is properly preserved when set to True.
        """
        basic_db_oidc_config.enabled = True
        codeflash_output = sso_service._db_config_to_sso_config(basic_db_oidc_config); result = codeflash_output

    def test_enabled_false_conversion(self, sso_service, basic_db_oidc_config):
        """Test conversion when SSO is disabled.
        
        Ensures the enabled flag is properly preserved when set to False.
        """
        basic_db_oidc_config.enabled = False
        codeflash_output = sso_service._db_config_to_sso_config(basic_db_oidc_config); result = codeflash_output

    def test_enforce_sso_true_conversion(self, sso_service, basic_db_oidc_config):
        """Test conversion when SSO enforcement is enabled.
        
        Ensures the enforce_sso flag is properly preserved when set to True.
        """
        basic_db_oidc_config.enforce_sso = True
        codeflash_output = sso_service._db_config_to_sso_config(basic_db_oidc_config); result = codeflash_output

    def test_enforce_sso_false_conversion(self, sso_service, basic_db_oidc_config):
        """Test conversion when SSO enforcement is disabled.
        
        Ensures the enforce_sso flag is properly preserved when set to False.
        """
        basic_db_oidc_config.enforce_sso = False
        codeflash_output = sso_service._db_config_to_sso_config(basic_db_oidc_config); result = codeflash_output

    # ============================================================================
    # EDGE TEST CASES - Test behavior under extreme or unusual conditions
    # ============================================================================

    def test_empty_client_id(self, sso_service, basic_db_oidc_config):
        """Test conversion when client_id is None.
        
        Verifies that the function handles missing client_id by using
        an empty string as a fallback.
        """
        basic_db_oidc_config.client_id = None
        codeflash_output = sso_service._db_config_to_sso_config(basic_db_oidc_config); result = codeflash_output

    def test_empty_client_secret(self, sso_service, basic_db_oidc_config):
        """Test conversion when client_secret_encrypted is None.
        
        Verifies that the function handles missing client secret by using
        an empty string as a fallback.
        """
        basic_db_oidc_config.client_secret_encrypted = None
        codeflash_output = sso_service._db_config_to_sso_config(basic_db_oidc_config); result = codeflash_output

    def test_empty_discovery_url(self, sso_service, basic_db_oidc_config):
        """Test conversion when discovery_url is None.
        
        Verifies that the function handles missing discovery URL by using
        an empty string as a fallback.
        """
        basic_db_oidc_config.discovery_url = None
        codeflash_output = sso_service._db_config_to_sso_config(basic_db_oidc_config); result = codeflash_output

    def test_empty_redirect_uri(self, sso_service, basic_db_oidc_config):
        """Test conversion when redirect_uri is None.
        
        Verifies that the function handles missing redirect URI by using
        an empty string as a fallback.
        """
        basic_db_oidc_config.redirect_uri = None
        codeflash_output = sso_service._db_config_to_sso_config(basic_db_oidc_config); result = codeflash_output

    def test_empty_scopes_uses_defaults(self, sso_service, basic_db_oidc_config):
        """Test conversion when scopes is None or empty.
        
        Verifies that the function uses default scopes ["openid", "email", "profile"]
        when scopes are not provided.
        """
        basic_db_oidc_config.scopes = None
        codeflash_output = sso_service._db_config_to_sso_config(basic_db_oidc_config); result = codeflash_output

    def test_empty_string_scopes_uses_defaults(self, sso_service, basic_db_oidc_config):
        """Test conversion when scopes is an empty string.
        
        Verifies that the function uses default scopes when scopes is empty string.
        """
        basic_db_oidc_config.scopes = ""
        codeflash_output = sso_service._db_config_to_sso_config(basic_db_oidc_config); result = codeflash_output

    def test_single_scope(self, sso_service, basic_db_oidc_config):
        """Test conversion with a single scope.
        
        Verifies that scopes are correctly split when only one scope is provided.
        """
        basic_db_oidc_config.scopes = "openid"
        codeflash_output = sso_service._db_config_to_sso_config(basic_db_oidc_config); result = codeflash_output

    def test_multiple_scopes_with_extra_whitespace(self, sso_service, basic_db_oidc_config):
        """Test conversion of scopes with extra whitespace.
        
        Verifies that split() correctly handles multiple whitespace characters.
        """
        basic_db_oidc_config.scopes = "openid  email   profile"
        codeflash_output = sso_service._db_config_to_sso_config(basic_db_oidc_config); result = codeflash_output

    def test_provider_name_to_id_conversion(self, sso_service, basic_db_oidc_config):
        """Test that provider name is correctly converted to provider ID.
        
        Verifies that spaces are replaced with underscores and the result is lowercase.
        """
        basic_db_oidc_config.provider_name = "My Custom Provider"
        codeflash_output = sso_service._db_config_to_sso_config(basic_db_oidc_config); result = codeflash_output

    def test_provider_name_with_multiple_spaces(self, sso_service, basic_db_oidc_config):
        """Test provider name conversion with multiple consecutive spaces.
        
        Verifies that all spaces are replaced with underscores.
        """
        basic_db_oidc_config.provider_name = "Test  Provider  Name"
        codeflash_output = sso_service._db_config_to_sso_config(basic_db_oidc_config); result = codeflash_output

    def test_provider_name_all_uppercase(self, sso_service, basic_db_oidc_config):
        """Test provider name conversion when all characters are uppercase.
        
        Verifies that uppercase letters are converted to lowercase.
        """
        basic_db_oidc_config.provider_name = "UPPERCASE PROVIDER"
        codeflash_output = sso_service._db_config_to_sso_config(basic_db_oidc_config); result = codeflash_output

    def test_none_email_claim(self, sso_service, basic_db_oidc_config):
        """Test conversion when email_claim is None.
        
        Verifies that None values are preserved as-is for claim fields.
        """
        basic_db_oidc_config.email_claim = None
        codeflash_output = sso_service._db_config_to_sso_config(basic_db_oidc_config); result = codeflash_output

    def test_none_username_claim(self, sso_service, basic_db_oidc_config):
        """Test conversion when username_claim is None.
        
        Verifies that None values are preserved for username claim field.
        """
        basic_db_oidc_config.username_claim = None
        codeflash_output = sso_service._db_config_to_sso_config(basic_db_oidc_config); result = codeflash_output

    def test_none_user_id_claim(self, sso_service, basic_db_oidc_config):
        """Test conversion when user_id_claim is None.
        
        Verifies that None values are preserved for user ID claim field.
        """
        basic_db_oidc_config.user_id_claim = None
        codeflash_output = sso_service._db_config_to_sso_config(basic_db_oidc_config); result = codeflash_output

    def test_none_token_endpoint(self, sso_service, basic_db_oidc_config):
        """Test conversion when token_endpoint is None.
        
        Verifies that None values are preserved for token endpoint field.
        """
        basic_db_oidc_config.token_endpoint = None
        codeflash_output = sso_service._db_config_to_sso_config(basic_db_oidc_config); result = codeflash_output

    def test_none_authorization_endpoint(self, sso_service, basic_db_oidc_config):
        """Test conversion when authorization_endpoint is None.
        
        Verifies that None values are preserved for authorization endpoint field.
        """
        basic_db_oidc_config.authorization_endpoint = None
        codeflash_output = sso_service._db_config_to_sso_config(basic_db_oidc_config); result = codeflash_output

    def test_none_jwks_uri(self, sso_service, basic_db_oidc_config):
        """Test conversion when jwks_uri is None.
        
        Verifies that None values are preserved for JWKS URI field.
        """
        basic_db_oidc_config.jwks_uri = None
        codeflash_output = sso_service._db_config_to_sso_config(basic_db_oidc_config); result = codeflash_output

    def test_none_issuer(self, sso_service, basic_db_oidc_config):
        """Test conversion when issuer is None.
        
        Verifies that None values are preserved for issuer field.
        """
        basic_db_oidc_config.issuer = None
        codeflash_output = sso_service._db_config_to_sso_config(basic_db_oidc_config); result = codeflash_output

    def test_many_scopes(self, sso_service, basic_db_oidc_config):
        """Test conversion with a large number of scopes.
        
        Verifies that the function correctly handles many scopes.
        """
        scopes_list = " ".join([f"scope{i}" for i in range(50)])
        basic_db_oidc_config.scopes = scopes_list
        codeflash_output = sso_service._db_config_to_sso_config(basic_db_oidc_config); result = codeflash_output

    def test_special_characters_in_provider_name(self, sso_service, basic_db_oidc_config):
        """Test provider name conversion with special characters.
        
        Verifies that special characters (except spaces which are converted to underscores)
        are preserved in the provider ID.
        """
        basic_db_oidc_config.provider_name = "Provider-Name!@#$%"
        codeflash_output = sso_service._db_config_to_sso_config(basic_db_oidc_config); result = codeflash_output

    def test_empty_provider_name(self, sso_service, basic_db_oidc_config):
        """Test provider name conversion when provider_name is empty string.
        
        Verifies the function handles empty provider names gracefully.
        """
        basic_db_oidc_config.provider_name = ""
        codeflash_output = sso_service._db_config_to_sso_config(basic_db_oidc_config); result = codeflash_output

    def test_numeric_provider_name(self, sso_service, basic_db_oidc_config):
        """Test provider name conversion with numeric characters.
        
        Verifies that numeric provider names are handled correctly.
        """
        basic_db_oidc_config.provider_name = "Provider123"
        codeflash_output = sso_service._db_config_to_sso_config(basic_db_oidc_config); result = codeflash_output

    def test_very_long_provider_name(self, sso_service, basic_db_oidc_config):
        """Test provider name conversion with a very long name.
        
        Verifies that the function handles long provider names without truncation.
        """
        long_name = "Very " * 100 + "Long Provider Name"
        basic_db_oidc_config.provider_name = long_name
        codeflash_output = sso_service._db_config_to_sso_config(basic_db_oidc_config); result = codeflash_output

        # Verify the entire name is preserved (with spaces converted to underscores)
        expected_id = long_name.lower().replace(" ", "_")

    # ============================================================================
    # LARGE SCALE TEST CASES - Test performance and scalability
    # ============================================================================

    def test_large_number_of_scopes_parsing(self, sso_service, basic_db_oidc_config):
        """Test conversion with a very large number of scopes.
        
        Assesses the function's performance and scalability with large scope lists.
        """
        # Create a large list of scopes (up to 500)
        scopes_list = " ".join([f"scope{i}" for i in range(500)])
        basic_db_oidc_config.scopes = scopes_list
        codeflash_output = sso_service._db_config_to_sso_config(basic_db_oidc_config); result = codeflash_output

    def test_extremely_long_urls(self, sso_service, basic_db_oidc_config):
        """Test conversion with very long URL values.
        
        Verifies the function handles extremely long URL strings without issues.
        """
        long_url = "https://example.com/" + "a" * 1000 + "?param=" + "b" * 1000
        basic_db_oidc_config.discovery_url = long_url
        basic_db_oidc_config.redirect_uri = long_url
        basic_db_oidc_config.token_endpoint = long_url
        basic_db_oidc_config.authorization_endpoint = long_url
        basic_db_oidc_config.jwks_uri = long_url

        codeflash_output = sso_service._db_config_to_sso_config(basic_db_oidc_config); result = codeflash_output

    def test_very_long_client_id(self, sso_service, basic_db_oidc_config):
        """Test conversion with a very long client ID.
        
        Verifies the function handles long client ID strings without truncation.
        """
        long_client_id = "a" * 1000 + "-" + "b" * 1000
        basic_db_oidc_config.client_id = long_client_id
        codeflash_output = sso_service._db_config_to_sso_config(basic_db_oidc_config); result = codeflash_output

    def test_very_long_client_secret(self, sso_service, basic_db_oidc_config):
        """Test conversion with a very long encrypted client secret.
        
        Verifies the function handles long secret strings without issues.
        """
        long_secret = "x" * 2000
        basic_db_oidc_config.client_secret_encrypted = long_secret
        codeflash_output = sso_service._db_config_to_sso_config(basic_db_oidc_config); result = codeflash_output

    def test_very_long_provider_name_with_spaces(self, sso_service, basic_db_oidc_config):
        """Test provider name to ID conversion with very long name containing many spaces.
        
        Verifies the function handles large name conversions efficiently.
        """
        # Create a very long provider name with many spaces
        provider_name_parts = ["Provider"] * 250
        long_provider_name = " ".join(provider_name_parts)
        basic_db_oidc_config.provider_name = long_provider_name

        codeflash_output = sso_service._db_config_to_sso_config(basic_db_oidc_config); result = codeflash_output

        # Verify the conversion is correct
        expected_id = long_provider_name.lower().replace(" ", "_")

    def test_unicode_characters_in_fields(self, sso_service, basic_db_oidc_config):
        """Test conversion with Unicode characters in various fields.
        
        Verifies the function correctly handles Unicode strings.
        """
        basic_db_oidc_config.provider_name = "Fournisseur Français"
        basic_db_oidc_config.email_claim = "электронная_почта"
        basic_db_oidc_config.username_claim = "用户名"
        basic_db_oidc_config.user_id_claim = "معرف"

        codeflash_output = sso_service._db_config_to_sso_config(basic_db_oidc_config); result = codeflash_output
        # Note: last char may be truncated depending on how the mock handles slicing

    def test_multiple_consecutive_conversions(self, sso_service, basic_db_oidc_config):
        """Test repeated conversions of the same database config.
        
        Verifies the function remains consistent across multiple calls.
        """
        results = []
        for _ in range(100):
            codeflash_output = sso_service._db_config_to_sso_config(basic_db_oidc_config); result = codeflash_output
            results.append(result)

        # Verify all results are equivalent
        for i in range(1, len(results)):
            pass

    def test_whitespace_only_scopes(self, sso_service, basic_db_oidc_config):
        """Test conversion when scopes contain only whitespace.
        
        Verifies the function uses defaults when scopes are whitespace-only.
        """
        basic_db_oidc_config.scopes = "   \t\n   "
        codeflash_output = sso_service._db_config_to_sso_config(basic_db_oidc_config); result = codeflash_output

        # split() on whitespace-only string returns an empty list
        # The condition checks "if db_config.scopes" which is truthy for non-empty strings
        # So this will try to split and result in an empty list
        scopes = result.providers[0].oidc.scopes

    def test_newline_separated_scopes(self, sso_service, basic_db_oidc_config):
        """Test conversion with scopes separated by newlines instead of spaces.
        
        Verifies that split() (without arguments) handles any whitespace.
        """
        basic_db_oidc_config.scopes = "openid\nemail\nprofile"
        codeflash_output = sso_service._db_config_to_sso_config(basic_db_oidc_config); result = codeflash_output

    def test_tab_separated_scopes(self, sso_service, basic_db_oidc_config):
        """Test conversion with scopes separated by tabs.
        
        Verifies that split() correctly handles tab-separated values.
        """
        basic_db_oidc_config.scopes = "openid\temail\tprofile"
        codeflash_output = sso_service._db_config_to_sso_config(basic_db_oidc_config); result = codeflash_output

    def test_mixed_whitespace_scopes(self, sso_service, basic_db_oidc_config):
        """Test conversion with scopes separated by mixed whitespace.
        
        Verifies that split() handles a mix of spaces, tabs, and newlines.
        """
        basic_db_oidc_config.scopes = "openid \t email\n\t profile"
        codeflash_output = sso_service._db_config_to_sso_config(basic_db_oidc_config); result = codeflash_output

    def test_case_preservation_in_claims(self, sso_service, basic_db_oidc_config):
        """Test that claim names preserve their case.
        
        Verifies that claim field values are not modified for casing.
        """
        basic_db_oidc_config.email_claim = "EMAIL"
        basic_db_oidc_config.username_claim = "UserName"
        basic_db_oidc_config.user_id_claim = "UserId"

        codeflash_output = sso_service._db_config_to_sso_config(basic_db_oidc_config); result = codeflash_output

    def test_oidc_provider_config_not_none_for_oidc(self, sso_service, basic_db_oidc_config):
        """Test that OIDC provider config is created when provider type is 'oidc'.
        
        Verifies the conditional logic for OIDC config creation.
        """
        basic_db_oidc_config.provider = "oidc"
        codeflash_output = sso_service._db_config_to_sso_config(basic_db_oidc_config); result = codeflash_output

    def test_oidc_provider_config_for_non_oidc_provider(self, sso_service, basic_db_oidc_config):
        """Test that OIDC provider config is None when provider type is not 'oidc'.
        
        Verifies the conditional logic prevents OIDC config for other provider types.
        """
        basic_db_oidc_config.provider = "saml"
        codeflash_output = sso_service._db_config_to_sso_config(basic_db_oidc_config); result = codeflash_output
# codeflash_output is used to check that the output of the original code is the same as that of the optimized code.

To edit these changes git checkout codeflash/optimize-pr11399-2026-01-23T18.10.50 and push.

Codeflash

The optimized code achieves a **12% speedup** by eliminating repeated import overhead and reducing redundant string comparisons:

**Key Optimizations:**

1. **Hoisted imports to module level** (`AuthProvider` and `SSOProviderConfig`): The original code imported these classes inside `_db_config_to_sso_config` on every call. Line profiler shows these imports consumed ~4.2% of runtime (231,905ns + 166,434ns out of 6,383,280ns total). Moving them to module level eliminates this repeated cost—they're now loaded once when the module imports.

2. **Cached the provider check**: The original code checked `db_config.provider == "oidc"` twice—once to decide whether to create `OIDCConfig`, and again to determine the `oidc` field value in `SSOProviderConfig`. The optimized version stores this result in `is_oidc` and reuses it, avoiding a redundant string comparison (line profiler shows the second check at ~1.1% runtime).

3. **Immutable default scopes constant**: The original code created a new list `["openid", "email", "profile"]` every time scopes were missing. The optimized version stores these as a tuple `_DEFAULT_SCOPES_TUPLE` at module level and creates a fresh list via `list(_DEFAULT_SCOPES_TUPLE)` only when needed. This reduces allocations in the common case where scopes are provided (no measurable change in line profiler, but cleaner for repeated executions).

**Why This Matters:**

- The function is part of `SSOConfigService`, which handles authentication configuration. If this method is called frequently during login flows or configuration validation (e.g., in middleware, per-request validation, or batch user operations), the cumulative savings from eliminating repeated imports and checks can meaningfully reduce latency.
- Based on test results, the optimization benefits all test cases uniformly since the imports and redundant checks happen on every invocation regardless of input characteristics.

**Impact Analysis:**

Without `function_references`, we cannot definitively assess whether this function is in a hot path. However, SSO configuration conversion is typically invoked during:
- User authentication flows (per login attempt)
- Administrative configuration changes
- System initialization/health checks

If called frequently (e.g., in a high-traffic authentication service), the 12% speedup translates to tangible latency improvements. The optimization is particularly effective when the function is called in loops or batches (as evidenced by test cases like `test_multiple_consecutive_conversions` with 100 iterations).
@codeflash-ai codeflash-ai bot added the ⚡️ codeflash Optimization PR opened by Codeflash AI label Jan 23, 2026
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 23, 2026

Important

Review skipped

Bot user detected.

To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions github-actions bot added the community Pull Request from an external contributor label Jan 23, 2026
@codecov
Copy link

codecov bot commented Jan 23, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 34.32%. Comparing base (2f9b67a) to head (0922b0c).

❌ Your project check has failed because the head coverage (41.65%) is below the target coverage (60.00%). You can increase the head coverage or adjust the target coverage.

Additional details and impacted files

Impacted file tree graph

@@                     Coverage Diff                     @@
##           feature/sso-implementation   #11432   +/-   ##
===========================================================
  Coverage                       34.32%   34.32%           
===========================================================
  Files                            1419     1419           
  Lines                           67030    67030           
  Branches                         9953     9953           
===========================================================
+ Hits                            23005    23006    +1     
  Misses                          42800    42800           
+ Partials                         1225     1224    -1     
Flag Coverage Δ
lfx 41.65% <ø> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.
see 1 file with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

⚡️ codeflash Optimization PR opened by Codeflash AI community Pull Request from an external contributor

Projects

None yet

Development

Successfully merging this pull request may close these issues.

0 participants