⚡️ Speed up function _looks_like_variable_name by 92% in PR #12129 (fix-api-key-components)#12140
Closed
codeflash-ai[bot] wants to merge 10 commits into
Closed
⚡️ Speed up function _looks_like_variable_name by 92% in PR #12129 (fix-api-key-components)#12140codeflash-ai[bot] wants to merge 10 commits into
_looks_like_variable_name by 92% in PR #12129 (fix-api-key-components)#12140codeflash-ai[bot] wants to merge 10 commits into
Conversation
Made-with: Cursor
…ai/langflow into fix-api-key-components
The optimization pre-compiles the regex pattern `[A-Za-z][A-Za-z0-9_]*` into a module-level constant and replaces `re.fullmatch()` with `re.match()` on the pre-compiled pattern, eliminating per-call compilation overhead that consumed 89% of the original runtime (8.6 ms out of 9.7 ms according to the profiler). The refactored code also removes a redundant `strip()` call—the original invoked `value.strip()` twice (once in the truthiness check, once in the regex line)—and short-circuits non-string inputs before any stripping occurs. The net result is a 92% speedup (2.03 ms → 1.05 ms) with identical behavior across all test cases.
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## release-1.8.1 #12140 +/- ##
================================================
Coverage ? 37.20%
================================================
Files ? 1592
Lines ? 78268
Branches ? 11866
================================================
Hits ? 29118
Misses ? 47482
Partials ? 1668
Flags with carried forward coverage won't be shown. Click here to find out more.
🚀 New features to boost your workflow:
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
⚡️ 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.📄 92% (0.92x) speedup for
_looks_like_variable_nameinsrc/backend/base/langflow/api/utils/core.py⏱️ Runtime :
2.03 milliseconds→1.05 milliseconds(best of78runs)📝 Explanation and details
The optimization pre-compiles the regex pattern
[A-Za-z][A-Za-z0-9_]*into a module-level constant and replacesre.fullmatch()withre.match()on the pre-compiled pattern, eliminating per-call compilation overhead that consumed 89% of the original runtime (8.6 ms out of 9.7 ms according to the profiler). The refactored code also removes a redundantstrip()call—the original invokedvalue.strip()twice (once in the truthiness check, once in the regex line)—and short-circuits non-string inputs before any stripping occurs. The net result is a 92% speedup (2.03 ms → 1.05 ms) with identical behavior across all test cases.✅ Correctness verification report:
🌀 Click to see Generated Regression Tests
import pytest # used for our unit tests
from langflow.api.utils.core import
_looks_like_variable_name # function under test
def test_basic_valid_names():
# Single-letter name should be valid
assert _looks_like_variable_name("a") is True
# Typical variable names starting with a letter and containing letters, digits and underscores
assert _looks_like_variable_name("var") is True
assert _looks_like_variable_name("var123") is True
assert _looks_like_variable_name("var_name") is True
# Uppercase letters are allowed
assert _looks_like_variable_name("VarName") is True
# Mixed letters, digits and underscores
assert _looks_like_variable_name("a1_b2_C3") is True
def test_basic_invalid_names():
# Empty string is invalid
assert _looks_like_variable_name("") is False
# Whitespace-only string is invalid
assert _looks_like_variable_name(" ") is False
# None is not a string and should be rejected
assert _looks_like_variable_name(None) is False
# Non-string types should be rejected (int, list, dict, bytes)
assert _looks_like_variable_name(0) is False
assert _looks_like_variable_name(123) is False
assert _looks_like_variable_name([]) is False
assert _looks_like_variable_name({}) is False
assert _looks_like_variable_name(b"var") is False
# Names that do not start with a letter are invalid
assert _looks_like_variable_name("1var") is False
assert _looks_like_variable_name("_var") is False # starts with underscore -> invalid per pattern
# Names containing invalid characters are invalid
assert _looks_like_variable_name("var-name") is False
assert _looks_like_variable_name("var.name") is False
assert _looks_like_variable_name("a b") is False # internal whitespace not allowed
def test_strip_and_whitespace_handling():
# Leading/trailing spaces should be ignored due to strip()
assert _looks_like_variable_name(" var ") is True
assert _looks_like_variable_name("\tvar\t") is True
# Trailing newline is stripped as well -> "a\n" becomes "a"
assert _looks_like_variable_name("a\n") is True
# A string that's only newline becomes empty after strip -> invalid
assert _looks_like_variable_name("\n") is False
def test_unicode_and_non_ascii_characters():
# Only ASCII letters are allowed by the regex [A-Za-z] for the first character
# Non-ASCII leading letters should fail
assert _looks_like_variable_name("ávar") is False
assert _looks_like_variable_name("μvar") is False
# Non-Latin scripts should fail
assert _looks_like_variable_name("变量") is False
# Emoji should fail
assert _looks_like_variable_name("😊var") is False
def test_boolean_edge_cases_and_truthiness():
# True is truthy but not a string -> should be rejected
assert _looks_like_variable_name(True) is False
# False is falsy -> early return False
assert _looks_like_variable_name(False) is False
# The string "None" is just a normal string that starts with a letter -> should be accepted
assert _looks_like_variable_name("None") is True
def test_extreme_lengths():
# Very long valid name: starts with ASCII letter followed by many digits and underscores
long_valid = "a" + "0" * 5000 + "_" * 1000 # still matches the pattern
assert looks_like_variable_name(long_valid) is True
# Very long invalid name: starts with underscore -> should be rejected regardless of length
long_invalid = "" + "a" * 6000
assert _looks_like_variable_name(long_invalid) is False
def test_large_scale_valid_names():
# Generate 1000 deterministic valid variable names and ensure all are accepted.
# Use a simple pattern that always starts with 'v' (ASCII letter) followed by digits.
for i in range(1000):
name = f"v{i}" # e.g., v0, v1, ..., v999
# Each generated name should look like a valid variable name
assert _looks_like_variable_name(name) is True
def test_large_scale_invalid_names():
# Generate 1000 deterministic invalid variable names and ensure all are rejected.
# Use a simple pattern that starts with a digit so it should be invalid.
for i in range(1000):
name = f"{i}v" # e.g., 0v, 1v, ..., 999v -> start with digit -> invalid
assert _looks_like_variable_name(name) is False
def test_whitespace_variations_and_newline_internal_behavior():
# Internal newline is not stripped: "a\nb" remains "a\nb" and therefore is invalid because of '\n'
assert _looks_like_variable_name("a\nb") is False
# Tab inside the string is not stripped and thus invalid
assert _looks_like_variable_name("a\tb") is False
# Trailing carriage return is stripped by strip() so "a\r" becomes "a"
assert _looks_like_variable_name("a\r") is True
#------------------------------------------------
import re
from typing import Any
imports
import pytest
from langflow.api.utils.core import _looks_like_variable_name
def test_simple_valid_lowercase_variable():
"""Test basic lowercase variable name."""
assert _looks_like_variable_name("x") is True
def test_simple_valid_uppercase_variable():
"""Test basic uppercase variable name."""
assert _looks_like_variable_name("X") is True
def test_valid_variable_with_digits():
"""Test variable name with digits after the first character."""
assert _looks_like_variable_name("var123") is True
def test_valid_variable_with_underscores():
"""Test variable name with underscores."""
assert _looks_like_variable_name("my_var") is True
def test_valid_variable_mixed_case():
"""Test variable name with mixed case."""
assert _looks_like_variable_name("myVar123") is True
def test_valid_variable_snake_case():
"""Test common snake_case variable name."""
assert _looks_like_variable_name("_private_var") is False
def test_invalid_starts_with_digit():
"""Test that variable names cannot start with a digit."""
assert _looks_like_variable_name("1var") is False
def test_invalid_starts_with_underscore():
"""Test that variable names cannot start with underscore (per regex)."""
assert _looks_like_variable_name("_var") is False
def test_invalid_contains_hyphen():
"""Test that variable names cannot contain hyphens."""
assert _looks_like_variable_name("my-var") is False
def test_invalid_contains_space():
"""Test that variable names cannot contain spaces."""
assert _looks_like_variable_name("my var") is False
def test_invalid_contains_special_char():
"""Test that variable names cannot contain special characters."""
assert _looks_like_variable_name("my$var") is False
def test_empty_string():
"""Test that empty string returns False."""
assert _looks_like_variable_name("") is False
def test_none_value():
"""Test that None returns False."""
assert _looks_like_variable_name(None) is False
def test_integer_input():
"""Test that integer input returns False (not a string)."""
assert _looks_like_variable_name(123) is False
def test_float_input():
"""Test that float input returns False (not a string)."""
assert _looks_like_variable_name(45.67) is False
def test_list_input():
"""Test that list input returns False (not a string)."""
assert _looks_like_variable_name(["var"]) is False
def test_dict_input():
"""Test that dict input returns False (not a string)."""
assert _looks_like_variable_name({"key": "value"}) is False
def test_single_letter_a():
"""Test single letter lowercase variable."""
assert _looks_like_variable_name("a") is True
def test_single_letter_z():
"""Test single letter lowercase at end of alphabet."""
assert _looks_like_variable_name("z") is True
def test_single_letter_A():
"""Test single letter uppercase variable."""
assert _looks_like_variable_name("A") is True
def test_single_letter_Z():
"""Test single letter uppercase at end of alphabet."""
assert _looks_like_variable_name("Z") is True
def test_whitespace_only_string():
"""Test that whitespace-only string returns False."""
assert _looks_like_variable_name(" ") is False
def test_leading_whitespace():
"""Test that leading whitespace is stripped before validation."""
assert _looks_like_variable_name(" valid_name") is False # underscore prefix after strip
def test_trailing_whitespace():
"""Test that trailing whitespace is stripped before validation."""
assert _looks_like_variable_name("valid_name ") is False # underscore not allowed at start
def test_leading_and_trailing_whitespace():
"""Test that both leading and trailing whitespace are stripped."""
assert _looks_like_variable_name(" validName ") is True
def test_whitespace_in_middle():
"""Test that whitespace in the middle causes validation to fail."""
assert _looks_like_variable_name("valid Name") is False
def test_tab_character():
"""Test that tab character is treated as whitespace."""
assert _looks_like_variable_name("\tvalidName\t") is True
def test_newline_character():
"""Test that newline character is treated as whitespace."""
assert _looks_like_variable_name("\nvalidName\n") is True
def test_digit_only_string():
"""Test that digit-only string returns False."""
assert _looks_like_variable_name("123") is False
def test_underscore_only_string():
"""Test that underscore-only string returns False."""
assert looks_like_variable_name("") is False
def test_multiple_underscores():
"""Test multiple underscores (not at start, which is invalid anyway)."""
assert _looks_like_variable_name("a__b") is True
def test_digits_and_underscores():
"""Test variable with digits and underscores."""
assert _looks_like_variable_name("a_1_b_2") is True
def test_long_valid_variable():
"""Test a long but valid variable name."""
assert _looks_like_variable_name("A" + "b" * 100 + "C123_xyz") is True
def test_special_char_pound():
"""Test that pound/hash character invalidates name."""
assert _looks_like_variable_name("var#name") is False
def test_special_char_at_sign():
"""Test that @ character invalidates name."""
assert _looks_like_variable_name("var@name") is False
def test_special_char_bracket():
"""Test that bracket invalidates name."""
assert _looks_like_variable_name("var[name]") is False
def test_special_char_paren():
"""Test that parenthesis invalidates name."""
assert _looks_like_variable_name("var(name)") is False
def test_special_char_dot():
"""Test that dot invalidates name."""
assert _looks_like_variable_name("var.name") is False
def test_special_char_comma():
"""Test that comma invalidates name."""
assert _looks_like_variable_name("var,name") is False
def test_special_char_colon():
"""Test that colon invalidates name."""
assert _looks_like_variable_name("var:name") is False
def test_special_char_semicolon():
"""Test that semicolon invalidates name."""
assert _looks_like_variable_name("var;name") is False
def test_special_char_quote():
"""Test that single quote invalidates name."""
assert _looks_like_variable_name("var'name") is False
def test_special_char_double_quote():
"""Test that double quote invalidates name."""
assert _looks_like_variable_name('var"name') is False
def test_special_char_backtick():
"""Test that backtick invalidates name."""
assert _looks_like_variable_name("var`name") is False
def test_special_char_backslash():
"""Test that backslash invalidates name."""
assert _looks_like_variable_name("var\name") is False
def test_special_char_forward_slash():
"""Test that forward slash invalidates name."""
assert _looks_like_variable_name("var/name") is False
def test_special_char_question_mark():
"""Test that question mark invalidates name."""
assert _looks_like_variable_name("var?name") is False
def test_special_char_exclamation():
"""Test that exclamation mark invalidates name."""
assert _looks_like_variable_name("var!name") is False
def test_special_char_percent():
"""Test that percent sign invalidates name."""
assert _looks_like_variable_name("var%name") is False
def test_special_char_caret():
"""Test that caret invalidates name."""
assert _looks_like_variable_name("var^name") is False
def test_special_char_ampersand():
"""Test that ampersand invalidates name."""
assert _looks_like_variable_name("var&name") is False
def test_special_char_asterisk():
"""Test that asterisk invalidates name."""
assert _looks_like_variable_name("var*name") is False
def test_special_char_plus():
"""Test that plus sign invalidates name."""
assert _looks_like_variable_name("var+name") is False
def test_special_char_equals():
"""Test that equals sign invalidates name."""
assert _looks_like_variable_name("var=name") is False
def test_unicode_non_ascii_letter():
"""Test that non-ASCII letters invalidate the name."""
assert _looks_like_variable_name("varñame") is False
def test_unicode_emoji():
"""Test that emoji invalidates the name."""
assert _looks_like_variable_name("var😊name") is False
def test_empty_after_strip():
"""Test value that becomes empty after stripping whitespace."""
assert _looks_like_variable_name("") is False
def test_false_boolean():
"""Test that False boolean returns False."""
assert _looks_like_variable_name(False) is False
def test_true_boolean():
"""Test that True boolean returns False (not a string)."""
assert _looks_like_variable_name(True) is False
def test_zero_integer():
"""Test that zero integer returns False."""
assert _looks_like_variable_name(0) is False
def test_tuple_input():
"""Test that tuple input returns False."""
assert _looks_like_variable_name(("var",)) is False
def test_set_input():
"""Test that set input returns False."""
assert _looks_like_variable_name({"var"}) is False
def test_very_long_variable_name():
"""Test variable name that is 1000 characters long."""
long_name = "a" + "b" * 998 + "c"
assert _looks_like_variable_name(long_name) is True
def test_very_long_invalid_variable_name_with_space():
"""Test very long name with space in middle."""
long_name = "a" * 500 + " " + "b" * 499
assert _looks_like_variable_name(long_name) is False
def test_many_underscores_in_long_name():
"""Test long variable name with many underscores."""
long_name = "a" + "_b" * 499 + "c"
assert _looks_like_variable_name(long_name) is True
def test_many_digits_in_long_name():
"""Test long variable name with many digits."""
long_name = "a" + "1b" * 499 + "c"
assert _looks_like_variable_name(long_name) is True
def test_batch_valid_names():
"""Test multiple valid variable names in sequence."""
valid_names = [
"var1", "MyClass", "test_func", "x", "Z", "a1b2c3",
"CamelCase", "snake_case", "mixedCase123", "AA", "Zz"
]
for name in valid_names:
assert _looks_like_variable_name(name) is True, f"Failed for {name}"
def test_batch_invalid_names():
"""Test multiple invalid variable names in sequence."""
invalid_names = [
"1var", "var", "var-name", "var name", "var.name",
"var$name", "", "123", "", "var@name", "var#name",
"var!name", "var?name"
]
for name in invalid_names:
assert _looks_like_variable_name(name) is False, f"Failed for {name}"
def test_boundary_digit_all_9s():
"""Test variable with all 9 digits after first character."""
assert _looks_like_variable_name("a999999999") is True
def test_boundary_mixed_case_extreme():
"""Test variable with extreme case alternation."""
alternating = "".join(["aB"[i % 2] for i in range(1000)])
assert _looks_like_variable_name(alternating) is True
def test_stress_whitespace_stripping():
"""Test that function handles heavy whitespace stripping."""
for i in range(100):
spaces = " " * i
assert _looks_like_variable_name(spaces + "validName" + spaces) is True
def test_stress_type_checking():
"""Test rapid type checking with different types."""
test_values = [1, 2.5, True, False, None, [], {}, set()]
for val in test_values:
# All non-string types should return False
result = _looks_like_variable_name(val)
assert result is False, f"Failed for type {type(val)}"
def test_comprehensive_digit_positions():
"""Test digits in every possible position of a long name."""
base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i in range(len(base)):
name = base[:i] + str(i % 10) + base[i:]
assert _looks_like_variable_name(name) is True
def test_comprehensive_underscore_positions():
"""Test underscores in various positions."""
base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i in range(1, len(base)): # Start at 1, can't have underscore at position 0
name = base[:i] + "_" + base[i:]
assert _looks_like_variable_name(name) is True
To edit these changes
git checkout codeflash/optimize-pr12129-2026-03-10T20.07.52and push.