Skip to content

Conversation

@mohammedahmed18
Copy link
Contributor

@mohammedahmed18 mohammedahmed18 commented Nov 25, 2025

PR Type

Enhancement


Description

  • Add cancel handling for demo optimization

  • Return original and optimized runtimes

  • Minor formatting in optimization summary


Diagram Walkthrough

flowchart LR
  start["start_demo_optimization"] -- "init + worktree" --> perform["perform_function_optimization"]
  perform -- "sync_perform_optimization" --> result["Return success with runtimes"]
  start -- "asyncio.CancelledError" --> cancel["Set cancel_event + cancelled response"]
Loading

File Walkthrough

Relevant files
Enhancement
beta.py
Add cancel handling to demo optimization flow                       

codeflash/lsp/beta.py

  • Create cancel_event for demo optimization.
  • Catch asyncio.CancelledError and set event.
  • Return standardized cancelled response.
  • Ensure optimizer cleanup in finally.
+4/-0     
perform_optimization.py
Return original and optimized runtimes in result                 

codeflash/lsp/features/perform_optimization.py

  • Include original_runtime in response payload.
  • Include optimized_runtime in response payload.
+2/-0     
Formatting
function_optimizer.py
Tweak file path formatting in summary                                       

codeflash/optimization/function_optimizer.py

  • Remove backticks around explanation.file_path in summary.
+1/-1     

@github-actions
Copy link

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

⏱️ Estimated effort to review: 2 🔵🔵⚪⚪⚪
🧪 No relevant tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Possible Issue

cancel_event is created and set in the CancelledError handler but never passed into downstream calls; verify that cancellation actually propagates to the optimization workflow or remove the unused event.

async def start_demo_optimization(params: DemoOptimizationParams) -> dict[str, str]:
    try:
        _init()
        cancel_event = threading.Event()
        # start by creating the worktree so that the demo file is not created in user workspace
        server.optimizer.worktree_mode()
        file_path = create_find_common_tags_file(server.args, params.functionName + ".py")
        # commit the new file for diff generation later
        create_worktree_snapshot_commit(server.optimizer.current_worktree, "added sample optimization file")

        server.optimizer.args.file = file_path
        server.optimizer.args.function = params.functionName
        server.optimizer.args.previous_checkpoint_functions = False

        initialization_result = _initialize_current_function_optimizer()
        if isinstance(initialization_result, dict):
            return initialization_result

        server.current_optimization_init_result = initialization_result.unwrap()
        return await perform_function_optimization(
            FunctionOptimizationParams(functionName=params.functionName, task_id=None)
        )
    except asyncio.CancelledError:
        cancel_event.set()
        return get_cancelled_reponse()
Type/Serialization Risk

Returning raw runtime objects may not be JSON-serializable; ensure original_runtime and optimized_runtime are primitive types (e.g., float) or serialized strings as expected by the LSP client.

"original_runtime": original_code_baseline.runtime,
"optimized_runtime": best_optimization.runtime,
Formatting Consistency

Removed backticks around file path may degrade markdown rendering; confirm intended formatting in LSP clients and that paths with special characters render safely.

"### ⚡️ Optimization Summary",
f"Function: `{self.function_to_optimize.qualified_name}`",
f"File: {explanation.file_path}",
f"Performance: {explanation.perf_improvement_line}",
"",

@github-actions
Copy link

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Possible issue
Guard cancel path robustness

cancel_event may be undefined here if the exception occurs before its creation,
leading to UnboundLocalError. Guard its use and ensure a correctly spelled cancel
response function is called.

codeflash/lsp/beta.py [513-515]

 except asyncio.CancelledError:
-    cancel_event.set()
-    return get_cancelled_reponse()
+    try:
+        cancel_event.set()  # may not exist if raised earlier
+    except UnboundLocalError:
+        pass
+    return get_cancelled_response()
Suggestion importance[1-10]: 7

__

Why: If asyncio.CancelledError is raised before line 494, cancel_event would be undefined, causing UnboundLocalError; also the function call appears misspelled (get_cancelled_reponse). Guarding access and fixing the name improves robustness.

Medium
General
Preserve Markdown code formatting

Removing backticks can break Markdown formatting and paths with underscores may
render as italics, degrading readability. Restore code formatting with backticks to
preserve output fidelity.

codeflash/optimization/function_optimizer.py [849]

-f"File: {explanation.file_path}",
+f"File: `{explanation.file_path}`",
Suggestion importance[1-10]: 6

__

Why: The PR removes backticks around explanation.file_path, which can harm Markdown rendering (e.g., underscores). Restoring backticks improves output readability without changing logic.

Low
Remove unused cancel flag

The cancel_event is created but never used or propagated, which can mislead and fail
to cancel long-running work. Either pass cancel_event into downstream functions that
support cancellation or remove it to avoid dead code and false assumptions.

codeflash/lsp/beta.py [493-495]

 _init()
-cancel_event = threading.Event()
+# Removed unused cancel_event to avoid dead code; ensure downstream receives a real cancel handle if needed.
 ...
Suggestion importance[1-10]: 5

__

Why: cancel_event is created at line 494 but never passed or used except in the except block, which can mislead; removing it or properly wiring it improves clarity. Impact is moderate since it's not functionally used for cancellation in the shown code.

Low

@mohammedahmed18 mohammedahmed18 merged commit 07c3586 into main Nov 25, 2025
22 of 23 checks passed
@mohammedahmed18 mohammedahmed18 deleted the lsp/retrun-runtime-info-and-cancel-demo-opt branch November 25, 2025 23:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants