From 30aedd1c3484aa447ca9f0f3cecd816e92734f80 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:55:28 +0000 Subject: [PATCH 1/2] fix(template): wait for an interrupted execution to end before the next one When a client abandons a long-running execution, the server interrupts the kernel. Starlette keeps cancelling the request task, so the shielded interrupt returned at once and the next execution's code reached the kernel first; ipykernel then aborted it with the interrupted cell. The interrupt now runs in its own task that waits for the interrupted execution to end, and the next execution waits for that task. Aborted execute replies (status "aborted", not "abort") now end the execution instead of hanging it. Co-Authored-By: mish@e2b.dev --- .changeset/interrupt-before-next-run.md | 5 +++ template/server/messaging.py | 44 ++++++++++++++++++++----- 2 files changed, 41 insertions(+), 8 deletions(-) create mode 100644 .changeset/interrupt-before-next-run.md diff --git a/.changeset/interrupt-before-next-run.md b/.changeset/interrupt-before-next-run.md new file mode 100644 index 00000000..0e784f72 --- /dev/null +++ b/.changeset/interrupt-before-next-run.md @@ -0,0 +1,5 @@ +--- +'@e2b/code-interpreter-template': patch +--- + +Fix the next execution timing out after a client abandons a long-running one: the server now waits for the interrupted execution to end before sending the next code to the kernel, and ends executions the kernel aborts instead of waiting for them forever. diff --git a/template/server/messaging.py b/template/server/messaging.py index 7248a5b4..d2230777 100644 --- a/template/server/messaging.py +++ b/template/server/messaging.py @@ -37,6 +37,7 @@ MAX_RECONNECT_RETRIES = 3 PING_TIMEOUT = 30 KEEPALIVE_INTERVAL = 5 # seconds between keepalive pings during streaming +INTERRUPT_TIMEOUT = 10 # seconds to wait for an interrupted execution to end class Execution: @@ -62,6 +63,7 @@ class ContextWebSocket: _receive_task: Optional[asyncio.Task] = None _global_env_vars: Optional[Dict[StrictStr, str]] = None _cleanup_task: Optional[asyncio.Task] = None + _interrupt_task: Optional[asyncio.Task] = None def __init__(self, context_id: str, session_id: str, language: str, cwd: str): self.language = language @@ -121,6 +123,26 @@ async def interrupt(self): except Exception as e: logger.error(f"Error interrupting kernel {self.context_id}: {e}") + async def _interrupt_execution(self, message_id: str): + """Interrupt the kernel and wait until the execution ends. + + A request sent to the kernel before the interrupted execution ends + would be aborted with it. + """ + queue = self._executions[message_id].queue + try: + await self.interrupt() + async with asyncio.timeout(INTERRUPT_TIMEOUT): + while (await queue.get()).type not in ( + OutputType.END_OF_EXECUTION, + OutputType.UNEXPECTED_END_OF_EXECUTION, + ): + pass + except TimeoutError: + logger.warning(f"Interrupted execution ({message_id}) did not end in time") + finally: + self._executions.pop(message_id, None) + def _get_execute_request( self, msg_id: str, code: Union[str, StrictStr], background: bool ) -> str: @@ -339,6 +361,11 @@ async def execute( finally: self._cleanup_task = None + if self._interrupt_task and not self._interrupt_task.done(): + logger.debug("Waiting for the interrupted execution to end") + await self._interrupt_task + self._interrupt_task = None + # Get the indentation level from the code code_indent = self._get_code_indentation(code) @@ -399,6 +426,9 @@ async def execute( # Stream the results. # If the client disconnects (Starlette cancels the task), we # interrupt the kernel so the next execution isn't blocked (#213). + # Starlette keeps cancelling this task, so the interrupt runs in + # its own task, which the next execution waits for. + abandoned = False try: async for item in self._wait_for_result(message_id): yield item @@ -406,15 +436,13 @@ async def execute( logger.warning( f"Client disconnected during execution ({message_id}), interrupting kernel" ) - # Shield the interrupt from the ongoing cancellation so - # the HTTP request to the kernel actually completes. - try: - await asyncio.shield(self.interrupt()) - except asyncio.CancelledError: - pass + abandoned = True + self._interrupt_task = asyncio.create_task( + self._interrupt_execution(message_id) + ) raise finally: - if message_id in self._executions: + if not abandoned and message_id in self._executions: del self._executions[message_id] # Clean up env vars in a separate request after the main code has run @@ -569,7 +597,7 @@ async def _process_message(self, data: dict): traceback="".join(data["content"].get("traceback", [])), ) ) - elif data["content"]["status"] == "abort": + elif data["content"]["status"] == "aborted": logger.debug(f"Execution {parent_msg_ig} was aborted") await queue.put( Error( From c1a1eac96cd7919f78b414d104915fc7a1de9dd8 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:11:34 +0000 Subject: [PATCH 2/2] fix(template): keep the interrupt wait running when the next request disconnects Co-Authored-By: mish@e2b.dev --- template/server/messaging.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/template/server/messaging.py b/template/server/messaging.py index d2230777..d2946af6 100644 --- a/template/server/messaging.py +++ b/template/server/messaging.py @@ -363,7 +363,7 @@ async def execute( if self._interrupt_task and not self._interrupt_task.done(): logger.debug("Waiting for the interrupted execution to end") - await self._interrupt_task + await asyncio.shield(self._interrupt_task) self._interrupt_task = None # Get the indentation level from the code