Skip to content

fix: upgrade dependencies to resolve Dependabot security alerts#1789

Merged
KRRT7 merged 21 commits into
mainfrom
fix-dependabot-vulns
Mar 10, 2026
Merged

fix: upgrade dependencies to resolve Dependabot security alerts#1789
KRRT7 merged 21 commits into
mainfrom
fix-dependabot-vulns

Conversation

@KRRT7

@KRRT7 KRRT7 commented Mar 7, 2026

Copy link
Copy Markdown
Contributor

Summary

  • Upgrade all Python deps via uv sync --upgrade (resolves werkzeug, filelock py>=3.10 alerts)
  • Run npm audit fix across JS test fixtures (resolves minimatch, rollup alerts)

Not fixable

  • filelock (py<3.10): patched version requires Python >=3.10
  • serialize-javascript in mocha: fix requires mocha 11 breaking change

Upgrade Python deps via uv sync --upgrade (werkzeug, filelock for py>=3.10,
and others). Run npm audit fix across JS test fixtures to patch minimatch
and rollup vulnerabilities.

Remaining unfixable:
- filelock <3.20.3 for py<3.10 (patched version requires py>=3.10)
- serialize-javascript in mocha ^10 (fix requires mocha 11 breaking change)
@claude

claude Bot commented Mar 7, 2026

Copy link
Copy Markdown
Contributor

Claude finished @KRRT7's task in 57s —— View job


PR Review Summary

  • Triage PR scope
  • Run lint and type checks
  • Resolve stale review threads
  • Code review
  • Duplicate detection
  • Test coverage
  • Merge optimization PRs

Prek Checks

uv run prek run --from-ref origin/mainall checks passed (ruff check, ruff format).

Mypy: 234 pre-existing errors across 9 files (primarily in codeflash/languages/function_optimizer.py, which was moved unchanged from optimization/function_optimizer.py). None introduced by this PR.


Code Review

This PR combines dependency upgrades for Dependabot alerts with a substantial CLI refactoring. Both are clean.

Dependency/security changes — straightforward: uv sync --upgrade, npm audit fix across JS fixtures. No issues.

Refactoring (cmd_init.py → focused modules):

The 1993-line cmd_init.py was split into:

  • init_config.py — config types, TOML validation, UI helpers
  • init_auth.py — API key + GitHub App setup
  • github_workflow.py — GitHub Actions workflow generation
  • console_constants.pyCODEFLASH_LOGO constant

All import paths updated correctly:

  • belongs_to_function_qualified moved from deleted optimization/function_context.pylanguages/python/context/code_context_extractor.py:1496
  • FunctionOptimizer moved from optimization/function_optimizer.pylanguages/function_optimizer.py
  • oauth_handler.py moved from code_utils/cli_cmds/
  • CODEFLASH_LOGO moved from cmd_init.pyconsole_constants.py, consumed in main.py:139 and tracer.py:203

Deferred imports: Heavy imports (posthog_cf, sentry, cmd_init, tracer_main) moved from module-level to call sites in main.py:31-65, reducing CLI startup from ~600ms to ~250ms. ✅

loop-runner.js fix (packages/codeflash/runtime/loop-runner.js:88-91): Added isInsideScopedDir to allow recursion into packages nested under scoped directories (e.g., node_modules/@jest/core/node_modules/jest-runner). Logic is correct.

apologize_and_exit() cleanup: The old return None # unreachable but satisfies type checker at cmd_init.py:219 was correctly removed since apologize_and_exit() is typed -> NoReturn. ✅


Duplicate Detection

No duplicates detected. DependencyManager enum was in cmd_init.py and is now only in github_workflow.py (where it's used). belongs_to_* functions moved from optimization/function_context.py to code_context_extractor.py — both cleanups reduce duplication rather than adding it.


Test Coverage

2479 passed, 57 skipped, 1 pre-existing failure:

FAILED tests/test_tracer.py::TestTracer::test_tracer_initialization_normal
  assert True is False  (Tracer.disable expected False, got True)

Neither codeflash/tracing/ nor tests/test_tracer.py were touched by this PR. The only tracer change was updating an import path (CODEFLASH_LOGO from cmd_initconsole_constants). This failure is pre-existing and unrelated to this PR.

Per-file coverage for new/changed production files:

File Coverage
console_constants.py 100%
init_config.py 62%
code_context_extractor.py 72%

init_config.py at 62% is lower than the 75% threshold, but this module was refactored out of cmd_init.py (not newly written), so the coverage baseline carries over from the pre-refactoring state.


Optimization PRs

No open PRs from codeflash-ai[bot].


Stale Review Threads

1 unresolved thread from codeflash-ai on code_context_extractor.py:1476 suggesting inlining belongs_to_method for a 46% speedup — suggestion is still applicable. Left open for the author to consider.


Move files closer to their consumers:
- function_context.py merged into code_context_extractor.py
- FunctionOptimizer base class to languages/function_optimizer.py
- test_runner, instrument_codeflash_capture, parse_line_profile to languages/python/
- oauth_handler.py to cli_cmds/

Split cmd_init.py (1993 lines) into focused modules:
- init_config.py: config types, validation, writing, shared UI
- init_auth.py: API key management + GitHub app installation
- github_workflow.py: GitHub Actions workflow generation
- cmd_init.py: init orchestrator + Python setup (639 lines)

Defer heavy imports (cmd_init, posthog, sentry) from module-level to
usage sites, reducing CLI startup from ~600ms to ~250ms. Replace
set_defaults(func=) with direct args.command dispatch in main().
@KRRT7 KRRT7 force-pushed the fix-dependabot-vulns branch from 4c93401 to 7cd1a3e Compare March 7, 2026 09:44
github-actions Bot and others added 2 commits March 7, 2026 09:46
Co-authored-by: Kevin Turcios <undefined@users.noreply.github.com>
The optimization wraps parser construction in `@lru_cache(maxsize=1)` so that the 35+ `add_argument` calls (each costing ~7 µs per profiler data) execute once per process instead of on every invocation of `parse_args`. This cuts parse_args time from 581 ms to 32 ms because ArgumentParser construction dominates the original runtime. The cache is safe because the parser definition is static; parsing different sys.argv values reuses the cached parser object without rebuilding its internal action registry.
@codeflash-ai

codeflash-ai Bot commented Mar 7, 2026

Copy link
Copy Markdown
Contributor

⚡️ Codeflash found optimizations for this PR

📄 38% (0.38x) speedup for parse_args in codeflash/cli_cmds/cli.py

⏱️ Runtime : 843 milliseconds 613 milliseconds (best of 5 runs)

A dependent PR with the suggested changes has been created. Please review:

If you approve, it will be merged into this PR (branch fix-dependabot-vulns).

Static Badge

@codeflash-ai

codeflash-ai Bot commented Mar 7, 2026

Copy link
Copy Markdown
Contributor

⚡️ Codeflash found optimizations for this PR

📄 152% (1.52x) speedup for determine_dependency_manager in codeflash/cli_cmds/github_workflow.py

⏱️ Runtime : 1.79 milliseconds 713 microseconds (best of 191 runs)

A dependent PR with the suggested changes has been created. Please review:

If you approve, it will be merged into this PR (branch fix-dependabot-vulns).

Static Badge

…2026-03-07T09.56.25

⚡️ Speed up function `parse_args` by 38% in PR #1789 (`fix-dependabot-vulns`)
@codeflash-ai

codeflash-ai Bot commented Mar 7, 2026

Copy link
Copy Markdown
Contributor

This PR is now faster! 🚀 @claude[bot] accepted my optimizations from:

@codeflash-ai

codeflash-ai Bot commented Mar 7, 2026

Copy link
Copy Markdown
Contributor

⚡️ Codeflash found optimizations for this PR

📄 122% (1.22x) speedup for get_dependency_manager_installation_string in codeflash/cli_cmds/github_workflow.py

⏱️ Runtime : 1.22 milliseconds 546 microseconds (best of 249 runs)

A dependent PR with the suggested changes has been created. Please review:

If you approve, it will be merged into this PR (branch fix-dependabot-vulns).

Static Badge

The optimization hoisted `Panel` and `Text` imports (from `rich.panel` and `rich.text`) to module scope and created a singleton `_THEME_SINGLETON = CodeflashTheme()` instead of instantiating it on each `inquirer.prompt` call. Line profiler shows that `prompt_api_key` spent ~22% of its runtime on these two imports plus ~11% on `CodeflashTheme().__init__` calls (which invokes `super().__init__()` to configure inquirer theme attributes). By importing once and reusing the theme instance, the optimized code eliminates repeated import overhead (from ~1.9ms down to ~0.0ms for imports) and theme construction overhead (from ~5ms to a one-time ~0.4ms initialization). This reduces the overall runtime from 21.4ms to 17.5ms (22% speedup) when `prompt_api_key` is invoked multiple times by the CLI, with no regressions in correctness or functionality.
@codeflash-ai

codeflash-ai Bot commented Mar 7, 2026

Copy link
Copy Markdown
Contributor

⚡️ Codeflash found optimizations for this PR

📄 22% (0.22x) speedup for prompt_api_key in codeflash/cli_cmds/init_auth.py

⏱️ Runtime : 21.4 milliseconds 17.5 milliseconds (best of 57 runs)

A dependent PR with the suggested changes has been created. Please review:

If you approve, it will be merged into this PR (branch fix-dependabot-vulns).

Static Badge

@codeflash-ai

codeflash-ai Bot commented Mar 7, 2026

Copy link
Copy Markdown
Contributor

⚡️ Codeflash found optimizations for this PR

📄 111% (1.11x) speedup for install_github_app in codeflash/cli_cmds/init_auth.py

⏱️ Runtime : 10.5 milliseconds 4.97 milliseconds (best of 11 runs)

A new Optimization Review has been created.

🔗 Review here

Static Badge

Comment thread codeflash/cli_cmds/init_config.py
The hot function `get_valid_subdirs` replaced `os.walk(...)[1]` (which builds full directory trees) with `os.scandir`, iterating only immediate children and checking `entry.is_dir()` directly. The profiler shows 82% of runtime was in the cached `get_valid_subdirs` call; within that function, `os.walk` was materializing nested structures unnecessarily. Switching `ignore_subdirs` from a list to a set reduced membership tests from O(n) to O(1), and consolidating two `startswith` checks into a single tuple-argument call eliminated redundant method dispatch. Across 34 hits in `get_suggestions`, per-call latency dropped from ~23 µs to ~21.6 µs, yielding a 17% speedup with no correctness regressions.
@codeflash-ai

codeflash-ai Bot commented Mar 7, 2026

Copy link
Copy Markdown
Contributor

⚡️ Codeflash found optimizations for this PR

📄 17% (0.17x) speedup for get_suggestions in codeflash/cli_cmds/init_config.py

⏱️ Runtime : 1.41 milliseconds 1.20 milliseconds (best of 76 runs)

A dependent PR with the suggested changes has been created. Please review:

If you approve, it will be merged into this PR (branch fix-dependabot-vulns).

Static Badge

KRRT7 and others added 2 commits March 7, 2026 08:21
Move files closer to their consumers:
- function_context.py merged into code_context_extractor.py
- FunctionOptimizer base class to languages/function_optimizer.py
- test_runner, instrument_codeflash_capture, parse_line_profile to languages/python/
- oauth_handler.py to cli_cmds/

Split cmd_init.py (1993 lines) into focused modules:
- init_config.py: config types, validation, writing, shared UI
- init_auth.py: API key management + GitHub app installation
- github_workflow.py: GitHub Actions workflow generation
- cmd_init.py: init orchestrator + Python setup (639 lines)

Defer heavy imports (cmd_init, posthog, sentry) from module-level to
usage sites, reducing CLI startup from ~600ms to ~250ms. Replace
set_defaults(func=) with direct args.command dispatch in main().
…2026-03-07T11.26.49

⚡️ Speed up function `prompt_api_key` by 22% in PR #1789 (`fix-dependabot-vulns`)
@codeflash-ai

codeflash-ai Bot commented Mar 7, 2026

Copy link
Copy Markdown
Contributor

This PR is now faster! 🚀 @KRRT7 accepted my optimizations from:

…2026-03-07T11.48.50

⚡️ Speed up function `get_suggestions` by 17% in PR #1789 (`fix-dependabot-vulns`)
@codeflash-ai

codeflash-ai Bot commented Mar 7, 2026

Copy link
Copy Markdown
Contributor

This PR is now faster! 🚀 @KRRT7 accepted my optimizations from:

KRRT7 and others added 4 commits March 7, 2026 08:27
Wrap jedi Name.name comparisons with bool() since jedi's Name.name
property is typed as Any.
- Fix get_suggestions() param type: str -> CommonSections (prevents silent no-match bugs)
- Fix generate_dynamic_workflow_content()/customize_codeflash_yaml_content() config param: tuple -> dict (runtime crash: dict-key access on a tuple)
- Fix get_dependency_installation_commands() return type: tuple[str,str] -> str (runtime crash: tuple passed to str.replace())
- Fix configure_pyproject_toml() else->elif isinstance(CLISetupInfo) for proper type narrowing
- Mark apologize_and_exit() as NoReturn to enable post-call type narrowing
- Remove unreachable return None statements in collect_setup_info()
- Refactor while-loop sentinels in collect_setup_info() to typed local vars
- Add missing type params to list/dict/tuple in LanguageSupport
- Add _get_theme() return type with TYPE_CHECKING import

Co-authored-by: Kevin Turcios <undefined@users.noreply.github.com>
@codeflash-ai

codeflash-ai Bot commented Mar 7, 2026

Copy link
Copy Markdown
Contributor

⚡️ Codeflash found optimizations for this PR

📄 40% (0.40x) speedup for collect_setup_info in codeflash/cli_cmds/cmd_init.py

⏱️ Runtime : 91.2 milliseconds 65.0 milliseconds (best of 26 runs)

A dependent PR with the suggested changes has been created. Please review:

If you approve, it will be merged into this PR (branch fix-dependabot-vulns).

Static Badge

@codeflash-ai

codeflash-ai Bot commented Mar 7, 2026

Copy link
Copy Markdown
Contributor

⚡️ Codeflash found optimizations for this PR

📄 14% (0.14x) speedup for get_dependency_installation_commands in codeflash/cli_cmds/github_workflow.py

⏱️ Runtime : 416 microseconds 365 microseconds (best of 250 runs)

A dependent PR with the suggested changes has been created. Please review:

If you approve, it will be merged into this PR (branch fix-dependabot-vulns).

Static Badge

@codeflash-ai

codeflash-ai Bot commented Mar 7, 2026

Copy link
Copy Markdown
Contributor

⚡️ Codeflash found optimizations for this PR

📄 71% (0.71x) speedup for convert_parents_to_tuple in codeflash/languages/base.py

⏱️ Runtime : 7.83 milliseconds 4.58 milliseconds (best of 78 runs)

A dependent PR with the suggested changes has been created. Please review:

If you approve, it will be merged into this PR (branch fix-dependabot-vulns).

Static Badge

KRRT7 and others added 2 commits March 7, 2026 12:26
The recursive search in loop-runner.js wasn't entering package
directories inside scoped namespaces (e.g. @jest/core), so it couldn't
find jest-runner nested at @jest/core/node_modules/jest-runner.

def belongs_to_method(name: Name, class_name: str, method_name: str) -> bool:
"""Check if the given name belongs to the specified method."""
return belongs_to_function(name, method_name) and belongs_to_class(name, class_name)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚡️Codeflash found 46% (0.46x) speedup for belongs_to_method in codeflash/languages/python/context/code_context_extractor.py

⏱️ Runtime : 297 milliseconds 203 milliseconds (best of 21 runs)

📝 Explanation and details

The optimized belongs_to_method inlines both helper-function checks to traverse the parent chain once instead of twice, eliminating ~10k redundant name.parent() calls (each costing ~28–32 µs per the profiler). The original called belongs_to_function (which walked up to find the function parent) and then belongs_to_class (which restarted from the original name and walked up again to find the class ancestor), resulting in 1.05 seconds total. The inlined version walks up once—validating the immediate function parent, then continuing upward to locate the class—cutting total time to 0.69 seconds. The 45% runtime improvement comes entirely from halving the parent-chain traversal cost, with no change to logic or return values.

Correctness verification report:

Test Status
⚙️ Existing Unit Tests 🔘 None Found
🌀 Generated Regression Tests 10 Passed
⏪ Replay Tests 🔘 None Found
🔎 Concolic Coverage Tests 🔘 None Found
📊 Tests Coverage 100.0%
🌀 Click to see Generated Regression Tests
import pytest
# Import the function under test
from codeflash.languages.python.context.code_context_extractor import (
    belongs_to_class, belongs_to_function, belongs_to_method)
from jedi import Script
from jedi.api.classes import Name

def get_name_at_position(source: str, line: int, column: int) -> Name:
    """
    Create a Name object by inferring at a specific position in source code.
    
    Args:
        source: The Python source code as a string
        line: The line number (1-indexed)
        column: The column number (0-indexed)
    
    Returns:
        A Name object from jedi at the specified position, or None if not found
    """
    script = Script(source)
    names = script.infer(line, column)
    if names:
        return names[0]
    return None

class TestBelongsToMethod:
    """Test suite for the belongs_to_method function."""
    
    def test_very_long_class_name(self):
        """Test with a very long class name."""
        source = '''
class VeryLongClassNameThatIsActuallyQuite ExtremelyLong:
    def my_method(self):
        x = 42
'''
        # Note: This might not parse due to invalid syntax, skip if needed
        try:
            name = get_name_at_position(source, 4, 8)
            if name is not None:
                codeflash_output = belongs_to_method(name, "VeryLongClassNameThatIsActuallyQuite", "my_method"); result = codeflash_output
        except:
            # Skip if source doesn't parse
            pass
    
    def test_method_with_dunder_names(self):
        """Test with dunder method names."""
        source = '''
class MyClass:
    def __str__(self):
        return "test"
'''
        name = get_name_at_position(source, 4, 15)  # Position of "test"
        if name is not None:
            codeflash_output = belongs_to_method(name, "MyClass", "__str__"); result = codeflash_output
    
    def test_many_classes_in_module(self):
        """Test module with many classes."""
        # Generate 50 classes
        classes_code = '\n'.join([f'''
class Class_{i}:
    def my_method(self):
        x = {i}
''' for i in range(50)])
        source = classes_code
        # Test a variable from one of the classes
        try:
            name = get_name_at_position(source, 205, 8)  # Approximate position
            if name is not None:
                codeflash_output = belongs_to_method(name, "Class_24", "my_method"); result = codeflash_output
        except:
            # Skip if calculation is off
            pass
    
    def test_many_parameters_in_method(self):
        """Test method with many parameters."""
        params = ', '.join([f'param_{i}' for i in range(100)])
        source = f'''
class MyClass:
    def my_method(self, {params}):
        x = param_50
'''
        name = get_name_at_position(source, 4, 8)  # Position of 'x'
        if name is not None:
            codeflash_output = belongs_to_method(name, "MyClass", "my_method"); result = codeflash_output

class TestBelongsToFunction:
    """Test suite for the belongs_to_function helper function."""
    
    def test_basic_function_membership(self):
        """Test that a variable inside a function is correctly identified."""
        source = '''
def my_function():
    x = 42
'''
        name = get_name_at_position(source, 3, 4)  # Position of 'x'
        result = belongs_to_function(name, "my_function")
    
    def test_function_definition_not_member(self):
        """Test that the function name itself is not a member."""
        source = '''
def my_function():
    pass
'''
        name = get_name_at_position(source, 2, 4)  # Position of 'my_function' in def
        result = belongs_to_function(name, "my_function")
    
    def test_not_in_different_function(self):
        """Test that variable in one function doesn't belong to another."""
        source = '''
def func_a():
    x = 1

def func_b():
    y = 2
'''
        name = get_name_at_position(source, 3, 4)  # x in func_a
        result = belongs_to_function(name, "func_b")

class TestBelongsToClass:
    """Test suite for the belongs_to_class helper function."""
    
    def test_basic_class_membership(self):
        """Test that a variable inside a class method belongs to the class."""
        source = '''
class MyClass:
    def my_method(self):
        x = 42
'''
        name = get_name_at_position(source, 4, 8)  # Position of 'x'
        result = belongs_to_class(name, "MyClass")
    
    def test_class_definition_not_member(self):
        """Test that class definition doesn't belong to itself."""
        source = '''
class MyClass:
    pass
'''
        name = get_name_at_position(source, 2, 6)  # Position of 'MyClass' in class def
        result = belongs_to_class(name, "MyClass")
    
    def test_not_in_different_class(self):
        """Test variable in one class doesn't belong to another."""
        source = '''
class ClassA:
    x = 1

class ClassB:
    y = 2
'''
        name = get_name_at_position(source, 3, 4)  # x in ClassA
        result = belongs_to_class(name, "ClassB")
# codeflash_output is used to check that the output of the original code is the same as that of the optimized code.

To test or edit this optimization locally git merge codeflash/optimize-pr1789-2026-03-07T19.01.30

Click to see suggested changes
Suggested change
return belongs_to_function(name, method_name) and belongs_to_class(name, class_name)
# Inline the checks from belongs_to_function and belongs_to_class to avoid
# traversing the parent chain twice (one for function check and one for class check).
if name.name == method_name: # Handles function definition and recursive function calls
return False
parent = name.parent()
if not parent or parent.type != "function":
return False
if parent.name != method_name:
return False
# Now walk ancestors once to find the class
p = parent
while p := p.parent():
if p.type == "class":
return bool(p.name == class_name)
return False

Static Badge

@KRRT7 KRRT7 merged commit 055103d into main Mar 10, 2026
25 of 27 checks passed
@KRRT7 KRRT7 deleted the fix-dependabot-vulns branch March 10, 2026 23:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant