Skip to content

⚡️ Speed up function replace_api_key_with_env_var_name by 23% in PR #12129 (fix-api-key-components)#12133

Closed
codeflash-ai[bot] wants to merge 6 commits into
release-1.8.1from
codeflash/optimize-pr12129-2026-03-10T17.52.35
Closed

⚡️ Speed up function replace_api_key_with_env_var_name by 23% in PR #12129 (fix-api-key-components)#12133
codeflash-ai[bot] wants to merge 6 commits into
release-1.8.1from
codeflash/optimize-pr12129-2026-03-10T17.52.35

Conversation

@codeflash-ai
Copy link
Copy Markdown
Contributor

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

⚡️ This pull request contains optimizations for PR #12129

If you approve this dependent PR, these changes will be merged into the original PR branch fix-api-key-components.

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


📄 23% (0.23x) speedup for replace_api_key_with_env_var_name in src/backend/base/langflow/api/utils/core.py

⏱️ Runtime : 899 microseconds 732 microseconds (best of 104 runs)

📝 Explanation and details

The optimization pre-compiles the regex pattern [A-Za-z][A-Za-z0-9_]* at module scope instead of recompiling it on every _looks_like_variable_name call. Line profiler shows the original re.fullmatch(...) consumed 92.7% (2.1 ms) of the helper's runtime, while the optimized version using the pre-compiled pattern drops this to 51% (369 µs)—a ~5.7× reduction in per-call cost. The helper is invoked 428 times per run, so eliminating repeated pattern compilation yields a cumulative 22% speedup across the entire replace_api_key_with_env_var_name function. The optimized code also hoists flow.get("data", {}).get("nodes", []) out of the loop header to avoid redundant dict lookups, though profiler data confirms regex compilation was the dominant bottleneck.

Correctness verification report:

Test Status
⚙️ Existing Unit Tests 🔘 None Found
🌀 Generated Regression Tests 56 Passed
⏪ Replay Tests 🔘 None Found
🔎 Concolic Coverage Tests 🔘 None Found
📊 Tests Coverage 100.0%
🌀 Click to see Generated Regression Tests
import pytest  # used for our unit tests
# import the functions to test from the exact source module
from langflow.api.utils.core import (_looks_like_variable_name,
                                     replace_api_key_with_env_var_name)


def test_variable_name_is_kept():
    # simple flow where api_key value looks like a variable name
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api": {"name": "api_key", "password": True, "value": "MY_API_KEY"}
                            }
                        }
                    }
                }
            ]
        }
    }
    # call the function under test
    out = replace_api_key_with_env_var_name(flow)
    # same object returned (mutation in place); ensure the value was not cleared
    assert out is flow
    assert out["data"]["nodes"][0]["data"]["node"]["template"]["api"]["value"] == "MY_API_KEY"


def test_raw_secret_is_cleared():
    # raw-looking secret should be nullified to avoid exporting secrets
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "secret": {"name": "api_key", "password": True, "value": "sk_test_abc123"}
                            }
                        }
                    }
                }
            ]
        }
    }
    replaced = replace_api_key_with_env_var_name(flow)
    # the secret should be set to None
    assert replaced["data"]["nodes"][0]["data"]["node"]["template"]["secret"]["value"] is None


def test_spaces_in_variable_name_are_considered_valid_and_kept():
    # variable names with surrounding whitespace should be considered valid (function strips for check)
    original_value = "  Var_1  "
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "v": {"name": "api_key", "password": True, "value": original_value}
                            }
                        }
                    }
                }
            ]
        }
    }
    out = replace_api_key_with_env_var_name(flow)
    # the original value (with spaces) is preserved because it looked like a variable name after stripping
    assert out["data"]["nodes"][0]["data"]["node"]["template"]["v"]["value"] == original_value


def test_non_dict_node_data_is_ignored():
    # If node["data"] is not a dict, function should continue without error and leave flow unchanged
    flow = {"data": {"nodes": [{"data": None}]}}
    # preserve a copy for comparison
    before = {"data": {"nodes": [{"data": None}]}}
    out = replace_api_key_with_env_var_name(flow)
    assert out == before


def test_template_not_dict_is_ignored():
    # If template is not a dict (e.g., a list), it should be ignored
    flow = {"data": {"nodes": [{"data": {"node": {"template": ["not", "a", "dict"]}}}]}}
    before = {"data": {"nodes": [{"data": {"node": {"template": ["not", "a", "dict"]}}}]}}
    out = replace_api_key_with_env_var_name(flow)
    assert out == before


def test_password_false_not_processed():
    # When password flag is falsy, the api_key entry should not be processed/cleared
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "x": {"name": "api_key", "password": False, "value": "sk_should_stay"}
                            }
                        }
                    }
                }
            ]
        }
    }
    out = replace_api_key_with_env_var_name(flow)
    # value should remain unchanged because password was False
    assert out["data"]["nodes"][0]["data"]["node"]["template"]["x"]["value"] == "sk_should_stay"


def test_missing_value_key_gets_created_and_set_to_none():
    # If the api_key dict lacks a "value" key but is marked password=True, the function should add it as None
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "a": {"name": "api_key", "password": True}  # no "value" key
                            }
                        }
                    }
                }
            ]
        }
    }
    out = replace_api_key_with_env_var_name(flow)
    # a "value" key should now exist and be None
    assert "value" in out["data"]["nodes"][0]["data"]["node"]["template"]["a"]
    assert out["data"]["nodes"][0]["data"]["node"]["template"]["a"]["value"] is None


def test_non_string_value_is_cleared():
    # If value is not a string (e.g., an int), it should be treated as not looking like a variable name and be cleared
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "num": {"name": "api_key", "password": True, "value": 12345}
                            }
                        }
                    }
                }
            ]
        }
    }
    out = replace_api_key_with_env_var_name(flow)
    assert out["data"]["nodes"][0]["data"]["node"]["template"]["num"]["value"] is None


def test_template_with_multiple_api_key_entries_only_first_checked_then_breaks():
    # When multiple entries exist in the same template that match the name/password criteria,
    # the function checks them in insertion order and breaks after handling the first one.
    tpl = {
        # first entry is raw secret -> it will be cleared and loop breaks, leaving second untouched
        "first": {"name": "api_key", "password": True, "value": "raw_secret_1"},
        "second": {"name": "api_key", "password": True, "value": "raw_secret_2"},
    }
    flow = {"data": {"nodes": [{"data": {"node": {"template": tpl}}}]}}
    out = replace_api_key_with_env_var_name(flow)
    # first should be cleared
    assert out["data"]["nodes"][0]["data"]["node"]["template"]["first"]["value"] is None
    # second remains unchanged because loop broke after first
    assert out["data"]["nodes"][0]["data"]["node"]["template"]["second"]["value"] == "raw_secret_2"


def test_looks_like_variable_name_various_cases():
    # Valid names
    assert _looks_like_variable_name("A") is True
    assert _looks_like_variable_name("a1") is True
    assert _looks_like_variable_name("Var_1") is True
    assert _looks_like_variable_name(" Var_1 ") is True  # leading/trailing spaces allowed (stripped)
    # Invalid names
    assert _looks_like_variable_name("") is False
    assert _looks_like_variable_name(None) is False
    assert _looks_like_variable_name("_starts_with_underscore") is False
    assert _looks_like_variable_name("1starts_with_digit") is False
    assert _looks_like_variable_name("has-dash") is False


def test_large_scale_many_nodes_only_expected_nodes_modified():
    # Build a flow with 1000 nodes. Only nodes at indices divisible by 100 will contain an api_key raw secret.
    nodes = []
    total_nodes = 1000
    modified_indices = set(i for i in range(total_nodes) if i % 100 == 0)
    for i in range(total_nodes):
        if i in modified_indices:
            # insert a node that will be processed and cleared (raw secret)
            node = {
                "data": {
                    "node": {
                        "template": {
                            "k": {"name": "api_key", "password": True, "value": f"raw_secret_{i}"}
                        }
                    }
                }
            }
        else:
            # other nodes are either missing template or have non-dict data to ensure they are ignored
            node = {"data": {"node": {"template": {"k": {"name": "api_key", "password": False, "value": "x"}}}}}
        nodes.append(node)
    flow = {"data": {"nodes": nodes}}
    # Invoke the function - this should run quickly even for 1000 nodes
    out = replace_api_key_with_env_var_name(flow)
    # Verify that only the nodes at the expected indices were cleared
    for idx in range(total_nodes):
        entry = out["data"]["nodes"][idx]["data"]["node"]["template"]["k"]
        if idx in modified_indices:
            # these were raw secrets, they should be set to None
            assert entry["value"] is None, f"node {idx} expected cleared"
        else:
            # these had password=False and should remain unchanged
            assert entry["value"] == "x", f"node {idx} expected unchanged"


def test_large_scale_many_entries_in_single_node_template():
    # Create a single node with 1000 template entries where only the last one is a raw secret.
    # Because the function stops at the first matching "api_key" entry, ensure behavior reflects that.
    template = {}
    # First 999 entries are non-matching names to skip easily
    for i in range(999):
        template[f"n{i}"] = {"name": f"not_api_{i}", "password": True, "value": f"v{i}"}
    # last entry is api_key raw secret -> will be encountered last and thus processed (cleared)
    template["last"] = {"name": "api_key", "password": True, "value": "super_secret"}
    flow = {"data": {"nodes": [{"data": {"node": {"template": template}}}]}}
    out = replace_api_key_with_env_var_name(flow)
    # Ensure the last entry was cleared
    assert out["data"]["nodes"][0]["data"]["node"]["template"]["last"]["value"] is None
    # Ensure none of the other non-api_key entries were touched
    for i in range(999):
        assert out["data"]["nodes"][0]["data"]["node"]["template"][f"n{i}"]["value"] == f"v{i}"
#------------------------------------------------
from __future__ import annotations

import re
from typing import Any

# imports
import pytest
from langflow.api.utils.core import replace_api_key_with_env_var_name


def _looks_like_variable_name(value: Any) -> bool:
    """Return True if value looks like a variable name."""
    if not value or not isinstance(value, str) or not value.strip():
        return False
    return bool(re.fullmatch(r"[A-Za-z][A-Za-z0-9_]*", value.strip()))


def test_empty_flow_returns_unchanged():
    """Test that an empty flow dict is returned unchanged."""
    flow = {}
    result = replace_api_key_with_env_var_name(flow)
    assert result == {}


def test_flow_without_data_returns_unchanged():
    """Test that a flow without 'data' key is returned unchanged."""
    flow = {"other_key": "value"}
    result = replace_api_key_with_env_var_name(flow)
    assert result == {"other_key": "value"}


def test_flow_with_empty_nodes_returns_unchanged():
    """Test that a flow with empty nodes list is returned unchanged."""
    flow = {"data": {"nodes": []}}
    result = replace_api_key_with_env_var_name(flow)
    assert result == {"data": {"nodes": []}}


def test_raw_api_key_gets_cleared():
    """Test that a raw API key value is cleared to None."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_config": {
                                    "name": "api_key",
                                    "password": True,
                                    "value": "sk-1234567890abcdef"
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["api_config"]["value"] is None


def test_valid_variable_name_is_preserved():
    """Test that a valid variable name (like API_KEY_VAR) is kept unchanged."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_config": {
                                    "name": "api_key",
                                    "password": True,
                                    "value": "API_KEY_VAR"
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    # The value should remain unchanged since it's a valid variable name
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["api_config"]["value"] == "API_KEY_VAR"


def test_lowercase_variable_name_preserved():
    """Test that a valid lowercase variable name is preserved."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_config": {
                                    "name": "api_key",
                                    "password": True,
                                    "value": "my_api_key"
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["api_config"]["value"] == "my_api_key"


def test_non_api_key_fields_unchanged():
    """Test that fields without name='api_key' are not modified."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "other_field": {
                                    "name": "other_name",
                                    "password": True,
                                    "value": "some_value"
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["other_field"]["value"] == "some_value"


def test_api_key_without_password_flag_unchanged():
    """Test that api_key entries without password=True are not modified."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_config": {
                                    "name": "api_key",
                                    "password": False,
                                    "value": "some_raw_value"
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["api_config"]["value"] == "some_raw_value"


def test_multiple_nodes_with_api_keys():
    """Test handling of multiple nodes with api_key fields."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_config": {
                                    "name": "api_key",
                                    "password": True,
                                    "value": "raw_key_1"
                                }
                            }
                        }
                    }
                },
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_config": {
                                    "name": "api_key",
                                    "password": True,
                                    "value": "VALID_VAR_NAME"
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    # First node's raw key should be cleared
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["api_config"]["value"] is None
    # Second node's valid variable name should be preserved
    assert result["data"]["nodes"][1]["data"]["node"]["template"]["api_config"]["value"] == "VALID_VAR_NAME"


def test_function_returns_same_dict_object():
    """Test that the function returns the same dict object (modified in-place)."""
    flow = {"data": {"nodes": []}}
    result = replace_api_key_with_env_var_name(flow)
    assert result is flow


def test_none_value_cleared():
    """Test that None api_key value stays None (not matching variable name pattern)."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_config": {
                                    "name": "api_key",
                                    "password": True,
                                    "value": None
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    # None is not a valid variable name, so it should be set to None (already was None)
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["api_config"]["value"] is None


def test_empty_string_value_cleared():
    """Test that empty string api_key value is cleared to None."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_config": {
                                    "name": "api_key",
                                    "password": True,
                                    "value": ""
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["api_config"]["value"] is None


def test_whitespace_only_value_cleared():
    """Test that whitespace-only api_key value is cleared to None."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_config": {
                                    "name": "api_key",
                                    "password": True,
                                    "value": "   "
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["api_config"]["value"] is None


def test_value_with_leading_trailing_whitespace_and_valid_name():
    """Test that variable name with whitespace is treated as valid (after strip)."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_config": {
                                    "name": "api_key",
                                    "password": True,
                                    "value": "  MY_VAR  "
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    # Variable name with surrounding whitespace should be preserved (not cleared)
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["api_config"]["value"] == "  MY_VAR  "


def test_value_starting_with_number_cleared():
    """Test that api_key starting with number is cleared (invalid variable name)."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_config": {
                                    "name": "api_key",
                                    "password": True,
                                    "value": "123_KEY"
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["api_config"]["value"] is None


def test_value_with_special_characters_cleared():
    """Test that api_key with special characters is cleared (invalid variable name)."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_config": {
                                    "name": "api_key",
                                    "password": True,
                                    "value": "MY-KEY"
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["api_config"]["value"] is None


def test_value_with_spaces_in_middle_cleared():
    """Test that api_key with spaces in the middle is cleared (invalid variable name)."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_config": {
                                    "name": "api_key",
                                    "password": True,
                                    "value": "MY KEY"
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["api_config"]["value"] is None


def test_node_data_not_dict_skipped():
    """Test that nodes with non-dict data are skipped."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": "not_a_dict"
                },
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_config": {
                                    "name": "api_key",
                                    "password": True,
                                    "value": "raw_key"
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    # Second node should be processed
    assert result["data"]["nodes"][1]["data"]["node"]["template"]["api_config"]["value"] is None


def test_node_inner_not_dict_skipped():
    """Test that nodes with non-dict node field are skipped."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": "not_a_dict"
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    # Structure should remain unchanged
    assert result["data"]["nodes"][0]["data"]["node"] == "not_a_dict"


def test_template_not_dict_skipped():
    """Test that nodes with non-dict template are skipped."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": "not_a_dict"
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    # Structure should remain unchanged
    assert result["data"]["nodes"][0]["data"]["node"]["template"] == "not_a_dict"


def test_template_value_not_dict_skipped():
    """Test that template values that are not dicts are skipped."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_config": "not_a_dict"
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    # String value should remain unchanged
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["api_config"] == "not_a_dict"


def test_single_character_variable_name_preserved():
    """Test that single character variable names are preserved."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_config": {
                                    "name": "api_key",
                                    "password": True,
                                    "value": "A"
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["api_config"]["value"] == "A"


def test_single_character_lowercase_variable_name_preserved():
    """Test that single lowercase character variable names are preserved."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_config": {
                                    "name": "api_key",
                                    "password": True,
                                    "value": "x"
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["api_config"]["value"] == "x"


def test_variable_name_with_numbers_preserved():
    """Test that variable names with numbers are preserved."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_config": {
                                    "name": "api_key",
                                    "password": True,
                                    "value": "VAR_2024_KEY"
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["api_config"]["value"] == "VAR_2024_KEY"


def test_api_key_value_is_integer_cleared():
    """Test that non-string api_key values (like integers) are cleared."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_config": {
                                    "name": "api_key",
                                    "password": True,
                                    "value": 12345
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["api_config"]["value"] is None


def test_api_key_value_is_list_cleared():
    """Test that non-string api_key values (like lists) are cleared."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_config": {
                                    "name": "api_key",
                                    "password": True,
                                    "value": ["key1", "key2"]
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["api_config"]["value"] is None


def test_api_key_value_is_dict_cleared():
    """Test that non-string api_key values (like dicts) are cleared."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_config": {
                                    "name": "api_key",
                                    "password": True,
                                    "value": {"key": "value"}
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["api_config"]["value"] is None


def test_missing_name_field_skipped():
    """Test that template values without 'name' field are skipped."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_config": {
                                    "password": True,
                                    "value": "raw_key"
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    # Value should remain unchanged (no 'name' field to match)
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["api_config"]["value"] == "raw_key"


def test_missing_password_field_skipped():
    """Test that template values without 'password' field are skipped."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_config": {
                                    "name": "api_key",
                                    "value": "raw_key"
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    # Value should remain unchanged (no 'password' field to check)
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["api_config"]["value"] == "raw_key"


def test_password_field_false_skipped():
    """Test that template values with password=False are skipped."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_config": {
                                    "name": "api_key",
                                    "password": False,
                                    "value": "raw_key"
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    # Value should remain unchanged (password is False)
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["api_config"]["value"] == "raw_key"


def test_password_field_none_skipped():
    """Test that template values with password=None are skipped."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_config": {
                                    "name": "api_key",
                                    "password": None,
                                    "value": "raw_key"
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    # Value should remain unchanged (password is falsy)
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["api_config"]["value"] == "raw_key"


def test_underscore_only_variable_name_preserved():
    """Test that underscore-only names are preserved if they match pattern."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_config": {
                                    "name": "api_key",
                                    "password": True,
                                    "value": "_"
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    # Underscore alone is not a valid variable name (must start with letter)
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["api_config"]["value"] is None


def test_multiple_underscores_with_valid_start_preserved():
    """Test that variable names with multiple underscores are preserved."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_config": {
                                    "name": "api_key",
                                    "password": True,
                                    "value": "A___B"
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["api_config"]["value"] == "A___B"


def test_very_long_valid_variable_name_preserved():
    """Test that very long valid variable names are preserved."""
    long_var_name = "A" + "b" * 1000 + "_VAR_" + "0" * 100
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_config": {
                                    "name": "api_key",
                                    "password": True,
                                    "value": long_var_name
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["api_config"]["value"] == long_var_name


def test_very_long_raw_key_cleared():
    """Test that very long raw API keys are cleared."""
    long_raw_key = "sk-" + "x" * 1000
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_config": {
                                    "name": "api_key",
                                    "password": True,
                                    "value": long_raw_key
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["api_config"]["value"] is None



def test_first_api_key_found_breaks_inner_loop():
    """Test that the inner loop breaks after finding first api_key with password."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_config_1": {
                                    "name": "api_key",
                                    "password": True,
                                    "value": "raw_key_1"
                                },
                                "api_config_2": {
                                    "name": "api_key",
                                    "password": True,
                                    "value": "raw_key_2"
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    # First api_key should be cleared, second should remain (loop breaks after first)
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["api_config_1"]["value"] is None
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["api_config_2"]["value"] == "raw_key_2"


def test_many_nodes_with_mixed_api_keys():
    """Test processing of many nodes with a mix of valid and raw api_keys."""
    nodes = []
    for i in range(100):
        if i % 2 == 0:
            # Even indices: raw keys that should be cleared
            nodes.append({
                "data": {
                    "node": {
                        "template": {
                            "api_config": {
                                "name": "api_key",
                                "password": True,
                                "value": f"raw_key_{i}"
                            }
                        }
                    }
                }
            })
        else:
            # Odd indices: valid variable names that should be preserved
            nodes.append({
                "data": {
                    "node": {
                        "template": {
                            "api_config": {
                                "name": "api_key",
                                "password": True,
                                "value": f"VAR_{i}"
                            }
                        }
                    }
                }
            })
    
    flow = {"data": {"nodes": nodes}}
    result = replace_api_key_with_env_var_name(flow)
    
    # Check even indices are cleared
    for i in range(0, 100, 2):
        assert result["data"]["nodes"][i]["data"]["node"]["template"]["api_config"]["value"] is None
    
    # Check odd indices are preserved
    for i in range(1, 100, 2):
        assert result["data"]["nodes"][i]["data"]["node"]["template"]["api_config"]["value"] == f"VAR_{i}"


def test_many_template_values_per_node():
    """Test processing of nodes with many template values."""
    template = {}
    for i in range(100):
        if i == 50:
            # One api_key with raw value
            template["api_config"] = {
                "name": "api_key",
                "password": True,
                "value": "raw_secret_key"
            }
        else:
            # Other fields
            template[f"field_{i}"] = {
                "name": f"param_{i}",
                "password": False,
                "value": f"value_{i}"
            }
    
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": template
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    
    # The api_key should be cleared
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["api_config"]["value"] is None
    # Other fields should be unchanged
    for i in range(100):
        if i != 50:
            assert result["data"]["nodes"][0]["data"]["node"]["template"][f"field_{i}"]["value"] == f"value_{i}"


def test_deeply_nested_flow_with_large_nodes():
    """Test processing of large flow structure with many nodes and nested data."""
    nodes = []
    for i in range(50):
        nodes.append({
            "id": f"node_{i}",
            "data": {
                "node": {
                    "template": {
                        f"param_{j}": {
                            "name": "api_key" if j == 25 else f"param_{j}",
                            "password": True if j == 25 else False,
                            "value": "sk-" + str(i) if j == 25 else f"value_{j}"
                        }
                        for j in range(50)
                    }
                }
            }
        })
    
    flow = {"data": {"nodes": nodes}}
    result = replace_api_key_with_env_var_name(flow)
    
    # All api_key values should be cleared
    for i in range(50):
        assert result["data"]["nodes"][i]["data"]["node"]["template"]["param_25"]["value"] is None


def test_many_nodes_all_with_valid_variable_names():
    """Test performance with many nodes, all having valid variable names."""
    nodes = []
    for i in range(100):
        nodes.append({
            "data": {
                "node": {
                    "template": {
                        "api_config": {
                            "name": "api_key",
                            "password": True,
                            "value": f"MY_API_KEY_{i}"
                        }
                    }
                }
            }
        })
    
    flow = {"data": {"nodes": nodes}}
    result = replace_api_key_with_env_var_name(flow)
    
    # All values should be preserved
    for i in range(100):
        assert result["data"]["nodes"][i]["data"]["node"]["template"]["api_config"]["value"] == f"MY_API_KEY_{i}"


def test_many_nodes_all_with_raw_keys():
    """Test performance with many nodes, all having raw API keys."""
    nodes = []
    for i in range(100):
        nodes.append({
            "data": {
                "node": {
                    "template": {
                        "api_config": {
                            "name": "api_key",
                            "password": True,
                            "value": "sk-" + "x" * 100 + str(i)
                        }
                    }
                }
            }
        })
    
    flow = {"data": {"nodes": nodes}}
    result = replace_api_key_with_env_var_name(flow)
    
    # All values should be cleared
    for i in range(100):
        assert result["data"]["nodes"][i]["data"]["node"]["template"]["api_config"]["value"] is None


def test_wide_template_with_many_fields_one_api_key():
    """Test processing of a template with many fields where only one is api_key."""
    template = {}
    for i in range(200):
        if i == 150:
            template["api_secret"] = {
                "name": "api_key",
                "password": True,
                "value": "raw_secret_12345"
            }
        else:
            template[f"config_{i}"] = {
                "name": f"config_{i}",
                "password": False,
                "value": f"config_value_{i}"
            }
    
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": template
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    
    # The api_key should be cleared
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["api_secret"]["value"] is None
    # Other fields should be unchanged
    for i in range(200):
        if i != 150:
            assert result["data"]["nodes"][0]["data"]["node"]["template"][f"config_{i}"]["value"] == f"config_value_{i}"


def test_large_number_of_nodes_no_api_keys():
    """Test performance with many nodes that have no api_key fields."""
    nodes = []
    for i in range(100):
        nodes.append({
            "data": {
                "node": {
                    "template": {
                        "param_a": {"name": "param_a", "password": False, "value": f"value_a_{i}"},
                        "param_b": {"name": "param_b", "password": False, "value": f"value_b_{i}"}
                    }
                }
            }
        })
    
    flow = {"data": {"nodes": nodes}}
    result = replace_api_key_with_env_var_name(flow)
    
    # All values should remain unchanged
    for i in range(100):
        assert result["data"]["nodes"][i]["data"]["node"]["template"]["param_a"]["value"] == f"value_a_{i}"
        assert result["data"]["nodes"][i]["data"]["node"]["template"]["param_b"]["value"] == f"value_b_{i}"


def test_alternating_structure_validity():
    """Test processing of nodes with alternating valid/invalid nested structures."""
    nodes = []
    for i in range(100):
        if i % 3 == 0:
            # Valid structure
            nodes.append({
                "data": {
                    "node": {
                        "template": {
                            "api_config": {
                                "name": "api_key",
                                "password": True,
                                "value": "raw_key_" + str(i)
                            }
                        }
                    }
                }
            })
        elif i % 3 == 1:
            # Invalid node_data
            nodes.append({"data": "invalid"})
        else:
            # Invalid node_inner
            nodes.append({"data": {"node": "invalid"}})
    
    flow = {"data": {"nodes": nodes}}
    result = replace_api_key_with_env_var_name(flow)
    
    # Check that valid structures are processed
    for i in range(0, 100, 3):
        assert result["data"]["nodes"][i]["data"]["node"]["template"]["api_config"]["value"] is None


def test_special_characters_in_other_template_fields():
    """Test that special characters in non-api_key fields don't affect processing."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "description": {"value": "Key: secret-@#$%^&*()"},
                                "api_config": {
                                    "name": "api_key",
                                    "password": True,
                                    "value": "raw_key"
                                },
                                "notes": {"value": "Some @#$% & *() text"}
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    
    # api_key should be cleared
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["api_config"]["value"] is None
    # Other fields should remain unchanged
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["description"]["value"] == "Key: secret-@#$%^&*()"
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["notes"]["value"] == "Some @#$% & *() text"

To edit these changes git checkout codeflash/optimize-pr12129-2026-03-10T17.52.35 and push.

Codeflash

HimavarshaVS and others added 3 commits March 10, 2026 12:51
The optimization pre-compiles the regex pattern `[A-Za-z][A-Za-z0-9_]*` at module scope instead of recompiling it on every `_looks_like_variable_name` call. Line profiler shows the original `re.fullmatch(...)` consumed 92.7% (2.1 ms) of the helper's runtime, while the optimized version using the pre-compiled pattern drops this to 51% (369 µs)—a ~5.7× reduction in per-call cost. The helper is invoked 428 times per run, so eliminating repeated pattern compilation yields a cumulative 22% speedup across the entire `replace_api_key_with_env_var_name` function. The optimized code also hoists `flow.get("data", {}).get("nodes", [])` out of the loop header to avoid redundant dict lookups, though profiler data confirms regex compilation was the dominant bottleneck.
@codeflash-ai codeflash-ai Bot added the ⚡️ codeflash Optimization PR opened by Codeflash AI label Mar 10, 2026
@github-actions github-actions Bot added the community Pull Request from an external contributor label Mar 10, 2026
@codecov
Copy link
Copy Markdown

codecov Bot commented Mar 10, 2026

Codecov Report

❌ Patch coverage is 43.66197% with 40 lines in your changes missing coverage. Please review.
✅ Project coverage is 37.19%. Comparing base (699e356) to head (4859499).
⚠️ Report is 7 commits behind head on release-1.8.1.

Files with missing lines Patch % Lines
src/lfx/src/lfx/base/models/unified_models.py 7.14% 25 Missing and 1 partial ⚠️
src/backend/base/langflow/api/utils/core.py 67.50% 13 Missing ⚠️
src/backend/base/langflow/api/v1/flows.py 66.66% 1 Missing ⚠️

❌ Your project status has failed because the head coverage (41.43%) 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               @@
##           release-1.8.1   #12133   +/-   ##
==============================================
  Coverage          37.18%   37.19%           
==============================================
  Files               1592     1592           
  Lines              78216    78275   +59     
  Branches           11865    11872    +7     
==============================================
+ Hits               29087    29116   +29     
- Misses             47461    47491   +30     
  Partials            1668     1668           
Flag Coverage Δ
backend 57.37% <67.44%> (+0.02%) ⬆️
lfx 41.43% <7.14%> (-0.04%) ⬇️

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

Files with missing lines Coverage Δ
src/frontend/src/modals/exportModal/index.tsx 64.44% <ø> (-1.52%) ⬇️
src/frontend/src/utils/reactflowUtils.ts 11.44% <ø> (+0.07%) ⬆️
src/backend/base/langflow/api/v1/flows.py 52.60% <66.66%> (-0.02%) ⬇️
src/backend/base/langflow/api/utils/core.py 63.23% <67.50%> (+0.14%) ⬆️
src/lfx/src/lfx/base/models/unified_models.py 23.19% <7.14%> (-0.55%) ⬇️

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

Base automatically changed from fix-api-key-components to release-1.8.1 March 12, 2026 16:27
@codeflash-ai codeflash-ai Bot deleted the codeflash/optimize-pr12129-2026-03-10T17.52.35 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.

2 participants