Skip to content

⚡️ 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
release-1.8.1from
codeflash/optimize-pr12129-2026-03-10T20.07.52
Closed

⚡️ Speed up function _looks_like_variable_name by 92% in PR #12129 (fix-api-key-components)#12140
codeflash-ai[bot] wants to merge 10 commits into
release-1.8.1from
codeflash/optimize-pr12129-2026-03-10T20.07.52

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.


📄 92% (0.92x) speedup for _looks_like_variable_name in src/backend/base/langflow/api/utils/core.py

⏱️ Runtime : 2.03 milliseconds 1.05 milliseconds (best of 78 runs)

📝 Explanation and details

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.

Correctness verification report:

Test Status
⚙️ Existing Unit Tests 🔘 None Found
🌀 Generated Regression Tests 2338 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
_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.52 and push.

Codeflash

HimavarshaVS and others added 9 commits March 10, 2026 12:51
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.
@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 41.66667% with 42 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 6.66% 27 Missing and 1 partial ⚠️
src/backend/base/langflow/api/utils/core.py 66.66% 13 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   #12140   +/-   ##
================================================
  Coverage                 ?   37.20%           
================================================
  Files                    ?     1592           
  Lines                    ?    78268           
  Branches                 ?    11866           
================================================
  Hits                     ?    29118           
  Misses                   ?    47482           
  Partials                 ?     1668           
Flag Coverage Δ
backend 57.39% <66.66%> (?)
lfx 41.43% <6.66%> (?)

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

Files with missing lines Coverage Δ
...d/src/CustomNodes/hooks/use-fetch-data-on-mount.ts 0.00% <ø> (ø)
...omponent/components/inputGlobalComponent/index.tsx 23.91% <ø> (ø)
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 65.31% <66.66%> (ø)
src/lfx/src/lfx/base/models/unified_models.py 23.16% <6.66%> (ø)
🚀 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-10T20.07.52 branch March 12, 2026 18:26
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