From 72d9a9eafcebb2f4bf06cf1575ac3d8f8d69ea53 Mon Sep 17 00:00:00 2001 From: Sarthak Agarwal Date: Thu, 29 Jan 2026 21:39:07 +0530 Subject: [PATCH 1/7] remove ignored linting issues --- codeflash/api/aiservice.py | 8 +-- codeflash/api/cfapi.py | 6 +- codeflash/benchmarking/codeflash_trace.py | 2 +- .../instrument_codeflash_trace.py | 2 +- codeflash/benchmarking/plugin/plugin.py | 12 ++-- codeflash/cli_cmds/cli_common.py | 2 +- codeflash/cli_cmds/cmd_init.py | 14 ++--- codeflash/code_utils/code_extractor.py | 60 +++++++++---------- codeflash/code_utils/code_replacer.py | 12 ++-- codeflash/code_utils/code_utils.py | 2 +- .../code_utils/codeflash_wrap_decorator.py | 6 +- codeflash/code_utils/concolic_utils.py | 2 +- codeflash/code_utils/config_consts.py | 2 +- codeflash/code_utils/config_parser.py | 3 +- codeflash/code_utils/deduplicate_code.py | 30 +++++----- codeflash/code_utils/env_utils.py | 2 +- codeflash/code_utils/formatter.py | 14 ++--- .../code_utils/instrument_existing_tests.py | 11 ++-- codeflash/code_utils/line_profile_utils.py | 10 ++-- codeflash/code_utils/oauth_handler.py | 2 +- codeflash/code_utils/shell_utils.py | 6 +- codeflash/code_utils/version_check.py | 2 +- codeflash/context/code_context_extractor.py | 20 +++---- .../context/unused_definition_remover.py | 10 ++-- codeflash/discovery/functions_to_optimize.py | 6 +- codeflash/lsp/beta.py | 2 +- .../lsp/features/perform_optimization.py | 2 +- codeflash/lsp/helpers.py | 2 +- codeflash/lsp/lsp_logger.py | 6 +- codeflash/lsp/lsp_message.py | 2 +- codeflash/optimization/function_context.py | 2 +- codeflash/optimization/function_optimizer.py | 4 +- codeflash/picklepatch/pickle_patcher.py | 17 ++---- codeflash/picklepatch/pickle_placeholder.py | 6 +- codeflash/telemetry/posthog_cf.py | 2 +- codeflash/telemetry/sentry.py | 2 +- codeflash/tracing/profile_stats.py | 2 +- codeflash/tracing/tracing_new_process.py | 10 ++-- codeflash/tracing/tracing_utils.py | 2 +- codeflash/verification/codeflash_capture.py | 2 +- codeflash/verification/comparator.py | 14 ++--- .../instrument_codeflash_capture.py | 14 +---- codeflash/verification/pytest_plugin.py | 8 +-- codeflash/verification/test_runner.py | 4 +- codeflash/verification/verifier.py | 2 +- pyproject.toml | 15 ++++- 46 files changed, 172 insertions(+), 194 deletions(-) diff --git a/codeflash/api/aiservice.py b/codeflash/api/aiservice.py index 4ef96b308..f4a775a0d 100644 --- a/codeflash/api/aiservice.py +++ b/codeflash/api/aiservice.py @@ -253,7 +253,7 @@ def optimize_python_code_line_profiler( # noqa: D417 line_profiler_results: str, n_candidates: int, experiment_metadata: ExperimentMetadata | None = None, - is_numerical_code: bool | None = None, # noqa: FBT001 + is_numerical_code: bool | None = None, ) -> list[OptimizedCandidate]: """Optimize the given python code for performance using line profiler results. @@ -646,7 +646,7 @@ def generate_regression_tests( # noqa: D417 test_timeout: int, trace_id: str, test_index: int, - is_numerical_code: bool | None = None, # noqa: FBT001 + is_numerical_code: bool | None = None, ) -> tuple[str, str, str] | None: """Generate regression tests for the given function by making a request to the Django endpoint. @@ -706,7 +706,7 @@ def generate_regression_tests( # noqa: D417 error = response.json()["error"] logger.error(f"Error generating tests: {response.status_code} - {error}") ph("cli-testgen-error-response", {"response_status_code": response.status_code, "error": error}) - return None # noqa: TRY300 + return None except Exception: logger.error(f"Error generating tests: {response.status_code} - {response.text}") ph("cli-testgen-error-response", {"response_status_code": response.status_code, "error": response.text}) @@ -722,7 +722,7 @@ def get_optimization_review( function_trace_id: str, coverage_message: str, replay_tests: str, - concolic_tests: str, # noqa: ARG002 + concolic_tests: str, calling_fn_details: str, ) -> OptimizationReviewResult: """Compute the optimization review of current Pull Request. diff --git a/codeflash/api/cfapi.py b/codeflash/api/cfapi.py index 37edcf793..f8ce2309c 100644 --- a/codeflash/api/cfapi.py +++ b/codeflash/api/cfapi.py @@ -81,7 +81,7 @@ def make_cfapi_request( else: response = requests.get(url, headers=cfapi_headers, params=params, timeout=60) response.raise_for_status() - return response # noqa: TRY300 + return response except requests.exceptions.HTTPError: # response may be either a string or JSON, so we handle both cases error_message = "" @@ -102,7 +102,7 @@ def make_cfapi_request( @lru_cache(maxsize=1) -def get_user_id(api_key: Optional[str] = None) -> Optional[str]: # noqa: PLR0911 +def get_user_id(api_key: Optional[str] = None) -> Optional[str]: """Retrieve the user's userid by making a request to the /cfapi/cli-get-user endpoint. :param api_key: The API key to use. If None, uses get_codeflash_api_key(). @@ -376,7 +376,7 @@ def get_blocklisted_functions() -> dict[str, set[str]] | dict[str, Any]: def is_function_being_optimized_again( owner: str, repo: str, pr_number: int, code_contexts: list[dict[str, str]] -) -> Any: # noqa: ANN401 +) -> Any: """Check if the function being optimized is being optimized again.""" response = make_cfapi_request( "/is-already-optimized", diff --git a/codeflash/benchmarking/codeflash_trace.py b/codeflash/benchmarking/codeflash_trace.py index d2ad4279e..6b60af7d2 100644 --- a/codeflash/benchmarking/codeflash_trace.py +++ b/codeflash/benchmarking/codeflash_trace.py @@ -108,7 +108,7 @@ def __call__(self, func: Callable) -> Callable: func_id = (func.__module__, func.__name__) @functools.wraps(func) - def wrapper(*args, **kwargs) -> Any: # noqa: ANN002, ANN003, ANN401 + def wrapper(*args, **kwargs) -> Any: # noqa: ANN002, ANN003 # Initialize thread-local active functions set if it doesn't exist if not hasattr(self._thread_local, "active_functions"): self._thread_local.active_functions = set() diff --git a/codeflash/benchmarking/instrument_codeflash_trace.py b/codeflash/benchmarking/instrument_codeflash_trace.py index 40a9a0390..bc779dd9c 100644 --- a/codeflash/benchmarking/instrument_codeflash_trace.py +++ b/codeflash/benchmarking/instrument_codeflash_trace.py @@ -53,7 +53,7 @@ def leave_FunctionDef(self, original_node: FunctionDef, updated_node: FunctionDe return updated_node - def leave_Module(self, original_node: cst.Module, updated_node: cst.Module) -> cst.Module: # noqa: ARG002 + def leave_Module(self, original_node: cst.Module, updated_node: cst.Module) -> cst.Module: # Create import statement for codeflash_trace if not self.added_codeflash_trace: return updated_node diff --git a/codeflash/benchmarking/plugin/plugin.py b/codeflash/benchmarking/plugin/plugin.py index 58053bc4f..4789279da 100644 --- a/codeflash/benchmarking/plugin/plugin.py +++ b/codeflash/benchmarking/plugin/plugin.py @@ -110,7 +110,7 @@ def get_function_benchmark_timings(trace_path: Path) -> dict[str, dict[Benchmark # Process each row for row in cursor.fetchall(): - module_name, class_name, function_name, benchmark_file, benchmark_func, benchmark_line, time_ns = row + module_name, class_name, function_name, benchmark_file, benchmark_func, _benchmark_line, time_ns = row # Create the function key (module_name.class_name.function_name) if class_name: @@ -172,7 +172,7 @@ def get_benchmark_timings(trace_path: Path) -> dict[BenchmarkKey, int]: # Process overhead information for row in cursor.fetchall(): - benchmark_file, benchmark_func, benchmark_line, total_overhead_ns = row + benchmark_file, benchmark_func, _benchmark_line, total_overhead_ns = row benchmark_key = BenchmarkKey(module_path=benchmark_file, function_name=benchmark_func) overhead_by_benchmark[benchmark_key] = total_overhead_ns or 0 # Handle NULL sum case @@ -184,7 +184,7 @@ def get_benchmark_timings(trace_path: Path) -> dict[BenchmarkKey, int]: # Process each row and subtract overhead for row in cursor.fetchall(): - benchmark_file, benchmark_func, benchmark_line, time_ns = row + benchmark_file, benchmark_func, _benchmark_line, time_ns = row # Create the benchmark key (file::function::line) benchmark_key = BenchmarkKey(module_path=benchmark_file, function_name=benchmark_func) @@ -200,7 +200,7 @@ def get_benchmark_timings(trace_path: Path) -> dict[BenchmarkKey, int]: # Pytest hooks @pytest.hookimpl - def pytest_sessionfinish(self, session, exitstatus) -> None: # noqa: ANN001, ARG002 + def pytest_sessionfinish(self, session, exitstatus) -> None: """Execute after whole test run is completed.""" # Write any remaining benchmark timings to the database codeflash_trace.close() @@ -236,7 +236,7 @@ class Benchmark: # noqa: D106 def __init__(self, request: pytest.FixtureRequest) -> None: self.request = request - def __call__(self, func, *args, **kwargs): # type: ignore # noqa: ANN001, ANN002, ANN003, ANN204, PGH003 + def __call__(self, func, *args, **kwargs): # type: ignore # noqa: ANN002, ANN003, ANN204, PGH003 """Handle both direct function calls and decorator usage.""" if args or kwargs: # Used as benchmark(func, *args, **kwargs) @@ -249,7 +249,7 @@ def wrapped_func(*args, **kwargs): # noqa: ANN002, ANN003, ANN202 self._run_benchmark(func) return wrapped_func - def _run_benchmark(self, func, *args, **kwargs): # noqa: ANN001, ANN002, ANN003, ANN202 + def _run_benchmark(self, func, *args, **kwargs): # noqa: ANN002, ANN003, ANN202 """Actual benchmark implementation.""" node_path = getattr(self.request.node, "path", None) or getattr(self.request.node, "fspath", None) if node_path is None: diff --git a/codeflash/cli_cmds/cli_common.py b/codeflash/cli_cmds/cli_common.py index 8e203c766..b8f04ec6e 100644 --- a/codeflash/cli_cmds/cli_common.py +++ b/codeflash/cli_cmds/cli_common.py @@ -43,7 +43,7 @@ def inquirer_wrapper(func: Callable[..., str | bool], *args: str | bool, **kwarg return func(*new_args, **new_kwargs) -def split_string_to_cli_width(string: str, is_confirm: bool = False) -> list[str]: # noqa: FBT001, FBT002 +def split_string_to_cli_width(string: str, is_confirm: bool = False) -> list[str]: cli_width, _ = shutil.get_terminal_size() # split string to lines that accommodate "[?] " prefix cli_width -= len("[?] ") diff --git a/codeflash/cli_cmds/cmd_init.py b/codeflash/cli_cmds/cmd_init.py index c1960a7cc..83df1c54e 100644 --- a/codeflash/cli_cmds/cmd_init.py +++ b/codeflash/cli_cmds/cmd_init.py @@ -663,7 +663,7 @@ def create_empty_pyproject_toml(pyproject_toml_path: Path) -> None: apologize_and_exit() -def install_github_actions(override_formatter_check: bool = False) -> None: # noqa: FBT001, FBT002 +def install_github_actions(override_formatter_check: bool = False) -> None: try: config, _config_file_path = parse_config_file(override_formatter_check=override_formatter_check) @@ -1089,7 +1089,7 @@ def install_github_actions(override_formatter_check: bool = False) -> None: # n apologize_and_exit() -def determine_dependency_manager(pyproject_data: dict[str, Any]) -> DependencyManager: # noqa: PLR0911 +def determine_dependency_manager(pyproject_data: dict[str, Any]) -> DependencyManager: """Determine which dependency manager is being used based on pyproject.toml contents.""" if (Path.cwd() / "poetry.lock").exists(): return DependencyManager.POETRY @@ -1251,10 +1251,7 @@ def collect_repo_files_for_workflow(git_root: Path) -> dict[str, Any]: def generate_dynamic_workflow_content( - optimize_yml_content: str, - config: tuple[dict[str, Any], Path], - git_root: Path, - benchmark_mode: bool = False, # noqa: FBT001, FBT002 + optimize_yml_content: str, config: tuple[dict[str, Any], Path], git_root: Path, benchmark_mode: bool = False ) -> str: """Generate workflow content with dynamic steps from AI service, falling back to static template. @@ -1378,10 +1375,7 @@ def generate_dynamic_workflow_content( def customize_codeflash_yaml_content( - optimize_yml_content: str, - config: tuple[dict[str, Any], Path], - git_root: Path, - benchmark_mode: bool = False, # noqa: FBT001, FBT002 + optimize_yml_content: str, config: tuple[dict[str, Any], Path], git_root: Path, benchmark_mode: bool = False ) -> str: module_path = str(Path(config["module_root"]).relative_to(git_root) / "**") optimize_yml_content = optimize_yml_content.replace("{{ codeflash_module_path }}", module_path) diff --git a/codeflash/code_utils/code_extractor.py b/codeflash/code_utils/code_extractor.py index 66dfd5eb4..4c6c8952e 100644 --- a/codeflash/code_utils/code_extractor.py +++ b/codeflash/code_utils/code_extractor.py @@ -36,28 +36,28 @@ def __init__(self) -> None: self.scope_depth = 0 self.if_else_depth = 0 - def visit_FunctionDef(self, node: cst.FunctionDef) -> Optional[bool]: # noqa: ARG002 + def visit_FunctionDef(self, node: cst.FunctionDef) -> Optional[bool]: self.scope_depth += 1 return True - def leave_FunctionDef(self, original_node: cst.FunctionDef) -> None: # noqa: ARG002 + def leave_FunctionDef(self, original_node: cst.FunctionDef) -> None: self.scope_depth -= 1 - def visit_ClassDef(self, node: cst.ClassDef) -> Optional[bool]: # noqa: ARG002 + def visit_ClassDef(self, node: cst.ClassDef) -> Optional[bool]: self.scope_depth += 1 return True - def leave_ClassDef(self, original_node: cst.ClassDef) -> None: # noqa: ARG002 + def leave_ClassDef(self, original_node: cst.ClassDef) -> None: self.scope_depth -= 1 - def visit_If(self, node: cst.If) -> Optional[bool]: # noqa: ARG002 + def visit_If(self, node: cst.If) -> Optional[bool]: self.if_else_depth += 1 return True - def leave_If(self, original_node: cst.If) -> None: # noqa: ARG002 + def leave_If(self, original_node: cst.If) -> None: self.if_else_depth -= 1 - def visit_Else(self, node: cst.Else) -> Optional[bool]: # noqa: ARG002 + def visit_Else(self, node: cst.Else) -> Optional[bool]: # Else blocks are already counted as part of the if statement return True @@ -111,24 +111,24 @@ def __init__(self, new_assignments: dict[str, cst.Assign], new_assignment_order: self.scope_depth = 0 self.if_else_depth = 0 - def visit_FunctionDef(self, node: cst.FunctionDef) -> None: # noqa: ARG002 + def visit_FunctionDef(self, node: cst.FunctionDef) -> None: self.scope_depth += 1 - def leave_FunctionDef(self, original_node: cst.FunctionDef, updated_node: cst.FunctionDef) -> cst.FunctionDef: # noqa: ARG002 + def leave_FunctionDef(self, original_node: cst.FunctionDef, updated_node: cst.FunctionDef) -> cst.FunctionDef: self.scope_depth -= 1 return updated_node - def visit_ClassDef(self, node: cst.ClassDef) -> None: # noqa: ARG002 + def visit_ClassDef(self, node: cst.ClassDef) -> None: self.scope_depth += 1 - def leave_ClassDef(self, original_node: cst.ClassDef, updated_node: cst.ClassDef) -> cst.ClassDef: # noqa: ARG002 + def leave_ClassDef(self, original_node: cst.ClassDef, updated_node: cst.ClassDef) -> cst.ClassDef: self.scope_depth -= 1 return updated_node - def visit_If(self, node: cst.If) -> None: # noqa: ARG002 + def visit_If(self, node: cst.If) -> None: self.if_else_depth += 1 - def leave_If(self, original_node: cst.If, updated_node: cst.If) -> cst.If: # noqa: ARG002 + def leave_If(self, original_node: cst.If, updated_node: cst.If) -> cst.If: self.if_else_depth -= 1 return updated_node @@ -150,7 +150,7 @@ def leave_Assign(self, original_node: cst.Assign, updated_node: cst.Assign) -> c return updated_node - def leave_Module(self, original_node: cst.Module, updated_node: cst.Module) -> cst.Module: # noqa: ARG002 + def leave_Module(self, original_node: cst.Module, updated_node: cst.Module) -> cst.Module: # Add any new assignments that weren't in the original file new_statements = list(updated_node.body) @@ -194,20 +194,20 @@ def __init__(self) -> None: self.global_statements = [] self.in_function_or_class = False - def visit_ClassDef(self, node: cst.ClassDef) -> bool: # noqa: ARG002 + def visit_ClassDef(self, node: cst.ClassDef) -> bool: # Don't visit inside classes self.in_function_or_class = True return False - def leave_ClassDef(self, original_node: cst.ClassDef) -> None: # noqa: ARG002 + def leave_ClassDef(self, original_node: cst.ClassDef) -> None: self.in_function_or_class = False - def visit_FunctionDef(self, node: cst.FunctionDef) -> bool: # noqa: ARG002 + def visit_FunctionDef(self, node: cst.FunctionDef) -> bool: # Don't visit inside functions self.in_function_or_class = True return False - def leave_FunctionDef(self, original_node: cst.FunctionDef) -> None: # noqa: ARG002 + def leave_FunctionDef(self, original_node: cst.FunctionDef) -> None: self.in_function_or_class = False def visit_SimpleStatementLine(self, node: cst.SimpleStatementLine) -> None: @@ -288,16 +288,16 @@ def visit_Module(self, node: cst.Module) -> None: self.depth = 0 self._collect_imports_from_block(node) - def visit_FunctionDef(self, node: cst.FunctionDef) -> None: # noqa: ARG002 + def visit_FunctionDef(self, node: cst.FunctionDef) -> None: self.depth += 1 - def leave_FunctionDef(self, node: cst.FunctionDef) -> None: # noqa: ARG002 + def leave_FunctionDef(self, node: cst.FunctionDef) -> None: self.depth -= 1 - def visit_ClassDef(self, node: cst.ClassDef) -> None: # noqa: ARG002 + def visit_ClassDef(self, node: cst.ClassDef) -> None: self.depth += 1 - def leave_ClassDef(self, node: cst.ClassDef) -> None: # noqa: ARG002 + def leave_ClassDef(self, node: cst.ClassDef) -> None: self.depth -= 1 def visit_If(self, node: cst.If) -> None: @@ -320,9 +320,7 @@ def __init__(self, global_statements: list[cst.SimpleStatementLine], last_import self.inserted = False def leave_SimpleStatementLine( - self, - original_node: cst.SimpleStatementLine, # noqa: ARG002 - updated_node: cst.SimpleStatementLine, + self, original_node: cst.SimpleStatementLine, updated_node: cst.SimpleStatementLine ) -> cst.Module: self.current_line += 1 @@ -333,7 +331,7 @@ def leave_SimpleStatementLine( return cst.Module(body=[updated_node]) - def leave_Module(self, original_node: cst.Module, updated_node: cst.Module) -> cst.Module: # noqa: ARG002 + def leave_Module(self, original_node: cst.Module, updated_node: cst.Module) -> cst.Module: # If there were no imports, add at the beginning of the module if self.last_import_line == 0 and not self.inserted: updated_body = list(updated_node.body) @@ -361,9 +359,7 @@ def find_last_import_line(target_code: str) -> int: class FutureAliasedImportTransformer(cst.CSTTransformer): def leave_ImportFrom( - self, - original_node: cst.ImportFrom, # noqa: ARG002 - updated_node: cst.ImportFrom, + self, original_node: cst.ImportFrom, updated_node: cst.ImportFrom ) -> cst.BaseSmallStatement | cst.FlattenSentinel[cst.BaseSmallStatement] | cst.RemovalSentinel: import libcst.matchers as m @@ -484,7 +480,7 @@ def resolve_star_import(module_name: str, project_root: Path) -> set[str]: if not name.startswith("_"): public_names.add(name) - return public_names # noqa: TRY300 + return public_names except Exception as e: logger.warning(f"Error resolving star import for {module_name}: {e}") @@ -973,7 +969,7 @@ def _is_target_function_call(self, node: ast.Call) -> bool: return False - def _get_call_name(self, func_node) -> Optional[str]: # noqa: ANN001 + def _get_call_name(self, func_node) -> Optional[str]: """Extract the name being called from a function node.""" # Fast path short-circuit for ast.Name nodes if isinstance(func_node, ast.Name): @@ -1363,7 +1359,7 @@ def is_numerical_code(code_string: str, function_name: str | None = None) -> boo # If numba is not installed and all modules used require numba for optimization, # return False since we can't optimize this code - if not has_numba and modules_used.issubset(NUMBA_REQUIRED_MODULES): # noqa : SIM103 + if not has_numba and modules_used.issubset(NUMBA_REQUIRED_MODULES): return False return True diff --git a/codeflash/code_utils/code_replacer.py b/codeflash/code_utils/code_replacer.py index 3b838eb8a..bb3f21522 100644 --- a/codeflash/code_utils/code_replacer.py +++ b/codeflash/code_utils/code_replacer.py @@ -109,7 +109,7 @@ def visit_Module(self, node: cst.Module) -> None: if isinstance(import_alias, cst.ImportAlias) and import_alias.name.value == "pytest": self.has_pytest_import = True - def leave_Module(self, original_node: cst.Module, updated_node: cst.Module) -> cst.Module: # noqa: ARG002 + def leave_Module(self, original_node: cst.Module, updated_node: cst.Module) -> cst.Module: """Add pytest import if not present.""" if not self.has_pytest_import: # Create import statement @@ -118,7 +118,7 @@ def leave_Module(self, original_node: cst.Module, updated_node: cst.Module) -> c updated_node = updated_node.with_changes(body=[import_stmt, *updated_node.body]) return updated_node - def leave_FunctionDef(self, original_node: cst.FunctionDef, updated_node: cst.FunctionDef) -> cst.FunctionDef: # noqa: ARG002 + def leave_FunctionDef(self, original_node: cst.FunctionDef, updated_node: cst.FunctionDef) -> cst.FunctionDef: """Add pytest mark to test functions.""" # Check if the mark already exists for decorator in updated_node.decorators: @@ -291,7 +291,7 @@ def visit_ClassDef(self, node: cst.ClassDef) -> bool: return True - def leave_ClassDef(self, node: cst.ClassDef) -> None: # noqa: ARG002 + def leave_ClassDef(self, node: cst.ClassDef) -> None: if self.current_class: self.current_class = None @@ -315,7 +315,7 @@ def __init__( ) self.current_class = None - def visit_FunctionDef(self, node: cst.FunctionDef) -> bool: # noqa: ARG002 + def visit_FunctionDef(self, node: cst.FunctionDef) -> bool: return False def leave_FunctionDef(self, original_node: cst.FunctionDef, updated_node: cst.FunctionDef) -> cst.FunctionDef: @@ -344,7 +344,7 @@ def leave_ClassDef(self, original_node: cst.ClassDef, updated_node: cst.ClassDef ) return updated_node - def leave_Module(self, original_node: cst.Module, updated_node: cst.Module) -> cst.Module: # noqa: ARG002 + def leave_Module(self, original_node: cst.Module, updated_node: cst.Module) -> cst.Module: node = updated_node max_function_index = None max_class_index = None @@ -440,7 +440,7 @@ def replace_function_definitions_in_module( module_abspath: Path, preexisting_objects: set[tuple[str, tuple[FunctionParent, ...]]], project_root_path: Path, - should_add_global_assignments: bool = True, # noqa: FBT001, FBT002 + should_add_global_assignments: bool = True, ) -> bool: source_code: str = module_abspath.read_text(encoding="utf8") code_to_apply = get_optimized_code_for_module(module_abspath.relative_to(project_root_path), optimized_code) diff --git a/codeflash/code_utils/code_utils.py b/codeflash/code_utils/code_utils.py index 693e1b882..bc23e844e 100644 --- a/codeflash/code_utils/code_utils.py +++ b/codeflash/code_utils/code_utils.py @@ -166,7 +166,7 @@ def filter_args(addopts_args: list[str]) -> list[str]: return filtered_args -def modify_addopts(config_file: Path) -> tuple[str, bool]: # noqa : PLR0911 +def modify_addopts(config_file: Path) -> tuple[str, bool]: file_type = config_file.suffix.lower() filename = config_file.name config = None diff --git a/codeflash/code_utils/codeflash_wrap_decorator.py b/codeflash/code_utils/codeflash_wrap_decorator.py index 535a0b723..a6b6d339f 100644 --- a/codeflash/code_utils/codeflash_wrap_decorator.py +++ b/codeflash/code_utils/codeflash_wrap_decorator.py @@ -46,7 +46,7 @@ def extract_test_context_from_env() -> tuple[str, str | None, str]: def codeflash_behavior_async(func: F) -> F: @wraps(func) - async def async_wrapper(*args: Any, **kwargs: Any) -> Any: # noqa: ANN401 + async def async_wrapper(*args: Any, **kwargs: Any) -> Any: loop = asyncio.get_running_loop() function_name = func.__name__ line_id = os.environ["CODEFLASH_CURRENT_LINE_ID"] @@ -122,7 +122,7 @@ async def async_wrapper(*args: Any, **kwargs: Any) -> Any: # noqa: ANN401 def codeflash_performance_async(func: F) -> F: @wraps(func) - async def async_wrapper(*args: Any, **kwargs: Any) -> Any: # noqa: ANN401 + async def async_wrapper(*args: Any, **kwargs: Any) -> Any: loop = asyncio.get_running_loop() function_name = func.__name__ line_id = os.environ["CODEFLASH_CURRENT_LINE_ID"] @@ -172,7 +172,7 @@ def codeflash_concurrency_async(func: F) -> F: """Measures concurrent vs sequential execution performance for async functions.""" @wraps(func) - async def async_wrapper(*args: Any, **kwargs: Any) -> Any: # noqa: ANN401 + async def async_wrapper(*args: Any, **kwargs: Any) -> Any: function_name = func.__name__ concurrency_factor = int(os.environ.get("CODEFLASH_CONCURRENCY_FACTOR", "10")) diff --git a/codeflash/code_utils/concolic_utils.py b/codeflash/code_utils/concolic_utils.py index db597d251..aab9a431f 100644 --- a/codeflash/code_utils/concolic_utils.py +++ b/codeflash/code_utils/concolic_utils.py @@ -71,7 +71,7 @@ def _transform_assert_line(self, line: str) -> Optional[str]: unittest_match = self.unittest_re.match(line) if unittest_match: - indent, assert_method, args = unittest_match.groups() + indent, _assert_method, args = unittest_match.groups() if args: arg_parts = self._first_top_level_arg(args) diff --git a/codeflash/code_utils/config_consts.py b/codeflash/code_utils/config_consts.py index e9c919012..e344fad8a 100644 --- a/codeflash/code_utils/config_consts.py +++ b/codeflash/code_utils/config_consts.py @@ -91,7 +91,7 @@ class EffortKeys(str, Enum): } -def get_effort_value(key: EffortKeys, effort: Union[EffortLevel, str]) -> Any: # noqa: ANN401 +def get_effort_value(key: EffortKeys, effort: Union[EffortLevel, str]) -> Any: key_str = key.value if isinstance(effort, str): diff --git a/codeflash/code_utils/config_parser.py b/codeflash/code_utils/config_parser.py index 96d50fb01..a4e3a1f4d 100644 --- a/codeflash/code_utils/config_parser.py +++ b/codeflash/code_utils/config_parser.py @@ -84,8 +84,7 @@ def find_conftest_files(test_paths: list[Path]) -> list[Path]: def parse_config_file( - config_file_path: Path | None = None, - override_formatter_check: bool = False, # noqa: FBT001, FBT002 + config_file_path: Path | None = None, override_formatter_check: bool = False ) -> tuple[dict[str, Any], Path]: config_file_path = find_pyproject_toml(config_file_path) try: diff --git a/codeflash/code_utils/deduplicate_code.py b/codeflash/code_utils/deduplicate_code.py index 35a4a29ff..59b32f272 100644 --- a/codeflash/code_utils/deduplicate_code.py +++ b/codeflash/code_utils/deduplicate_code.py @@ -50,33 +50,33 @@ def get_normalized_name(self, name: str) -> str: self.var_counter += 1 return self.var_mapping[name] - def visit_Import(self, node): # noqa : ANN001, ANN201 + def visit_Import(self, node): # noqa: ANN201 """Track imported names.""" for alias in node.names: name = alias.asname if alias.asname else alias.name self.imports.add(name.split(".")[0]) return node - def visit_ImportFrom(self, node): # noqa : ANN001, ANN201 + def visit_ImportFrom(self, node): # noqa: ANN201 """Track imported names from modules.""" for alias in node.names: name = alias.asname if alias.asname else alias.name self.imports.add(name) return node - def visit_Global(self, node): # noqa : ANN001, ANN201 + def visit_Global(self, node): # noqa: ANN201 """Track global variable declarations.""" # Avoid repeated .add calls by using set.update with list self.global_vars.update(node.names) return node - def visit_Nonlocal(self, node): # noqa : ANN001, ANN201 + def visit_Nonlocal(self, node): # noqa: ANN201 """Track nonlocal variable declarations.""" # Using set.update for batch insertion (faster than add-in-loop) self.nonlocal_vars.update(node.names) return node - def visit_FunctionDef(self, node): # noqa : ANN001, ANN201 + def visit_FunctionDef(self, node): # noqa: ANN201 """Process function but keep function name and parameters unchanged.""" self.enter_scope() @@ -95,18 +95,18 @@ def visit_FunctionDef(self, node): # noqa : ANN001, ANN201 self.exit_scope() return node - def visit_AsyncFunctionDef(self, node): # noqa : ANN001, ANN201 + def visit_AsyncFunctionDef(self, node): # noqa: ANN201 """Handle async functions same as regular functions.""" return self.visit_FunctionDef(node) - def visit_ClassDef(self, node): # noqa : ANN001, ANN201 + def visit_ClassDef(self, node): # noqa: ANN201 """Process class but keep class name unchanged.""" self.enter_scope() node = self.generic_visit(node) self.exit_scope() return node - def visit_Name(self, node): # noqa : ANN001, ANN201 + def visit_Name(self, node): # noqa: ANN201 """Normalize variable names in Name nodes.""" if isinstance(node.ctx, (ast.Store, ast.Del)): # For assignments and deletions, check if we should normalize @@ -118,19 +118,19 @@ def visit_Name(self, node): # noqa : ANN001, ANN201 and node.id not in self.nonlocal_vars ): node.id = self.get_normalized_name(node.id) - elif isinstance(node.ctx, ast.Load): # noqa : SIM102 + elif isinstance(node.ctx, ast.Load): # For loading, use existing mapping if available if node.id in self.var_mapping: node.id = self.var_mapping[node.id] return node - def visit_ExceptHandler(self, node): # noqa : ANN001, ANN201 + def visit_ExceptHandler(self, node): # noqa: ANN201 """Normalize exception variable names.""" if node.name: node.name = self.get_normalized_name(node.name) return self.generic_visit(node) - def visit_comprehension(self, node): # noqa : ANN001, ANN201 + def visit_comprehension(self, node): # noqa: ANN201 """Normalize comprehension target variables.""" # Create new scope for comprehension old_mapping = dict(self.var_mapping) @@ -144,17 +144,17 @@ def visit_comprehension(self, node): # noqa : ANN001, ANN201 self.var_counter = old_counter return node - def visit_For(self, node): # noqa : ANN001, ANN201 + def visit_For(self, node): # noqa: ANN201 """Handle for loop target variables.""" # The target in a for loop is a local variable that should be normalized return self.generic_visit(node) - def visit_With(self, node): # noqa : ANN001, ANN201 + def visit_With(self, node): # noqa: ANN201 """Handle with statement as variables.""" return self.generic_visit(node) -def normalize_code(code: str, remove_docstrings: bool = True, return_ast_dump: bool = False) -> str: # noqa : FBT002, FBT001 +def normalize_code(code: str, remove_docstrings: bool = True, return_ast_dump: bool = False) -> str: """Normalize Python code by parsing, cleaning, and normalizing only variable names. Function names, class names, and parameters are preserved. @@ -193,7 +193,7 @@ def normalize_code(code: str, remove_docstrings: bool = True, return_ast_dump: b raise ValueError(msg) from e -def remove_docstrings_from_ast(node): # noqa : ANN001, ANN201 +def remove_docstrings_from_ast(node): # noqa: ANN201 """Remove docstrings from AST nodes.""" # Only FunctionDef, AsyncFunctionDef, ClassDef, and Module can contain docstrings in their body[0] node_types = (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Module) diff --git a/codeflash/code_utils/env_utils.py b/codeflash/code_utils/env_utils.py index 76621327c..b29eaf031 100644 --- a/codeflash/code_utils/env_utils.py +++ b/codeflash/code_utils/env_utils.py @@ -16,7 +16,7 @@ from codeflash.lsp.helpers import is_LSP_enabled -def check_formatter_installed(formatter_cmds: list[str], exit_on_failure: bool = True) -> bool: # noqa +def check_formatter_installed(formatter_cmds: list[str], exit_on_failure: bool = True) -> bool: if not formatter_cmds or formatter_cmds[0] == "disabled": return True first_cmd = formatter_cmds[0] diff --git a/codeflash/code_utils/formatter.py b/codeflash/code_utils/formatter.py index c64b316fc..f9a38a217 100644 --- a/codeflash/code_utils/formatter.py +++ b/codeflash/code_utils/formatter.py @@ -40,11 +40,7 @@ def split_lines(text: str) -> list[str]: def apply_formatter_cmds( - cmds: list[str], - path: Path, - test_dir_str: Optional[str], - print_status: bool, # noqa - exit_on_failure: bool = True, # noqa + cmds: list[str], path: Path, test_dir_str: Optional[str], print_status: bool, exit_on_failure: bool = True ) -> tuple[Path, str, bool]: if not path.exists(): msg = f"File {path} does not exist. Cannot apply formatter commands." @@ -111,9 +107,9 @@ def format_code( formatter_cmds: list[str], path: Union[str, Path], optimized_code: str = "", - check_diff: bool = False, # noqa - print_status: bool = True, # noqa - exit_on_failure: bool = True, # noqa + check_diff: bool = False, + print_status: bool = True, + exit_on_failure: bool = True, ) -> str: if is_LSP_enabled(): exit_on_failure = False @@ -174,7 +170,7 @@ def format_code( return formatted_code -def sort_imports(code: str, **kwargs: Any) -> str: # noqa : ANN401 +def sort_imports(code: str, **kwargs: Any) -> str: try: # Deduplicate and sort imports, modify the code in memory, not on disk sorted_code = isort.code(code, **kwargs) diff --git a/codeflash/code_utils/instrument_existing_tests.py b/codeflash/code_utils/instrument_existing_tests.py index 94c5cd068..31d340086 100644 --- a/codeflash/code_utils/instrument_existing_tests.py +++ b/codeflash/code_utils/instrument_existing_tests.py @@ -89,7 +89,7 @@ def find_and_update_line_node( # it's much more efficient to visit nodes manually. We'll only descend into expressions/statements. # Helper for manual walk - def iter_ast_calls(node): # noqa: ANN202, ANN001 + def iter_ast_calls(node): # noqa: ANN202 # Generator to yield each ast.Call in test_node, preserves node identity stack = [node] while stack: @@ -690,7 +690,7 @@ def detect_frameworks_from_code(code: str) -> dict[str, str]: frameworks["tensorflow"] = alias.asname if alias.asname else module_name elif module_name == "jax": frameworks["jax"] = alias.asname if alias.asname else module_name - elif isinstance(node, ast.ImportFrom): # noqa: SIM102 + elif isinstance(node, ast.ImportFrom): if node.module: module_name = node.module.split(".")[0] if module_name == "torch" and "torch" not in frameworks: @@ -910,8 +910,7 @@ def _create_device_sync_precompute_statements(used_frameworks: dict[str, str] | def _create_device_sync_statements( - used_frameworks: dict[str, str] | None, - for_return_value: bool = False, # noqa: FBT001, FBT002 + used_frameworks: dict[str, str] | None, for_return_value: bool = False ) -> list[ast.stmt]: """Create AST statements for device synchronization using pre-computed conditions. @@ -1450,7 +1449,7 @@ def visit_ClassDef(self, node: cst.ClassDef) -> None: # Track when we enter a class self.context_stack.append(node.name.value) - def leave_ClassDef(self, original_node: cst.ClassDef, updated_node: cst.ClassDef) -> cst.ClassDef: # noqa: ARG002 + def leave_ClassDef(self, original_node: cst.ClassDef, updated_node: cst.ClassDef) -> cst.ClassDef: # Pop the context when we leave a class self.context_stack.pop() return updated_node @@ -1530,7 +1529,7 @@ def visit_ImportFrom(self, node: cst.ImportFrom) -> None: if import_alias.name.value == decorator_name: self.has_import = True - def leave_Module(self, original_node: cst.Module, updated_node: cst.Module) -> cst.Module: # noqa: ARG002 + def leave_Module(self, original_node: cst.Module, updated_node: cst.Module) -> cst.Module: # If the import is already there, don't add it again if self.has_import: return updated_node diff --git a/codeflash/code_utils/line_profile_utils.py b/codeflash/code_utils/line_profile_utils.py index dc7bae316..93997b2c6 100644 --- a/codeflash/code_utils/line_profile_utils.py +++ b/codeflash/code_utils/line_profile_utils.py @@ -204,7 +204,7 @@ def visit_ClassDef(self, node: cst.ClassDef) -> None: # Track when we enter a class self.context_stack.append(node.name.value) - def leave_ClassDef(self, original_node: cst.ClassDef, updated_node: cst.ClassDef) -> cst.ClassDef: # noqa: ARG002 + def leave_ClassDef(self, original_node: cst.ClassDef, updated_node: cst.ClassDef) -> cst.ClassDef: # Pop the context when we leave a class self.context_stack.pop() return updated_node @@ -268,7 +268,7 @@ def leave_ImportFrom(self, original_node: cst.ImportFrom, updated_node: cst.Impo return updated_node - def leave_Module(self, original_node: cst.Module, updated_node: cst.Module) -> cst.Module: # noqa: ARG002 + def leave_Module(self, original_node: cst.Module, updated_node: cst.Module) -> cst.Module: if not self.found_import: return updated_node @@ -332,11 +332,11 @@ def add_profile_enable(original_code: str, line_profile_output_file: str) -> str class ImportAdder(cst.CSTTransformer): - def __init__(self, import_statement) -> None: # noqa: ANN001 + def __init__(self, import_statement) -> None: self.import_statement = import_statement self.has_import = False - def leave_Module(self, original_node, updated_node): # noqa: ANN001, ANN201, ARG002 + def leave_Module(self, original_node, updated_node): # noqa: ANN201 # If the import is already there, don't add it again if self.has_import: return updated_node @@ -347,7 +347,7 @@ def leave_Module(self, original_node, updated_node): # noqa: ANN001, ANN201, AR # Add the import to the module's body return updated_node.with_changes(body=[import_node, *list(updated_node.body)]) - def visit_ImportFrom(self, node) -> None: # noqa: ANN001 + def visit_ImportFrom(self, node) -> None: # Check if the profile is already imported from line_profiler if node.module and node.module.value == "line_profiler": for import_alias in node.names: diff --git a/codeflash/code_utils/oauth_handler.py b/codeflash/code_utils/oauth_handler.py index 65e9f1341..eff0a3bd6 100644 --- a/codeflash/code_utils/oauth_handler.py +++ b/codeflash/code_utils/oauth_handler.py @@ -702,7 +702,7 @@ def _wait_for_manual_code_input(oauth: OAuthHandler) -> None: if not oauth.is_complete: oauth.manual_code = code.strip() oauth.is_complete = True - except Exception: # noqa: S110 + except Exception: pass diff --git a/codeflash/code_utils/shell_utils.py b/codeflash/code_utils/shell_utils.py index ee4dfb5df..df2cff2d6 100644 --- a/codeflash/code_utils/shell_utils.py +++ b/codeflash/code_utils/shell_utils.py @@ -242,9 +242,9 @@ def get_cross_platform_subprocess_run_args( cwd: Path | str | None = None, env: Mapping[str, str] | None = None, timeout: Optional[float] = None, - check: bool = False, # noqa: FBT001, FBT002 - text: bool = True, # noqa: FBT001, FBT002 - capture_output: bool = True, # noqa: FBT001, FBT002 (only for non-Windows) + check: bool = False, + text: bool = True, + capture_output: bool = True, ) -> dict[str, str]: run_args = {"cwd": cwd, "env": env, "text": text, "timeout": timeout, "check": check} if sys.platform == "win32": diff --git a/codeflash/code_utils/version_check.py b/codeflash/code_utils/version_check.py index 1c1bda200..95fd3c023 100644 --- a/codeflash/code_utils/version_check.py +++ b/codeflash/code_utils/version_check.py @@ -39,7 +39,7 @@ def get_latest_version_from_pypi() -> str | None: return latest_version logger.debug(f"Failed to fetch version from PyPI: {response.status_code}") - return None # noqa: TRY300 + return None except requests.RequestException as e: logger.debug(f"Network error fetching version from PyPI: {e}") return None diff --git a/codeflash/context/code_context_extractor.py b/codeflash/context/code_context_extractor.py index 164440f9b..ac8171056 100644 --- a/codeflash/context/code_context_extractor.py +++ b/codeflash/context/code_context_extractor.py @@ -63,7 +63,7 @@ def get_code_optimization_context( qualified_names.update({f"{qn.rsplit('.', 1)[0]}.__init__" for qn in qualified_names if "." in qn}) # Get FunctionSource representation of helpers of helpers of FTO - helpers_of_helpers_dict, helpers_of_helpers_list = get_function_sources_from_jedi( + helpers_of_helpers_dict, _helpers_of_helpers_list = get_function_sources_from_jedi( helpers_of_fto_qualified_names_dict, project_root_path ) @@ -188,7 +188,7 @@ def extract_code_string_context_from_files( helpers_of_fto: dict[Path, set[FunctionSource]], helpers_of_helpers: dict[Path, set[FunctionSource]], project_root_path: Path, - remove_docstrings: bool = False, # noqa: FBT001, FBT002 + remove_docstrings: bool = False, code_context_type: CodeContextType = CodeContextType.READ_ONLY, ) -> CodeString: """Extract code context from files containing target functions and their helpers. @@ -296,7 +296,7 @@ def extract_code_markdown_context_from_files( helpers_of_fto: dict[Path, set[FunctionSource]], helpers_of_helpers: dict[Path, set[FunctionSource]], project_root_path: Path, - remove_docstrings: bool = False, # noqa: FBT001, FBT002 + remove_docstrings: bool = False, code_context_type: CodeContextType = CodeContextType.READ_ONLY, ) -> CodeStringsMarkdown: """Extract code context from files containing target functions and their helpers, formatting them as markdown. @@ -684,7 +684,7 @@ def parse_code_and_prune_cst( code_context_type: CodeContextType, target_functions: set[str], helpers_of_helper_functions: set[str] = set(), # noqa: B006 - remove_docstrings: bool = False, # noqa: FBT001, FBT002 + remove_docstrings: bool = False, ) -> str: """Create a read-only version of the code by parsing and filtering the code to keep only class contextual information, and other module scoped variables.""" module = cst.parse_module(code) @@ -715,7 +715,7 @@ def parse_code_and_prune_cst( return "" -def prune_cst_for_read_writable_code( # noqa: PLR0911 +def prune_cst_for_read_writable_code( node: cst.CSTNode, target_functions: set[str], defs_with_usages: dict[str, UsageInfo], prefix: str = "" ) -> tuple[cst.CSTNode | None, bool]: """Recursively filter the node and its children to build the read-writable codeblock. This contains nodes that lead to target functions. @@ -814,7 +814,7 @@ def prune_cst_for_read_writable_code( # noqa: PLR0911 return (node.with_changes(**updates) if updates else node), True -def prune_cst_for_code_hashing( # noqa: PLR0911 +def prune_cst_for_code_hashing( node: cst.CSTNode, target_functions: set[str], prefix: str = "" ) -> tuple[cst.CSTNode | None, bool]: """Recursively filter the node and its children to build the read-writable codeblock. This contains nodes that lead to target functions. @@ -903,12 +903,12 @@ def prune_cst_for_code_hashing( # noqa: PLR0911 return (node.with_changes(**updates) if updates else node), True -def prune_cst_for_read_only_code( # noqa: PLR0911 +def prune_cst_for_read_only_code( node: cst.CSTNode, target_functions: set[str], helpers_of_helper_functions: set[str], prefix: str = "", - remove_docstrings: bool = False, # noqa: FBT001, FBT002 + remove_docstrings: bool = False, ) -> tuple[cst.CSTNode | None, bool]: """Recursively filter the node for read-only context. @@ -1008,12 +1008,12 @@ def prune_cst_for_read_only_code( # noqa: PLR0911 return None, False -def prune_cst_for_testgen_code( # noqa: PLR0911 +def prune_cst_for_testgen_code( node: cst.CSTNode, target_functions: set[str], helpers_of_helper_functions: set[str], prefix: str = "", - remove_docstrings: bool = False, # noqa: FBT001, FBT002 + remove_docstrings: bool = False, ) -> tuple[cst.CSTNode | None, bool]: """Recursively filter the node for testgen context. diff --git a/codeflash/context/unused_definition_remover.py b/codeflash/context/unused_definition_remover.py index 823cb735b..a68d276c2 100644 --- a/codeflash/context/unused_definition_remover.py +++ b/codeflash/context/unused_definition_remover.py @@ -208,7 +208,7 @@ def _extract_names_from_annotation(self, node: cst.CSTNode) -> None: self._extract_names_from_annotation(node.value) # No need to check the attribute name itself as it's likely not a top-level definition - def leave_FunctionDef(self, original_node: cst.FunctionDef) -> None: # noqa: ARG002 + def leave_FunctionDef(self, original_node: cst.FunctionDef) -> None: self.function_depth -= 1 if self.function_depth == 0 and self.class_depth == 0: @@ -237,7 +237,7 @@ def visit_ClassDef(self, node: cst.ClassDef) -> None: self.class_depth += 1 - def leave_ClassDef(self, original_node: cst.ClassDef) -> None: # noqa: ARG002 + def leave_ClassDef(self, original_node: cst.ClassDef) -> None: self.class_depth -= 1 if self.class_depth == 0: @@ -260,7 +260,7 @@ def visit_Assign(self, node: cst.Assign) -> None: # Use the first tracked name as the current top-level name (for dependency tracking) self.current_top_level_name = tracked_names[0] - def leave_Assign(self, original_node: cst.Assign) -> None: # noqa: ARG002 + def leave_Assign(self, original_node: cst.Assign) -> None: if self.processing_variable: self.processing_variable = False self.current_variable_names.clear() @@ -363,7 +363,7 @@ def mark_as_used_recursively(self, name: str) -> None: self.mark_as_used_recursively(dep) -def remove_unused_definitions_recursively( # noqa: PLR0911 +def remove_unused_definitions_recursively( node: cst.CSTNode, definitions: dict[str, UsageInfo] ) -> tuple[cst.CSTNode | None, bool]: """Recursively filter the node to remove unused definitions. @@ -546,7 +546,7 @@ def remove_unused_definitions_by_function_names(code: str, qualified_function_na # Apply the recursive removal transformation modified_module, _ = remove_unused_definitions_recursively(module, defs_with_usages) - return modified_module.code if modified_module else "" # noqa: TRY300 + return modified_module.code if modified_module else "" except Exception as e: # If any other error occurs during processing, return the original code logger.debug(f"Error processing code to remove unused definitions: {type(e).__name__}: {e}") diff --git a/codeflash/discovery/functions_to_optimize.py b/codeflash/discovery/functions_to_optimize.py index 7e980f906..368cbd470 100644 --- a/codeflash/discovery/functions_to_optimize.py +++ b/codeflash/discovery/functions_to_optimize.py @@ -59,7 +59,7 @@ def __init__(self) -> None: super().__init__() self.has_return_statement: bool = False - def visit_Return(self, node: cst.Return) -> None: # noqa: ARG002 + def visit_Return(self, node: cst.Return) -> None: self.has_return_statement = True @@ -251,7 +251,7 @@ def get_functions_to_optimize( return filtered_modified_functions, functions_count, trace_file_path -def get_functions_within_git_diff(uncommitted_changes: bool) -> dict[str, list[FunctionToOptimize]]: # noqa: FBT001 +def get_functions_within_git_diff(uncommitted_changes: bool) -> dict[str, list[FunctionToOptimize]]: modified_lines: dict[str, list[int]] = get_git_diff(uncommitted_changes=uncommitted_changes) return get_functions_within_lines(modified_lines) @@ -472,7 +472,7 @@ def get_all_replay_test_functions( def is_git_repo(file_path: str) -> bool: try: git.Repo(file_path, search_parent_directories=True) - return True # noqa: TRY300 + return True except git.InvalidGitRepositoryError: return False diff --git a/codeflash/lsp/beta.py b/codeflash/lsp/beta.py index a38cb1cde..75f761f19 100644 --- a/codeflash/lsp/beta.py +++ b/codeflash/lsp/beta.py @@ -409,7 +409,7 @@ def provide_api_key(params: ProvideApiKeyParams) -> dict[str, str]: _init() if not is_successful(result): return {"status": "error", "message": result.failure()} - return {"status": "success", "message": "Api key saved successfully", "user_id": user_id} # noqa: TRY300 + return {"status": "success", "message": "Api key saved successfully", "user_id": user_id} except Exception: return {"status": "error", "message": "something went wrong while saving the api key"} diff --git a/codeflash/lsp/features/perform_optimization.py b/codeflash/lsp/features/perform_optimization.py index d6269f339..8cf1906db 100644 --- a/codeflash/lsp/features/perform_optimization.py +++ b/codeflash/lsp/features/perform_optimization.py @@ -25,7 +25,7 @@ def abort_if_cancelled(cancel_event: threading.Event) -> None: raise RuntimeError("cancelled") -def sync_perform_optimization(server: CodeflashLanguageServer, cancel_event: threading.Event, params) -> dict[str, str]: # noqa +def sync_perform_optimization(server: CodeflashLanguageServer, cancel_event: threading.Event, params) -> dict[str, str]: server.show_message_log(f"Starting optimization for function: {params.functionName}", "Info") should_run_experiment, code_context, original_helper_code = server.current_optimization_init_result function_optimizer = server.optimizer.current_function_optimizer diff --git a/codeflash/lsp/helpers.py b/codeflash/lsp/helpers.py index 4dfb42738..b8840e046 100644 --- a/codeflash/lsp/helpers.py +++ b/codeflash/lsp/helpers.py @@ -46,7 +46,7 @@ def report_to_markdown_table(report: dict[TestType, dict[str, int]], title: str) return table -def simplify_worktree_paths(msg: str, highlight: bool = True) -> str: # noqa: FBT001, FBT002 +def simplify_worktree_paths(msg: str, highlight: bool = True) -> str: path_in_msg = worktree_path_regex.search(msg) if path_in_msg: # Use Path.name to handle both Unix and Windows path separators diff --git a/codeflash/lsp/lsp_logger.py b/codeflash/lsp/lsp_logger.py index 14af72ea3..8f522ba39 100644 --- a/codeflash/lsp/lsp_logger.py +++ b/codeflash/lsp/lsp_logger.py @@ -85,11 +85,7 @@ def extract_tags(msg: str) -> tuple[LspMessageTags, str]: def enhanced_log( - msg: str | Any, # noqa: ANN401 - actual_log_fn: Callable[[str, Any, Any], None], - level: str, - *args: Any, # noqa: ANN401 - **kwargs: Any, # noqa: ANN401 + msg: str | Any, actual_log_fn: Callable[[str, Any, Any], None], level: str, *args: Any, **kwargs: Any ) -> None: if not isinstance(msg, str): actual_log_fn(msg, *args, **kwargs) diff --git a/codeflash/lsp/lsp_message.py b/codeflash/lsp/lsp_message.py index 020c6eef2..873646b70 100644 --- a/codeflash/lsp/lsp_message.py +++ b/codeflash/lsp/lsp_message.py @@ -27,7 +27,7 @@ class LspMessage: takes_time: bool = False message_id: Optional[str] = None - def _loop_through(self, obj: Any) -> Any: # noqa: ANN401 + def _loop_through(self, obj: Any) -> Any: if isinstance(obj, list): return [self._loop_through(i) for i in obj] if isinstance(obj, dict): diff --git a/codeflash/optimization/function_context.py b/codeflash/optimization/function_context.py index c7fbe461e..eb710945f 100644 --- a/codeflash/optimization/function_context.py +++ b/codeflash/optimization/function_context.py @@ -41,6 +41,6 @@ def belongs_to_function_qualified(name: Name, qualified_function_name: str) -> b return False if (name := name.parent()) and name.type == "function": return get_qualified_name(name.module_name, name.full_name) == qualified_function_name - return False # noqa: TRY300 + return False except ValueError: return False diff --git a/codeflash/optimization/function_optimizer.py b/codeflash/optimization/function_optimizer.py index 697061b9c..33cc57bcf 100644 --- a/codeflash/optimization/function_optimizer.py +++ b/codeflash/optimization/function_optimizer.py @@ -1625,8 +1625,8 @@ def generate_optimizations( self, read_writable_code: CodeStringsMarkdown, read_only_context_code: str, - run_experiment: bool = False, # noqa: FBT001, FBT002 - is_numerical_code: bool | None = None, # noqa: FBT001 + run_experiment: bool = False, + is_numerical_code: bool | None = None, ) -> Result[tuple[OptimizationSet, str], str]: """Generate optimization candidates for the function. Backend handles multi-model diversity.""" n_candidates = get_effort_value(EffortKeys.N_OPTIMIZER_CANDIDATES, self.effort) diff --git a/codeflash/picklepatch/pickle_patcher.py b/codeflash/picklepatch/pickle_patcher.py index ed0cac493..199277740 100644 --- a/codeflash/picklepatch/pickle_patcher.py +++ b/codeflash/picklepatch/pickle_patcher.py @@ -94,7 +94,7 @@ def _pickle( obj: object, path: list[str] | None = None, # noqa: ARG004 protocol: int | None = None, - **kwargs: Any, # noqa: ANN401 + **kwargs: Any, ) -> tuple[bool, bytes | str]: """Try to pickle an object using pickle first, then dill. If both fail, create a placeholder. @@ -123,7 +123,7 @@ def _pickle( return False, str(e) @staticmethod - def _recursive_pickle( # noqa: PLR0911 + def _recursive_pickle( obj: object, max_depth: int, path: list[str] | None = None, @@ -192,7 +192,7 @@ def _handle_dict( error_msg: str, # noqa: ARG004 path: list[str], protocol: int | None = None, - **kwargs: Any, # noqa: ANN401 + **kwargs: Any, ) -> bytes: """Handle pickling for dictionary objects. @@ -258,7 +258,7 @@ def _handle_sequence( error_msg: str, # noqa: ARG004 path: list[str], protocol: int | None = None, - **kwargs: Any, # noqa: ANN401 + **kwargs: Any, ) -> bytes: """Handle pickling for sequence types (list, tuple, set). @@ -311,12 +311,7 @@ def _handle_sequence( @staticmethod def _handle_object( - obj: object, - max_depth: int, - error_msg: str, - path: list[str], - protocol: int | None = None, - **kwargs: Any, # noqa: ANN401 + obj: object, max_depth: int, error_msg: str, path: list[str], protocol: int | None = None, **kwargs: Any ) -> bytes: """Handle pickling for custom objects with __dict__. @@ -366,7 +361,7 @@ def _handle_object( if success: return result # Fall through to placeholder creation - except Exception: # noqa: S110 + except Exception: pass # Fall through to placeholder creation # If we get here, just use a placeholder diff --git a/codeflash/picklepatch/pickle_placeholder.py b/codeflash/picklepatch/pickle_placeholder.py index 4268a9146..89c4d63f1 100644 --- a/codeflash/picklepatch/pickle_placeholder.py +++ b/codeflash/picklepatch/pickle_placeholder.py @@ -31,7 +31,7 @@ def __init__(self, obj_type: str, obj_str: str, error_msg: str, path: list[str] self.__dict__["error_msg"] = error_msg self.__dict__["path"] = path if path is not None else [] - def __getattr__(self, name) -> Any: # noqa: ANN001, ANN401 + def __getattr__(self, name) -> Any: """Raise a custom error when any attribute is accessed.""" path_str = ".".join(self.__dict__["path"]) if self.__dict__["path"] else "root object" msg = ( @@ -40,11 +40,11 @@ def __getattr__(self, name) -> Any: # noqa: ANN001, ANN401 ) raise PicklePlaceholderAccessError(msg) - def __setattr__(self, name: str, value: Any) -> None: # noqa: ANN401 + def __setattr__(self, name: str, value: Any) -> None: """Prevent setting attributes.""" self.__getattr__(name) # This will raise our custom error - def __call__(self, *args: Any, **kwargs: Any) -> Any: # noqa: ANN401, ARG002 + def __call__(self, *args: Any, **kwargs: Any) -> Any: """Raise a custom error when the object is called.""" path_str = ".".join(self.__dict__["path"]) if self.__dict__["path"] else "root object" msg = ( diff --git a/codeflash/telemetry/posthog_cf.py b/codeflash/telemetry/posthog_cf.py index ee9d733e3..505811cbe 100644 --- a/codeflash/telemetry/posthog_cf.py +++ b/codeflash/telemetry/posthog_cf.py @@ -12,7 +12,7 @@ _posthog = None -def initialize_posthog(enabled: bool = True) -> None: # noqa: FBT001, FBT002 +def initialize_posthog(enabled: bool = True) -> None: """Enable or disable PostHog. :param enabled: Whether to enable PostHog. diff --git a/codeflash/telemetry/sentry.py b/codeflash/telemetry/sentry.py index b7ff00094..790187355 100644 --- a/codeflash/telemetry/sentry.py +++ b/codeflash/telemetry/sentry.py @@ -4,7 +4,7 @@ from sentry_sdk.integrations.logging import LoggingIntegration -def init_sentry(enabled: bool = False, exclude_errors: bool = False) -> None: # noqa: FBT001, FBT002 +def init_sentry(enabled: bool = False, exclude_errors: bool = False) -> None: if enabled: sentry_logging = LoggingIntegration( level=logging.INFO, # Capture info and above as breadcrumbs diff --git a/codeflash/tracing/profile_stats.py b/codeflash/tracing/profile_stats.py index e810c9409..36bf9e113 100644 --- a/codeflash/tracing/profile_stats.py +++ b/codeflash/tracing/profile_stats.py @@ -71,7 +71,7 @@ def print_stats(self, *amount) -> pstats.Stats: # noqa: ANN002 time_unit = {"ns": "nanoseconds", "us": "microseconds", "ms": "milliseconds", "s": "seconds"}[self.time_unit] print(f"in {self.total_tt:.3f} {time_unit}", file=self.stream) print(file=self.stream) - width, list_ = self.get_print_list(amount) + _width, list_ = self.get_print_list(amount) if list_: self.print_title() for func in list_: diff --git a/codeflash/tracing/tracing_new_process.py b/codeflash/tracing/tracing_new_process.py index 52ca31f8b..e4b80bffb 100644 --- a/codeflash/tracing/tracing_new_process.py +++ b/codeflash/tracing/tracing_new_process.py @@ -76,7 +76,7 @@ def __init__( config: dict, result_pickle_file_path: Path, functions: list[str] | None = None, - disable: bool = False, # noqa: FBT001, FBT002 + disable: bool = False, project_root: Path | None = None, max_function_count: int = 256, timeout: int | None = None, # seconds @@ -309,7 +309,7 @@ def __exit__( with self.result_pickle_file_path.open("wb") as file: pickle.dump(pickle_data, file) - def tracer_logic(self, frame: FrameType, event: str) -> None: # noqa: PLR0911 + def tracer_logic(self, frame: FrameType, event: str) -> None: if event != "call": return if None is not self.timeout and (time.time() - self.start_time) > self.timeout: @@ -470,7 +470,7 @@ def trace_dispatch_call(self, frame: FrameType, t: int) -> int: # In multi-threaded contexts, we need to be more careful about frame comparisons if self.cur and frame.f_back is not self.cur[-2]: # This happens when we're in a different thread - rpt, rit, ret, rfn, rframe, rcur = self.cur + _rpt, _rit, _ret, _rfn, rframe, _rcur = self.cur # Only attempt to handle the frame mismatch if we have a valid rframe if ( @@ -494,7 +494,7 @@ def trace_dispatch_call(self, frame: FrameType, t: int) -> int: class_name = arguments["self"].__class__.__name__ elif "cls" in arguments and hasattr(arguments["cls"], "__name__"): class_name = arguments["cls"].__name__ - except Exception: # noqa: S110 + except Exception: pass fn = (fcode.co_filename, fcode.co_firstlineno, fcode.co_name, class_name) @@ -505,7 +505,7 @@ def trace_dispatch_call(self, frame: FrameType, t: int) -> int: timings[fn] = cc, ns + 1, tt, ct, callers else: timings[fn] = 0, 0, 0, 0, {} - return 1 # noqa: TRY300 + return 1 except Exception: # Handle any errors gracefully return 0 diff --git a/codeflash/tracing/tracing_utils.py b/codeflash/tracing/tracing_utils.py index ac8b3c888..5f2299386 100644 --- a/codeflash/tracing/tracing_utils.py +++ b/codeflash/tracing/tracing_utils.py @@ -28,7 +28,7 @@ def path_belongs_to_site_packages(file_path: Path) -> bool: def is_git_repo(file_path: str) -> bool: try: git.Repo(file_path, search_parent_directories=True) - return True # noqa: TRY300 + return True except git.InvalidGitRepositoryError: return False diff --git a/codeflash/verification/codeflash_capture.py b/codeflash/verification/codeflash_capture.py index 991f4d624..e19483404 100644 --- a/codeflash/verification/codeflash_capture.py +++ b/codeflash/verification/codeflash_capture.py @@ -97,7 +97,7 @@ def get_test_info_from_stack(tests_root: str) -> tuple[str, str | None, str, str return test_module_name, test_class_name, test_name, line_id -def codeflash_capture(function_name: str, tmp_dir_path: str, tests_root: str, is_fto: bool = False) -> Callable: # noqa: FBT001, FBT002 +def codeflash_capture(function_name: str, tmp_dir_path: str, tests_root: str, is_fto: bool = False) -> Callable: """Define a decorator to instrument the init function, collect test info, and capture the instance state.""" def decorator(wrapped: Callable) -> Callable: diff --git a/codeflash/verification/comparator.py b/codeflash/verification/comparator.py index e370d35ad..5e75fc345 100644 --- a/codeflash/verification/comparator.py +++ b/codeflash/verification/comparator.py @@ -88,7 +88,7 @@ def _get_wrapped_exception(exc: BaseException) -> Optional[BaseException]: # no return _extract_exception_from_message(str(exc)) -def comparator(orig: Any, new: Any, superset_obj=False) -> bool: # noqa: ANN001, ANN401, FBT002, PLR0911 +def comparator(orig: Any, new: Any, superset_obj=False) -> bool: """Compare two objects for equality recursively. If superset_obj is True, the new object is allowed to have more keys than the original object. However, the existing keys/values must be equivalent.""" try: # Handle exceptions specially - before type check to allow wrapper comparison @@ -113,7 +113,7 @@ def comparator(orig: Any, new: Any, superset_obj=False) -> bool: # noqa: ANN001 # Check if new wraps something that matches orig wrapped_new = _get_wrapped_exception(new) - if wrapped_new is not None and comparator(orig, wrapped_new, superset_obj): # noqa: SIM103 + if wrapped_new is not None and comparator(orig, wrapped_new, superset_obj): return True return False @@ -237,7 +237,7 @@ def comparator(orig: Any, new: Any, superset_obj=False) -> bool: # noqa: ANN001 continue if key not in new_keys or not comparator(orig_keys[key], new_keys[key], superset_obj): return False - return True # noqa: TRY300 + return True except sqlalchemy.exc.NoInspectionAvailable: pass @@ -357,12 +357,12 @@ def comparator(orig: Any, new: Any, superset_obj=False) -> bool: # noqa: ANN001 try: if HAS_NUMPY and np.isnan(orig): return np.isnan(new) - except Exception: # noqa: S110 + except Exception: pass try: if HAS_NUMPY and np.isinf(orig): return np.isinf(new) - except Exception: # noqa: S110 + except Exception: pass if HAS_TORCH: @@ -471,7 +471,7 @@ def comparator(orig: Any, new: Any, superset_obj=False) -> bool: # noqa: ANN001 try: if hasattr(orig, "__eq__") and str(type(orig.__eq__)) == "": return orig == new - except Exception: # noqa: S110 + except Exception: pass # For class objects @@ -503,7 +503,7 @@ def comparator(orig: Any, new: Any, superset_obj=False) -> bool: # noqa: ANN001 # TODO : Add other types here logger.warning(f"Unknown comparator input type: {type(orig)}") sentry_sdk.capture_exception(RuntimeError(f"Unknown comparator input type: {type(orig)}")) - return False # noqa: TRY300 + return False except RecursionError as e: logger.error(f"RecursionError while comparing objects: {e}") sentry_sdk.capture_exception(e) diff --git a/codeflash/verification/instrument_codeflash_capture.py b/codeflash/verification/instrument_codeflash_capture.py index 19a29013b..9a5d71b9e 100644 --- a/codeflash/verification/instrument_codeflash_capture.py +++ b/codeflash/verification/instrument_codeflash_capture.py @@ -54,12 +54,7 @@ def instrument_codeflash_capture( def add_codeflash_capture_to_init( - target_classes: set[str], - fto_name: str, - tmp_dir_path: str, - code: str, - tests_root: Path, - is_fto: bool = False, # noqa: FBT001, FBT002 + target_classes: set[str], fto_name: str, tmp_dir_path: str, code: str, tests_root: Path, is_fto: bool = False ) -> str: """Add codeflash_capture decorator to __init__ function in the specified class.""" tree = ast.parse(code) @@ -76,12 +71,7 @@ class InitDecorator(ast.NodeTransformer): """AST transformer that adds codeflash_capture decorator to specific class's __init__.""" def __init__( - self, - target_classes: set[str], - fto_name: str, - tmp_dir_path: str, - tests_root: Path, - is_fto=False, # noqa: ANN001, FBT002 + self, target_classes: set[str], fto_name: str, tmp_dir_path: str, tests_root: Path, is_fto=False ) -> None: self.target_classes = target_classes self.fto_name = fto_name diff --git a/codeflash/verification/pytest_plugin.py b/codeflash/verification/pytest_plugin.py index ff3fcb4c5..a962d96e6 100644 --- a/codeflash/verification/pytest_plugin.py +++ b/codeflash/verification/pytest_plugin.py @@ -437,7 +437,7 @@ def _clear_lru_caches(self, item: pytest.Item) -> None: "importlib", } - def _clear_cache_for_object(obj: Any) -> None: # noqa: ANN401 + def _clear_cache_for_object(obj: Any) -> None: if obj in processed_functions: return processed_functions.add(obj) @@ -469,9 +469,9 @@ def _clear_cache_for_object(obj: Any) -> None: # noqa: ANN401 for _, obj in inspect.getmembers(module): if callable(obj): _clear_cache_for_object(obj) - except Exception: # noqa: S110 + except Exception: pass - except Exception: # noqa: S110 + except Exception: pass def _set_nodeid(self, nodeid: str, count: int) -> str: @@ -581,7 +581,7 @@ def pytest_runtest_setup(self, item: pytest.Item) -> None: os.environ["CODEFLASH_TEST_FUNCTION"] = test_function_name @pytest.hookimpl(trylast=True) - def pytest_runtest_teardown(self, item: pytest.Item) -> None: # noqa: ARG002 + def pytest_runtest_teardown(self, item: pytest.Item) -> None: """Clean up test context environment variables after each test.""" for var in ["CODEFLASH_TEST_MODULE", "CODEFLASH_TEST_CLASS", "CODEFLASH_TEST_FUNCTION"]: os.environ.pop(var, None) diff --git a/codeflash/verification/test_runner.py b/codeflash/verification/test_runner.py index ece39e1e0..76fc0d629 100644 --- a/codeflash/verification/test_runner.py +++ b/codeflash/verification/test_runner.py @@ -164,8 +164,8 @@ def run_line_profile_tests( *, pytest_target_runtime_seconds: float = TOTAL_LOOPING_TIME_EFFECTIVE, pytest_timeout: int | None = None, - pytest_min_loops: int = 5, # noqa: ARG001 - pytest_max_loops: int = 100_000, # noqa: ARG001 + pytest_min_loops: int = 5, + pytest_max_loops: int = 100_000, ) -> tuple[Path, subprocess.CompletedProcess]: if test_framework in {"pytest", "unittest"}: # pytest runs both pytest and unittest tests pytest_cmd_list = ( diff --git a/codeflash/verification/verifier.py b/codeflash/verification/verifier.py index f60718020..c9a553019 100644 --- a/codeflash/verification/verifier.py +++ b/codeflash/verification/verifier.py @@ -27,7 +27,7 @@ def generate_tests( test_index: int, test_path: Path, test_perf_path: Path, - is_numerical_code: bool | None = None, # noqa: FBT001 + is_numerical_code: bool | None = None, ) -> tuple[str, str, Path] | None: # TODO: Sometimes this recreates the original Class definition. This overrides and messes up the original # class import. Remove the recreation of the class definition diff --git a/pyproject.toml b/pyproject.toml index 1714532d0..0e6219d29 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -255,7 +255,20 @@ ignore = [ "PERF203", "LOG015", "PLC0415", - "UP045" + "UP045", + # Style rules - valid code patterns we allow in this codebase + "FBT001", # Boolean positional arg - common in Python APIs + "FBT002", # Boolean default arg - common in Python APIs + "ARG001", # Unused function arg - required for interface implementations + "ARG002", # Unused method arg - required for interface implementations (e.g., libcst visitors) + "ANN401", # typing.Any - sometimes necessary + "ANN001", # Missing type annotation - not all internal code needs full typing + "TRY300", # Try/except style preference + "TRY401", # Logging exception style preference + "S110", # try-except-pass - sometimes legitimate + "PLR0911", # Too many return statements - complex functions sometimes need this + "SIM102", # Nested if style - sometimes clearer than combined conditions + "SIM103", # Return negation style - preference ] [tool.ruff.lint.flake8-type-checking] From c2316692c5c8aa1ee0e0cd8246e8d4b56ce2ca6f Mon Sep 17 00:00:00 2001 From: Kevin Turcios Date: Thu, 29 Jan 2026 12:00:03 -0500 Subject: [PATCH 2/7] revert --- pyproject.toml | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 0e6219d29..18f1c98f2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -256,19 +256,6 @@ ignore = [ "LOG015", "PLC0415", "UP045", - # Style rules - valid code patterns we allow in this codebase - "FBT001", # Boolean positional arg - common in Python APIs - "FBT002", # Boolean default arg - common in Python APIs - "ARG001", # Unused function arg - required for interface implementations - "ARG002", # Unused method arg - required for interface implementations (e.g., libcst visitors) - "ANN401", # typing.Any - sometimes necessary - "ANN001", # Missing type annotation - not all internal code needs full typing - "TRY300", # Try/except style preference - "TRY401", # Logging exception style preference - "S110", # try-except-pass - sometimes legitimate - "PLR0911", # Too many return statements - complex functions sometimes need this - "SIM102", # Nested if style - sometimes clearer than combined conditions - "SIM103", # Return negation style - preference ] [tool.ruff.lint.flake8-type-checking] From 9c1bef27e0826cae8f81c695356db8d7f8c0fb9b Mon Sep 17 00:00:00 2001 From: Kevin Turcios Date: Thu, 29 Jan 2026 12:01:12 -0500 Subject: [PATCH 3/7] LP doesn't use it. --- codeflash/verification/test_runner.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/codeflash/verification/test_runner.py b/codeflash/verification/test_runner.py index 76fc0d629..b4922b10e 100644 --- a/codeflash/verification/test_runner.py +++ b/codeflash/verification/test_runner.py @@ -164,8 +164,6 @@ def run_line_profile_tests( *, pytest_target_runtime_seconds: float = TOTAL_LOOPING_TIME_EFFECTIVE, pytest_timeout: int | None = None, - pytest_min_loops: int = 5, - pytest_max_loops: int = 100_000, ) -> tuple[Path, subprocess.CompletedProcess]: if test_framework in {"pytest", "unittest"}: # pytest runs both pytest and unittest tests pytest_cmd_list = ( From e52dc0c647e62176626d4fd80e11e19f02d01d2c Mon Sep 17 00:00:00 2001 From: Kevin Turcios Date: Thu, 29 Jan 2026 12:05:46 -0500 Subject: [PATCH 4/7] we do want to log --- codeflash/verification/pytest_plugin.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codeflash/verification/pytest_plugin.py b/codeflash/verification/pytest_plugin.py index a962d96e6..6279dcd92 100644 --- a/codeflash/verification/pytest_plugin.py +++ b/codeflash/verification/pytest_plugin.py @@ -469,9 +469,9 @@ def _clear_cache_for_object(obj: Any) -> None: for _, obj in inspect.getmembers(module): if callable(obj): _clear_cache_for_object(obj) - except Exception: + except Exception: # noqa: S110 pass - except Exception: + except Exception: # noqa: S110 pass def _set_nodeid(self, nodeid: str, count: int) -> str: From 47a3778ff7a475208acffef9f3a93864bef744a2 Mon Sep 17 00:00:00 2001 From: Kevin Turcios Date: Thu, 29 Jan 2026 12:07:47 -0500 Subject: [PATCH 5/7] ignore s110 --- codeflash/verification/pytest_plugin.py | 8 ++++---- pyproject.toml | 1 + 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/codeflash/verification/pytest_plugin.py b/codeflash/verification/pytest_plugin.py index 6279dcd92..40324dbcb 100644 --- a/codeflash/verification/pytest_plugin.py +++ b/codeflash/verification/pytest_plugin.py @@ -12,7 +12,7 @@ import time as _time_module import warnings from pathlib import Path -from typing import TYPE_CHECKING, Any, Callable, Optional +from typing import TYPE_CHECKING, Callable, Optional from unittest import TestCase # PyTest Imports @@ -437,7 +437,7 @@ def _clear_lru_caches(self, item: pytest.Item) -> None: "importlib", } - def _clear_cache_for_object(obj: Any) -> None: + def _clear_cache_for_object(obj: obj) -> None: if obj in processed_functions: return processed_functions.add(obj) @@ -469,9 +469,9 @@ def _clear_cache_for_object(obj: Any) -> None: for _, obj in inspect.getmembers(module): if callable(obj): _clear_cache_for_object(obj) - except Exception: # noqa: S110 + except Exception: pass - except Exception: # noqa: S110 + except Exception: pass def _set_nodeid(self, nodeid: str, count: int) -> str: diff --git a/pyproject.toml b/pyproject.toml index 18f1c98f2..77c289b36 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -256,6 +256,7 @@ ignore = [ "LOG015", "PLC0415", "UP045", + "S110", # try-except-pass - we do this a lot ] [tool.ruff.lint.flake8-type-checking] From 1e34a3d8a32e7890077397b7995710f35f9a34c9 Mon Sep 17 00:00:00 2001 From: "codeflash-ai[bot]" <148906541+codeflash-ai[bot]@users.noreply.github.com> Date: Thu, 29 Jan 2026 17:08:10 +0000 Subject: [PATCH 6/7] Optimize determine_dependency_manager The optimization achieves a **14% runtime improvement** by caching `Path.cwd()` once at the start of the function instead of calling it twice during the lock file checks. **Key optimization:** - **Single Path.cwd() call**: The original code called `Path.cwd()` twice (lines checking `poetry.lock` and `uv.lock`), while the optimized version calls it once and reuses the result via the `cwd` variable. **Why this matters:** `Path.cwd()` is a relatively expensive operation that involves system calls to retrieve the current working directory. Line profiler results show: - Original: First lock check took 3.59ms (57.2% of total time), second took 2.26ms (36% of total time) - Optimized: The single `cwd = Path.cwd()` took 1.79ms (32.7%), with subsequent checks using the cached path taking 2.05ms (37.4%) and 1.22ms (22.1%) The net effect is reducing filesystem/system call overhead from ~5.85ms to ~5.05ms across the lock file checks. **Performance characteristics:** Based on the annotated tests, this optimization provides consistent **11-19% speedups** across nearly all test cases: - Best speedup (19.2%): Test with uv-prefixed keys like "uvApp" - Strong improvements (16-17%): Tests checking lock files or no tool sections - Consistent gains (11-15%): Tests with tool section parsing The optimization is particularly beneficial when `determine_dependency_manager` is called frequently, as indicated by the function_references showing it's invoked during GitHub Actions workflow generation (both in `generate_dynamic_workflow_content` and `customize_codeflash_yaml_content`). Since these are CI/CD initialization paths that may be called multiple times during repository setup, the cumulative savings become meaningful. --- codeflash/cli_cmds/cmd_init.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/codeflash/cli_cmds/cmd_init.py b/codeflash/cli_cmds/cmd_init.py index 83df1c54e..b7527bd8b 100644 --- a/codeflash/cli_cmds/cmd_init.py +++ b/codeflash/cli_cmds/cmd_init.py @@ -1091,9 +1091,10 @@ def install_github_actions(override_formatter_check: bool = False) -> None: def determine_dependency_manager(pyproject_data: dict[str, Any]) -> DependencyManager: """Determine which dependency manager is being used based on pyproject.toml contents.""" - if (Path.cwd() / "poetry.lock").exists(): + cwd = Path.cwd() + if (cwd / "poetry.lock").exists(): return DependencyManager.POETRY - if (Path.cwd() / "uv.lock").exists(): + if (cwd / "uv.lock").exists(): return DependencyManager.UV if "tool" not in pyproject_data: return DependencyManager.PIP From 1d3aeb997d10c483c15aa45d283dd8d2332c1fa7 Mon Sep 17 00:00:00 2001 From: Kevin Turcios Date: Thu, 29 Jan 2026 12:10:56 -0500 Subject: [PATCH 7/7] wrapped --- codeflash/api/aiservice.py | 1 - codeflash/benchmarking/plugin/plugin.py | 6 +++--- codeflash/code_utils/code_extractor.py | 21 ++++++++----------- .../code_utils/instrument_existing_tests.py | 17 +++++++-------- codeflash/main.py | 12 +++++------ codeflash/optimization/function_optimizer.py | 2 -- codeflash/telemetry/posthog_cf.py | 2 +- codeflash/telemetry/sentry.py | 2 +- codeflash/tracer.py | 4 ++-- codeflash/tracing/tracing_new_process.py | 1 + .../instrument_codeflash_capture.py | 6 +++--- pyproject.toml | 1 + 12 files changed, 35 insertions(+), 40 deletions(-) diff --git a/codeflash/api/aiservice.py b/codeflash/api/aiservice.py index 2d80ab004..c1f1e5e42 100644 --- a/codeflash/api/aiservice.py +++ b/codeflash/api/aiservice.py @@ -722,7 +722,6 @@ def get_optimization_review( function_trace_id: str, coverage_message: str, replay_tests: str, - concolic_tests: str, calling_fn_details: str, ) -> OptimizationReviewResult: """Compute the optimization review of current Pull Request. diff --git a/codeflash/benchmarking/plugin/plugin.py b/codeflash/benchmarking/plugin/plugin.py index 4789279da..8c502d143 100644 --- a/codeflash/benchmarking/plugin/plugin.py +++ b/codeflash/benchmarking/plugin/plugin.py @@ -200,7 +200,7 @@ def get_benchmark_timings(trace_path: Path) -> dict[BenchmarkKey, int]: # Pytest hooks @pytest.hookimpl - def pytest_sessionfinish(self, session, exitstatus) -> None: + def pytest_sessionfinish(self, session, exitstatus) -> None: # noqa: ANN001 """Execute after whole test run is completed.""" # Write any remaining benchmark timings to the database codeflash_trace.close() @@ -218,7 +218,7 @@ def pytest_collection_modifyitems(config: pytest.Config, items: list[pytest.Item skip_no_benchmark = pytest.mark.skip(reason="Test requires benchmark fixture") for item in items: # Check for direct benchmark fixture usage - has_fixture = hasattr(item, "fixturenames") and "benchmark" in item.fixturenames + has_fixture = hasattr(item, "fixturenames") and "benchmark" in item.fixturenames # ty:ignore[unsupported-operator] # Check for @pytest.mark.benchmark marker has_marker = False @@ -236,7 +236,7 @@ class Benchmark: # noqa: D106 def __init__(self, request: pytest.FixtureRequest) -> None: self.request = request - def __call__(self, func, *args, **kwargs): # type: ignore # noqa: ANN002, ANN003, ANN204, PGH003 + def __call__(self, func, *args, **kwargs): # noqa: ANN001, ANN002, ANN003, ANN204 """Handle both direct function calls and decorator usage.""" if args or kwargs: # Used as benchmark(func, *args, **kwargs) diff --git a/codeflash/code_utils/code_extractor.py b/codeflash/code_utils/code_extractor.py index 647686422..84d359b20 100644 --- a/codeflash/code_utils/code_extractor.py +++ b/codeflash/code_utils/code_extractor.py @@ -44,14 +44,14 @@ def visit_FunctionDef(self, node: cst.FunctionDef) -> Optional[bool]: self.scope_depth += 1 return True - def leave_FunctionDef(self, original_node: cst.FunctionDef) -> None: # noqa: ARG002 + def leave_FunctionDef(self, original_node: cst.FunctionDef) -> None: self.scope_depth -= 1 - def visit_ClassDef(self, node: cst.ClassDef) -> Optional[bool]: # noqa: ARG002 + def visit_ClassDef(self, node: cst.ClassDef) -> Optional[bool]: self.scope_depth += 1 return True - def leave_ClassDef(self, original_node: cst.ClassDef) -> None: # noqa: ARG002 + def leave_ClassDef(self, original_node: cst.ClassDef) -> None: self.scope_depth -= 1 @@ -65,7 +65,7 @@ def __init__(self, new_functions: dict[str, cst.FunctionDef], new_function_order self.processed_functions: set[str] = set() self.scope_depth = 0 - def visit_FunctionDef(self, node: cst.FunctionDef) -> None: # noqa: ARG002 + def visit_FunctionDef(self, node: cst.FunctionDef) -> None: self.scope_depth += 1 def leave_FunctionDef(self, original_node: cst.FunctionDef, updated_node: cst.FunctionDef) -> cst.FunctionDef: @@ -80,14 +80,14 @@ def leave_FunctionDef(self, original_node: cst.FunctionDef, updated_node: cst.Fu return self.new_functions[name] return updated_node - def visit_ClassDef(self, node: cst.ClassDef) -> None: # noqa: ARG002 + def visit_ClassDef(self, node: cst.ClassDef) -> None: self.scope_depth += 1 - def leave_ClassDef(self, original_node: cst.ClassDef, updated_node: cst.ClassDef) -> cst.ClassDef: # noqa: ARG002 + def leave_ClassDef(self, original_node: cst.ClassDef, updated_node: cst.ClassDef) -> cst.ClassDef: self.scope_depth -= 1 return updated_node - def leave_Module(self, original_node: cst.Module, updated_node: cst.Module) -> cst.Module: # noqa: ARG002 + def leave_Module(self, original_node: cst.Module, updated_node: cst.Module) -> cst.Module: # Add any new functions that weren't in the original file new_statements = list(updated_node.body) @@ -370,7 +370,7 @@ def __init__(self, global_statements: list[cst.SimpleStatementLine]) -> None: super().__init__() self.global_statements = global_statements - def leave_Module(self, original_node: cst.Module, updated_node: cst.Module) -> cst.Module: # noqa: ARG002 + def leave_Module(self, original_node: cst.Module, updated_node: cst.Module) -> cst.Module: if not self.global_statements: return updated_node @@ -1553,10 +1553,7 @@ def is_numerical_code(code_string: str, function_name: str | None = None) -> boo # If numba is not installed and all modules used require numba for optimization, # return False since we can't optimize this code - if not has_numba and modules_used.issubset(NUMBA_REQUIRED_MODULES): - return False - - return True + return not (not has_numba and modules_used.issubset(NUMBA_REQUIRED_MODULES)) def get_opt_review_metrics( diff --git a/codeflash/code_utils/instrument_existing_tests.py b/codeflash/code_utils/instrument_existing_tests.py index 31d340086..6315830ce 100644 --- a/codeflash/code_utils/instrument_existing_tests.py +++ b/codeflash/code_utils/instrument_existing_tests.py @@ -690,15 +690,14 @@ def detect_frameworks_from_code(code: str) -> dict[str, str]: frameworks["tensorflow"] = alias.asname if alias.asname else module_name elif module_name == "jax": frameworks["jax"] = alias.asname if alias.asname else module_name - elif isinstance(node, ast.ImportFrom): - if node.module: - module_name = node.module.split(".")[0] - if module_name == "torch" and "torch" not in frameworks: - frameworks["torch"] = module_name - elif module_name == "tensorflow" and "tensorflow" not in frameworks: - frameworks["tensorflow"] = module_name - elif module_name == "jax" and "jax" not in frameworks: - frameworks["jax"] = module_name + elif isinstance(node, ast.ImportFrom) and node.module: + module_name = node.module.split(".")[0] + if module_name == "torch" and "torch" not in frameworks: + frameworks["torch"] = module_name + elif module_name == "tensorflow" and "tensorflow" not in frameworks: + frameworks["tensorflow"] = module_name + elif module_name == "jax" and "jax" not in frameworks: + frameworks["jax"] = module_name return frameworks diff --git a/codeflash/main.py b/codeflash/main.py index 31afd0305..f01d8e737 100644 --- a/codeflash/main.py +++ b/codeflash/main.py @@ -30,21 +30,21 @@ def main() -> None: if args.config_file and Path.exists(args.config_file): pyproject_config, _ = parse_config_file(args.config_file) disable_telemetry = pyproject_config.get("disable_telemetry", False) - init_sentry(not disable_telemetry, exclude_errors=True) - posthog_cf.initialize_posthog(not disable_telemetry) + init_sentry(enabled=not disable_telemetry, exclude_errors=True) + posthog_cf.initialize_posthog(enabled=not disable_telemetry) args.func() elif args.verify_setup: args = process_pyproject_config(args) - init_sentry(not args.disable_telemetry, exclude_errors=True) - posthog_cf.initialize_posthog(not args.disable_telemetry) + init_sentry(enabled=not args.disable_telemetry, exclude_errors=True) + posthog_cf.initialize_posthog(enabled=not args.disable_telemetry) ask_run_end_to_end_test(args) else: args = process_pyproject_config(args) if not env_utils.check_formatter_installed(args.formatter_cmds): return args.previous_checkpoint_functions = ask_should_use_checkpoint_get_functions(args) - init_sentry(not args.disable_telemetry, exclude_errors=True) - posthog_cf.initialize_posthog(not args.disable_telemetry) + init_sentry(enabled=not args.disable_telemetry, exclude_errors=True) + posthog_cf.initialize_posthog(enabled=not args.disable_telemetry) from codeflash.optimization import optimizer diff --git a/codeflash/optimization/function_optimizer.py b/codeflash/optimization/function_optimizer.py index ce02fd990..13ec73d37 100644 --- a/codeflash/optimization/function_optimizer.py +++ b/codeflash/optimization/function_optimizer.py @@ -2486,8 +2486,6 @@ def run_and_parse_tests( pytest_cmd=self.test_cfg.pytest_cmd, pytest_timeout=INDIVIDUAL_TESTCASE_TIMEOUT, pytest_target_runtime_seconds=testing_time, - pytest_min_loops=1, - pytest_max_loops=1, test_framework=self.test_cfg.test_framework, ) elif testing_type == TestingMode.PERFORMANCE: diff --git a/codeflash/telemetry/posthog_cf.py b/codeflash/telemetry/posthog_cf.py index 505811cbe..15df7d509 100644 --- a/codeflash/telemetry/posthog_cf.py +++ b/codeflash/telemetry/posthog_cf.py @@ -12,7 +12,7 @@ _posthog = None -def initialize_posthog(enabled: bool = True) -> None: +def initialize_posthog(*, enabled: bool = True) -> None: """Enable or disable PostHog. :param enabled: Whether to enable PostHog. diff --git a/codeflash/telemetry/sentry.py b/codeflash/telemetry/sentry.py index 790187355..2357439dc 100644 --- a/codeflash/telemetry/sentry.py +++ b/codeflash/telemetry/sentry.py @@ -4,7 +4,7 @@ from sentry_sdk.integrations.logging import LoggingIntegration -def init_sentry(enabled: bool = False, exclude_errors: bool = False) -> None: +def init_sentry(*, enabled: bool = False, exclude_errors: bool = False) -> None: if enabled: sentry_logging = LoggingIntegration( level=logging.INFO, # Capture info and above as breadcrumbs diff --git a/codeflash/tracer.py b/codeflash/tracer.py index 8c7a7621f..56183532b 100644 --- a/codeflash/tracer.py +++ b/codeflash/tracer.py @@ -227,8 +227,8 @@ def main(args: Namespace | None = None) -> ArgumentParser: args = process_pyproject_config(args) args.previous_checkpoint_functions = None - init_sentry(not args.disable_telemetry, exclude_errors=True) - posthog_cf.initialize_posthog(not args.disable_telemetry) + init_sentry(enabled=not args.disable_telemetry, exclude_errors=True) + posthog_cf.initialize_posthog(enabled=not args.disable_telemetry) from codeflash.optimization import optimizer diff --git a/codeflash/tracing/tracing_new_process.py b/codeflash/tracing/tracing_new_process.py index e4b80bffb..e2e54a708 100644 --- a/codeflash/tracing/tracing_new_process.py +++ b/codeflash/tracing/tracing_new_process.py @@ -76,6 +76,7 @@ def __init__( config: dict, result_pickle_file_path: Path, functions: list[str] | None = None, + *, disable: bool = False, project_root: Path | None = None, max_function_count: int = 256, diff --git a/codeflash/verification/instrument_codeflash_capture.py b/codeflash/verification/instrument_codeflash_capture.py index 9a5d71b9e..fc1bc36c4 100644 --- a/codeflash/verification/instrument_codeflash_capture.py +++ b/codeflash/verification/instrument_codeflash_capture.py @@ -54,11 +54,11 @@ def instrument_codeflash_capture( def add_codeflash_capture_to_init( - target_classes: set[str], fto_name: str, tmp_dir_path: str, code: str, tests_root: Path, is_fto: bool = False + target_classes: set[str], fto_name: str, tmp_dir_path: str, code: str, tests_root: Path, *, is_fto: bool = False ) -> str: """Add codeflash_capture decorator to __init__ function in the specified class.""" tree = ast.parse(code) - transformer = InitDecorator(target_classes, fto_name, tmp_dir_path, tests_root, is_fto) + transformer = InitDecorator(target_classes, fto_name, tmp_dir_path, tests_root, is_fto=is_fto) modified_tree = transformer.visit(tree) if transformer.inserted_decorator: ast.fix_missing_locations(modified_tree) @@ -71,7 +71,7 @@ class InitDecorator(ast.NodeTransformer): """AST transformer that adds codeflash_capture decorator to specific class's __init__.""" def __init__( - self, target_classes: set[str], fto_name: str, tmp_dir_path: str, tests_root: Path, is_fto=False + self, target_classes: set[str], fto_name: str, tmp_dir_path: str, tests_root: Path, *, is_fto: bool = False ) -> None: self.target_classes = target_classes self.fto_name = fto_name diff --git a/pyproject.toml b/pyproject.toml index 77c289b36..16faa442b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -257,6 +257,7 @@ ignore = [ "PLC0415", "UP045", "S110", # try-except-pass - we do this a lot + "ARG002", ] [tool.ruff.lint.flake8-type-checking]