Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

Cancel queued execution requests on interruption (#1812)

Akshay Agrawal79ffeeb29ef8
diff --git a/marimo/_runtime/requests.py b/marimo/_runtime/requests.py
index aaed3157aa..80585dbe8a 100644
--- a/marimo/_runtime/requests.py
+++ b/marimo/_runtime/requests.py
@@ -1,6 +1,7 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+import time
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Tuple, TypeVar, Union
from uuid import uuid4
@@ -24,6 +25,7 @@ SerializedCLIArgs = Dict[str, ListOrValue[Primitive]]
class ExecutionRequest:
cell_id: CellId_t
code: str
+ timestamp: float = field(default_factory=time.time)
@dataclass
@@ -36,11 +38,15 @@ class ExecuteMultipleRequest:
cell_ids: List[CellId_t]
# code to register/run for each cell
codes: List[str]
+ # time at which the request was received
+ timestamp: float = field(default_factory=time.time)
@property
def execution_requests(self) -> List[ExecutionRequest]:
return [
- ExecutionRequest(cell_id=cell_id, code=code)
+ ExecutionRequest(
+ cell_id=cell_id, code=code, timestamp=self.timestamp
+ )
for cell_id, code in zip(self.cell_ids, self.codes)
]
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index 1531d75da2..e4d53d63b5 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -26,7 +26,7 @@ from typing import (
from uuid import uuid4
from marimo import _loggers
-from marimo._ast.cell import CellConfig, CellId_t
+from marimo._ast.cell import CellConfig, CellId_t, CellImpl
from marimo._ast.compiler import compile_cell
from marimo._ast.visitor import Name
from marimo._config.config import ExecutionType, MarimoConfig, OnCellChangeType
@@ -34,6 +34,7 @@ from marimo._data.preview_column import get_column_preview
from marimo._messaging.cell_output import CellChannel
from marimo._messaging.errors import (
Error,
+ MarimoInterruptionError,
MarimoStrictExecutionError,
MarimoSyntaxError,
UnknownError,
@@ -312,6 +313,10 @@ class Kernel:
self.stderr = stderr
self.stdin = stdin
self.enqueue_control_request = enqueue_control_request
+ # timestamp at which most recently processed interrupt was seen;
+ # the kernel rejects run requests that were issued before that
+ # timestamp, to save the user from having to spam the interrupt button
+ self.last_interrupt_timestamp: Optional[float] = None
self._preparation_hooks = (
preparation_hooks
@@ -982,6 +987,16 @@ class Kernel:
if isinstance(error, MarimoStrictExecutionError):
self.errors[cell_id] = (error,)
+ def note_time_of_interruption(
+ cell_impl: CellImpl,
+ runner: cell_runner.Runner,
+ run_result: cell_runner.RunResult,
+ ) -> None:
+ del cell_impl
+ del runner
+ if isinstance(run_result.exception, MarimoInterrupt):
+ self.last_interrupt_timestamp = time.time()
+
runner = cell_runner.Runner(
roots=roots,
graph=self.graph,
@@ -993,7 +1008,8 @@ class Kernel:
execution_context=self._install_execution_context,
preparation_hooks=self._preparation_hooks + [invalidate_state],
pre_execution_hooks=self._pre_execution_hooks,
- post_execution_hooks=self._post_execution_hooks,
+ post_execution_hooks=self._post_execution_hooks
+ + [note_time_of_interruption],
on_finish_hooks=(
self._on_finish_hooks
+ [broadcast_missing_packages, propagate_kernel_errors]
@@ -1045,10 +1061,35 @@ class Kernel:
Cells may use top-level await, which is why this function is async.
"""
+ filtered_requests: list[ExecutionRequest] = []
+ for request in execution_requests:
+ if (
+ self.last_interrupt_timestamp is not None
+ and request.timestamp < self.last_interrupt_timestamp
+ ):
+ CellOp.broadcast_error(
+ data=[MarimoInterruptionError()],
+ clear_console=False,
+ cell_id=request.cell_id,
+ )
+
+ # TODO(akshayka): This hack is needed because the FE
+ # sets status to queued when a cell is manually run; remove
+ # once setting status to queued on receipt of request is moved
+ # to backend (which will require moving execution requests to
+ # a dedicated multiprocessing queue and processing execution
+ # requests in a background thread).
+ CellOp.broadcast_status(
+ cell_id=request.cell_id,
+ status="idle",
+ )
+
+ else:
+ filtered_requests.append(request)
await self._run_cells(
self.mutate_graph(
- execution_requests,
+ filtered_requests,
deletion_requests=[
# Always delete the scratchpad cell
DeleteCellRequest(cell_id=SCRATCH_CELL_ID)
diff --git a/marimo/_smoke_tests/bugs/1684.py b/marimo/_smoke_tests/bugs/1684.py
index a2c29d281d..75da36e645 100644
--- a/marimo/_smoke_tests/bugs/1684.py
+++ b/marimo/_smoke_tests/bugs/1684.py
@@ -1,3 +1,4 @@
+# Copyright 2024 Marimo. All rights reserved.
import marimo
__generated_with = "0.7.5"
diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.py
index bc6c0b21b8..453bf25adc 100644
--- a/tests/_runtime/test_runtime.py
+++ b/tests/_runtime/test_runtime.py
@@ -694,6 +694,34 @@ class TestExecution:
# make sure the interrupt wasn't caught by the try/except
assert k.globals["tries"] == 0
+ async def test_interrupt_cancels_old_run_requests(
+ self, any_kernel: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ k = any_kernel
+ er_interrupt = exec_req.get(
+ """
+ from marimo._runtime.control_flow import MarimoInterrupt
+
+ tries = 0
+ while tries < 5:
+ try:
+ raise MarimoInterrupt
+ except Exception:
+ ...
+ tries += 1
+ """
+ )
+ er_other = exec_req.get("x = 0")
+ # set a timestamp that's guaranteed to be less than the time
+ # of the interrupt -- so er_other shouldn't run
+ er_other.timestamp = -1
+ await k.run([er_interrupt])
+ # make sure the interrupt wasn't caught by the try/except
+ assert k.globals["tries"] == 0
+ await k.run([er_other])
+ assert er_other.cell_id not in k.graph.cells
+ assert "x" not in k.globals
+
async def test_running_in_notebook(
self, any_kernel: Kernel, exec_req: ExecReqProvider
) -> None:
@@ -1016,13 +1044,15 @@ class TestStrictExecution:
[
ExecutionRequest(
cell_id="0",
- code=textwrap.dedent("""
+ code=textwrap.dedent(
+ """
try:
missing
except:
pass
x = 1
- """),
+ """
+ ),
),
]
)