Skip to content

⚡️ Speed up method AuthSettings.validate_superuser by 41% in PR #9674 (auto-login-removals)#9814

Closed
codeflash-ai[bot] wants to merge 2 commits into
auto-login-removalsfrom
codeflash/optimize-pr9674-2025-09-11T02.05.39
Closed

⚡️ Speed up method AuthSettings.validate_superuser by 41% in PR #9674 (auto-login-removals)#9814
codeflash-ai[bot] wants to merge 2 commits into
auto-login-removalsfrom
codeflash/optimize-pr9674-2025-09-11T02.05.39

Conversation

@codeflash-ai
Copy link
Copy Markdown
Contributor

@codeflash-ai codeflash-ai Bot commented Sep 11, 2025

⚡️ This pull request contains optimizations for PR #9674

If you approve this dependent PR, these changes will be merged into the original PR branch auto-login-removals.

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


📄 41% (0.41x) speedup for AuthSettings.validate_superuser in langflow/services/settings/auth.py

⏱️ Runtime : 4.80 milliseconds 3.41 milliseconds (best of 14 runs)

📝 Explanation and details

The optimized code achieves a 40% speedup by caching attribute lookups that would otherwise be performed multiple times within the validation method.

Key optimizations:

  1. Cached info.data lookup: The original code calls info.data.get() up to 3 times per invocation. The optimized version stores info.data in a local variable data and reuses it, eliminating repeated attribute access overhead.

  2. Cached info.field_name lookup: Similarly, info.field_name is accessed multiple times in the original code. The optimized version caches it as field_name, reducing attribute lookup overhead.

  3. Cached auto_login value: The data.get("AUTO_LOGIN") result is stored in auto_login variable, avoiding the dictionary lookup and method call overhead when the condition is checked.

Why this works:
In Python, attribute access (like info.data) and method calls (like .get()) have non-trivial overhead. When these operations are performed repeatedly within a tight loop or frequently-called validation method, caching them in local variables provides measurable performance benefits. Local variable access is significantly faster than attribute lookups in Python's execution model.

Test case performance:
The optimization is particularly effective for the large-scale test cases (test_large_scale_* functions) that call the validator 500+ times in loops, where the cumulative effect of eliminating repeated attribute lookups becomes substantial. The basic test cases also benefit, but the gains are more pronounced in high-frequency validation scenarios.

Correctness verification report:

Test Status
⚙️ Existing Unit Tests 🔘 None Found
🌀 Generated Regression Tests 3016 Passed
⏪ Replay Tests 🔘 None Found
🔎 Concolic Coverage Tests 🔘 None Found
📊 Tests Coverage 100.0%
🌀 Generated Regression Tests and Runtime
from typing import Literal

# imports
import pytest  # used for our unit tests
# function to test
from langflow.logging.logger import logger
from langflow.services.settings.auth import AuthSettings
from langflow.services.settings.constants import (DEFAULT_SUPERUSER,
                                                  DEFAULT_SUPERUSER_PASSWORD)
from passlib.context import CryptContext
from pydantic import Field, SecretStr, ValidationError, field_validator
from pydantic_settings import BaseSettings, SettingsConfigDict

# unit tests

# --- Basic Test Cases ---





















#------------------------------------------------
import pytest  # used for our unit tests
from langflow.services.settings.auth import AuthSettings
# function to test (already provided in prompt)
from langflow.services.settings.constants import (DEFAULT_SUPERUSER,
                                                  DEFAULT_SUPERUSER_PASSWORD)
from pydantic import SecretStr, ValidationError

# Basic Test Cases

def test_superuser_and_password_default_values():
    """
    Test that SUPERUSER and SUPERUSER_PASSWORD retain their default values when AUTO_LOGIN is False.
    """
    settings = {
        "AUTO_LOGIN": False,
        "SUPERUSER": "admin",
        "SUPERUSER_PASSWORD": SecretStr("adminpassword"),
    }
    # Simulate info object for field_validator
    class Info:
        def __init__(self, field_name, data):
            self.field_name = field_name
            self.data = data
    # Test SUPERUSER
    codeflash_output = AuthSettings.validate_superuser("admin", Info("SUPERUSER", settings)); result_user = codeflash_output
    # Test SUPERUSER_PASSWORD
    codeflash_output = AuthSettings.validate_superuser(SecretStr("adminpassword"), Info("SUPERUSER_PASSWORD", settings)); result_pwd = codeflash_output

def test_superuser_and_password_default_values_with_auto_login_false():
    """
    Test that SUPERUSER and SUPERUSER_PASSWORD retain provided values when AUTO_LOGIN is False.
    """
    settings = {
        "AUTO_LOGIN": False,
        "SUPERUSER": "customuser",
        "SUPERUSER_PASSWORD": SecretStr("custompassword"),
    }
    class Info:
        def __init__(self, field_name, data):
            self.field_name = field_name
            self.data = data
    codeflash_output = AuthSettings.validate_superuser("customuser", Info("SUPERUSER", settings))

def test_auto_login_forces_default_superuser_and_password():
    """
    Test that when AUTO_LOGIN is True, SUPERUSER and SUPERUSER_PASSWORD are forced to default values.
    """
    settings = {
        "AUTO_LOGIN": True,
        "SUPERUSER": "notdefault",
        "SUPERUSER_PASSWORD": SecretStr("notdefaultpassword"),
    }
    class Info:
        def __init__(self, field_name, data):
            self.field_name = field_name
            self.data = data
    # SUPERUSER is forced to DEFAULT_SUPERUSER
    codeflash_output = AuthSettings.validate_superuser("notdefault", Info("SUPERUSER", settings))
    # SUPERUSER_PASSWORD is forced to DEFAULT_SUPERUSER_PASSWORD
    codeflash_output = AuthSettings.validate_superuser(SecretStr("notdefaultpassword"), Info("SUPERUSER_PASSWORD", settings)); result_pwd = codeflash_output

def test_auto_login_with_default_values():
    """
    Test that when AUTO_LOGIN is True and values are already default, they remain unchanged.
    """
    settings = {
        "AUTO_LOGIN": True,
        "SUPERUSER": DEFAULT_SUPERUSER,
        "SUPERUSER_PASSWORD": DEFAULT_SUPERUSER_PASSWORD,
    }
    class Info:
        def __init__(self, field_name, data):
            self.field_name = field_name
            self.data = data
    codeflash_output = AuthSettings.validate_superuser(DEFAULT_SUPERUSER, Info("SUPERUSER", settings))
    codeflash_output = AuthSettings.validate_superuser(DEFAULT_SUPERUSER_PASSWORD, Info("SUPERUSER_PASSWORD", settings)); result_pwd = codeflash_output

# Edge Test Cases

def test_clear_superuser_credentials_with_auto_login_true():
    """
    Test that when AUTO_LOGIN is True and clear_superuser_credentials is True,
    SUPERUSER_PASSWORD is cleared to an empty string.
    """
    settings = {
        "AUTO_LOGIN": True,
        "SUPERUSER": "admin",
        "SUPERUSER_PASSWORD": SecretStr("adminpassword"),
        "clear_superuser_credentials": True,
    }
    class Info:
        def __init__(self, field_name, data):
            self.field_name = field_name
            self.data = data
    # SUPERUSER should still be default
    codeflash_output = AuthSettings.validate_superuser("admin", Info("SUPERUSER", settings))
    # SUPERUSER_PASSWORD should be cleared
    codeflash_output = AuthSettings.validate_superuser(SecretStr("adminpassword"), Info("SUPERUSER_PASSWORD", settings)); result_pwd = codeflash_output

def test_clear_superuser_credentials_with_auto_login_false():
    """
    Test that clear_superuser_credentials does NOT clear password when AUTO_LOGIN is False.
    """
    settings = {
        "AUTO_LOGIN": False,
        "SUPERUSER": "admin",
        "SUPERUSER_PASSWORD": SecretStr("adminpassword"),
        "clear_superuser_credentials": True,
    }
    class Info:
        def __init__(self, field_name, data):
            self.field_name = field_name
            self.data = data
    codeflash_output = AuthSettings.validate_superuser(SecretStr("adminpassword"), Info("SUPERUSER_PASSWORD", settings)); result_pwd = codeflash_output


def test_superuser_password_type_enforcement_secretstr():
    """
    Test that SUPERUSER_PASSWORD can be passed as a SecretStr and is returned as SecretStr if AUTO_LOGIN is True.
    """
    settings = {
        "AUTO_LOGIN": True,
        "SUPERUSER": "admin",
        "SUPERUSER_PASSWORD": SecretStr("adminpassword"),
    }
    class Info:
        def __init__(self, field_name, data):
            self.field_name = field_name
            self.data = data
    codeflash_output = AuthSettings.validate_superuser(SecretStr("adminpassword"), Info("SUPERUSER_PASSWORD", settings)); result = codeflash_output


def test_superuser_none_value():
    """
    Test that SUPERUSER can be None and is returned as is if AUTO_LOGIN is False.
    """
    settings = {
        "AUTO_LOGIN": False,
        "SUPERUSER": None,
        "SUPERUSER_PASSWORD": SecretStr("adminpassword"),
    }
    class Info:
        def __init__(self, field_name, data):
            self.field_name = field_name
            self.data = data
    codeflash_output = AuthSettings.validate_superuser(None, Info("SUPERUSER", settings)); result = codeflash_output

def test_superuser_password_none_value():
    """
    Test that SUPERUSER_PASSWORD can be None and is returned as is if AUTO_LOGIN is False.
    """
    settings = {
        "AUTO_LOGIN": False,
        "SUPERUSER": "admin",
        "SUPERUSER_PASSWORD": None,
    }
    class Info:
        def __init__(self, field_name, data):
            self.field_name = field_name
            self.data = data
    codeflash_output = AuthSettings.validate_superuser(None, Info("SUPERUSER_PASSWORD", settings)); result = codeflash_output

# Large Scale Test Cases

def test_large_scale_auto_login_true():
    """
    Test that with a large number of different superuser values, AUTO_LOGIN forces the default value.
    """
    settings = {
        "AUTO_LOGIN": True,
        "SUPERUSER_PASSWORD": SecretStr("notdefaultpassword"),
    }
    class Info:
        def __init__(self, field_name, data):
            self.field_name = field_name
            self.data = data
    # Test with 500 different superuser names
    for i in range(500):
        user = f"user_{i}"
        settings["SUPERUSER"] = user
        codeflash_output = AuthSettings.validate_superuser(user, Info("SUPERUSER", settings)); result = codeflash_output

def test_large_scale_auto_login_false():
    """
    Test that with a large number of different superuser values, AUTO_LOGIN=False preserves the value.
    """
    settings = {
        "AUTO_LOGIN": False,
        "SUPERUSER_PASSWORD": SecretStr("notdefaultpassword"),
    }
    class Info:
        def __init__(self, field_name, data):
            self.field_name = field_name
            self.data = data
    # Test with 500 different superuser names
    for i in range(500):
        user = f"user_{i}"
        settings["SUPERUSER"] = user
        codeflash_output = AuthSettings.validate_superuser(user, Info("SUPERUSER", settings)); result = codeflash_output

def test_large_scale_clear_superuser_credentials():
    """
    Test that clear_superuser_credentials clears the password for many different values when AUTO_LOGIN is True.
    """
    settings = {
        "AUTO_LOGIN": True,
        "clear_superuser_credentials": True,
    }
    class Info:
        def __init__(self, field_name, data):
            self.field_name = field_name
            self.data = data
    # Test with 500 different passwords
    for i in range(500):
        pwd = SecretStr(f"password_{i}")
        settings["SUPERUSER_PASSWORD"] = pwd
        codeflash_output = AuthSettings.validate_superuser(pwd, Info("SUPERUSER_PASSWORD", settings)); result = codeflash_output

def test_large_scale_superuser_password_preserved():
    """
    Test that with many different passwords, AUTO_LOGIN=False preserves the password value.
    """
    settings = {
        "AUTO_LOGIN": False,
    }
    class Info:
        def __init__(self, field_name, data):
            self.field_name = field_name
            self.data = data
    # Test with 500 different passwords
    for i in range(500):
        pwd = SecretStr(f"password_{i}")
        settings["SUPERUSER_PASSWORD"] = pwd
        codeflash_output = AuthSettings.validate_superuser(pwd, Info("SUPERUSER_PASSWORD", settings)); result = codeflash_output

def test_large_scale_superuser_password_empty():
    """
    Test that with many empty passwords, AUTO_LOGIN=False returns empty string.
    """
    settings = {
        "AUTO_LOGIN": False,
    }
    class Info:
        def __init__(self, field_name, data):
            self.field_name = field_name
            self.data = data
    for i in range(500):
        pwd = ""
        settings["SUPERUSER_PASSWORD"] = pwd
        codeflash_output = AuthSettings.validate_superuser(pwd, Info("SUPERUSER_PASSWORD", settings)); result = codeflash_output

def test_large_scale_superuser_password_none():
    """
    Test that with many None passwords, AUTO_LOGIN=False returns None.
    """
    settings = {
        "AUTO_LOGIN": False,
    }
    class Info:
        def __init__(self, field_name, data):
            self.field_name = field_name
            self.data = data
    for i in range(500):
        pwd = None
        settings["SUPERUSER_PASSWORD"] = pwd
        codeflash_output = AuthSettings.validate_superuser(pwd, Info("SUPERUSER_PASSWORD", settings)); 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-pr9674-2025-09-11T02.05.39 and push.

Codeflash

The optimized code achieves a 40% speedup by **caching attribute lookups** that would otherwise be performed multiple times within the validation method.

**Key optimizations:**

1. **Cached `info.data` lookup**: The original code calls `info.data.get()` up to 3 times per invocation. The optimized version stores `info.data` in a local variable `data` and reuses it, eliminating repeated attribute access overhead.

2. **Cached `info.field_name` lookup**: Similarly, `info.field_name` is accessed multiple times in the original code. The optimized version caches it as `field_name`, reducing attribute lookup overhead.

3. **Cached `auto_login` value**: The `data.get("AUTO_LOGIN")` result is stored in `auto_login` variable, avoiding the dictionary lookup and method call overhead when the condition is checked.

**Why this works:**
In Python, attribute access (like `info.data`) and method calls (like `.get()`) have non-trivial overhead. When these operations are performed repeatedly within a tight loop or frequently-called validation method, caching them in local variables provides measurable performance benefits. Local variable access is significantly faster than attribute lookups in Python's execution model.

**Test case performance:**
The optimization is particularly effective for the large-scale test cases (`test_large_scale_*` functions) that call the validator 500+ times in loops, where the cumulative effect of eliminating repeated attribute lookups becomes substantial. The basic test cases also benefit, but the gains are more pronounced in high-frequency validation scenarios.
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Sep 11, 2025

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.

@sonarqubecloud
Copy link
Copy Markdown

@codeflash-ai codeflash-ai Bot closed this Sep 11, 2025
@codeflash-ai
Copy link
Copy Markdown
Contributor Author

codeflash-ai Bot commented Sep 11, 2025

This PR has been automatically closed because the original PR #9674 by jordanrfrazier was closed.

@codeflash-ai codeflash-ai Bot deleted the codeflash/optimize-pr9674-2025-09-11T02.05.39 branch September 11, 2025 16:59
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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

0 participants