You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The new execution context uses a single dict ContextVar and is manually copied when offloading to a thread. Verify all code paths that need task-scoped data run inside the execution_context manager and that contextvars.copy_context is always used when submitting to executors; otherwise, task_id may be missing or stale in logs/messages.
@contextlib.contextmanagerdefexecution_context(**kwargs: str) ->None:
"""Temporarily set context values for the current async task."""# Create a fresh copy per usecurrent= {**server.execution_context_vars.get(), **kwargs}
token=server.execution_context_vars.set(current)
try:
yieldfinally:
server.execution_context_vars.reset(token)
@server.feature("initializeFunctionOptimization")definitialize_function_optimization(params: FunctionOptimizationInitParams) ->dict[str, str]:
withexecution_context(task_id=params.task_id):
document_uri=params.textDocument.uridocument=server.workspace.get_text_document(document_uri)
server.show_message_log(
f"Initializing optimization for function: {params.functionName} in {document_uri}", "Info"
)
ifserver.optimizerisNone:
_initialize_optimizer_if_api_key_is_valid()
server.optimizer.worktree_mode()
original_args, _=server.optimizer.original_args_and_test_cfgserver.optimizer.args.function=params.functionNameoriginal_relative_file_path=Path(document.path).relative_to(original_args.project_root)
server.optimizer.args.file=server.optimizer.current_worktree/original_relative_file_pathserver.optimizer.args.previous_checkpoint_functions=False
Abort checkpoints raise RuntimeError("cancelled") but callers only handle asyncio.CancelledError. Ensure RuntimeError is caught and converted to a canceled response, or switch to a consistent exception type to avoid surfacing as generic errors.
The singleton creates a global LanguageServer but there is no explicit reset/shutdown path. Validate that tests or multiple CLI invocations won’t accidentally reuse shared state (optimizer, cancel_event, context vars) across sessions, and consider thread-safety for instance creation.
classCodeflashServerSingleton:
_instance: CodeflashLanguageServer|None=None@classmethoddefget(cls) ->CodeflashLanguageServer:
ifcls._instanceisNone:
cls._instance=CodeflashLanguageServer(
"codeflash-language-server", "v1.0", protocol_cls=CodeflashLanguageServerProtocol
)
returncls._instancedef__init__(self) ->None:
# This is a singleton class, so we don't want to initialize.
...
Avoid assigning server.cancel_event per request on the shared singleton, which can race across concurrent tasks. Instead, store the event in the context vars and have sync code fetch it from the server’s context storage.
Why: This addresses a real concurrency bug risk: storing per-request cancellation state on a shared singleton. Using context to keep the event task-local aligns with the new execution_context pattern and reduces race conditions.
Medium
Use dedicated cancellation exception
Raise a distinct, caught exception type rather than a generic RuntimeError so upstream can map it to a canceled response reliably. Update call sites to catch it and return get_cancelled_reponse() instead of bubbling an unhandled error.
Why: Introducing a specific cancellation exception can improve clarity and handling, but the current code already maps asyncio.CancelledError to a canceled response and uses a cancel_event with checks. This is a minor robustness improvement.
Low
Validate singleton initialization timing
Ensure the singleton server is created with the correct protocol class only once to avoid multiple event loops or protocol mismatch. Verify that CodeflashServerSingleton.get() is safe to call at import time in all execution contexts (tests, workers).
+# Defer singleton creation until first feature registration/runtime use if needed elsewhere
server = CodeflashServerSingleton.get()
Suggestion importance[1-10]: 5
__
Why: The suggestion is conceptually valid—import-time singleton instantiation can be risky—but it asks to "ensure/verify" behavior without concrete code change. Impact is moderate and context-aware, yet not critical.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
PR Type
Enhancement, Bug fix
Description
Introduce singleton LSP server instance
Add per-task execution context vars
Implement cancellation abort checkpoints
Simplify server feature handlers' signatures
Diagram Walkthrough
File Walkthrough
beta.py
Feature handlers refactor with context and cancelcodeflash/lsp/beta.py
CodeflashServerSingletonusage.task_idparam and execution context manager.perform_optimization.py
Add cancellable optimization checkpointscodeflash/lsp/features/perform_optimization.py
lsp_message.py
Propagate task_id in LSP messagescodeflash/lsp/lsp_message.py
task_idfrom execution context in messages.server.py
Server singleton and context vars supportcodeflash/lsp/server.py
CodeflashServerSingleton.execution_context_varscontextvar to server.