Skip to content

Conversation

@codeflash-ai
Copy link
Contributor

@codeflash-ai codeflash-ai bot commented Nov 20, 2025

⚡️ This pull request contains optimizations for PR #928

If you approve this dependent PR, these changes will be merged into the original PR branch feat/cli/login.

This PR will be automatically closed if the original PR is merged.


📄 11% (0.11x) speedup for should_attempt_browser_launch in codeflash/code_utils/oauth_handler.py

⏱️ Runtime : 248 microseconds 224 microseconds (best of 63 runs)

📝 Explanation and details

The optimization achieves a 10% speedup through several targeted micro-optimizations that reduce function call overhead and expensive operations:

Key Performance Improvements:

  1. LRU Cache on expensive browser detection: get_browser_name_fallback() calls webbrowser.get(), which is very expensive (~50ms based on profiler results). Adding @lru_cache(maxsize=1) eliminates repeated calls during the process lifetime.

  2. Set vs List for blocklist: Changed browser_blocklist from a list to a set, making the in operation O(1) instead of O(n). While the list is small (6 items), this still provides measurable improvement.

  3. Local variable caching: Created local references to os.environ and sys.platform to avoid repeated attribute lookups, which are slower than local variable access in Python.

  4. Early exit optimization: Restructured browser environment detection to check BROWSER env var first before falling back to the expensive get_browser_name_fallback(), avoiding the costly call when possible.

  5. Efficient display variable checking: Replaced the any() generator expression with a direct for-loop that can short-circuit on the first match, avoiding unnecessary environment variable lookups.

Impact on Workloads:
Based on the function reference, should_attempt_browser_launch() is called during OAuth signin flows in the CLI. Since authentication is user-initiated and relatively infrequent, the 10% improvement provides a better user experience by making browser launch decisions faster, especially in scenarios where multiple checks might occur or when the expensive browser fallback is avoided.

Test Case Performance:
The optimizations show consistent 10-30% improvements across most test cases, with particularly strong gains (up to 31.6%) in scenarios that benefit from the display variable short-circuiting and local variable optimizations. Only the browser blocklist test shows a slight regression due to set creation overhead, but this is outweighed by the O(1) lookup benefits in real usage.

Correctness verification report:

Test Status
⚙️ Existing Unit Tests 🔘 None Found
🌀 Generated Regression Tests 19 Passed
⏪ Replay Tests 🔘 None Found
🔎 Concolic Coverage Tests 🔘 None Found
📊 Tests Coverage 85.0%
🌀 Generated Regression Tests and Runtime
from __future__ import annotations

import os
import sys

# imports
import pytest

from codeflash.code_utils.oauth_handler import should_attempt_browser_launch

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


def test_default_linux_with_display(monkeypatch):
    """Linux, no special env vars, DISPLAY set: should launch browser."""
    monkeypatch.setattr(sys, "platform", "linux")
    os.environ["DISPLAY"] = ":0"
    codeflash_output = should_attempt_browser_launch()  # 6.08μs -> 5.36μs (13.5% faster)


def test_default_linux_no_display(monkeypatch):
    """Linux, no DISPLAY: should not launch browser."""
    monkeypatch.setattr(sys, "platform", "linux")
    os.environ.pop("DISPLAY", None)
    os.environ.pop("WAYLAND_DISPLAY", None)
    os.environ.pop("MIR_SOCKET", None)
    codeflash_output = should_attempt_browser_launch()  # 4.47μs -> 3.87μs (15.6% faster)


def test_default_windows(monkeypatch):
    """Windows, no special env vars: should launch browser."""
    monkeypatch.setattr(sys, "platform", "win32")
    codeflash_output = should_attempt_browser_launch()  # 5.25μs -> 4.55μs (15.4% faster)


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


@pytest.mark.parametrize("browser_name", ["www-browser", "lynx", "links", "w3m", "elinks", "links2"])
def test_browser_blocklist_env(monkeypatch, browser_name):
    """BROWSER env is blocklisted: should not launch browser."""
    monkeypatch.setattr(sys, "platform", "linux")
    os.environ["DISPLAY"] = ":0"
    os.environ["BROWSER"] = browser_name
    codeflash_output = should_attempt_browser_launch()  # 11.8μs -> 14.6μs (19.4% slower)


def test_browser_blocklist_fallback(monkeypatch):
    """Fallback browser name is blocklisted: should not launch browser."""
    monkeypatch.setattr(sys, "platform", "darwin")
    os.environ.pop("BROWSER", None)
    # Patch get_browser_name_fallback to return a blocklisted name
    monkeypatch.setattr(__name__ + ".get_browser_name_fallback", lambda: "lynx")
    codeflash_output = should_attempt_browser_launch()


def test_ci_env(monkeypatch):
    """CI env set: should not launch browser."""
    monkeypatch.setattr(sys, "platform", "darwin")
    os.environ["CI"] = "true"
    codeflash_output = should_attempt_browser_launch()  # 6.14μs -> 5.49μs (11.9% faster)


def test_debian_frontend_noninteractive(monkeypatch):
    """DEBIAN_FRONTEND=noninteractive: should not launch browser."""
    monkeypatch.setattr(sys, "platform", "linux")
    os.environ["DISPLAY"] = ":0"
    os.environ["DEBIAN_FRONTEND"] = "noninteractive"
    codeflash_output = should_attempt_browser_launch()  # 5.83μs -> 5.13μs (13.7% faster)


def test_ssh_linux_with_display(monkeypatch):
    """Linux SSH session, DISPLAY set: should launch browser."""
    monkeypatch.setattr(sys, "platform", "linux")
    os.environ["SSH_CONNECTION"] = "foo"
    os.environ["DISPLAY"] = ":0"
    codeflash_output = should_attempt_browser_launch()  # 5.74μs -> 5.03μs (14.1% faster)


def test_ssh_linux_no_display(monkeypatch):
    """Linux SSH session, no DISPLAY: should not launch browser."""
    monkeypatch.setattr(sys, "platform", "linux")
    os.environ["SSH_CONNECTION"] = "foo"
    os.environ.pop("DISPLAY", None)
    os.environ.pop("WAYLAND_DISPLAY", None)
    os.environ.pop("MIR_SOCKET", None)
    codeflash_output = should_attempt_browser_launch()  # 4.55μs -> 3.90μs (16.7% faster)


def test_ssh_mac(monkeypatch):
    """MacOS SSH session: should not launch browser."""
    monkeypatch.setattr(sys, "platform", "darwin")
    os.environ["SSH_CONNECTION"] = "foo"
    codeflash_output = should_attempt_browser_launch()  # 5.51μs -> 4.85μs (13.6% faster)


def test_ssh_windows(monkeypatch):
    """Windows SSH session: should not launch browser."""
    monkeypatch.setattr(sys, "platform", "win32")
    os.environ["SSH_CONNECTION"] = "foo"
    codeflash_output = should_attempt_browser_launch()  # 5.51μs -> 4.78μs (15.3% faster)


def test_wayland_display(monkeypatch):
    """Linux, WAYLAND_DISPLAY set: should launch browser."""
    monkeypatch.setattr(sys, "platform", "linux")
    os.environ["WAYLAND_DISPLAY"] = "wayland-0"
    codeflash_output = should_attempt_browser_launch()  # 5.45μs -> 4.74μs (15.0% faster)


def test_mir_socket(monkeypatch):
    """Linux, MIR_SOCKET set: should launch browser."""
    monkeypatch.setattr(sys, "platform", "linux")
    os.environ["MIR_SOCKET"] = "/tmp/mir"
    codeflash_output = should_attempt_browser_launch()  # 5.41μs -> 4.78μs (13.2% faster)


def test_non_linux_display_vars(monkeypatch):
    """macOS, DISPLAY set: should launch browser (DISPLAY ignored)."""
    monkeypatch.setattr(sys, "platform", "darwin")
    os.environ["DISPLAY"] = ":0"
    codeflash_output = should_attempt_browser_launch()  # 5.57μs -> 4.65μs (19.8% faster)


def test_empty_env(monkeypatch):
    """No env vars, non-linux: should launch browser."""
    monkeypatch.setattr(sys, "platform", "win32")
    os.environ.clear()
    codeflash_output = should_attempt_browser_launch()  # 8.53μs -> 7.72μs (10.4% faster)


def test_unknown_platform(monkeypatch):
    """Unknown platform: should launch browser (treated as non-linux)."""
    monkeypatch.setattr(sys, "platform", "unknownos")
    codeflash_output = should_attempt_browser_launch()  # 8.12μs -> 7.18μs (13.1% faster)


def test_linux_display_vars_empty(monkeypatch):
    """Linux, display vars set but empty: should not launch browser."""
    monkeypatch.setattr(sys, "platform", "linux")
    os.environ["DISPLAY"] = ""
    os.environ["WAYLAND_DISPLAY"] = ""
    os.environ["MIR_SOCKET"] = ""
    codeflash_output = should_attempt_browser_launch()  # 10.9μs -> 8.82μs (23.5% faster)


def test_linux_display_vars_partial(monkeypatch):
    """Linux, one display var set, others missing: should launch browser."""
    monkeypatch.setattr(sys, "platform", "linux")
    os.environ["DISPLAY"] = ":1"
    os.environ.pop("WAYLAND_DISPLAY", None)
    os.environ.pop("MIR_SOCKET", None)
    codeflash_output = should_attempt_browser_launch()  # 9.86μs -> 7.49μs (31.6% faster)


def test_linux_display_vars_none(monkeypatch):
    """Linux, no display vars at all: should not launch browser."""
    monkeypatch.setattr(sys, "platform", "linux")
    for v in ["DISPLAY", "WAYLAND_DISPLAY", "MIR_SOCKET"]:
        os.environ.pop(v, None)
    codeflash_output = should_attempt_browser_launch()  # 10.4μs -> 8.47μs (22.8% faster)


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

To edit these changes git checkout codeflash/optimize-pr928-2025-11-20T19.51.06 and push.

Codeflash Static Badge

The optimization achieves a **10% speedup** through several targeted micro-optimizations that reduce function call overhead and expensive operations:

**Key Performance Improvements:**

1. **LRU Cache on expensive browser detection**: `get_browser_name_fallback()` calls `webbrowser.get()`, which is very expensive (~50ms based on profiler results). Adding `@lru_cache(maxsize=1)` eliminates repeated calls during the process lifetime.

2. **Set vs List for blocklist**: Changed `browser_blocklist` from a list to a set, making the `in` operation O(1) instead of O(n). While the list is small (6 items), this still provides measurable improvement.

3. **Local variable caching**: Created local references to `os.environ` and `sys.platform` to avoid repeated attribute lookups, which are slower than local variable access in Python.

4. **Early exit optimization**: Restructured browser environment detection to check `BROWSER` env var first before falling back to the expensive `get_browser_name_fallback()`, avoiding the costly call when possible.

5. **Efficient display variable checking**: Replaced the `any()` generator expression with a direct for-loop that can short-circuit on the first match, avoiding unnecessary environment variable lookups.

**Impact on Workloads:**
Based on the function reference, `should_attempt_browser_launch()` is called during OAuth signin flows in the CLI. Since authentication is user-initiated and relatively infrequent, the 10% improvement provides a better user experience by making browser launch decisions faster, especially in scenarios where multiple checks might occur or when the expensive browser fallback is avoided.

**Test Case Performance:**
The optimizations show consistent 10-30% improvements across most test cases, with particularly strong gains (up to 31.6%) in scenarios that benefit from the display variable short-circuiting and local variable optimizations. Only the browser blocklist test shows a slight regression due to set creation overhead, but this is outweighed by the O(1) lookup benefits in real usage.
@codeflash-ai codeflash-ai bot added ⚡️ codeflash Optimization PR opened by Codeflash AI 🎯 Quality: High Optimization Quality according to Codeflash labels Nov 20, 2025
@codeflash-ai codeflash-ai bot mentioned this pull request Nov 20, 2025
@KRRT7
Copy link
Contributor

KRRT7 commented Nov 20, 2025

there are some good things here but I'm not liking the local pre-bindings @aseembits93

@codeflash-ai codeflash-ai bot deleted the codeflash/optimize-pr928-2025-11-20T19.51.06 branch November 20, 2025 23:44
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 🎯 Quality: High Optimization Quality according to Codeflash

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants