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.

Fix: wait for thread completion in test client cleanup (#7783)

Akshay Agrawal88fdd8c9e381
diff --git a/tests/_server/api/endpoints/test_auto_instantiate.py b/tests/_server/api/endpoints/test_auto_instantiate.py
index a0c612b8ac..5b46024e98 100644
--- a/tests/_server/api/endpoints/test_auto_instantiate.py
+++ b/tests/_server/api/endpoints/test_auto_instantiate.py
@@ -36,7 +36,6 @@ class TestAutoInstantiateEditMode:
"""In edit mode, auto_instantiated should be False."""
session_id = "test-edit-mode"
ws_url = _create_ws_url(session_id)
- headers = _create_headers(session_id)
with client.websocket_connect(ws_url) as websocket:
data = websocket.receive_json()
@@ -46,8 +45,6 @@ class TestAutoInstantiateEditMode:
# In edit mode, auto_instantiated should be False
assert kernel_ready.auto_instantiated is False
- client.post("/api/kernel/shutdown", headers=headers)
-
def test_instantiate_endpoint_allowed_in_edit_mode(
self, client: TestClient
) -> None:
@@ -56,7 +53,11 @@ class TestAutoInstantiateEditMode:
ws_url = _create_ws_url(session_id)
headers = _create_headers(session_id)
- with client.websocket_connect(ws_url):
+ with client.websocket_connect(ws_url) as websocket:
+ # Wait for the session to be fully established
+ data = websocket.receive_json()
+ assert data["op"] == "kernel-ready"
+
# The /instantiate endpoint should work in edit mode
response = client.post(
"/api/kernel/instantiate",
@@ -65,8 +66,6 @@ class TestAutoInstantiateEditMode:
)
assert response.status_code == 200
- client.post("/api/kernel/shutdown", headers=headers)
-
class TestAutoInstantiateRunMode:
"""Tests for auto-instantiate in run mode."""
@@ -78,25 +77,19 @@ class TestAutoInstantiateRunMode:
from tests._server.conftest import get_session_manager
session_manager = get_session_manager(client)
- original_mode = session_manager.mode
session_id = "test-run-mode"
- headers = _create_headers(session_id)
- try:
- # Switch to run mode
- session_manager.mode = SessionMode.RUN
- ws_url = _create_ws_url(session_id)
+ # Switch to run mode
+ session_manager.mode = SessionMode.RUN
+ ws_url = _create_ws_url(session_id)
- with client.websocket_connect(ws_url) as websocket:
- data = websocket.receive_json()
- assert data["op"] == "kernel-ready"
+ with client.websocket_connect(ws_url) as websocket:
+ data = websocket.receive_json()
+ assert data["op"] == "kernel-ready"
- kernel_ready = parse_raw(data["data"], KernelReadyNotification)
- # In run mode, auto_instantiated should be True
- assert kernel_ready.auto_instantiated is True
- finally:
- session_manager.mode = original_mode
- client.post("/api/kernel/shutdown", headers=headers)
+ kernel_ready = parse_raw(data["data"], KernelReadyNotification)
+ # In run mode, auto_instantiated should be True
+ assert kernel_ready.auto_instantiated is True
def test_instantiate_endpoint_blocked_in_run_mode(
self, client: TestClient
@@ -109,27 +102,25 @@ class TestAutoInstantiateRunMode:
from tests._server.conftest import get_session_manager
session_manager = get_session_manager(client)
- original_mode = session_manager.mode
session_id = "test-instantiate-run"
headers = _create_headers(session_id)
- try:
- # Switch to run mode
- session_manager.mode = SessionMode.RUN
- ws_url = _create_ws_url(session_id)
-
- with client.websocket_connect(ws_url):
- # The /instantiate endpoint should be blocked in run mode
- # Returns 401 because @requires("edit") checks permissions
- response = client.post(
- "/api/kernel/instantiate",
- headers=headers,
- json={"objectIds": [], "values": [], "autoRun": False},
- )
- assert response.status_code == 401
- finally:
- session_manager.mode = original_mode
- client.post("/api/kernel/shutdown", headers=headers)
+ session_manager.mode = SessionMode.RUN
+ ws_url = _create_ws_url(session_id)
+
+ with client.websocket_connect(ws_url) as websocket:
+ # Wait for the session to be fully established
+ data = websocket.receive_json()
+ assert data["op"] == "kernel-ready"
+
+ # The /instantiate endpoint should be blocked in run mode
+ # Returns 401 because @requires("edit") checks permissions
+ response = client.post(
+ "/api/kernel/instantiate",
+ headers=headers,
+ json={"objectIds": [], "values": [], "autoRun": False},
+ )
+ assert response.status_code == 401
class TestAutoInstantiateHTTPRequest:
@@ -224,23 +215,20 @@ class TestInstantiateNotebookRequest:
ws_url = _create_ws_url(session_id)
headers = _create_headers(session_id)
- try:
- with client.websocket_connect(ws_url) as websocket:
- # Get the kernel-ready message
- data = websocket.receive_json()
- assert data["op"] == "kernel-ready"
-
- # Send instantiate without codes (should use file codes)
- response = client.post(
- "/api/kernel/instantiate",
- headers=headers,
- json={
- "objectIds": [],
- "values": [],
- "autoRun": True,
- # No codes field
- },
- )
- assert response.status_code == 200
- finally:
- client.post("/api/kernel/shutdown", headers=headers)
+ with client.websocket_connect(ws_url) as websocket:
+ # Get the kernel-ready message
+ data = websocket.receive_json()
+ assert data["op"] == "kernel-ready"
+
+ # Send instantiate without codes (should use file codes)
+ response = client.post(
+ "/api/kernel/instantiate",
+ headers=headers,
+ json={
+ "objectIds": [],
+ "values": [],
+ "autoRun": True,
+ # No codes field
+ },
+ )
+ assert response.status_code == 200
diff --git a/tests/_server/api/endpoints/test_execution.py b/tests/_server/api/endpoints/test_execution.py
index 48f3a20bd8..888fb690ef 100644
--- a/tests/_server/api/endpoints/test_execution.py
+++ b/tests/_server/api/endpoints/test_execution.py
@@ -126,11 +126,6 @@ class TestExecutionRoutes_EditMode:
assert response.status_code == 200, response.text
assert response.headers["content-type"] == "application/json"
assert "success" in response.json()
- auth_token = get_session_manager(client).auth_token
- client.post(
- "/api/kernel/shutdown",
- headers=token_header(auth_token),
- )
@staticmethod
@with_session(SESSION_ID)
diff --git a/tests/_server/api/endpoints/test_file_explorer.py b/tests/_server/api/endpoints/test_file_explorer.py
index 602da47158..dda5d9a152 100644
--- a/tests/_server/api/endpoints/test_file_explorer.py
+++ b/tests/_server/api/endpoints/test_file_explorer.py
@@ -133,10 +133,6 @@ def test_update_file_with_session(client: TestClient) -> None:
assert "@app.cell" in file_contents
assert "x=10; x" in file_contents
- # Shutdown
- client.post("/api/kernel/shutdown", headers=HEADERS)
-
- # Clean up
sm.watch = False
sm._watcher_manager.stop_all()
diff --git a/tests/_server/api/endpoints/test_home.py b/tests/_server/api/endpoints/test_home.py
index 503cecc001..af79171354 100644
--- a/tests/_server/api/endpoints/test_home.py
+++ b/tests/_server/api/endpoints/test_home.py
@@ -344,6 +344,3 @@ def test_running_notebooks_handles_files_outside_directory(
finally:
session_manager.file_router = original_file_router
session.app_file_manager.filename = original_filename
-
- # Shutdown to clean up
- client.post("/api/kernel/shutdown", headers=headers)
diff --git a/tests/_server/api/endpoints/test_kiosk.py b/tests/_server/api/endpoints/test_kiosk.py
index d8f6ab453f..a28583248e 100644
--- a/tests/_server/api/endpoints/test_kiosk.py
+++ b/tests/_server/api/endpoints/test_kiosk.py
@@ -152,8 +152,6 @@ async def test_connect_kiosk_with_session(client: TestClient) -> None:
"data": {"cell_id": "cell-3"},
}
- client.post("/api/kernel/shutdown", headers=HEADERS)
-
def _receive_until(op: str, websocket: WebSocketTestSession) -> dict[str, Any]:
while True:
diff --git a/tests/_server/api/endpoints/test_resume_session.py b/tests/_server/api/endpoints/test_resume_session.py
index f2618835af..debbc98906 100644
--- a/tests/_server/api/endpoints/test_resume_session.py
+++ b/tests/_server/api/endpoints/test_resume_session.py
@@ -163,7 +163,6 @@ def test_refresh_session(client: TestClient) -> None:
assert get_session(client, "789")
# Shutdown the kernel
- client.post("/api/kernel/shutdown", headers=HEADERS)
def test_save_session(client: TestClient) -> None:
@@ -243,7 +242,6 @@ def test_save_session(client: TestClient) -> None:
assert get_session(client, "456")
# Shutdown the kernel
- client.post("/api/kernel/shutdown", headers=HEADERS)
def test_save_config(client: TestClient) -> None:
@@ -270,7 +268,6 @@ def test_save_config(client: TestClient) -> None:
assert '"width": "full"' in response.text
# Shutdown the kernel
- client.post("/api/kernel/shutdown", headers=HEADERS)
def test_restart_session(client: TestClient) -> None:
@@ -300,7 +297,6 @@ def test_restart_session(client: TestClient) -> None:
)
# Shutdown the kernel
- client.post("/api/kernel/shutdown", headers=HEADERS)
@pytest.mark.flaky(reruns=5)
@@ -377,7 +373,6 @@ def test_resume_session_with_watch(client: TestClient) -> None:
session_manager.watch = False
session_manager._watcher_manager.stop_all()
- client.post("/api/kernel/shutdown", headers=HEADERS)
@contextmanager
diff --git a/tests/_server/api/endpoints/test_ws.py b/tests/_server/api/endpoints/test_ws.py
index b9dbe338f6..984a325624 100644
--- a/tests/_server/api/endpoints/test_ws.py
+++ b/tests/_server/api/endpoints/test_ws.py
@@ -96,9 +96,6 @@ def test_ws(client: TestClient) -> None:
with client.websocket_connect(WS_URL) as websocket:
data = websocket.receive_json()
assert_kernel_ready_response(data)
- # shut down after websocket context manager exists, otherwise
- # the test fails on windows (event loop closed twice)
- client.post("/api/kernel/shutdown", headers=HEADERS)
def test_without_session(client: TestClient) -> None:
@@ -107,7 +104,6 @@ def test_without_session(client: TestClient) -> None:
raise AssertionError()
assert exc_info.value.code == 1000
assert exc_info.value.reason == "MARIMO_NO_SESSION_ID"
- client.post("/api/kernel/shutdown", headers=HEADERS)
def test_disconnect_and_reconnect(client: TestClient) -> None:
@@ -121,8 +117,6 @@ def test_disconnect_and_reconnect(client: TestClient) -> None:
data = websocket.receive_json()
assert data["op"] == "alert"
- client.post("/api/kernel/shutdown", headers=HEADERS)
-
def test_disconnect_then_reconnect_then_refresh(client: TestClient) -> None:
with client.websocket_connect(WS_URL) as websocket:
@@ -142,8 +136,6 @@ def test_disconnect_then_reconnect_then_refresh(client: TestClient) -> None:
data = websocket.receive_json()
assert_kernel_ready_response(data, create_response({"resumed": True}))
- client.post("/api/kernel/shutdown", headers=HEADERS)
-
def test_allows_multiple_connections_with_other_sessions(
client: TestClient,
@@ -158,7 +150,6 @@ def test_allows_multiple_connections_with_other_sessions(
assert_kernel_ready_response(
data, create_response({"resumed": True})
)
- client.post("/api/kernel/shutdown", headers=HEADERS)
def test_fails_on_multiple_connections_with_other_sessions(
@@ -173,7 +164,6 @@ def test_fails_on_multiple_connections_with_other_sessions(
raise AssertionError()
assert exc_info.value.code == 1003
assert exc_info.value.reason == "MARIMO_ALREADY_CONNECTED"
- client.post("/api/kernel/shutdown", headers=HEADERS)
def test_allows_multiple_connections_with_same_file(
@@ -191,7 +181,6 @@ def test_allows_multiple_connections_with_same_file(
with client.websocket_connect(ws_2) as other_websocket:
data = other_websocket.receive_json()
assert_parse_ready_response(data)
- client.post("/api/kernel/shutdown", headers=HEADERS)
def test_fails_on_multiple_connections_with_same_file(
@@ -209,7 +198,6 @@ def test_fails_on_multiple_connections_with_same_file(
raise AssertionError()
assert exc_info.value.code == 1003
assert exc_info.value.reason == "MARIMO_ALREADY_CONNECTED"
- client.post("/api/kernel/shutdown", headers=HEADERS)
async def test_file_watcher_calls_reload(client: TestClient) -> None:
@@ -240,9 +228,7 @@ async def test_file_watcher_calls_reload(client: TestClient) -> None:
break
else:
raise AssertionError(f"Expected {expected}, but never received it")
- session_manager.mode = SessionMode.EDIT
session_manager.watch = False
- client.post("/api/kernel/shutdown", headers=HEADERS)
async def test_query_params(client: TestClient) -> None:
@@ -259,7 +245,6 @@ async def test_query_params(client: TestClient) -> None:
"bar": ["2", "3"],
"baz": "4",
}
- client.post("/api/kernel/shutdown", headers=HEADERS)
async def test_connect_kiosk_without_session(client: TestClient) -> None:
@@ -271,7 +256,6 @@ async def test_connect_kiosk_without_session(client: TestClient) -> None:
raise AssertionError()
assert exc_info.value.code == WebSocketCodes.NORMAL_CLOSE
assert exc_info.value.reason == "MARIMO_NO_SESSION"
- client.post("/api/kernel/shutdown", headers=HEADERS)
async def test_connect_kiosk_with_session(client: TestClient) -> None:
@@ -288,7 +272,6 @@ async def test_connect_kiosk_with_session(client: TestClient) -> None:
assert_kernel_ready_response(
data, create_response({"kiosk": True, "resumed": True})
)
- client.post("/api/kernel/shutdown", headers=HEADERS)
async def test_cannot_connect_kiosk_with_run_session(
@@ -311,9 +294,6 @@ async def test_cannot_connect_kiosk_with_run_session(
assert exc_info.value.code == WebSocketCodes.FORBIDDEN
assert exc_info.value.reason == "MARIMO_KIOSK_NOT_ALLOWED"
- client.post("/api/kernel/shutdown", headers=HEADERS)
- session_manager.mode = SessionMode.EDIT
-
async def test_connects_to_existing_session_with_same_file(
client: TestClient,
@@ -357,8 +337,6 @@ async def test_connects_to_existing_session_with_same_file(
assert len(messages2) == 4
assert messages2[0]["op"] == "variables"
- client.post("/api/kernel/shutdown", headers=HEADERS)
-
def flush_messages(
websocket: WebSocketTestSession, at_least: int = 0
@@ -393,12 +371,6 @@ def test_ws_requires_authentication(client: TestClient) -> None:
assert exc_info.value.code == WebSocketCodes.UNAUTHORIZED
assert exc_info.value.reason == "MARIMO_UNAUTHORIZED"
- # Ensure shutdown
- try:
- client.post("/api/kernel/shutdown", headers=HEADERS)
- except Exception:
- pass
-
def test_ws_sync_requires_authentication(client: TestClient) -> None:
"""Test that WebSocket sync endpoint requires authentication."""
@@ -419,7 +391,6 @@ def test_ws_with_valid_authentication(client: TestClient) -> None:
assert_kernel_ready_response(data)
# Clean up
- client.post("/api/kernel/shutdown", headers=HEADERS)
# ==============================================================================
@@ -463,8 +434,6 @@ async def test_session_resumption(client: TestClient) -> None:
replayed = flush_messages(websocket, at_least=1)
assert len(replayed) >= 1
- client.post("/api/kernel/shutdown", headers=HEADERS)
-
# ==============================================================================
# Edge Cases - Disconnection/Reconnection
@@ -496,9 +465,6 @@ async def test_reconnection_cancels_close_handle(client: TestClient) -> None:
session = session_manager.get_session("123")
assert session is not None
- session_manager.mode = SessionMode.EDIT
- client.post("/api/kernel/shutdown", headers=HEADERS)
-
async def test_run_mode_ttl_expiration(client: TestClient) -> None:
"""Test that sessions expire after TTL in RUN mode."""
@@ -526,8 +492,6 @@ async def test_run_mode_ttl_expiration(client: TestClient) -> None:
session = session_manager.get_session("123")
assert session is None
- session_manager.mode = SessionMode.EDIT
-
# ==============================================================================
# Edge Cases - Connection Validation
@@ -576,8 +540,6 @@ async def test_rtc_config_with_loro_unavailable(client: TestClient) -> None:
data = websocket.receive_json()
assert_kernel_ready_response(data)
- client.post("/api/kernel/shutdown", headers=HEADERS)
-
# ============================================================================
# Advanced WebSocket State Machine Tests
@@ -601,8 +563,6 @@ async def test_rapid_reconnection_cancels_ttl_cleanup(
data = websocket.receive_json()
assert data["op"] == "alert"
- client.post("/api/kernel/shutdown", headers=HEADERS)
-
async def test_multiple_rapid_reconnections(client: TestClient) -> None:
"""Test multiple rapid connect/disconnect cycles don't break session."""
@@ -614,8 +574,6 @@ async def test_multiple_rapid_reconnections(client: TestClient) -> None:
else:
assert data["op"] == "reconnected"
- client.post("/api/kernel/shutdown", headers=HEADERS)
-
async def test_websocket_message_queue_delivery(client: TestClient) -> None:
"""Test that kernel messages are queued and delivered."""
@@ -631,5 +589,3 @@ async def test_websocket_message_queue_delivery(client: TestClient) -> None:
messages = flush_messages(websocket, at_least=1)
assert len(messages) >= 1
-
- client.post("/api/kernel/shutdown", headers=HEADERS)
diff --git a/tests/_server/api/endpoints/test_ws_rtc.py b/tests/_server/api/endpoints/test_ws_rtc.py
index 551c535205..b3d6496ecb 100644
--- a/tests/_server/api/endpoints/test_ws_rtc.py
+++ b/tests/_server/api/endpoints/test_ws_rtc.py
@@ -149,9 +149,6 @@ async def test_loro_sync(client: TestClient) -> None:
assert len(sync_msg1) > 0
assert len(sync_msg2) > 0
- # Clean up by shutting down the kernel
- client.post("/api/kernel/shutdown", headers=HEADERS)
-
@pytest.mark.skipif(
"sys.version_info < (3, 11) or sys.version_info >= (3, 14)"
@@ -197,8 +194,6 @@ async def test_loro_cleanup_on_session_close(
assert len(DOC_MANAGER.loro_docs_clients[file_key]) == 0
- client.post("/api/kernel/shutdown", headers=HEADERS)
-
@pytest.mark.skipif(
"sys.version_info < (3, 11) or sys.version_info >= (3, 14)"
@@ -246,8 +241,6 @@ async def test_loro_persistence(client: TestClient) -> None:
# Verify initial sync contains data
assert len(sync_msg) > 0
- client.post("/api/kernel/shutdown", headers=HEADERS)
-
# ==============================================================================
# Edge Cases - RTC Availability and Graceful Degradation
@@ -291,8 +284,6 @@ async def test_rtc_degrades_without_loro(client: TestClient) -> None:
# Verify no RTC doc was created
assert file_key not in DOC_MANAGER.loro_docs
- client.post("/api/kernel/shutdown", headers=HEADERS)
-
# ==============================================================================
# Edge Cases - RTC Sync Endpoint
@@ -361,5 +352,3 @@ async def test_ws_sync_cleanup_on_main_disconnect(client: TestClient) -> None:
# Client should be removed
if file_key in DOC_MANAGER.loro_docs_clients:
assert len(DOC_MANAGER.loro_docs_clients[file_key]) == 0
-
- client.post("/api/kernel/shutdown", headers=HEADERS)
diff --git a/tests/_server/conftest.py b/tests/_server/conftest.py
index 026a62c816..3bef2e51b1 100644
--- a/tests/_server/conftest.py
+++ b/tests/_server/conftest.py
@@ -2,6 +2,7 @@
from __future__ import annotations
import sys
+import threading
from pathlib import Path
from tempfile import TemporaryDirectory
from typing import TYPE_CHECKING
@@ -17,6 +18,7 @@ from marimo._server.config import StarletteServerStateInit
from marimo._server.main import create_starlette_app
from marimo._server.session_manager import SessionManager
from marimo._server.utils import initialize_asyncio
+from marimo._session.session import SessionImpl
from marimo._session.state.session_view import SessionView
from tests._server.mocks import get_mock_session_manager
from tests.utils import assert_serialize_roundtrip
@@ -24,7 +26,8 @@ from tests.utils import assert_serialize_roundtrip
if TYPE_CHECKING:
from collections.abc import Generator, Iterator
-app = create_starlette_app(base_url="", enable_auth=True)
+# Module-level app only for client_with_lifespans fixture
+_module_app = create_starlette_app(base_url="", enable_auth=True)
@pytest.fixture(scope="session", autouse=True)
@@ -35,7 +38,7 @@ def init() -> bool:
@pytest.fixture(scope="module")
def client_with_lifespans() -> Generator[TestClient, None, None]:
- with TestClient(app) as c:
+ with TestClient(_module_app) as c:
yield c
@@ -60,6 +63,9 @@ def user_config_manager() -> Iterator[UserConfigManager]:
@pytest.fixture
def client(user_config_manager: UserConfigManager) -> Iterator[TestClient]:
main = sys.modules["__main__"]
+
+ # Create fresh app for this test to avoid shared state issues
+ app = create_starlette_app(base_url="", enable_auth=True)
client = TestClient(app)
StarletteServerStateInit(
port=1234,
@@ -82,7 +88,28 @@ def client(user_config_manager: UserConfigManager) -> Iterator[TestClient]:
app.state.server = uvicorn_server
yield client
- sys.modules["__main__"] = main
+
+ try:
+ session_manager: SessionManager = client.app.state.session_manager
+ kernel_tasks = []
+ # Kernels started in run mode run in their own threads; if these kernels
+ # execute code, they may patch and restore their own main modules.
+ # To ensure that this fixture correctly restores the original saved
+ # main module, we wait for threads to finish before restoring the module.
+ for session in session_manager.sessions.values():
+ assert isinstance(session, SessionImpl)
+ kernel_task = session._kernel_manager.kernel_task
+ if kernel_task is not None and isinstance(
+ kernel_task, threading.Thread
+ ):
+ kernel_tasks.append(kernel_task)
+
+ session_manager.shutdown()
+ for task in kernel_tasks:
+ if task.is_alive():
+ task.join()
+ finally:
+ sys.modules["__main__"] = main
def get_session_manager(client: TestClient) -> SessionManager: