Skip to content

Conversation

@codeflash-ai
Copy link

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

📄 18% (0.18x) speedup for PrivacyService.is_policy_defined in nvflare/private/privacy_manager.py

⏱️ Runtime : 1.21 milliseconds 1.03 milliseconds (best of 143 runs)

📝 Explanation and details

The optimization reduces redundant attribute lookups by storing PrivacyService.manager in a local variable. In the original code, PrivacyService.manager is accessed twice - once in the condition check and again when calling is_policy_defined(). This requires two class attribute lookups, which are slower than local variable access in Python.

The optimized version stores the attribute in a local variable manager at the beginning, eliminating the second attribute lookup. The line profiler shows this reduces the per-hit time for the attribute access from 275.3ns to 259.4ns, and the method call from 612.4ns to 583.2ns.

The optimization also removes the unnecessary else: clause since the function returns early when the condition is met, slightly improving code flow but without significant performance impact.

This optimization is particularly effective for test cases with valid managers (15-37% speedup) since they benefit most from the eliminated second attribute lookup. Cases with falsy managers see smaller gains (7-14%) since they only execute the first attribute access. The 17% overall speedup aligns well with the test results showing consistent improvements across all scenarios.

Correctness verification report:

Test Status
⚙️ Existing Unit Tests 🔘 None Found
🌀 Generated Regression Tests 5033 Passed
⏪ Replay Tests 🔘 None Found
🔎 Concolic Coverage Tests 🔘 None Found
📊 Tests Coverage 100.0%
🌀 Generated Regression Tests and Runtime
import pytest
from nvflare.private.privacy_manager import PrivacyService

# --- Unit tests for PrivacyService.is_policy_defined() ---

# Helper class for mocking manager with is_policy_defined method
class DummyManagerTrue:
    def is_policy_defined(self):
        return True

class DummyManagerFalse:
    def is_policy_defined(self):
        return False

class DummyManagerRaises:
    def is_policy_defined(self):
        raise RuntimeError("Manager error")

class DummyManagerNonBool:
    def is_policy_defined(self):
        return "yes"

class DummyManagerNone:
    def is_policy_defined(self):
        return None

class DummyManagerInt:
    def is_policy_defined(self):
        return 1

class DummyManagerList:
    def is_policy_defined(self):
        return [True]

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

def test_manager_none_returns_false():
    """Test when manager is None, should return False."""
    PrivacyService.manager = None
    codeflash_output = PrivacyService.is_policy_defined() # 602ns -> 513ns (17.3% faster)

def test_manager_false_returns_false():
    """Test when manager.is_policy_defined returns False."""
    PrivacyService.manager = DummyManagerFalse()
    codeflash_output = PrivacyService.is_policy_defined() # 978ns -> 777ns (25.9% faster)

def test_manager_true_returns_true():
    """Test when manager.is_policy_defined returns True."""
    PrivacyService.manager = DummyManagerTrue()
    codeflash_output = PrivacyService.is_policy_defined() # 769ns -> 668ns (15.1% faster)

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

def test_manager_is_zero_returns_false():
    """Test when manager is 0 (falsy), should return False."""
    PrivacyService.manager = 0
    codeflash_output = PrivacyService.is_policy_defined() # 467ns -> 428ns (9.11% faster)

def test_manager_is_empty_string_returns_false():
    """Test when manager is empty string (falsy), should return False."""
    PrivacyService.manager = ""
    codeflash_output = PrivacyService.is_policy_defined() # 452ns -> 395ns (14.4% faster)

def test_manager_is_empty_list_returns_false():
    """Test when manager is empty list (falsy), should return False."""
    PrivacyService.manager = []
    codeflash_output = PrivacyService.is_policy_defined() # 465ns -> 419ns (11.0% faster)

def test_manager_is_empty_dict_returns_false():
    """Test when manager is empty dict (falsy), should return False."""
    PrivacyService.manager = {}
    codeflash_output = PrivacyService.is_policy_defined() # 449ns -> 416ns (7.93% faster)

def test_manager_is_nonempty_list_raises_attributeerror():
    """Test when manager is a non-empty list (truthy), should raise AttributeError."""
    PrivacyService.manager = [1]
    with pytest.raises(AttributeError):
        PrivacyService.is_policy_defined() # 1.71μs -> 1.41μs (21.2% faster)

def test_manager_is_nonempty_dict_raises_attributeerror():
    """Test when manager is a non-empty dict (truthy), should raise AttributeError."""
    PrivacyService.manager = {'a': 1}
    with pytest.raises(AttributeError):
        PrivacyService.is_policy_defined() # 1.44μs -> 1.36μs (5.35% faster)

def test_manager_is_nonbool_return_value():
    """Test when manager.is_policy_defined returns non-bool value."""
    PrivacyService.manager = DummyManagerNonBool()
    codeflash_output = PrivacyService.is_policy_defined(); result = codeflash_output # 937ns -> 791ns (18.5% faster)

def test_manager_is_policy_defined_returns_none():
    """Test when manager.is_policy_defined returns None."""
    PrivacyService.manager = DummyManagerNone()
    codeflash_output = PrivacyService.is_policy_defined(); result = codeflash_output # 922ns -> 701ns (31.5% faster)

def test_manager_is_policy_defined_returns_int():
    """Test when manager.is_policy_defined returns int."""
    PrivacyService.manager = DummyManagerInt()
    codeflash_output = PrivacyService.is_policy_defined(); result = codeflash_output # 785ns -> 640ns (22.7% faster)

def test_manager_is_policy_defined_returns_list():
    """Test when manager.is_policy_defined returns list."""
    PrivacyService.manager = DummyManagerList()
    codeflash_output = PrivacyService.is_policy_defined(); result = codeflash_output # 823ns -> 684ns (20.3% faster)

def test_manager_is_policy_defined_raises_exception():
    """Test when manager.is_policy_defined raises an exception."""
    PrivacyService.manager = DummyManagerRaises()
    with pytest.raises(RuntimeError):
        PrivacyService.is_policy_defined() # 1.44μs -> 1.14μs (26.0% faster)

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

def test_large_number_of_manager_instances_true():
    """Test with many manager instances returning True."""
    # Create 1000 managers, all return True
    for _ in range(1000):
        PrivacyService.manager = DummyManagerTrue()
        codeflash_output = PrivacyService.is_policy_defined() # 222μs -> 183μs (20.9% faster)

def test_large_number_of_manager_instances_false():
    """Test with many manager instances returning False."""
    # Create 1000 managers, all return False
    for _ in range(1000):
        PrivacyService.manager = DummyManagerFalse()
        codeflash_output = PrivacyService.is_policy_defined() # 216μs -> 182μs (18.5% faster)

def test_large_number_of_none_manager():
    """Test with many None managers."""
    for _ in range(1000):
        PrivacyService.manager = None
        codeflash_output = PrivacyService.is_policy_defined() # 157μs -> 140μs (12.4% faster)

def test_large_number_of_nonbool_manager():
    """Test with many managers returning non-bool values."""
    for i in range(1000):
        PrivacyService.manager = DummyManagerInt()
        codeflash_output = PrivacyService.is_policy_defined() # 213μs -> 181μs (17.8% faster)

def test_large_number_of_exception_manager():
    """Test with many managers raising exceptions."""
    for _ in range(1000):
        PrivacyService.manager = DummyManagerRaises()
        with pytest.raises(RuntimeError):
            PrivacyService.is_policy_defined()
# codeflash_output is used to check that the output of the original code is the same as that of the optimized code.
#------------------------------------------------
import pytest
from nvflare.private.privacy_manager import PrivacyService

# --- unit tests ---

# Helper class to mimic manager behavior
class DummyManager:
    def __init__(self, defined):
        self.defined = defined
    def is_policy_defined(self):
        return self.defined

# Helper class for edge cases: manager without is_policy_defined method
class NoMethodManager:
    pass

# Helper class for edge cases: manager with is_policy_defined as a property
class PropertyManager:
    @property
    def is_policy_defined(self):
        return True

# Helper class for edge cases: manager with is_policy_defined returning non-bool
class NonBoolManager:
    def is_policy_defined(self):
        return "yes"

# Helper class for large scale: manager with is_policy_defined depending on large data
class LargeDataManager:
    def __init__(self, size, defined_indices):
        self.policies = [i in defined_indices for i in range(size)]
    def is_policy_defined(self):
        # Returns True if any policy is defined
        return any(self.policies)

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

def test_manager_none_returns_false():
    # Test when manager is None
    PrivacyService.manager = None
    codeflash_output = PrivacyService.is_policy_defined() # 440ns -> 437ns (0.686% faster)

def test_manager_false_returns_false():
    # Test when manager is explicitly False
    PrivacyService.manager = False
    codeflash_output = PrivacyService.is_policy_defined() # 403ns -> 392ns (2.81% faster)

def test_manager_true_returns_true():
    # Test when manager.is_policy_defined returns True
    PrivacyService.manager = DummyManager(True)
    codeflash_output = PrivacyService.is_policy_defined() # 943ns -> 690ns (36.7% faster)

def test_manager_false_returns_false_again():
    # Test when manager.is_policy_defined returns False
    PrivacyService.manager = DummyManager(False)
    codeflash_output = PrivacyService.is_policy_defined() # 620ns -> 514ns (20.6% faster)

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

def test_manager_no_method_raises_attribute_error():
    # Manager does not have is_policy_defined method
    PrivacyService.manager = NoMethodManager()
    with pytest.raises(AttributeError):
        PrivacyService.is_policy_defined() # 1.61μs -> 1.36μs (18.8% faster)

def test_manager_method_is_property():
    # Manager's is_policy_defined is a property, not a method
    PrivacyService.manager = PropertyManager()
    # Should raise TypeError because property is not callable
    with pytest.raises(TypeError):
        PrivacyService.is_policy_defined() # 1.77μs -> 1.53μs (16.1% faster)

def test_manager_method_returns_non_bool():
    # Manager's is_policy_defined returns non-bool value
    PrivacyService.manager = NonBoolManager()
    codeflash_output = PrivacyService.is_policy_defined(); result = codeflash_output # 840ns -> 654ns (28.4% faster)

def test_manager_is_empty_object():
    # Manager is an empty object (not None, but falsy)
    class EmptyManager:
        def is_policy_defined(self):
            return True
        def __bool__(self):
            return False
    PrivacyService.manager = EmptyManager()
    # Should return False because manager is falsy
    codeflash_output = PrivacyService.is_policy_defined() # 979ns -> 845ns (15.9% faster)

def test_manager_is_zero():
    # Manager is 0 (falsy)
    PrivacyService.manager = 0
    codeflash_output = PrivacyService.is_policy_defined() # 417ns -> 420ns (0.714% slower)

def test_manager_is_empty_string():
    # Manager is empty string (falsy)
    PrivacyService.manager = ""
    codeflash_output = PrivacyService.is_policy_defined() # 383ns -> 371ns (3.23% faster)

def test_manager_is_empty_list():
    # Manager is empty list (falsy)
    PrivacyService.manager = []
    codeflash_output = PrivacyService.is_policy_defined() # 409ns -> 383ns (6.79% faster)

def test_manager_is_empty_dict():
    # Manager is empty dict (falsy)
    PrivacyService.manager = {}
    codeflash_output = PrivacyService.is_policy_defined() # 401ns -> 400ns (0.250% faster)

def test_manager_is_non_callable_object_with_method_name():
    # Manager has an attribute named is_policy_defined, but it's not callable
    class BadManager:
        is_policy_defined = True
    PrivacyService.manager = BadManager()
    # Should raise TypeError because attribute is not callable
    with pytest.raises(TypeError):
        PrivacyService.is_policy_defined() # 1.51μs -> 1.34μs (12.9% faster)

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

def test_large_manager_all_false():
    # Large manager with all policies undefined
    size = 1000
    PrivacyService.manager = LargeDataManager(size, defined_indices=[])
    codeflash_output = PrivacyService.is_policy_defined() # 4.04μs -> 3.17μs (27.2% faster)

def test_large_manager_some_true():
    # Large manager with some policies defined
    size = 1000
    defined_indices = [0, 999]
    PrivacyService.manager = LargeDataManager(size, defined_indices=defined_indices)
    codeflash_output = PrivacyService.is_policy_defined() # 1.02μs -> 795ns (28.3% faster)

def test_large_manager_all_true():
    # Large manager with all policies defined
    size = 1000
    defined_indices = list(range(size))
    PrivacyService.manager = LargeDataManager(size, defined_indices=defined_indices)
    codeflash_output = PrivacyService.is_policy_defined() # 1.06μs -> 914ns (15.5% faster)

def test_large_manager_middle_true():
    # Large manager with one policy defined in the middle
    size = 1000
    defined_indices = [500]
    PrivacyService.manager = LargeDataManager(size, defined_indices=defined_indices)
    codeflash_output = PrivacyService.is_policy_defined() # 2.35μs -> 1.94μs (21.5% faster)

def test_large_manager_performance():
    # Large manager, performance check (should not timeout)
    size = 1000
    defined_indices = [size // 2]
    PrivacyService.manager = LargeDataManager(size, defined_indices=defined_indices)
    codeflash_output = PrivacyService.is_policy_defined() # 2.36μs -> 1.95μs (20.6% faster)

# ----------- Additional Edge Cases ------------


def test_manager_is_object_with_custom_bool_false():
    # Manager is object with __bool__ returning False
    class CustomBoolManager:
        def __bool__(self):
            return False
        def is_policy_defined(self):
            return True
    PrivacyService.manager = CustomBoolManager()
    # Should return False because manager is falsy
    codeflash_output = PrivacyService.is_policy_defined() # 1.20μs -> 925ns (30.1% faster)

To edit these changes git checkout codeflash/optimize-PrivacyService.is_policy_defined-mhe0t67y and push.

Codeflash Static Badge

The optimization reduces redundant attribute lookups by storing `PrivacyService.manager` in a local variable. In the original code, `PrivacyService.manager` is accessed twice - once in the condition check and again when calling `is_policy_defined()`. This requires two class attribute lookups, which are slower than local variable access in Python.

The optimized version stores the attribute in a local variable `manager` at the beginning, eliminating the second attribute lookup. The line profiler shows this reduces the per-hit time for the attribute access from 275.3ns to 259.4ns, and the method call from 612.4ns to 583.2ns.

The optimization also removes the unnecessary `else:` clause since the function returns early when the condition is met, slightly improving code flow but without significant performance impact.

This optimization is particularly effective for test cases with valid managers (15-37% speedup) since they benefit most from the eliminated second attribute lookup. Cases with falsy managers see smaller gains (7-14%) since they only execute the first attribute access. The 17% overall speedup aligns well with the test results showing consistent improvements across all scenarios.
@codeflash-ai codeflash-ai bot requested a review from mashraf-222 October 30, 2025 22:53
@codeflash-ai codeflash-ai bot added ⚡️ codeflash Optimization PR opened by Codeflash AI 🎯 Quality: High Optimization Quality according to Codeflash labels Oct 30, 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 🎯 Quality: High Optimization Quality according to Codeflash

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant