Skip to content

Conversation

@codeflash-ai
Copy link

@codeflash-ai codeflash-ai bot commented Oct 23, 2025

📄 24% (0.24x) speedup for Configure.multi_tenancy in weaviate/collections/classes/config.py

⏱️ Runtime : 3.18 milliseconds 2.57 milliseconds (best of 32 runs)

📝 Explanation and details

The optimization applies constructor caching by storing the _MultiTenancyConfigCreate class reference in a local variable ctor before calling it. This eliminates repeated global name lookups during function execution.

Key change: Instead of directly calling _MultiTenancyConfigCreate(...), the code now assigns the class to ctor = _MultiTenancyConfigCreate and then calls ctor(...).

Why it's faster: In Python, global name resolution (looking up _MultiTenancyConfigCreate from the module's global namespace) has overhead compared to accessing a local variable. The line profiler shows this optimization reduces the constructor call time from 1077.4ns per hit to 885.8ns per hit - an 18% improvement on the most expensive line.

Performance characteristics: The optimization is most effective for:

  • Frequent calls: Tests show 20-40% speedups across all parameter combinations
  • Bulk operations: Large-scale tests with 500-1000 iterations see consistent 23-26% improvements
  • Simple parameter variations: All test cases benefit similarly regardless of boolean/None parameter values

The 23% overall speedup comes primarily from reducing the overhead of global namespace lookups, which becomes significant when the function is called repeatedly in tight loops or high-frequency scenarios.

Correctness verification report:

Test Status
⚙️ Existing Unit Tests 🔘 None Found
🌀 Generated Regression Tests 2530 Passed
⏪ Replay Tests 🔘 None Found
🔎 Concolic Coverage Tests 🔘 None Found
📊 Tests Coverage 100.0%
🌀 Generated Regression Tests and Runtime
import pytest
from weaviate.collections.classes.config import Configure


# function to test
class _MultiTenancyConfigCreate:
    """Stub class for MultiTenancyConfigCreate, emulating expected behavior."""
    def __init__(self, enabled, autoTenantCreation=None, autoTenantActivation=None):
        # Validate types and values
        if not isinstance(enabled, bool):
            raise TypeError("enabled must be a boolean")
        if autoTenantCreation is not None and not isinstance(autoTenantCreation, bool):
            raise TypeError("auto_tenant_creation must be a boolean or None")
        if autoTenantActivation is not None and not isinstance(autoTenantActivation, bool):
            raise TypeError("auto_tenant_activation must be a boolean or None")
        self.enabled = enabled
        self.autoTenantCreation = autoTenantCreation
        self.autoTenantActivation = autoTenantActivation

    def __eq__(self, other):
        if not isinstance(other, _MultiTenancyConfigCreate):
            return False
        return (
            self.enabled == other.enabled and
            self.autoTenantCreation == other.autoTenantCreation and
            self.autoTenantActivation == other.autoTenantActivation
        )

    def __repr__(self):
        return (
            f"_MultiTenancyConfigCreate("
            f"enabled={self.enabled}, "
            f"autoTenantCreation={self.autoTenantCreation}, "
            f"autoTenantActivation={self.autoTenantActivation})"
        )
from weaviate.collections.classes.config import Configure

# unit tests

# ----------- Basic Test Cases ------------

def test_default_parameters():
    """Test default behavior: all defaults."""
    codeflash_output = Configure.multi_tenancy(); config = codeflash_output # 6.41μs -> 5.17μs (24.0% faster)

def test_enabled_false():
    """Test with enabled set to False."""
    codeflash_output = Configure.multi_tenancy(enabled=False); config = codeflash_output # 4.95μs -> 3.74μs (32.4% faster)

def test_auto_tenant_creation_true():
    """Test with auto_tenant_creation True."""
    codeflash_output = Configure.multi_tenancy(auto_tenant_creation=True); config = codeflash_output # 4.43μs -> 3.39μs (30.7% faster)

def test_auto_tenant_activation_true():
    """Test with auto_tenant_activation True."""
    codeflash_output = Configure.multi_tenancy(auto_tenant_activation=True); config = codeflash_output # 4.90μs -> 3.64μs (34.7% faster)

def test_all_parameters_false():
    """Test with all parameters set to False."""
    codeflash_output = Configure.multi_tenancy(enabled=False, auto_tenant_creation=False, auto_tenant_activation=False); config = codeflash_output # 4.59μs -> 3.64μs (26.3% faster)

def test_all_parameters_true():
    """Test with all parameters set to True."""
    codeflash_output = Configure.multi_tenancy(enabled=True, auto_tenant_creation=True, auto_tenant_activation=True); config = codeflash_output # 4.71μs -> 3.39μs (38.8% faster)

def test_mixed_parameters():
    """Test with mixed True/False/None values."""
    codeflash_output = Configure.multi_tenancy(enabled=False, auto_tenant_creation=None, auto_tenant_activation=True); config = codeflash_output # 4.89μs -> 3.82μs (28.2% faster)

# ----------- Edge Test Cases ------------









def test_equality_and_repr():
    """Edge: test __eq__ and __repr__ for determinism and correctness."""
    codeflash_output = Configure.multi_tenancy(enabled=True, auto_tenant_creation=False, auto_tenant_activation=True); config1 = codeflash_output # 9.94μs -> 8.28μs (20.0% faster)
    codeflash_output = Configure.multi_tenancy(enabled=True, auto_tenant_creation=False, auto_tenant_activation=True); config2 = codeflash_output # 2.12μs -> 1.65μs (29.0% faster)
    codeflash_output = Configure.multi_tenancy(enabled=False, auto_tenant_creation=False, auto_tenant_activation=True); config3 = codeflash_output # 1.37μs -> 1.11μs (23.5% faster)

# ----------- Large Scale Test Cases ------------

def test_bulk_creation_determinism():
    """Large scale: create many configs with alternating values and check determinism."""
    configs = []
    for i in range(1000):
        enabled = (i % 2 == 0)
        auto_tenant_creation = (i % 3 == 0)
        auto_tenant_activation = (i % 5 == 0)
        codeflash_output = Configure.multi_tenancy(
            enabled=enabled,
            auto_tenant_creation=auto_tenant_creation,
            auto_tenant_activation=auto_tenant_activation,
        ); config = codeflash_output # 1.23ms -> 992μs (23.9% faster)
        configs.append(config)

def test_bulk_equality_and_repr():
    """Large scale: test equality and repr for many configs."""
    configs = [
        Configure.multi_tenancy(enabled=True, auto_tenant_creation=False, auto_tenant_activation=True)
        for _ in range(500)
    ]
    # All configs should be equal
    for config in configs:
        pass
    # Changing one should break equality
    configs[250] = Configure.multi_tenancy(enabled=False, auto_tenant_creation=False, auto_tenant_activation=True)


#------------------------------------------------
import pytest
from weaviate.collections.classes.config import Configure


# function to test
class _MultiTenancyConfigCreate:
    """Dummy config class to mimic the actual config object returned by multi_tenancy."""
    def __init__(self, enabled, autoTenantCreation=None, autoTenantActivation=None):
        self.enabled = enabled
        self.autoTenantCreation = autoTenantCreation
        self.autoTenantActivation = autoTenantActivation

    def __eq__(self, other):
        # Used for test equality
        if not isinstance(other, _MultiTenancyConfigCreate):
            return False
        return (
            self.enabled == other.enabled and
            self.autoTenantCreation == other.autoTenantCreation and
            self.autoTenantActivation == other.autoTenantActivation
        )

    def __repr__(self):
        return (
            f"_MultiTenancyConfigCreate(enabled={self.enabled!r}, "
            f"autoTenantCreation={self.autoTenantCreation!r}, "
            f"autoTenantActivation={self.autoTenantActivation!r})"
        )
from weaviate.collections.classes.config import Configure

# unit tests

# Basic Test Cases

def test_defaults_enabled_true():
    """Test default parameters: enabled should be True, others None."""
    codeflash_output = Configure.multi_tenancy(); config = codeflash_output # 10.1μs -> 9.19μs (9.54% faster)

def test_enabled_false():
    """Test with enabled=False, others default."""
    codeflash_output = Configure.multi_tenancy(enabled=False); config = codeflash_output # 6.75μs -> 5.62μs (20.0% faster)

def test_auto_tenant_creation_true():
    """Test with auto_tenant_creation=True."""
    codeflash_output = Configure.multi_tenancy(auto_tenant_creation=True); config = codeflash_output # 5.76μs -> 4.57μs (26.0% faster)

def test_auto_tenant_activation_true():
    """Test with auto_tenant_activation=True."""
    codeflash_output = Configure.multi_tenancy(auto_tenant_activation=True); config = codeflash_output # 5.55μs -> 3.98μs (39.6% faster)

def test_all_false():
    """Test with all parameters set to False."""
    codeflash_output = Configure.multi_tenancy(enabled=False, auto_tenant_creation=False, auto_tenant_activation=False); config = codeflash_output # 5.42μs -> 3.95μs (37.1% faster)

def test_all_true():
    """Test with all parameters set to True."""
    codeflash_output = Configure.multi_tenancy(enabled=True, auto_tenant_creation=True, auto_tenant_activation=True); config = codeflash_output # 5.20μs -> 3.96μs (31.2% faster)

def test_mixed_values():
    """Test with enabled=False, auto_tenant_creation=True, auto_tenant_activation=False."""
    codeflash_output = Configure.multi_tenancy(enabled=False, auto_tenant_creation=True, auto_tenant_activation=False); config = codeflash_output # 5.17μs -> 3.79μs (36.3% faster)

# Edge Test Cases





def test_auto_tenant_creation_none():
    """Test that auto_tenant_creation=None is accepted."""
    codeflash_output = Configure.multi_tenancy(auto_tenant_creation=None); config = codeflash_output # 9.78μs -> 8.10μs (20.6% faster)

def test_auto_tenant_activation_none():
    """Test that auto_tenant_activation=None is accepted."""
    codeflash_output = Configure.multi_tenancy(auto_tenant_activation=None); config = codeflash_output # 6.00μs -> 4.84μs (23.9% faster)

def test_extra_argument_type_error():
    """Test passing an unexpected argument raises TypeError."""
    with pytest.raises(TypeError):
        Configure.multi_tenancy(enabled=True, unknown_arg=True) # 1.50μs -> 1.18μs (27.6% faster)

def test_boundary_bool_values():
    """Test boundary values for bools (True and False)."""
    for val in [True, False]:
        codeflash_output = Configure.multi_tenancy(enabled=val, auto_tenant_creation=val, auto_tenant_activation=val); config = codeflash_output # 8.93μs -> 7.07μs (26.3% faster)

def test_multiple_calls_consistency():
    """Test that multiple calls with same arguments return equal objects."""
    codeflash_output = Configure.multi_tenancy(enabled=True, auto_tenant_creation=True, auto_tenant_activation=False); config1 = codeflash_output # 4.81μs -> 3.69μs (30.2% faster)
    codeflash_output = Configure.multi_tenancy(enabled=True, auto_tenant_creation=True, auto_tenant_activation=False); config2 = codeflash_output # 1.87μs -> 1.32μs (41.6% faster)

def test_object_repr():
    """Test that __repr__ returns a correct string."""
    codeflash_output = Configure.multi_tenancy(enabled=False, auto_tenant_creation=True, auto_tenant_activation=None); config = codeflash_output # 4.78μs -> 3.69μs (29.8% faster)
    rep = repr(config)

# Large Scale Test Cases

def test_large_batch_creation():
    """Test creating many configs in a loop with alternating values."""
    configs = []
    for i in range(500):  # Under 1000 as required
        codeflash_output = Configure.multi_tenancy(
            enabled=bool(i % 2),
            auto_tenant_creation=bool((i+1) % 2),
            auto_tenant_activation=None if i % 3 == 0 else bool(i % 2)
        ); config = codeflash_output # 612μs -> 495μs (23.7% faster)
        configs.append(config)
    # Check that all configs are unique by their tuple of values
    tuples = {(c.enabled, c.autoTenantCreation, c.autoTenantActivation) for c in configs}

def test_large_scale_all_true():
    """Test with all parameters True for a large batch."""
    configs = [Configure.multi_tenancy(True, True, True) for _ in range(1000)] # 6.09μs -> 4.94μs (23.4% faster)
    for config in configs:
        pass

def test_large_scale_all_false():
    """Test with all parameters False for a large batch."""
    configs = [Configure.multi_tenancy(False, False, False) for _ in range(1000)] # 4.46μs -> 3.52μs (26.5% faster)
    for config in configs:
        pass

def test_large_scale_none_activation():
    """Test with auto_tenant_activation=None for a large batch."""
    configs = [Configure.multi_tenancy(True, False, None) for _ in range(1000)] # 4.76μs -> 3.38μs (41.1% faster)
    for config in configs:
        pass

def test_large_scale_alternating():
    """Test alternating enabled and auto_tenant_creation values for a large batch."""
    for i in range(1000):
        codeflash_output = Configure.multi_tenancy(
            enabled=bool(i % 2),
            auto_tenant_creation=bool((i+1) % 2),
            auto_tenant_activation=bool(i % 2)
        ); config = codeflash_output # 1.19ms -> 964μs (23.6% faster)
# codeflash_output is used to check that the output of the original code is the same as that of the optimized code.
#------------------------------------------------
from weaviate.collections.classes.config import Configure
import pytest

def test_Configure_multi_tenancy():
    with pytest.raises(ValidationError):
        Configure.multi_tenancy(enabled=False, auto_tenant_creation=None, auto_tenant_activation=None)

Timer unit: 1e-09 s

To edit these changes git checkout codeflash/optimize-Configure.multi_tenancy-mh36icuv and push.

Codeflash

The optimization applies **constructor caching** by storing the `_MultiTenancyConfigCreate` class reference in a local variable `ctor` before calling it. This eliminates repeated global name lookups during function execution.

**Key change:** Instead of directly calling `_MultiTenancyConfigCreate(...)`, the code now assigns the class to `ctor = _MultiTenancyConfigCreate` and then calls `ctor(...)`.

**Why it's faster:** In Python, global name resolution (looking up `_MultiTenancyConfigCreate` from the module's global namespace) has overhead compared to accessing a local variable. The line profiler shows this optimization reduces the constructor call time from 1077.4ns per hit to 885.8ns per hit - an 18% improvement on the most expensive line.

**Performance characteristics:** The optimization is most effective for:
- **Frequent calls**: Tests show 20-40% speedups across all parameter combinations
- **Bulk operations**: Large-scale tests with 500-1000 iterations see consistent 23-26% improvements  
- **Simple parameter variations**: All test cases benefit similarly regardless of boolean/None parameter values

The 23% overall speedup comes primarily from reducing the overhead of global namespace lookups, which becomes significant when the function is called repeatedly in tight loops or high-frequency scenarios.
@codeflash-ai codeflash-ai bot requested a review from mashraf-222 October 23, 2025 08:47
@codeflash-ai codeflash-ai bot added the ⚡️ codeflash Optimization PR opened by Codeflash AI label Oct 23, 2025
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.

1 participant