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.

feat: add `--session-ttl` flag to marimo edit (#7863)

Anirudh Dagar2033b70abd85
diff --git a/marimo/_cli/cli.py b/marimo/_cli/cli.py
index 40d43e4309..415dc40c5a 100644
--- a/marimo/_cli/cli.py
+++ b/marimo/_cli/cli.py
@@ -397,6 +397,13 @@ edit_help_msg = "\n".join(
type=float,
help="Enable a global timeout to shut down the server after specified number of minutes of no connection",
)
+ "--session-ttl",
+ default=None,
+ show_default=False,
+ type=int,
+ help="Seconds to wait before closing a session on websocket disconnect. If None is provided, sessions are not automatically closed.",
+)
@click.argument(
"name",
required=False,
@@ -425,6 +432,7 @@ def edit(
server_startup_command: Optional[str],
asset_url: Optional[str],
timeout: Optional[float],
+ session_ttl: Optional[int],
name: Optional[str],
args: tuple[str, ...],
) -> None:
@@ -539,7 +547,7 @@ def edit(
base_url=base_url,
allow_origins=allow_origins,
redirect_console_to_browser=True,
- ttl_seconds=None,
+ ttl_seconds=session_ttl,
remote_url=remote_url,
mcp=mcp,
server_startup_command=server_startup_command,
diff --git a/marimo/_server/api/endpoints/ws_endpoint.py b/marimo/_server/api/endpoints/ws_endpoint.py
index 40b55fdf5d..272c9a36ca 100644
--- a/marimo/_server/api/endpoints/ws_endpoint.py
+++ b/marimo/_server/api/endpoints/ws_endpoint.py
@@ -327,10 +327,13 @@ class WebSocketHandler(SessionConsumer):
if session:
session.disconnect_consumer(self)
- if self.manager.mode == SessionMode.RUN:
- # When the websocket is closed, we wait session.ttl_seconds before
- # closing the session. This is to prevent the session from being
- # closed if the during an intermittent network issue.
+ # When the websocket is closed, we wait session.ttl_seconds before
+ # closing the session. This prevents the session from being closed
+ # during intermittent network issues.
+ # In RUN mode, this always applies.
+ # In EDIT mode, this only applies when --session-ttl is explicitly set.
+ if self.manager.ttl_seconds is not None:
+
def _close() -> None:
if self.status != ConnectionState.OPEN:
LOGGER.debug(
diff --git a/tests/_cli/test_cli.py b/tests/_cli/test_cli.py
index b0cfb351e5..caca374523 100644
--- a/tests/_cli/test_cli.py
+++ b/tests/_cli/test_cli.py
@@ -1427,3 +1427,29 @@ def test_cli_edit_with_timeout() -> None:
stdout, _ = p.communicate(timeout=5)
assert "Timeout due to inactivity" in stdout
+
+
+def test_cli_edit_with_session_ttl() -> None:
+ """Test that --session-ttl option is accepted by edit command."""
+ port = _get_port()
+ p = subprocess.Popen(
+ [
+ "marimo",
+ "edit",
+ "--no-token",
+ "--headless",
+ "-p",
+ str(port),
+ "--session-ttl",
+ "300",
+ "--skip-update-check",
+ ],
+ stderr=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ )
+ try:
+ contents = _try_fetch(port)
+ _check_contents(p, b'"mode": "home"', contents)
+ finally:
+ p.kill()
+ p.wait(timeout=5)
diff --git a/tests/_server/api/endpoints/test_ws.py b/tests/_server/api/endpoints/test_ws.py
index 984a325624..6b4c00948c 100644
--- a/tests/_server/api/endpoints/test_ws.py
+++ b/tests/_server/api/endpoints/test_ws.py
@@ -466,10 +466,23 @@ async def test_reconnection_cancels_close_handle(client: TestClient) -> None:
assert session is not None
-async def test_run_mode_ttl_expiration(client: TestClient) -> None:
- """Test that sessions expire after TTL in RUN mode."""
+ ("mode", "manager_ttl"),
+ [
+ (
+ SessionMode.RUN,
+ 120,
+ ), # RUN mode always uses TTL which has to be integer: default 120.
+ (SessionMode.EDIT, 120), # EDIT mode with --session-ttl
+ ],
+)
+async def test_session_ttl_expiration(
+ client: TestClient, mode: SessionMode, manager_ttl: int | None
+) -> None:
+ """Test that sessions expire after TTL in RUN mode or when TTL cleanup applies in EDIT mode."""
session_manager = get_session_manager(client)
- session_manager.mode = SessionMode.RUN
+ session_manager.mode = mode
+ session_manager.ttl_seconds = manager_ttl
with client.websocket_connect(WS_URL) as websocket:
data = websocket.receive_json()
@@ -479,7 +492,6 @@ async def test_run_mode_ttl_expiration(client: TestClient) -> None:
assert session is not None
# Override TTL to be very short for testing
- original_ttl = session.ttl_seconds
session.ttl_seconds = 0.1
# Close websocket
@@ -493,6 +505,34 @@ async def test_run_mode_ttl_expiration(client: TestClient) -> None:
assert session is None
+async def test_edit_mode_without_session_ttl_no_delayed_cleanup(
+ client: TestClient,
+) -> None:
+ """Test that EDIT mode without --session-ttl doesn't use TTL-based cleanup.
+
+ This is the default behavior for `marimo edit` (without --session-ttl flag).
+ Sessions persist for reconnection - no delayed TTL cleanup is scheduled.
+ """
+ session_manager = get_session_manager(client)
+ session_manager.mode = SessionMode.EDIT
+ # Default: no --session-ttl flag passed
+ assert session_manager.ttl_seconds is None
+
+ with client.websocket_connect(WS_URL) as websocket:
+ data = websocket.receive_json()
+ assert_kernel_ready_response(data)
+
+ session = session_manager.get_session("123")
+ assert session is not None
+
+ # Wait for disconnect handling
+ await asyncio.sleep(0.1)
+
+ # Session should still exist
+ session = session_manager.get_session("123")
+ assert session is not None
+
+
# ==============================================================================
# Edge Cases - Connection Validation
# ==============================================================================