Skip to content

Conversation

@codeflash-ai
Copy link

@codeflash-ai codeflash-ai bot commented Oct 29, 2025

📄 12% (0.12x) speedup for cookie_parser in starlette/requests.py

⏱️ Runtime : 1.70 milliseconds 1.51 milliseconds (best of 129 runs)

📝 Explanation and details

Optimizations Made:

  • Cached http_cookies._unquote and str.strip outside the loop to avoid repeated attribute/method lookups in tight loops.
  • Otherwise preserved all behavior, docstrings, comments, and variable names exactly as required.
    This reduces loop overhead without changing output or side effects.

Correctness verification report:

Test Status
⚙️ Existing Unit Tests 🔘 None Found
🌀 Generated Regression Tests 87 Passed
⏪ Replay Tests 🔘 None Found
🔎 Concolic Coverage Tests 1 Passed
📊 Tests Coverage 100.0%
🌀 Generated Regression Tests and Runtime
from http import cookies as http_cookies

# imports
import pytest  # used for our unit tests
from starlette.requests import cookie_parser

# unit tests

# -------------------
# Basic Test Cases
# -------------------

def test_empty_string_returns_empty_dict():
    # Test that an empty cookie string returns an empty dictionary
    codeflash_output = cookie_parser("") # 1.30μs -> 1.70μs (23.9% slower)

def test_single_cookie_pair():
    # Test a single key=value pair
    codeflash_output = cookie_parser("foo=bar") # 3.00μs -> 2.84μs (5.74% faster)

def test_multiple_cookie_pairs():
    # Test multiple key=value pairs separated by semicolons
    codeflash_output = cookie_parser("foo=bar;baz=qux") # 3.14μs -> 3.23μs (2.79% slower)

def test_spaces_around_pairs():
    # Test that spaces around the key and value are stripped
    codeflash_output = cookie_parser(" foo = bar ; baz = qux ") # 3.23μs -> 3.29μs (1.83% slower)

def test_cookie_with_empty_value():
    # Test a cookie with an empty value
    codeflash_output = cookie_parser("foo=") # 2.13μs -> 2.12μs (0.377% faster)

def test_cookie_with_empty_key():
    # Test a cookie with an empty key (should be allowed, per Mozilla bug)
    codeflash_output = cookie_parser("=bar") # 2.34μs -> 2.40μs (2.54% slower)

def test_cookie_with_no_equals():
    # Test a chunk with no '=' (should be treated as empty key)
    codeflash_output = cookie_parser("bar") # 2.02μs -> 2.02μs (0.099% faster)

def test_cookie_with_quoted_value():
    # Test a cookie with a quoted value (should be unquoted)
    codeflash_output = cookie_parser('foo="bar"') # 3.37μs -> 3.47μs (3.03% slower)

def test_cookie_with_multiple_equals_in_value():
    # Test a cookie with '=' in the value (only the first '=' splits)
    codeflash_output = cookie_parser("foo=bar=baz") # 2.32μs -> 2.30μs (0.914% faster)

def test_cookie_with_trailing_semicolon():
    # Test a cookie string with a trailing semicolon (should ignore empty chunk)
    codeflash_output = cookie_parser("foo=bar;") # 2.74μs -> 2.83μs (2.90% slower)

def test_cookie_with_leading_semicolon():
    # Test a cookie string with a leading semicolon (should ignore empty chunk)
    codeflash_output = cookie_parser(";foo=bar") # 2.67μs -> 2.66μs (0.225% faster)

def test_cookie_with_multiple_empty_chunks():
    # Test a cookie string with multiple empty chunks (should ignore them)
    codeflash_output = cookie_parser("; ;foo=bar;;") # 3.49μs -> 3.42μs (2.08% faster)

def test_cookie_with_duplicate_keys():
    # Test that the last occurrence of a key wins
    codeflash_output = cookie_parser("foo=bar;foo=baz") # 3.02μs -> 2.86μs (5.42% faster)

# -------------------
# Edge Test Cases
# -------------------

def test_cookie_with_only_semicolons():
    # All chunks are empty, should return empty dict
    codeflash_output = cookie_parser(";;;") # 1.63μs -> 1.75μs (6.59% slower)

def test_cookie_with_only_spaces_and_semicolons():
    # All chunks are empty or whitespace, should return empty dict
    codeflash_output = cookie_parser(" ; ; ; ") # 1.66μs -> 1.88μs (11.5% slower)

def test_cookie_with_empty_key_and_value():
    # Should ignore empty key and value
    codeflash_output = cookie_parser("=") # 1.41μs -> 1.61μs (12.5% slower)

def test_cookie_with_empty_key_and_nonempty_value():
    # Should parse as key "" and value "bar"
    codeflash_output = cookie_parser("=bar") # 2.37μs -> 2.36μs (0.296% faster)

def test_cookie_with_nonascii_characters():
    # Should preserve unicode in key and value
    codeflash_output = cookie_parser("ключ=значение;foo=бар") # 4.36μs -> 4.35μs (0.276% faster)

def test_cookie_with_escaped_quotes():
    # Should unquote value, preserving inner quotes
    codeflash_output = cookie_parser('foo="b\\"ar"') # 5.20μs -> 5.27μs (1.29% slower)

def test_cookie_with_whitespace_in_value():
    # Should preserve whitespace inside quoted value
    codeflash_output = cookie_parser('foo="bar baz"') # 2.95μs -> 2.98μs (1.01% slower)

def test_cookie_with_whitespace_in_unquoted_value():
    # Should preserve whitespace in unquoted value
    codeflash_output = cookie_parser('foo=bar baz') # 2.27μs -> 2.27μs (0.132% slower)

def test_cookie_with_special_characters():
    # Should preserve special characters in value
    codeflash_output = cookie_parser('foo=bar!@#$%^&*()_+-=') # 2.19μs -> 2.18μs (0.597% faster)

def test_cookie_with_multiple_equals_and_semicolons():
    # Should parse correctly with multiple '=' and ';'
    codeflash_output = cookie_parser('foo=bar=baz;qux=quux=quuz') # 2.99μs -> 3.00μs (0.134% slower)

def test_cookie_with_empty_chunks_between_pairs():
    # Should ignore empty chunks between pairs
    codeflash_output = cookie_parser('foo=bar;;baz=qux;;;quux=corge') # 4.14μs -> 3.98μs (4.02% faster)

def test_cookie_with_key_only_spaces():
    # Key is only spaces, should be stripped to empty
    codeflash_output = cookie_parser("   =bar") # 2.31μs -> 2.36μs (2.07% slower)

def test_cookie_with_value_only_spaces():
    # Value is only spaces, should be stripped to empty string
    codeflash_output = cookie_parser("foo=   ") # 2.11μs -> 2.17μs (2.63% slower)

def test_cookie_with_key_and_value_only_spaces():
    # Both key and value are spaces, should be ignored
    codeflash_output = cookie_parser("   =   ") # 1.47μs -> 1.62μs (9.21% slower)

def test_cookie_with_duplicate_keys_and_empty_value():
    # Last occurrence wins, even if value is empty
    codeflash_output = cookie_parser("foo=bar;foo=") # 3.27μs -> 3.16μs (3.42% faster)

def test_cookie_with_duplicate_keys_and_empty_key():
    # Last occurrence of empty key wins
    codeflash_output = cookie_parser("=bar;=baz") # 2.99μs -> 2.91μs (2.61% faster)

def test_cookie_with_duplicate_keys_and_empty_value_and_key():
    # Last occurrence of empty key and value is ignored
    codeflash_output = cookie_parser("foo=bar;foo=;foo=") # 3.52μs -> 3.56μs (1.24% slower)

def test_cookie_with_key_value_containing_semicolon():
    # Semicolon in value is not possible, but let's check if value is quoted
    codeflash_output = cookie_parser('foo="bar;baz"') # 3.11μs -> 3.08μs (1.24% faster)

def test_cookie_with_key_containing_equals():
    # '=' in key is not standard, but let's check
    codeflash_output = cookie_parser("foo=bar;ba=z=qux") # 2.90μs -> 2.85μs (1.61% faster)

def test_cookie_with_only_equals_sign():
    # Only '=' should be ignored (empty key and value)
    codeflash_output = cookie_parser("=") # 1.43μs -> 1.57μs (8.80% slower)

def test_cookie_with_mixed_empty_and_nonempty_chunks():
    # Should ignore empty chunks and parse valid pairs
    codeflash_output = cookie_parser(";foo=bar;;baz=qux;") # 3.56μs -> 3.40μs (4.73% faster)

# -------------------
# Large Scale Test Cases
# -------------------

def test_large_number_of_cookies():
    # Test with 1000 cookies to check scalability
    cookie_string = ";".join(f"key{i}=val{i}" for i in range(1000))
    expected = {f"key{i}": f"val{i}" for i in range(1000)}
    codeflash_output = cookie_parser(cookie_string) # 311μs -> 269μs (15.4% faster)

def test_large_number_of_duplicate_keys():
    # Test with 1000 duplicate keys, last one should win
    cookie_string = ";".join(f"foo=val{i}" for i in range(1000))
    codeflash_output = cookie_parser(cookie_string) # 296μs -> 256μs (15.6% faster)

def test_large_cookie_values():
    # Test with a very large value
    large_val = "x" * 1000
    codeflash_output = cookie_parser(f"foo={large_val}") # 2.77μs -> 2.80μs (0.964% slower)

def test_large_cookie_keys():
    # Test with a very large key
    large_key = "k" * 1000
    codeflash_output = cookie_parser(f"{large_key}=bar") # 3.56μs -> 3.63μs (1.79% slower)

def test_large_cookie_with_quoted_value():
    # Test with a large quoted value
    large_val = "y" * 1000
    codeflash_output = cookie_parser(f'foo="{large_val}"') # 4.27μs -> 4.24μs (0.802% faster)

def test_large_cookie_with_mixed_content():
    # Test with a mix of empty, normal, and large cookies
    parts = ["foo=bar", "", "baz=qux", "x=" + "y" * 500, "   =   ", "a=b"]
    cookie_string = ";".join(parts)
    expected = {"foo": "bar", "baz": "qux", "x": "y" * 500, "a": "b"}
    codeflash_output = cookie_parser(cookie_string) # 5.40μs -> 5.30μs (1.96% faster)

def test_large_cookie_with_unicode():
    # Test a large cookie with unicode characters
    unicode_val = "ü" * 500
    codeflash_output = cookie_parser(f"foo={unicode_val}") # 3.13μs -> 3.15μs (0.698% slower)
# codeflash_output is used to check that the output of the original code is the same as that of the optimized code.
#------------------------------------------------
from http import cookies as http_cookies

# imports
import pytest  # used for our unit tests
from starlette.requests import cookie_parser

# unit tests

# -----------------------
# BASIC TEST CASES
# -----------------------

def test_single_cookie():
    # Basic: One cookie, standard format
    codeflash_output = cookie_parser("foo=bar") # 2.42μs -> 2.35μs (3.28% faster)

def test_multiple_cookies():
    # Basic: Multiple cookies, standard format
    codeflash_output = cookie_parser("foo=bar;baz=qux") # 2.98μs -> 3.02μs (1.49% slower)

def test_spaces_around_delimiters():
    # Basic: Spaces around delimiters should be stripped
    codeflash_output = cookie_parser(" foo = bar ; baz = qux ") # 3.23μs -> 3.21μs (0.311% faster)

def test_empty_string():
    # Basic: Empty string should produce empty dict
    codeflash_output = cookie_parser("") # 1.11μs -> 1.38μs (19.1% slower)

def test_trailing_semicolon():
    # Basic: Trailing semicolon should be ignored
    codeflash_output = cookie_parser("foo=bar;") # 2.73μs -> 2.75μs (0.582% slower)

def test_leading_semicolon():
    # Basic: Leading semicolon should be ignored
    codeflash_output = cookie_parser(";foo=bar") # 2.62μs -> 2.54μs (3.03% faster)

def test_cookie_with_empty_value():
    # Basic: Cookie with empty value
    codeflash_output = cookie_parser("foo=") # 2.06μs -> 2.14μs (3.64% slower)

def test_cookie_with_empty_key():
    # Basic: Cookie with empty key (should be allowed)
    codeflash_output = cookie_parser("=bar") # 2.29μs -> 2.30μs (0.348% slower)

def test_cookie_with_empty_key_and_value():
    # Basic: Cookie with both empty key and value
    codeflash_output = cookie_parser("=") # 1.39μs -> 1.57μs (11.3% slower)

def test_cookie_with_no_equals():
    # Basic: Cookie chunk with no equals (should be key "" and value chunk)
    codeflash_output = cookie_parser("bar") # 2.06μs -> 2.02μs (1.63% faster)

def test_cookie_with_no_equals_and_spaces():
    # Basic: Cookie chunk with no equals and spaces
    codeflash_output = cookie_parser("  bar  ") # 2.05μs -> 2.14μs (4.25% slower)

def test_cookie_with_multiple_equals():
    # Basic: Only the first equals should split key/value
    codeflash_output = cookie_parser("foo=bar=baz") # 2.32μs -> 2.48μs (6.58% slower)

def test_cookie_with_url_encoded_value():
    # Basic: Value is quoted (should be unquoted)
    codeflash_output = cookie_parser('foo="bar%20baz"') # 3.31μs -> 3.33μs (0.720% slower)

def test_cookie_with_quoted_value():
    # Basic: Value is quoted (should be unquoted)
    codeflash_output = cookie_parser('foo="bar baz"') # 3.04μs -> 2.96μs (2.46% faster)

def test_cookie_with_escaped_quotes():
    # Basic: Value with escaped quotes
    codeflash_output = cookie_parser('foo="bar\\"baz"') # 4.76μs -> 4.78μs (0.439% slower)

def test_cookie_with_empty_chunks():
    # Basic: Empty chunks should be ignored
    codeflash_output = cookie_parser("foo=bar;;baz=qux") # 3.40μs -> 3.35μs (1.49% faster)

# -----------------------
# EDGE TEST CASES
# -----------------------

def test_cookie_with_only_spaces():
    # Edge: Only spaces should produce empty dict
    codeflash_output = cookie_parser("   ") # 1.21μs -> 1.48μs (18.1% slower)

def test_cookie_with_semicolons_only():
    # Edge: Only semicolons should produce empty dict
    codeflash_output = cookie_parser(";;;") # 1.69μs -> 1.80μs (6.39% slower)

def test_cookie_with_key_only():
    # Edge: Key only, no equals, should be key "" and value "foo"
    codeflash_output = cookie_parser("foo") # 2.08μs -> 2.06μs (0.825% faster)

def test_cookie_with_value_only_and_spaces():
    # Edge: Chunk with only value and spaces
    codeflash_output = cookie_parser("   bar   ") # 2.05μs -> 2.10μs (2.61% slower)

def test_cookie_with_duplicate_keys():
    # Edge: Duplicate keys, last one should win
    codeflash_output = cookie_parser("foo=bar;foo=baz") # 3.19μs -> 3.10μs (2.81% faster)

def test_cookie_with_unicode_characters():
    # Edge: Unicode characters in key and value
    codeflash_output = cookie_parser("føø=bår;baz=qux") # 3.80μs -> 3.75μs (1.41% faster)

def test_cookie_with_special_characters():
    # Edge: Special characters in key and value
    codeflash_output = cookie_parser("foo=bar!@#;baz=$%^") # 2.85μs -> 2.93μs (2.66% slower)

def test_cookie_with_control_characters():
    # Edge: Control characters in value (should be preserved)
    codeflash_output = cookie_parser("foo=bar\nbaz") # 2.13μs -> 2.14μs (0.467% slower)

def test_cookie_with_long_key_and_value():
    # Edge: Very long key and value
    long_key = "k" * 100
    long_val = "v" * 100
    codeflash_output = cookie_parser(f"{long_key}={long_val}") # 2.34μs -> 2.47μs (5.35% slower)

def test_cookie_with_empty_chunks_and_spaces():
    # Edge: Mix of empty chunks and spaces
    codeflash_output = cookie_parser(" ; ;foo=bar; ;baz=qux; ; ") # 3.85μs -> 3.79μs (1.58% faster)

def test_cookie_with_equals_in_value():
    # Edge: Value contains equals signs
    codeflash_output = cookie_parser("foo=bar=baz=qux") # 2.11μs -> 2.15μs (2.09% slower)

def test_cookie_with_key_and_value_with_spaces():
    # Edge: Key and value have spaces inside
    codeflash_output = cookie_parser("foo bar=baz qux") # 2.17μs -> 2.21μs (1.99% slower)

def test_cookie_with_key_and_value_with_semicolons_inside_quotes():
    # Edge: Semicolons inside quoted value should not split
    codeflash_output = cookie_parser('foo="bar;baz";qux=quux') # 3.61μs -> 3.60μs (0.222% faster)

def test_cookie_with_key_and_value_with_equals_inside_quotes():
    # Edge: Equals inside quoted value should not split
    codeflash_output = cookie_parser('foo="bar=baz";qux=quux') # 3.93μs -> 3.88μs (1.37% faster)

def test_cookie_with_key_and_value_with_leading_and_trailing_quotes():
    # Edge: Value with leading/trailing quotes
    codeflash_output = cookie_parser('foo="bar"') # 2.90μs -> 2.82μs (2.87% faster)

def test_cookie_with_key_and_value_with_mismatched_quotes():
    # Edge: Value with mismatched quotes (should not unquote)
    codeflash_output = cookie_parser('foo="bar') # 2.22μs -> 2.28μs (2.50% slower)

def test_cookie_with_key_and_value_with_empty_quotes():
    # Edge: Value is empty quotes
    codeflash_output = cookie_parser('foo=""') # 2.88μs -> 2.83μs (1.73% faster)

def test_cookie_with_key_and_value_with_escaped_semicolon():
    # Edge: Value with escaped semicolon (should not split)
    codeflash_output = cookie_parser(r'foo="bar\;baz";qux=quux') # 3.59μs -> 3.55μs (1.27% faster)

def test_cookie_with_key_and_value_with_escaped_equals():
    # Edge: Value with escaped equals (should not split)
    codeflash_output = cookie_parser(r'foo="bar\=baz";qux=quux') # 5.58μs -> 5.49μs (1.51% faster)

def test_cookie_with_key_and_value_with_empty_key_and_spaces():
    # Edge: Key is empty and value has spaces
    codeflash_output = cookie_parser("=   bar   ") # 2.43μs -> 2.42μs (0.289% faster)

# -----------------------
# LARGE SCALE TEST CASES
# -----------------------

def test_large_number_of_cookies():
    # Large: 1000 cookies, keys and values are unique
    cookies = ";".join(f"key{i}=val{i}" for i in range(1000))
    expected = {f"key{i}": f"val{i}" for i in range(1000)}
    codeflash_output = cookie_parser(cookies) # 311μs -> 270μs (15.2% faster)

def test_large_cookie_string_with_long_values():
    # Large: 100 cookies, each value is 100 chars
    cookies = ";".join(f"key{i}={'v'*100}" for i in range(100))
    expected = {f"key{i}": "v"*100 for i in range(100)}
    codeflash_output = cookie_parser(cookies) # 39.5μs -> 35.8μs (10.3% faster)

def test_large_cookie_string_with_long_keys():
    # Large: 100 cookies, each key is 100 chars
    cookies = ";".join(f"{'k'*100}{i}=val{i}" for i in range(100))
    expected = {f"{'k'*100}{i}": f"val{i}" for i in range(100)}
    codeflash_output = cookie_parser(cookies) # 46.3μs -> 43.2μs (7.34% faster)

def test_large_cookie_string_with_spaces_and_empty_chunks():
    # Large: 500 cookies, with spaces and empty chunks mixed in
    cookies = " ; ".join(f"key{i}=val{i}" for i in range(500))
    cookies = f" ; ; {cookies} ; ; "
    expected = {f"key{i}": f"val{i}" for i in range(500)}
    codeflash_output = cookie_parser(cookies) # 172μs -> 150μs (15.1% faster)

def test_large_cookie_string_with_duplicates():
    # Large: 100 cookies, each duplicated, last wins
    cookies = ";".join(f"key{i}=val{i};key{i}=newval{i}" for i in range(100))
    expected = {f"key{i}": f"newval{i}" for i in range(100)}
    codeflash_output = cookie_parser(cookies) # 69.3μs -> 60.5μs (14.5% faster)

def test_large_cookie_string_with_mixed_formats():
    # Large: 100 cookies, some with equals, some without, some quoted
    cookies = []
    expected = {}
    for i in range(100):
        if i % 3 == 0:
            cookies.append(f"key{i}=val{i}")
            expected[f"key{i}"] = f"val{i}"
        elif i % 3 == 1:
            cookies.append(f'"key{i}"="val{i}"')
            expected[f'"key{i}"'] = f"val{i}"
        else:
            cookies.append(f"val{i}")
            expected[""] = f"val{i}"  # last one wins for key ""
    cookie_str = ";".join(cookies)
    codeflash_output = cookie_parser(cookie_str) # 40.7μs -> 36.8μs (10.6% faster)

def test_large_cookie_string_with_unicode():
    # Large: 100 cookies, unicode keys and values
    cookies = ";".join(f"ключ{i}=значение{i}" for i in range(100))
    expected = {f"ключ{i}": f"значение{i}" for i in range(100)}
    codeflash_output = cookie_parser(cookies) # 43.0μs -> 39.9μs (7.63% faster)

def test_large_cookie_string_with_special_characters():
    # Large: 100 cookies, special characters in values
    cookies = ";".join(f"key{i}=!@#{i}$%^&*()" for i in range(100))
    expected = {f"key{i}": f"!@#{i}$%^&*()" for i in range(100)}
    codeflash_output = cookie_parser(cookies) # 36.7μs -> 32.5μs (13.2% faster)

def test_large_cookie_string_with_long_empty_chunks():
    # Large: 100 cookies, with many empty chunks between
    cookies = ";;;;".join(f"key{i}=val{i}" for i in range(100))
    expected = {f"key{i}": f"val{i}" for i in range(100)}
    codeflash_output = cookie_parser(cookies) # 59.9μs -> 52.7μs (13.6% faster)

def test_large_cookie_string_with_long_quoted_values():
    # Large: 100 cookies, quoted values with spaces and special chars
    cookies = ";".join(f'key{i}="val {i} !@# $%^&*()"' for i in range(100))
    expected = {f"key{i}": f"val {i} !@# $%^&*()" for i in range(100)}
    codeflash_output = cookie_parser(cookies) # 55.2μs -> 50.8μs (8.70% faster)
# codeflash_output is used to check that the output of the original code is the same as that of the optimized code.
#------------------------------------------------
from starlette.requests import cookie_parser

def test_cookie_parser():
    cookie_parser('=;\x00')
🔎 Concolic Coverage Tests and Runtime
Test File::Test Function Original ⏱️ Optimized ⏱️ Speedup
codeflash_concolic_b9ikc1l3/tmpgg5_6czg/test_concolic_coverage.py::test_cookie_parser 2.58μs 2.67μs -3.26%⚠️

To edit these changes git checkout codeflash/optimize-cookie_parser-mhccerjp and push.

Codeflash

**Optimizations Made:**
- Cached `http_cookies._unquote` and `str.strip` outside the loop to avoid repeated attribute/method lookups in tight loops.
- Otherwise preserved all behavior, docstrings, comments, and variable names exactly as required.  
This reduces loop overhead without changing output or side effects.
@codeflash-ai codeflash-ai bot requested a review from mashraf-222 October 29, 2025 18:42
@codeflash-ai codeflash-ai bot added the ⚡️ codeflash Optimization PR opened by Codeflash AI label Oct 29, 2025
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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant