Skip to content

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

Closed
codeflash-ai[bot] wants to merge 7 commits into
release-1.8.1from
codeflash/optimize-pr12129-2026-03-10T19.02.48
Closed

⚡️ Speed up function replace_api_key_with_env_var_name by 59% in PR #12129 (fix-api-key-components)#12138
codeflash-ai[bot] wants to merge 7 commits into
release-1.8.1from
codeflash/optimize-pr12129-2026-03-10T19.02.48

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.


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

⏱️ Runtime : 2.98 milliseconds 1.87 milliseconds (best of 131 runs)

📝 Explanation and details

The hot function _looks_like_variable_name originally called re.fullmatch inside a tight loop (2764 hits), recompiling the pattern string on each call—this consumed 89.8% of its runtime (~8.15 ms of 9.07 ms total). The optimization precompiles the regex to a module-level constant _VARIABLE_NAME_PATTERN and replaces fullmatch with match on the stripped string, cutting per-call cost from ~2947 ns to ~684 ns. Early-exit checks for non-string types, empty values, and whitespace-only strings now proceed sequentially before the regex match, avoiding redundant strip() evaluations and boosting cache locality. This yields a 59% overall speedup (2.98 ms → 1.87 ms) with identical test results across all 1000+ node stress tests.

Correctness verification report:

Test Status
⚙️ Existing Unit Tests 🔘 None Found
🌀 Generated Regression Tests 50 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
from langflow.api.utils.core import replace_api_key_with_env_var_name


def test_basic_keep_variable_name():
    # Basic case: when the api_key value looks like a variable name, it should be kept unchanged.
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "first": {"name": "api_key", "password": True, "value": "MY_API_KEY"},
                            }
                        }
                    }
                }
            ]
        }
    }
    returned = replace_api_key_with_env_var_name(flow)  # call the function
    # Function modifies in-place and returns the same object
    assert returned is flow
    # The variable-like API key should be preserved exactly as provided
    assert flow["data"]["nodes"][0]["data"]["node"]["template"]["first"]["value"] == "MY_API_KEY"


def test_basic_clear_raw_secret():
    # Basic case: raw API secret strings (not valid variable names) should be cleared (set to None).
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api": {"name": "api_key", "password": True, "value": "sk_live_12345SECRET"},
                            }
                        }
                    }
                }
            ]
        }
    }
    replace_api_key_with_env_var_name(flow)
    # Raw secrets are replaced with None
    assert flow["data"]["nodes"][0]["data"]["node"]["template"]["api"]["value"] is None


def test_multiple_keys_in_template_only_first_processed_per_node():
    # If a node's template has multiple entries, the function processes values in iteration order
    # and stops after handling the first matching api_key (either keeping var name or clearing raw secret).
    flow = {
        "data": {
            "nodes": [
                # Node 0: first entry is a variable name -> it should stop there and not clear the second raw secret
                {
                    "data": {
                        "node": {
                            "template": {
                                "a": {"name": "api_key", "password": True, "value": "VAR_KEEP"},
                                "b": {"name": "api_key", "password": True, "value": "sk_should_remain"},
                            }
                        }
                    }
                },
                # Node 1: first entry is a raw secret -> it should be cleared and the second should remain untouched
                {
                    "data": {
                        "node": {
                            "template": {
                                "x": {"name": "api_key", "password": True, "value": "sk_clear_me"},
                                "y": {"name": "api_key", "password": True, "value": "VAR_Y"},
                            }
                        }
                    }
                },
            ]
        }
    }

    replace_api_key_with_env_var_name(flow)

    # Node 0: since the first api_key looked like a variable name, it should be preserved;
    # the second entry should be left unchanged (not cleared) because we broke out after the first.
    assert flow["data"]["nodes"][0]["data"]["node"]["template"]["a"]["value"] == "VAR_KEEP"
    assert flow["data"]["nodes"][0]["data"]["node"]["template"]["b"]["value"] == "sk_should_remain"

    # Node 1: the first api_key was raw and should be cleared; the second should remain unchanged
    assert flow["data"]["nodes"][1]["data"]["node"]["template"]["x"]["value"] is None
    assert flow["data"]["nodes"][1]["data"]["node"]["template"]["y"]["value"] == "VAR_Y"


def test_non_dict_node_data_and_inner_skips():
    # Nodes with non-dict 'data', or non-dict 'node', or non-dict 'template' should be skipped safely.
    flow = {
        "data": {
            "nodes": [
                {"data": None},  # skipped
                {"data": {"node": None}},  # skipped
                {"data": {"node": {"template": None}}},  # skipped
                # One valid node at the end should still be processed correctly
                {
                    "data": {
                        "node": {
                            "template": {
                                "only": {"name": "api_key", "password": True, "value": "raw_secret_42"},
                            }
                        }
                    }
                },
            ]
        }
    }

    replace_api_key_with_env_var_name(flow)
    # Only the valid node should have been touched and its raw secret cleared
    assert flow["data"]["nodes"][-1]["data"]["node"]["template"]["only"]["value"] is None
    # Earlier nodes remain as they were (no exceptions thrown)
    assert flow["data"]["nodes"][0]["data"] is None
    assert flow["data"]["nodes"][1]["data"]["node"] is None
    assert flow["data"]["nodes"][2]["data"]["node"]["template"] is None


def test_password_false_or_missing_is_not_processed():
    # If 'password' is False or missing, the api_key entry should not be processed.
    flow = {
        "data": {
            "nodes": [
                # password explicitly False
                {
                    "data": {
                        "node": {
                            "template": {
                                "one": {"name": "api_key", "password": False, "value": "sk_should_stay"},
                            }
                        }
                    }
                },
                # password missing -> treated as falsy by .get and should not be processed
                {
                    "data": {
                        "node": {
                            "template": {
                                "two": {"name": "api_key", "value": "sk_should_also_stay"},
                            }
                        }
                    }
                },
            ]
        }
    }
    replace_api_key_with_env_var_name(flow)
    # Values should remain unchanged because password is False or missing
    assert flow["data"]["nodes"][0]["data"]["node"]["template"]["one"]["value"] == "sk_should_stay"
    assert flow["data"]["nodes"][1]["data"]["node"]["template"]["two"]["value"] == "sk_should_also_stay"


def test_empty_and_whitespace_values_cleared_when_password_true():
    # Empty strings or whitespace-only strings are not considered valid variable names and should be cleared.
    flow = {
        "data": {
            "nodes": [
                {"data": {"node": {"template": {"e": {"name": "api_key", "password": True, "value": ""}}}}},  # empty
                {"data": {"node": {"template": {"w": {"name": "api_key", "password": True, "value": "   "}}}}},  # whitespace-only
                {"data": {"node": {"template": {"n": {"name": "api_key", "password": True, "value": None}}}}},  # None
            ]
        }
    }
    replace_api_key_with_env_var_name(flow)
    # All three should end up as None (either cleared or already None)
    assert flow["data"]["nodes"][0]["data"]["node"]["template"]["e"]["value"] is None
    assert flow["data"]["nodes"][1]["data"]["node"]["template"]["w"]["value"] is None
    assert flow["data"]["nodes"][2]["data"]["node"]["template"]["n"]["value"] is None


def test_variable_name_with_spaces_detected_but_value_preserved():
    # A value like "  API1 " is recognized as a valid variable name because of .strip(),
    # but the original value is preserved (including spaces) because the function does not modify it.
    original_value = "  API1 "
    flow = {
        "data": {
            "nodes": [
                {"data": {"node": {"template": {"v": {"name": "api_key", "password": True, "value": original_value}}}}}
            ]
        }
    }
    replace_api_key_with_env_var_name(flow)
    # The original string (including spaces) should be preserved unchanged
    assert flow["data"]["nodes"][0]["data"]["node"]["template"]["v"]["value"] == original_value


def test_special_characters_cleared():
    # Values that contain special characters and do not match the variable-name pattern should be cleared.
    flow = {
        "data": {
            "nodes": [
                {"data": {"node": {"template": {"s": {"name": "api_key", "password": True, "value": "$ECRET!"}}}}}
            ]
        }
    }
    replace_api_key_with_env_var_name(flow)
    assert flow["data"]["nodes"][0]["data"]["node"]["template"]["s"]["value"] is None


def test_large_scale_many_nodes():
    # Large-scale test: create 1000 nodes to ensure the function scales and behaves deterministically.
    nodes = []
    count = 1000
    for i in range(count):
        # Even indices get raw secrets that should be cleared; odd indices get valid variable-like names.
        if i % 2 == 0:
            val = f"raw_secret_{i}"
        else:
            val = f"VAR{i}"  # valid variable name: starts with letter, followed by digits
        nodes.append(
            {
                "data": {
                    "node": {
                        "template": {
                            "k": {"name": "api_key", "password": True, "value": val}
                        }
                    }
                }
            }
        )
    flow = {"data": {"nodes": nodes}}
    original_id = id(flow)
    replace_api_key_with_env_var_name(flow)
    # Verify that half (even indices) were cleared, and the other half left intact
    cleared = 0
    preserved = 0
    for i, node in enumerate(flow["data"]["nodes"]):
        v = node["data"]["node"]["template"]["k"]["value"]
        if i % 2 == 0:
            # even indices should have been cleared to None
            assert v is None
            cleared += 1
        else:
            # odd indices should retain their variable-like string
            assert v == f"VAR{i}"
            preserved += 1
    assert cleared == count // 2
    assert preserved == count - (count // 2)
    # Ensure object identity remains the same (function returns the same object)
    assert id(flow) == original_id


def test_large_scale_many_template_entries_only_first_handled():
    # Large-scale inner-loop test: one node with 1000 template entries.
    # Since the function stops after handling the first matching api_key entry,
    # only the first should be processed.
    entries = {}
    total = 1000
    # Make the first entry a raw secret so it gets cleared, and others also raw (but should remain unchanged)
    for i in range(total):
        entries[f"k{i}"] = {"name": "api_key", "password": True, "value": f"raw_{i}"}
    flow = {"data": {"nodes": [{"data": {"node": {"template": entries}}}]}}
    replace_api_key_with_env_var_name(flow)
    tpl = flow["data"]["nodes"][0]["data"]["node"]["template"]
    # Only the first entry (in insertion order) should have been cleared, the rest left as-is.
    # Python dict preserves insertion order; our first key is 'k0'.
    assert tpl["k0"]["value"] is None
    # Verify that at least one later key remains unchanged (e.g., k1)
    assert tpl["k1"]["value"] == "raw_1"
#------------------------------------------------
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_dict():
    """Test that an empty flow dict is returned unchanged."""
    flow = {}
    result = replace_api_key_with_env_var_name(flow)
    assert result == {}
    assert result is flow  # should be the same object


def test_flow_with_no_data_key():
    """Test flow dict without 'data' key returns unchanged."""
    flow = {"nodes": []}
    result = replace_api_key_with_env_var_name(flow)
    assert result == {"nodes": []}


def test_flow_with_empty_nodes_list():
    """Test flow with data but empty nodes list."""
    flow = {"data": {"nodes": []}}
    result = replace_api_key_with_env_var_name(flow)
    assert result == {"data": {"nodes": []}}


def test_replaces_raw_api_key_with_none():
    """Test that a raw (non-variable) api_key value is replaced with None."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_key_field": {
                                    "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_key_field"]["value"] is None


def test_keeps_valid_variable_name_unchanged():
    """Test that a valid variable name (like MY_API_KEY) is preserved."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_key_field": {
                                    "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_key_field"]["value"] == "MY_API_KEY"


def test_multiple_template_fields_only_processes_api_key():
    """Test that only api_key field is processed, other fields are untouched."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "username": {
                                    "name": "username",
                                    "password": False,
                                    "value": "myuser"
                                },
                                "api_key_field": {
                                    "name": "api_key",
                                    "password": True,
                                    "value": "raw_secret_key_12345"
                                },
                                "timeout": {
                                    "name": "timeout",
                                    "password": False,
                                    "value": 30
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    template = result["data"]["nodes"][0]["data"]["node"]["template"]
    assert template["username"]["value"] == "myuser"
    assert template["api_key_field"]["value"] is None
    assert template["timeout"]["value"] == 30


def test_api_key_without_password_flag_ignored():
    """Test that api_key without password=True is not processed."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_key_field": {
                                    "name": "api_key",
                                    "password": False,
                                    "value": "raw_secret_key"
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["api_key_field"]["value"] == "raw_secret_key"


def test_multiple_nodes_with_api_keys():
    """Test that api_keys in multiple nodes are all processed."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_key_field": {
                                    "name": "api_key",
                                    "password": True,
                                    "value": "raw_key_1"
                                }
                            }
                        }
                    }
                },
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_key_field": {
                                    "name": "api_key",
                                    "password": True,
                                    "value": "VALID_VAR_NAME"
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["api_key_field"]["value"] is None
    assert result["data"]["nodes"][1]["data"]["node"]["template"]["api_key_field"]["value"] == "VALID_VAR_NAME"


def test_api_key_value_is_none_initially():
    """Test that None value for api_key remains None."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_key_field": {
                                    "name": "api_key",
                                    "password": True,
                                    "value": None
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["api_key_field"]["value"] is None


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


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


def test_api_key_with_special_characters_is_cleared():
    """Test that api_key with special characters is replaced with None."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_key_field": {
                                    "name": "api_key",
                                    "password": True,
                                    "value": "sk-@#$%^&*()"
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["api_key_field"]["value"] is None


def test_api_key_starting_with_number_is_cleared():
    """Test that api_key starting with number is not a valid variable name and is cleared."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_key_field": {
                                    "name": "api_key",
                                    "password": True,
                                    "value": "123_API_KEY"
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["api_key_field"]["value"] is None


def test_valid_variable_name_with_underscores():
    """Test that valid variable names with underscores are preserved."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_key_field": {
                                    "name": "api_key",
                                    "password": True,
                                    "value": "_API_KEY_NAME"
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    # _API_KEY_NAME starts with underscore, which is valid in Python but not by the regex [A-Za-z][A-Za-z0-9_]*
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["api_key_field"]["value"] is None


def test_single_letter_variable_name():
    """Test that single letter variable names are preserved."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_key_field": {
                                    "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_key_field"]["value"] == "X"


def test_node_data_is_not_dict():
    """Test that node with non-dict data is skipped."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": "not_a_dict"
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    assert result == flow


def test_node_inner_is_not_dict():
    """Test that node with non-dict inner node is skipped."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": "not_a_dict"
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    assert result == flow


def test_template_is_not_dict():
    """Test that node with non-dict template is skipped."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": "not_a_dict"
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    assert result == flow


def test_template_value_is_not_dict():
    """Test that template field that is not a dict is skipped."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "field1": "string_value",
                                "field2": 123,
                                "field3": None
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    assert result == flow


def test_template_value_dict_without_name_key():
    """Test that dict without name key is skipped."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "field1": {
                                    "password": True,
                                    "value": "something"
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    assert result == flow


def test_api_key_field_without_password_key():
    """Test that api_key field without password key is skipped."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "field1": {
                                    "name": "api_key",
                                    "value": "secret"
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["field1"]["value"] == "secret"


def test_api_key_value_with_dash():
    """Test that api_key with dash is not a valid variable name and is cleared."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_key_field": {
                                    "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_key_field"]["value"] is None


def test_api_key_value_with_dot():
    """Test that api_key with dot is not a valid variable name and is cleared."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_key_field": {
                                    "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_key_field"]["value"] is None


def test_api_key_value_lowercase_variable_name():
    """Test that lowercase valid variable names are preserved."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_key_field": {
                                    "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_key_field"]["value"] == "my_api_key"


def test_api_key_value_mixed_case_with_numbers():
    """Test that mixed case valid variable names with numbers are preserved."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_key_field": {
                                    "name": "api_key",
                                    "password": True,
                                    "value": "Api_Key_123"
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["api_key_field"]["value"] == "Api_Key_123"


def test_first_occurrence_breaks_loop():
    """Test that processing stops after first api_key field found in template."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "field1": {
                                    "name": "api_key",
                                    "password": True,
                                    "value": "raw_key_1"
                                },
                                "field2": {
                                    "name": "api_key",
                                    "password": True,
                                    "value": "raw_key_2"
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    # First api_key field should be cleared, but due to break, second one won't be processed
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["field1"]["value"] is None
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["field2"]["value"] == "raw_key_2"


def test_flow_with_nested_non_dict_data():
    """Test flow with various non-dict values at different levels."""
    flow = {
        "data": {
            "nodes": [
                {"data": None},
                {"data": 123},
                {"data": []},
                {"data": {"node": None}},
                {"data": {"node": {"template": None}}}
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    assert result == flow


def test_empty_template_dict():
    """Test that empty template dict is handled correctly."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {}
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    assert result == flow


def test_password_false_value():
    """Test that api_key with password=False is not processed."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_key_field": {
                                    "name": "api_key",
                                    "password": False,
                                    "value": "some_value"
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["api_key_field"]["value"] == "some_value"


def test_password_zero_value():
    """Test that api_key with password=0 (falsy) is not processed."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_key_field": {
                                    "name": "api_key",
                                    "password": 0,
                                    "value": "some_value"
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["api_key_field"]["value"] == "some_value"


def test_password_empty_string_value():
    """Test that api_key with password='' (falsy) is not processed."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_key_field": {
                                    "name": "api_key",
                                    "password": "",
                                    "value": "some_value"
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["api_key_field"]["value"] == "some_value"


def test_api_key_value_is_integer():
    """Test that api_key with integer value is not a valid variable name and is cleared."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_key_field": {
                                    "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_key_field"]["value"] is None


def test_api_key_value_is_list():
    """Test that api_key with list value is not a valid variable name and is cleared."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_key_field": {
                                    "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_key_field"]["value"] is None


def test_api_key_value_is_dict():
    """Test that api_key with dict value is not a valid variable name and is cleared."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_key_field": {
                                    "name": "api_key",
                                    "password": True,
                                    "value": {"nested": "value"}
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["api_key_field"]["value"] is None


def test_many_nodes_with_api_keys():
    """Test processing flow with 100 nodes containing api_keys."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_key_field": {
                                    "name": "api_key",
                                    "password": True,
                                    "value": f"raw_key_{i}" if i % 2 == 0 else f"VAR_NAME_{i}"
                                }
                            }
                        }
                    }
                }
                for i in range(100)
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    # Check that raw keys (even indices) are cleared and variable names (odd indices) are preserved
    for i in range(100):
        value = result["data"]["nodes"][i]["data"]["node"]["template"]["api_key_field"]["value"]
        if i % 2 == 0:
            assert value is None, f"Node {i}: expected None for raw_key_{i}"
        else:
            assert value == f"VAR_NAME_{i}", f"Node {i}: expected VAR_NAME_{i}"


def test_many_template_fields_per_node():
    """Test node with 100 template fields, one containing api_key."""
    template = {}
    for i in range(100):
        if i == 50:
            template[f"field_{i}"] = {
                "name": "api_key",
                "password": True,
                "value": "raw_secret_key"
            }
        else:
            template[f"field_{i}"] = {
                "name": f"field_name_{i}",
                "password": False,
                "value": f"value_{i}"
            }
    
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": template
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    result_template = result["data"]["nodes"][0]["data"]["node"]["template"]
    # Check that only the api_key field at index 50 is cleared
    assert result_template["field_50"]["value"] is None
    # Check that other fields are unchanged
    for i in range(100):
        if i != 50:
            assert result_template[f"field_{i}"]["value"] == f"value_{i}"


def test_deeply_nested_structure_with_multiple_nodes():
    """Test complex flow with 200 nodes and multiple levels of nesting."""
    flow = {
        "data": {
            "nodes": [
                {
                    "id": f"node_{i}",
                    "data": {
                        "node": {
                            "template": {
                                "config_field": {
                                    "name": "config",
                                    "password": False,
                                    "value": f"config_{i}"
                                },
                                "api_key_field": {
                                    "name": "api_key",
                                    "password": True,
                                    "value": f"ApiKey_{i}" if i % 3 == 0 else f"raw_{i}"
                                },
                                "other_field": {
                                    "name": "other",
                                    "password": False,
                                    "value": f"other_{i}"
                                }
                            }
                        }
                    }
                }
                for i in range(200)
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    # Verify that all nodes are processed correctly
    for i in range(200):
        value = result["data"]["nodes"][i]["data"]["node"]["template"]["api_key_field"]["value"]
        if i % 3 == 0:
            # Valid variable name should be preserved
            assert value == f"ApiKey_{i}", f"Node {i}: expected valid variable name preserved"
        else:
            # Raw key should be cleared
            assert value is None, f"Node {i}: expected None for raw key"


def test_large_number_of_different_variable_formats():
    """Test 500 nodes with different valid variable name formats."""
    valid_names = [
        "a", "Z", "varName", "VAR_NAME", "var123", "Var_123",
        "apiKey", "ApiKey", "API_KEY", "api_key_name", "x1y2z3"
    ]
    invalid_names = [
        "123var", "var-name", "var.name", "var@name", "var name",
        "var[0]", "var(1)", "var{2}", "", " ", "  "
    ]
    
    flow = {
        "data": {
            "nodes": []
        }
    }
    
    # Add nodes with valid variable names
    for i, valid_name in enumerate(valid_names * 40):
        flow["data"]["nodes"].append({
            "data": {
                "node": {
                    "template": {
                        "api_key_field": {
                            "name": "api_key",
                            "password": True,
                            "value": valid_name
                        }
                    }
                }
            }
        })
    
    result = replace_api_key_with_env_var_name(flow)
    
    # Verify that all valid names are preserved
    for i in range(len(valid_names) * 40):
        value = result["data"]["nodes"][i]["data"]["node"]["template"]["api_key_field"]["value"]
        assert value == valid_names[i % len(valid_names)], f"Node {i}: valid name should be preserved"


def test_mixed_valid_invalid_keys_1000_nodes():
    """Test with 1000 nodes alternating between valid and invalid api_key formats."""
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": {
                                "api_key_field": {
                                    "name": "api_key",
                                    "password": True,
                                    "value": "VALID_KEY" if i % 2 == 0 else f"raw_secret_{i}"
                                }
                            }
                        }
                    }
                }
                for i in range(1000)
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    
    # Verify patterns across all 1000 nodes
    for i in range(1000):
        value = result["data"]["nodes"][i]["data"]["node"]["template"]["api_key_field"]["value"]
        if i % 2 == 0:
            assert value == "VALID_KEY", f"Node {i}: expected valid key preserved"
        else:
            assert value is None, f"Node {i}: expected raw key cleared"


def test_performance_large_template_with_many_fields():
    """Test processing a single node with 500 template fields."""
    template = {}
    for i in range(500):
        template[f"field_{i}"] = {
            "name": f"api_key" if i == 250 else f"field_{i}",
            "password": True if i == 250 else False,
            "value": "raw_api_secret_key" if i == 250 else f"value_{i}"
        }
    
    flow = {
        "data": {
            "nodes": [
                {
                    "data": {
                        "node": {
                            "template": template
                        }
                    }
                }
            ]
        }
    }
    result = replace_api_key_with_env_var_name(flow)
    
    # Verify that the api_key field (at index 250) is cleared
    assert result["data"]["nodes"][0]["data"]["node"]["template"]["field_250"]["value"] is None
    # Verify that other fields remain unchanged
    for i in range(500):
        if i != 250:
            assert result["data"]["nodes"][0]["data"]["node"]["template"][f"field_{i}"]["value"] == f"value_{i}"

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

Codeflash

HimavarshaVS and others added 5 commits March 10, 2026 12:51
The hot function `_looks_like_variable_name` originally called `re.fullmatch` inside a tight loop (2764 hits), recompiling the pattern string on each call—this consumed 89.8% of its runtime (~8.15 ms of 9.07 ms total). The optimization precompiles the regex to a module-level constant `_VARIABLE_NAME_PATTERN` and replaces `fullmatch` with `match` on the stripped string, cutting per-call cost from ~2947 ns to ~684 ns. Early-exit checks for non-string types, empty values, and whitespace-only strings now proceed sequentially before the regex match, avoiding redundant `strip()` evaluations and boosting cache locality. This yields a 59% overall speedup (2.98 ms → 1.87 ms) with identical test results across all 1000+ node stress tests.
@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 45.83333% with 39 lines in your changes missing coverage. Please review.
⚠️ Please upload report for BASE (release-1.8.1@d7cb9a0). Learn more about missing BASE report.

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 70.73% 12 Missing ⚠️
src/backend/base/langflow/api/v1/flows.py 66.66% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@               Coverage Diff                @@
##             release-1.8.1   #12138   +/-   ##
================================================
  Coverage                 ?   37.18%           
================================================
  Files                    ?     1592           
  Lines                    ?    78276           
  Branches                 ?    11872           
================================================
  Hits                     ?    29110           
  Misses                   ?    47499           
  Partials                 ?     1667           
Flag Coverage Δ
backend 57.34% <70.45%> (?)
lfx 41.43% <7.14%> (?)

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% <ø> (ø)
src/frontend/src/utils/reactflowUtils.ts 11.44% <ø> (ø)
src/backend/base/langflow/api/v1/flows.py 52.60% <66.66%> (ø)
src/backend/base/langflow/api/utils/core.py 63.73% <70.73%> (ø)
src/lfx/src/lfx/base/models/unified_models.py 23.19% <7.14%> (ø)
🚀 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-10T19.02.48 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