Skip to content

⚡️ Speed up function apply_tweaks by 15% in PR #12152 (dk/le-558)#12157

Closed
codeflash-ai[bot] wants to merge 1 commit into
dk/le-558from
codeflash/optimize-pr12152-2026-03-11T20.46.04
Closed

⚡️ Speed up function apply_tweaks by 15% in PR #12152 (dk/le-558)#12157
codeflash-ai[bot] wants to merge 1 commit into
dk/le-558from
codeflash/optimize-pr12152-2026-03-11T20.46.04

Conversation

@codeflash-ai
Copy link
Copy Markdown
Contributor

@codeflash-ai codeflash-ai Bot commented Mar 11, 2026

⚡️ This pull request contains optimizations for PR #12152

If you approve this dependent PR, these changes will be merged into the original PR branch dk/le-558.

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


📄 15% (0.15x) speedup for apply_tweaks in src/backend/base/langflow/processing/process.py

⏱️ Runtime : 1.16 milliseconds 1.01 milliseconds (best of 142 runs)

📝 Explanation and details

The hot loop previously performed tweak_name in template_data (line 35 in original) then immediately re-checked tweak_name in template_data (line 39) before every indexing operation, causing redundant membership tests and repeated dictionary lookups—template_data[tweak_name] appeared 14 times across branches. The optimization hoists template_data.get(tweak_name) into a local entry variable once per iteration and replaces all subsequent template_data[tweak_name] references with direct entry accesses, eliminating ~10 dictionary lookups per processed tweak. Line profiler shows the redundant membership check consumed 7.2% of total time (line 35: 658 µs), and subsequent template_data[tweak_name].get("type", "") lookups took another 7.2% (line 39: 661 µs); the optimized version collapses these into a single entry.get("type", "") call costing 6.3% (line 23: 572 µs). Additionally, validate_and_repair_json is bound to the local alias repair outside the loop to avoid repeated global lookups (~20 ns per hit, negligible but measurable at scale). No behavior changes; all security checks, field-type logic, and load_from_db handling remain identical.

Correctness verification report:

Test Status
⚙️ Existing Unit Tests 14 Passed
🌀 Generated Regression Tests 44 Passed
⏪ Replay Tests 🔘 None Found
🔎 Concolic Coverage Tests 🔘 None Found
📊 Tests Coverage 100.0%
⚙️ Click to see Existing Unit Tests
🌀 Click to see Generated Regression Tests
from copy import deepcopy

# imports
import pytest  # used for our unit tests
# import the function under test from the provided module path
from langflow.processing.process import apply_tweaks


def test_return_when_template_not_dict():
    # If template is missing or not a dict, apply_tweaks should return without modifying node.
    node = {"id": "n1", "data": {"node": {"template": None}}}
    node_copy = deepcopy(node)
    tweaks = {"some_field": "value"}  # arbitrary tweaks
    apply_tweaks(node, tweaks)
    # The template should remain exactly as it was (None)
    assert node["data"]["node"]["template"] is None
    # Other parts of node should be unchanged
    assert node == node_copy


def test_ignore_unknown_tweak_and_code_field():
    # Template has 'existing' and 'code' fields. Tweaks try to set unknown 'missing' and override 'code'.
    template = {
        "existing": {"type": "string", "value": "oldvalue"},
        "code": {"type": "string", "value": "print('no change')"},
    }
    node = {"id": "n2", "data": {"node": {"template": template}}}
    tweaks = {
        "missing": "will_be_ignored",  # not in template -> ignored
        "code": "evil()",              # should be explicitly blocked by apply_tweaks
    }
    apply_tweaks(node, tweaks)
    # Unknown tweak should not create new keys
    assert "missing" not in template
    # 'existing' should be unchanged
    assert template["existing"]["value"] == "oldvalue"
    # 'code' should not be overridden
    assert template["code"]["value"] == "print('no change')"


def test_nesteddict_mcp_dict_and_scalar_replacements_and_load_from_db_flags():
    # Construct a template covering multiple branches:
    template = {
        "nested": {"type": "NestedDict", "value": {"initial": True}},
        "mcp_field": {"type": "mcp", "value": {"orig": 1}},
        "dict_field": {"type": "dict", "value": {"a": 0}, "load_from_db": True},
        "dict_multi": {"type": "dict", "value": {}, "load_from_db": True},
        "file_scalar": {"type": "file", "file_path": "old/path", "load_from_db": True},
        "simple": {"type": "string", "value": "old", "load_from_db": True},
        "non_dict_but_dict_tweak": {"type": "string", "value": "s", "load_from_db": True},
    }
    node = {"id": "n3", "data": {"node": {"template": template}}}

    # Tweaks exercise:
    tweaks = {
        # For NestedDict, we pass a dict; validate_and_repair_json is expected to accept dicts.
        "nested": {"x": 1, "y": {"z": 2}},
        # For mcp type, the dict should be set directly as the 'value'
        "mcp_field": {"k": "v"},
        # For dict_field, use the single-key {"value": actual} to trigger unwrapping behavior
        "dict_field": {"value": {"inner": 2}},
        # For dict_multi, supply a multi-key dict which should be set directly
        "dict_multi": {"a": 1, "b": 2},
        # For file_scalar, supply a scalar path -> should set file_path and set load_from_db False
        "file_scalar": "new/path/to/file",
        # For simple, supply a scalar -> should set 'value' and set load_from_db False
        "simple": "newvalue",
        # For a field declared as non-dict, but tweak is a dict: keys should be merged into the template entry
        "non_dict_but_dict_tweak": {"custom_key": 123},
    }

    apply_tweaks(node, tweaks)

    # NestedDict: expect the 'value' replaced by the validated tweak dict
    assert template["nested"]["value"] == {"x": 1, "y": {"z": 2}}

    # mcp_field: 'value' should be the tweak dict exactly
    assert template["mcp_field"]["value"] == {"k": "v"}

    # dict_field: single-key {"value": ...} should be unwrapped to the inner dict
    assert template["dict_field"]["value"] == {"inner": 2}
    # load_from_db should have been present and set to False due to override
    assert template["dict_field"]["load_from_db"] is False

    # dict_multi: multi-key dict assigned directly
    assert template["dict_multi"]["value"] == {"a": 1, "b": 2}
    assert template["dict_multi"]["load_from_db"] is False

    # file_scalar: scalar tweak should create/replace 'file_path' and clear load_from_db
    assert template["file_scalar"]["file_path"] == "new/path/to/file"
    assert template["file_scalar"]["load_from_db"] is False

    # simple: scalar tweak sets 'value' and clears load_from_db
    assert template["simple"]["value"] == "newvalue"
    assert template["simple"]["load_from_db"] is False

    # non_dict_but_dict_tweak: dict tweak on non-dict type should add keys into the field dict
    assert template["non_dict_but_dict_tweak"]["custom_key"] == 123
    # and ensure load_from_db is cleared because it existed originally
    assert template["non_dict_but_dict_tweak"]["load_from_db"] is False


def test_dict_type_unwrap_edge_case_and_multi_key_behavior():
    # Tests the caveat: a legitimate single-key dict {"value": x} will be unwrapped for type 'dict'
    template = {
        "maybe_unwrap": {"type": "dict", "value": {"old": 0}},
        "no_unwrap": {"type": "dict", "value": {"old": 0}},
    }
    node = {"id": "n4", "data": {"node": {"template": template}}}

    # First tweak provides {"value": 42} which should unwrap to 42
    # Second tweak provides a multi-key dict which should be set as-is
    tweaks = {
        "maybe_unwrap": {"value": 42},
        "no_unwrap": {"a": 1, "value": 99},
    }

    apply_tweaks(node, tweaks)

    # maybe_unwrap becomes the scalar 42 (unwrapped)
    assert template["maybe_unwrap"]["value"] == 42
    # no_unwrap becomes the dict {'a':1, 'value':99} (not unwrapped because more than one key)
    assert template["no_unwrap"]["value"] == {"a": 1, "value": 99}


def test_file_field_dict_tweak_sets_load_from_db_false_and_key_mapping():
    # When a dict tweak is supplied to a 'file' field, keys should be assigned,
    # and 'load_from_db' in the template should be set to False if not supplied in tweak.
    template = {
        "file_obj": {"type": "file", "file_path": "orig", "load_from_db": True}
    }
    node = {"id": "n5", "data": {"node": {"template": template}}}

    tweaks = {
        # Provide a dict that does NOT include 'load_from_db' -> so template's load_from_db should be set to False
        "file_obj": {"file_path": "updated/location", "extra": "info"},
    }

    apply_tweaks(node, tweaks)

    # file_path should be updated from the dict tweak
    assert template["file_obj"]["file_path"] == "updated/location"
    # extra key should be set on the template's field dict
    assert template["file_obj"]["extra"] == "info"
    # load_from_db must be set to False by apply_tweaks
    assert template["file_obj"]["load_from_db"] is False


def test_large_scale_template_and_tweaks_performance_and_correctness():
    # Construct a large template of 1000 fields with alternating types to stress test loop logic.
    large_template = {}
    tweaks = {}
    N = 1000

    for i in range(N):
        if i % 3 == 0:
            # string-like field with load_from_db flag
            large_template[f"f{i}"] = {"type": "string", "value": f"old{i}", "load_from_db": True}
            tweaks[f"f{i}"] = f"new{i}"
        elif i % 3 == 1:
            # dict-like field
            large_template[f"f{i}"] = {"type": "dict", "value": {"a": 0}, "load_from_db": True}
            # Alternate between unwrapping single-key {"value": ...} and multi-key dicts
            if i % 2 == 1:
                tweaks[f"f{i}"] = {"value": {"idx": i}}
            else:
                tweaks[f"f{i}"] = {"idx": i, "other": i + 1}
        else:
            # file-like field
            large_template[f"f{i}"] = {"type": "file", "file_path": f"old/path/{i}", "load_from_db": True}
            tweaks[f"f{i}"] = f"/new/path/{i}"

    node = {"id": "large", "data": {"node": {"template": large_template}}}

    apply_tweaks(node, tweaks)

    # Spot-check a handful of items across the range to ensure they were updated appropriately.
    # Check first, middle, and last indices for coverage.
    samples = [0, 1, 2, N // 2, N - 1]
    for idx in samples:
        key = f"f{idx}"
        entry = large_template[key]
        if idx % 3 == 0:
            # string field -> value should be updated to "new{idx}" and load_from_db False
            assert entry["value"] == f"new{idx}"
            assert entry["load_from_db"] is False
        elif idx % 3 == 1:
            # dict field -> either unwrapped or set directly
            tweak_val = tweaks[key]
            if isinstance(tweak_val, dict) and len(tweak_val) == 1 and "value" in tweak_val:
                # unwrapped case: value should equal the inner dict
                assert entry["value"] == tweak_val["value"]
            else:
                # multi-key dict case
                assert entry["value"] == tweak_val
            assert entry["load_from_db"] is False
        else:
            # file field -> file_path updated and load_from_db False
            assert entry["file_path"] == tweaks[key]
            assert entry["load_from_db"] is False
#------------------------------------------------
import sys
from types import ModuleType
from typing import Any

# imports
import pytest
from langflow.processing.process import apply_tweaks


class TestApplyTweaksBasic:
    """Basic tests for apply_tweaks function with normal inputs"""
    
    def test_empty_tweaks(self):
        """Test that empty tweaks dict does not modify node"""
        node = {
            "data": {
                "node": {
                    "template": {
                        "field1": {"type": "str", "value": "original"}
                    }
                }
            }
        }
        original_value = node["data"]["node"]["template"]["field1"]["value"]
        apply_tweaks(node, {})
        assert node["data"]["node"]["template"]["field1"]["value"] == original_value
    
    def test_simple_value_tweak(self):
        """Test applying a simple value tweak"""
        node = {
            "data": {
                "node": {
                    "template": {
                        "field1": {"type": "str", "value": "original"}
                    }
                }
            }
        }
        apply_tweaks(node, {"field1": "new_value"})
        assert node["data"]["node"]["template"]["field1"]["value"] == "new_value"
    
    def test_tweak_nonexistent_field_ignored(self):
        """Test that tweaks for nonexistent fields are ignored"""
        node = {
            "data": {
                "node": {
                    "template": {
                        "field1": {"type": "str", "value": "original"}
                    }
                }
            }
        }
        apply_tweaks(node, {"nonexistent": "value"})
        assert "nonexistent" not in node["data"]["node"]["template"]
    
    def test_code_field_ignored(self):
        """Test that 'code' field is never overridden"""
        node = {
            "data": {
                "node": {
                    "template": {
                        "code": {"type": "code", "value": "original_code"}
                    }
                }
            }
        }
        apply_tweaks(node, {"code": "malicious_code"})
        # Code field should remain unchanged
        assert node["data"]["node"]["template"]["code"]["value"] == "original_code"
    
    def test_nested_dict_field_type(self):
        """Test NestedDict field type applies validate_and_repair_json"""
        node = {
            "data": {
                "node": {
                    "template": {
                        "config": {"type": "NestedDict", "value": {}}
                    }
                }
            }
        }
        tweak_data = {"nested": "value"}
        apply_tweaks(node, {"config": tweak_data})
        assert node["data"]["node"]["template"]["config"]["value"] == tweak_data
    
    def test_mcp_field_type(self):
        """Test MCP field type sets value directly"""
        node = {
            "data": {
                "node": {
                    "template": {
                        "mcp_field": {"type": "mcp", "value": {}}
                    }
                }
            }
        }
        mcp_value = {"key": "value"}
        apply_tweaks(node, {"mcp_field": mcp_value})
        assert node["data"]["node"]["template"]["mcp_field"]["value"] == mcp_value
    
    def test_dict_field_unwrap_single_value_key(self):
        """Test dict field type with single 'value' key unwraps it"""
        node = {
            "data": {
                "node": {
                    "template": {
                        "dict_field": {"type": "dict", "value": {}}
                    }
                }
            }
        }
        apply_tweaks(node, {"dict_field": {"value": "unwrapped"}})
        assert node["data"]["node"]["template"]["dict_field"]["value"] == "unwrapped"
    
    def test_dict_field_multiple_keys(self):
        """Test dict field type with multiple keys sets entire dict"""
        node = {
            "data": {
                "node": {
                    "template": {
                        "dict_field": {"type": "dict", "value": {}}
                    }
                }
            }
        }
        dict_value = {"key1": "val1", "key2": "val2"}
        apply_tweaks(node, {"dict_field": dict_value})
        assert node["data"]["node"]["template"]["dict_field"]["value"] == dict_value
    
    def test_file_field_type(self):
        """Test file field type maps keys to file_path"""
        node = {
            "data": {
                "node": {
                    "template": {
                        "file_field": {"type": "file", "file_path": ""}
                    }
                }
            }
        }
        apply_tweaks(node, {"file_field": {"path": "/tmp/file.txt"}})
        assert node["data"]["node"]["template"]["file_field"]["file_path"] == "/tmp/file.txt"
    
    def test_numeric_value_tweak(self):
        """Test that numeric values can be tweaked"""
        node = {
            "data": {
                "node": {
                    "template": {
                        "number": {"type": "int", "value": 0}
                    }
                }
            }
        }
        apply_tweaks(node, {"number": 42})
        assert node["data"]["node"]["template"]["number"]["value"] == 42
    
    def test_boolean_value_tweak(self):
        """Test that boolean values can be tweaked"""
        node = {
            "data": {
                "node": {
                    "template": {
                        "flag": {"type": "bool", "value": False}
                    }
                }
            }
        }
        apply_tweaks(node, {"flag": True})
        assert node["data"]["node"]["template"]["flag"]["value"] is True


class TestApplyTweaksEdgeCases:
    """Edge case tests for unusual or boundary conditions"""
    
    def test_missing_data_key(self):
        """Test that function returns gracefully when 'data' key is missing"""
        node = {"id": "test_node"}
        apply_tweaks(node, {"field": "value"})
        # Should not raise an error
        assert "data" not in node or node.get("data") is None or isinstance(node.get("data"), dict)
    
    def test_missing_node_key(self):
        """Test that function returns gracefully when 'node' key is missing"""
        node = {"data": {}}
        apply_tweaks(node, {"field": "value"})
        # Should not raise an error
        assert isinstance(node["data"], dict)
    
    def test_missing_template_key(self):
        """Test that function returns gracefully when 'template' key is missing"""
        node = {"data": {"node": {}}}
        apply_tweaks(node, {"field": "value"})
        # Should not raise an error
        assert isinstance(node["data"]["node"], dict)
    
    def test_template_is_not_dict(self):
        """Test that function logs warning when template is not a dict"""
        node = {
            "id": "node1",
            "data": {
                "node": {
                    "template": "not_a_dict"
                }
            }
        }
        # Should return early without error
        apply_tweaks(node, {"field": "value"})
        # Template should remain unchanged
        assert node["data"]["node"]["template"] == "not_a_dict"
    
    def test_template_is_none(self):
        """Test that function handles None template gracefully"""
        node = {
            "data": {
                "node": {
                    "template": None
                }
            }
        }
        apply_tweaks(node, {"field": "value"})
        assert node["data"]["node"]["template"] is None
    
    def test_template_is_list(self):
        """Test that function returns when template is a list"""
        node = {
            "data": {
                "node": {
                    "template": [1, 2, 3]
                }
            }
        }
        apply_tweaks(node, {"field": "value"})
        assert node["data"]["node"]["template"] == [1, 2, 3]
    
    def test_load_from_db_flag_set_to_false(self):
        """Test that load_from_db is set to False when not in tweaks"""
        node = {
            "data": {
                "node": {
                    "template": {
                        "field": {"type": "str", "value": "original", "load_from_db": True}
                    }
                }
            }
        }
        apply_tweaks(node, {"field": "new"})
        assert node["data"]["node"]["template"]["field"]["load_from_db"] is False
    
    def test_load_from_db_preserved_when_in_tweaks(self):
        """Test that load_from_db is preserved when explicitly set in tweaks"""
        node = {
            "data": {
                "node": {
                    "template": {
                        "field": {"type": "str", "value": "original", "load_from_db": True}
                    }
                }
            }
        }
        apply_tweaks(node, {"field": {"load_from_db": True}})
        # load_from_db should remain True since it was in tweaks
        assert node["data"]["node"]["template"]["field"]["load_from_db"] is True
    
    def test_empty_node_tweaks_dict(self):
        """Test with empty tweaks dictionary"""
        node = {
            "data": {
                "node": {
                    "template": {
                        "field1": {"type": "str", "value": "original"}
                    }
                }
            }
        }
        apply_tweaks(node, {})
        assert node["data"]["node"]["template"]["field1"]["value"] == "original"
    
    def test_multiple_tweaks_applied(self):
        """Test that multiple tweaks are all applied"""
        node = {
            "data": {
                "node": {
                    "template": {
                        "field1": {"type": "str", "value": "val1"},
                        "field2": {"type": "int", "value": 10},
                        "field3": {"type": "bool", "value": False}
                    }
                }
            }
        }
        apply_tweaks(node, {"field1": "new1", "field2": 20, "field3": True})
        assert node["data"]["node"]["template"]["field1"]["value"] == "new1"
        assert node["data"]["node"]["template"]["field2"]["value"] == 20
        assert node["data"]["node"]["template"]["field3"]["value"] is True
    
    def test_tweak_with_none_value(self):
        """Test that None values can be set via tweaks"""
        node = {
            "data": {
                "node": {
                    "template": {
                        "field": {"type": "str", "value": "original"}
                    }
                }
            }
        }
        apply_tweaks(node, {"field": None})
        assert node["data"]["node"]["template"]["field"]["value"] is None
    
    def test_tweak_with_empty_string(self):
        """Test that empty strings can be set via tweaks"""
        node = {
            "data": {
                "node": {
                    "template": {
                        "field": {"type": "str", "value": "original"}
                    }
                }
            }
        }
        apply_tweaks(node, {"field": ""})
        assert node["data"]["node"]["template"]["field"]["value"] == ""
    
    def test_tweak_with_empty_dict(self):
        """Test that empty dicts can be set via tweaks"""
        node = {
            "data": {
                "node": {
                    "template": {
                        "field": {"type": "dict", "value": {"key": "val"}}
                    }
                }
            }
        }
        apply_tweaks(node, {"field": {}})
        assert node["data"]["node"]["template"]["field"]["value"] == {}
    
    def test_special_characters_in_string_value(self):
        """Test that special characters in string values are preserved"""
        node = {
            "data": {
                "node": {
                    "template": {
                        "field": {"type": "str", "value": ""}
                    }
                }
            }
        }
        special_str = "!@#$%^&*()_+-=[]{}|;':\",./<>?"
        apply_tweaks(node, {"field": special_str})
        assert node["data"]["node"]["template"]["field"]["value"] == special_str
    
    def test_unicode_characters_in_value(self):
        """Test that unicode characters are handled correctly"""
        node = {
            "data": {
                "node": {
                    "template": {
                        "field": {"type": "str", "value": ""}
                    }
                }
            }
        }
        unicode_str = "Hello 世界 🌍 Привет"
        apply_tweaks(node, {"field": unicode_str})
        assert node["data"]["node"]["template"]["field"]["value"] == unicode_str
    
    def test_dict_with_nested_dict_value(self):
        """Test that nested dicts in tweak values are preserved"""
        node = {
            "data": {
                "node": {
                    "template": {
                        "config": {"type": "str", "value": ""}
                    }
                }
            }
        }
        nested = {"level1": {"level2": {"level3": "deep"}}}
        apply_tweaks(node, {"config": nested})
        assert node["data"]["node"]["template"]["config"]["value"] == nested
    
    def test_field_type_missing(self):
        """Test handling when field 'type' key is missing"""
        node = {
            "data": {
                "node": {
                    "template": {
                        "field": {"value": "original"}  # no 'type' key
                    }
                }
            }
        }
        apply_tweaks(node, {"field": "new"})
        # Should use default behavior (empty string for type)
        assert node["data"]["node"]["template"]["field"]["value"] == "new"
    
    def test_file_type_without_dict_tweak(self):
        """Test file type with scalar tweak value"""
        node = {
            "data": {
                "node": {
                    "template": {
                        "file": {"type": "file", "file_path": "", "load_from_db": True}
                    }
                }
            }
        }
        apply_tweaks(node, {"file": "/path/to/file"})
        assert node["data"]["node"]["template"]["file"]["file_path"] == "/path/to/file"
        assert node["data"]["node"]["template"]["file"]["load_from_db"] is False
    
    def test_list_as_tweak_value(self):
        """Test that lists can be set as tweak values"""
        node = {
            "data": {
                "node": {
                    "template": {
                        "items": {"type": "list", "value": []}
                    }
                }
            }
        }
        list_value = [1, 2, 3, "four"]
        apply_tweaks(node, {"items": list_value})
        assert node["data"]["node"]["template"]["items"]["value"] == list_value
    
    def test_float_value(self):
        """Test that float values can be tweaked"""
        node = {
            "data": {
                "node": {
                    "template": {
                        "price": {"type": "float", "value": 0.0}
                    }
                }
            }
        }
        apply_tweaks(node, {"price": 19.99})
        assert node["data"]["node"]["template"]["price"]["value"] == 19.99
    
    def test_very_long_string_value(self):
        """Test handling of very long string values"""
        node = {
            "data": {
                "node": {
                    "template": {
                        "text": {"type": "str", "value": ""}
                    }
                }
            }
        }
        long_string = "x" * 10000
        apply_tweaks(node, {"text": long_string})
        assert node["data"]["node"]["template"]["text"]["value"] == long_string


class TestApplyTweaksLargeScale:
    """Large-scale tests for performance and scalability"""
    
    def test_many_fields_in_template(self):
        """Test applying tweaks with many fields in template"""
        template = {}
        tweaks = {}
        for i in range(500):
            field_name = f"field_{i}"
            template[field_name] = {"type": "str", "value": f"original_{i}"}
            tweaks[field_name] = f"new_{i}"
        
        node = {
            "data": {
                "node": {
                    "template": template
                }
            }
        }
        apply_tweaks(node, tweaks)
        
        # Verify all tweaks were applied
        for i in range(500):
            field_name = f"field_{i}"
            assert node["data"]["node"]["template"][field_name]["value"] == f"new_{i}"
    
    def test_many_tweaks_some_nonexistent(self):
        """Test applying many tweaks where some target nonexistent fields"""
        template = {
            "field_1": {"type": "str", "value": "original"},
            "field_50": {"type": "str", "value": "original"},
            "field_100": {"type": "str", "value": "original"}
        }
        tweaks = {}
        for i in range(200):
            tweaks[f"field_{i}"] = f"new_{i}"
        
        node = {
            "data": {
                "node": {
                    "template": template
                }
            }
        }
        apply_tweaks(node, tweaks)
        
        # Only existing fields should be modified
        assert node["data"]["node"]["template"]["field_1"]["value"] == "new_1"
        assert node["data"]["node"]["template"]["field_50"]["value"] == "new_50"
        assert node["data"]["node"]["template"]["field_100"]["value"] == "new_100"
    
    def test_large_dict_as_tweak_value(self):
        """Test setting a large dictionary as tweak value"""
        node = {
            "data": {
                "node": {
                    "template": {
                        "config": {"type": "dict", "value": {}}
                    }
                }
            }
        }
        large_dict = {f"key_{i}": f"value_{i}" for i in range(1000)}
        apply_tweaks(node, {"config": large_dict})
        assert node["data"]["node"]["template"]["config"]["value"] == large_dict
    
    def test_nested_dict_field_with_many_tweaks(self):
        """Test NestedDict field type with many tweaks applied"""
        template = {}
        tweaks = {}
        for i in range(100):
            field_name = f"nested_{i}"
            template[field_name] = {"type": "NestedDict", "value": {}}
            tweaks[field_name] = {"data": f"value_{i}"}
        
        node = {
            "data": {
                "node": {
                    "template": template
                }
            }
        }
        apply_tweaks(node, tweaks)
        
        # Verify all nested dicts were applied
        for i in range(100):
            field_name = f"nested_{i}"
            assert node["data"]["node"]["template"][field_name]["value"] == {"data": f"value_{i}"}
    
    def test_file_fields_with_many_tweaks(self):
        """Test multiple file fields with path tweaks"""
        template = {}
        tweaks = {}
        for i in range(200):
            field_name = f"file_{i}"
            template[field_name] = {"type": "file", "file_path": "", "load_from_db": True}
            tweaks[field_name] = {f"path_{i}": f"/tmp/file_{i}.txt"}
        
        node = {
            "data": {
                "node": {
                    "template": template
                }
            }
        }
        apply_tweaks(node, tweaks)
        
        # Verify file paths were set correctly
        for i in range(200):
            field_name = f"file_{i}"
            assert node["data"]["node"]["template"][field_name]["file_path"] == f"/tmp/file_{i}.txt"
            assert node["data"]["node"]["template"][field_name]["load_from_db"] is False
    
    def test_mixed_field_types_at_scale(self):
        """Test applying tweaks with mixed field types at scale"""
        template = {}
        tweaks = {}
        for i in range(250):
            field_type = ["str", "int", "dict", "NestedDict", "file"][i % 5]
            field_name = f"mixed_{i}"
            
            if field_type == "dict":
                template[field_name] = {"type": "dict", "value": {}}
                tweaks[field_name] = {"key": f"val_{i}"}
            elif field_type == "NestedDict":
                template[field_name] = {"type": "NestedDict", "value": {}}
                tweaks[field_name] = {"nested": f"val_{i}"}
            elif field_type == "file":
                template[field_name] = {"type": "file", "file_path": ""}
                tweaks[field_name] = {f"path": f"/tmp/file_{i}"}
            elif field_type == "int":
                template[field_name] = {"type": "int", "value": 0}
                tweaks[field_name] = i
            else:  # str
                template[field_name] = {"type": "str", "value": ""}
                tweaks[field_name] = f"value_{i}"
        
        node = {
            "data": {
                "node": {
                    "template": template
                }
            }
        }
        apply_tweaks(node, tweaks)
        
        # Verify diverse tweaks were applied correctly
        for i in range(250):
            field_name = f"mixed_{i}"
            field_type = ["str", "int", "dict", "NestedDict", "file"][i % 5]
            
            if field_type == "file":
                assert node["data"]["node"]["template"][field_name]["file_path"] == f"/tmp/file_{i}"
            elif field_type in ["dict", "NestedDict"]:
                assert isinstance(node["data"]["node"]["template"][field_name]["value"], dict)
            elif field_type == "int":
                assert node["data"]["node"]["template"][field_name]["value"] == i
            else:
                assert node["data"]["node"]["template"][field_name]["value"] == f"value_{i}"

To edit these changes git checkout codeflash/optimize-pr12152-2026-03-11T20.46.04 and push.

Codeflash

The hot loop previously performed `tweak_name in template_data` (line 35 in original) then immediately re-checked `tweak_name in template_data` (line 39) before every indexing operation, causing redundant membership tests and repeated dictionary lookups—`template_data[tweak_name]` appeared 14 times across branches. The optimization hoists `template_data.get(tweak_name)` into a local `entry` variable once per iteration and replaces all subsequent `template_data[tweak_name]` references with direct `entry` accesses, eliminating ~10 dictionary lookups per processed tweak. Line profiler shows the redundant membership check consumed 7.2% of total time (line 35: 658 µs), and subsequent `template_data[tweak_name].get("type", "")` lookups took another 7.2% (line 39: 661 µs); the optimized version collapses these into a single `entry.get("type", "")` call costing 6.3% (line 23: 572 µs). Additionally, `validate_and_repair_json` is bound to the local alias `repair` outside the loop to avoid repeated global lookups (~20 ns per hit, negligible but measurable at scale). No behavior changes; all security checks, field-type logic, and `load_from_db` handling remain identical.
@codeflash-ai codeflash-ai Bot added the ⚡️ codeflash Optimization PR opened by Codeflash AI label Mar 11, 2026
@github-actions github-actions Bot added the community Pull Request from an external contributor label Mar 11, 2026
@github-actions
Copy link
Copy Markdown
Contributor

Frontend Unit Test Coverage Report

Coverage Summary

Lines Statements Branches Functions
Coverage: 23%
23.45% (8229/35085) 16.17% (4452/27531) 16.23% (1197/7375)

Unit Test Results

Tests Skipped Failures Errors Time
2720 0 💤 0 ❌ 0 🔥 46.162s ⏱️

@codecov
Copy link
Copy Markdown

codecov Bot commented Mar 11, 2026

Codecov Report

❌ Patch coverage is 70.83333% with 7 lines in your changes missing coverage. Please review.
✅ Project coverage is 37.34%. Comparing base (5b966f3) to head (d6fd0b9).

Files with missing lines Patch % Lines
src/backend/base/langflow/processing/process.py 70.83% 7 Missing ⚠️

❌ Your project status has failed because the head coverage (41.69%) 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             @@
##           dk/le-558   #12157   +/-   ##
==========================================
  Coverage      37.33%   37.34%           
==========================================
  Files           1592     1592           
  Lines          78289    78290    +1     
  Branches       11866    11866           
==========================================
+ Hits           29233    29237    +4     
+ Misses         47387    47384    -3     
  Partials        1669     1669           
Flag Coverage Δ
backend 57.41% <70.83%> (+0.01%) ⬆️
frontend 21.01% <ø> (ø)
lfx 41.69% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
src/backend/base/langflow/processing/process.py 72.58% <70.83%> (+1.03%) ⬆️

... and 5 files 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.

@codeflash-ai codeflash-ai Bot deleted the codeflash/optimize-pr12152-2026-03-11T20.46.04 branch March 12, 2026 18:21
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.

1 participant