⚡️ Speed up method ChatOutputResponse.coerce_session_id_uuid_to_str by 16% in PR #11958 (fix/lfx-chatresp-uuid)#11960
Closed
codeflash-ai[bot] wants to merge 1 commit into
Conversation
The validator now inlines the `isinstance(value, UUID)` check and `str(value)` conversion directly, eliminating the overhead of calling `coerce_to_str_if_uuid` (a separate function invocation that crosses module boundaries from `langflow.utils.schemas` to `langflow.schema.validators`). Each validator invocation—which happens on every `ChatOutputResponse` instantiation with a `session_id`—saves one function call plus the associated stack frame setup/teardown, reducing per-instance overhead from ~13 µs to ~11.2 µs. The trade-off is duplicated logic if other validators needed the same coercion, but the function is only called from this single site, making inlining a straightforward win.
Contributor
Codecov Report✅ All modified and coverable lines are covered by tests. ❌ Your project status has failed because the head coverage (41.54%) is below the target coverage (60.00%). You can increase the head coverage or adjust the target coverage. Additional details and impacted files@@ Coverage Diff @@
## fix/lfx-chatresp-uuid #11960 +/- ##
=========================================================
+ Coverage 36.02% 36.41% +0.38%
=========================================================
Files 1570 1570
Lines 76679 76678 -1
Branches 11629 11629
=========================================================
+ Hits 27623 27919 +296
+ Misses 47479 47182 -297
Partials 1577 1577
Flags with carried forward coverage won't be shown. Click here to find out more.
🚀 New features to boost your workflow:
|
Contributor
|
Closing automated codeflash PR. |
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 #11958
If you approve this dependent PR, these changes will be merged into the original PR branch
fix/lfx-chatresp-uuid.📄 16% (0.16x) speedup for
ChatOutputResponse.coerce_session_id_uuid_to_strinsrc/backend/base/langflow/utils/schemas.py⏱️ Runtime :
13.0 microseconds→11.2 microseconds(best of189runs)📝 Explanation and details
The validator now inlines the
isinstance(value, UUID)check andstr(value)conversion directly, eliminating the overhead of callingcoerce_to_str_if_uuid(a separate function invocation that crosses module boundaries fromlangflow.utils.schemastolangflow.schema.validators). Each validator invocation—which happens on everyChatOutputResponseinstantiation with asession_id—saves one function call plus the associated stack frame setup/teardown, reducing per-instance overhead from ~13 µs to ~11.2 µs. The trade-off is duplicated logic if other validators needed the same coercion, but the function is only called from this single site, making inlining a straightforward win.✅ Correctness verification report:
🌀 Click to see Generated Regression Tests
from typing import Any, List
from uuid import UUID, uuid4 # real UUID class and factory
imports
import pytest # used for our unit tests
from langflow.utils.schemas import ChatOutputResponse
def test_coerce_uuid_to_str_returns_string():
# Create a real UUID instance
u = uuid4()
# Call the classmethod under test directly on the real class
codeflash_output = ChatOutputResponse.coerce_session_id_uuid_to_str(u); result = codeflash_output
def test_coerce_string_is_returned_unchanged():
# Provide a normal string value (already the intended target type)
s = "session-123"
# The method should leave non-UUID strings unchanged
codeflash_output = ChatOutputResponse.coerce_session_id_uuid_to_str(s); result = codeflash_output
def test_coerce_none_returns_none():
# None should be preserved
codeflash_output = ChatOutputResponse.coerce_session_id_uuid_to_str(None); result = codeflash_output
@pytest.mark.parametrize(
"value",
[
0, # integer zero
42, # arbitrary integer
3.14, # float
True, # boolean (subclass of int in Python)
[], # empty list
["a", "b"], # list with strings
{"k": "v"}, # dict
UUID(int=0), # special-case UUID (all zeros) remains converted to string
],
)
def test_non_uuid_values_returned_unchanged_except_real_uuid(value: Any):
# When the input is a UUID instance it should be converted to str,
# otherwise the input should be returned unchanged by identity or value.
codeflash_output = ChatOutputResponse.coerce_session_id_uuid_to_str(value); result = codeflash_output
if isinstance(value, UUID):
pass
else:
pass
def test_string_uuid_like_value_is_unchanged():
# A string that looks like a UUID must be left as a string (no changes)
uuid_str = str(uuid4())
# Provide the textual UUID (not a UUID object)
codeflash_output = ChatOutputResponse.coerce_session_id_uuid_to_str(uuid_str); result = codeflash_output
def test_validator_used_in_pydantic_model_converts_uuid_to_str():
# Create a real UUID and pass it when constructing the Pydantic model.
# ChatOutputResponse defines a field validator that should convert UUID => str.
u = uuid4()
# Construct a real ChatOutputResponse instance using required fields:
# -
messageandtypeare required per the schema snippet.model = ChatOutputResponse(message="hello", type="text", session_id=u)
def test_validator_preserves_provided_string_on_model():
# When a string is provided to the model, it should remain a string and unchanged.
s = "explicit-session-id"
model = ChatOutputResponse(message="hi", type="text", session_id=s)
def test_model_allows_none_session_id():
# None should be an acceptable value for session_id at model level.
model = ChatOutputResponse(message="none-case", type="text", session_id=None)
def test_bulk_conversion_of_uuid_list_to_strings():
# Create a large list of UUIDs (1000 elements)
uuids: List[UUID] = [uuid4() for _ in range(1000)]
# Convert all using the classmethod and collect results
results = [ChatOutputResponse.coerce_session_id_uuid_to_str(u) for u in uuids]
for original, converted in zip(uuids, results):
pass
def test_many_mixed_values_roundtrip_behavior():
# Create 1000 mixed values: UUIDs, strings, None, ints
mixed: List[Any] = []
for i in range(250):
mixed.append(uuid4()) # 250 UUIDs
for i in range(250):
mixed.append(f"str-{i}") # 250 strings
for i in range(250):
mixed.append(None) # 250 None
for i in range(250):
mixed.append(i) # 250 ints
codeflash_output is used to check that the output of the original code is the same as that of the optimized code.
#------------------------------------------------
from uuid import UUID
imports
import pytest
from langflow.utils.schemas import ChatOutputResponse
def test_coerce_session_id_uuid_to_str_with_uuid_object():
"""Test that a UUID object is converted to a string."""
test_uuid = UUID('550e8400-e29b-41d4-a716-446655440000')
response = ChatOutputResponse(
message="test",
type="test",
session_id=test_uuid
)
def test_coerce_session_id_uuid_to_str_with_string():
"""Test that a string session_id remains a string."""
test_session_id = "550e8400-e29b-41d4-a716-446655440000"
response = ChatOutputResponse(
message="test",
type="test",
session_id=test_session_id
)
def test_coerce_session_id_uuid_to_str_with_none():
"""Test that None session_id remains None."""
response = ChatOutputResponse(
message="test",
type="test",
session_id=None
)
def test_coerce_session_id_uuid_to_str_not_provided():
"""Test that omitting session_id defaults to None."""
response = ChatOutputResponse(
message="test",
type="test"
)
def test_coerce_session_id_uuid_to_str_with_empty_string():
"""Test that an empty string session_id remains an empty string."""
response = ChatOutputResponse(
message="test",
type="test",
session_id=""
)
def test_coerce_session_id_uuid_to_str_with_uuid_from_string():
"""Test that UUID created from string is properly converted."""
uuid_str = '12345678-1234-5678-1234-567812345678'
test_uuid = UUID(uuid_str)
response = ChatOutputResponse(
message="test",
type="test",
session_id=test_uuid
)
def test_coerce_session_id_uuid_to_str_with_special_characters_in_string():
"""Test that a string with special characters is preserved."""
special_session_id = "session-id_with.special:chars@123"
response = ChatOutputResponse(
message="test",
type="test",
session_id=special_session_id
)
def test_coerce_session_id_uuid_to_str_with_uuid_version_1():
"""Test UUID version 1 conversion."""
import uuid
test_uuid = uuid.uuid1()
response = ChatOutputResponse(
message="test",
type="test",
session_id=test_uuid
)
def test_coerce_session_id_uuid_to_str_with_uuid_version_4():
"""Test UUID version 4 conversion."""
import uuid
test_uuid = uuid.uuid4()
response = ChatOutputResponse(
message="test",
type="test",
session_id=test_uuid
)
def test_coerce_session_id_uuid_to_str_with_very_long_string():
"""Test that a very long string session_id is preserved."""
long_session_id = "x" * 1000
response = ChatOutputResponse(
message="test",
type="test",
session_id=long_session_id
)
def test_coerce_session_id_uuid_to_str_with_numeric_string():
"""Test that a numeric string session_id remains a string."""
numeric_session_id = "123456789"
response = ChatOutputResponse(
message="test",
type="test",
session_id=numeric_session_id
)
def test_coerce_session_id_uuid_to_str_with_whitespace_string():
"""Test that a string with whitespace is preserved."""
whitespace_session_id = " session id with spaces "
response = ChatOutputResponse(
message="test",
type="test",
session_id=whitespace_session_id
)
def test_coerce_session_id_uuid_to_str_uuid_case_preservation():
"""Test that UUID string representation maintains lowercase."""
test_uuid = UUID('550E8400-E29B-41D4-A716-446655440000')
response = ChatOutputResponse(
message="test",
type="test",
session_id=test_uuid
)
def test_coerce_session_id_uuid_to_str_multiple_instances_with_uuids():
"""Test creating many ChatOutputResponse instances with UUID session_ids."""
import uuid
def test_coerce_session_id_uuid_to_str_multiple_instances_with_strings():
"""Test creating many ChatOutputResponse instances with string session_ids."""
# Create 100 instances with string session_ids
responses = []
for i in range(100):
response = ChatOutputResponse(
message=f"test_{i}",
type="test",
session_id=f"session_{i}"
)
responses.append(response)
for idx, response in enumerate(responses):
pass
def test_coerce_session_id_uuid_to_str_mixed_types_bulk():
"""Test creating many instances with mixed session_id types."""
import uuid
responses = []
# Create instances with mixed types: UUID, string, None
for i in range(100):
if i % 3 == 0:
# Use UUID
session_id = uuid.uuid4()
elif i % 3 == 1:
# Use string
session_id = f"session_{i}"
else:
# Use None
session_id = None
def test_coerce_session_id_uuid_to_str_repeated_same_uuid():
"""Test that the same UUID is consistently converted."""
test_uuid = UUID('550e8400-e29b-41d4-a716-446655440000')
expected_str = '550e8400-e29b-41d4-a716-446655440000'
def test_coerce_session_id_uuid_to_str_performance_with_large_message():
"""Test that session_id coercion works efficiently with large messages."""
import uuid
test_uuid = uuid.uuid4()
large_message = "x" * 10000 # 10KB message
def test_coerce_session_id_uuid_to_str_batch_conversion_correctness():
"""Test batch conversion maintains correctness of each UUID."""
import uuid
codeflash_output is used to check that the output of the original code is the same as that of the optimized code.
To edit these changes
git checkout codeflash/optimize-pr11958-2026-03-01T23.22.11and push.