Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 60 additions & 1 deletion src/colab_cli/commands/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -391,17 +391,76 @@ def _stopOne(name: str, s: SessionState) -> None:
state.history.log_event(name, "session_terminated", {"reason": "user_requested"})


def _stop_untracked_assignment(endpoint: str, url: str, token: str) -> None:
"""Terminate a backend assignment that has no local session metadata."""
from colab_cli.common import state

typer.echo(f"[colab] Stopping untracked assignment '{endpoint}'...")
try:
ColabRuntime(url, token).stop(shutdown_kernel=True)
except Exception:
pass
state.client.unassign(endpoint)
state.history.log_event(
endpoint,
"session_terminated",
{"reason": "user_requested", "untracked": True},
)


def stop(
session: Annotated[
Optional[str], typer.Option("-s", "--session", help="Session name")
] = None,
endpoint: Annotated[
Optional[str],
typer.Option(
"--endpoint",
help=(
"Backend assignment endpoint ID (e.g. from 'colab sessions') "
"to stop a tracked or untracked '[?]' runtime directly"
),
),
] = None,
allSessions: Annotated[
bool, typer.Option("--all", help="Stop all active sessions")
] = False,
):
"""Stop a session, or all sessions with --all"""
"""Stop a session, backend endpoint, or all sessions"""
from colab_cli.common import state

if endpoint is not None:
if session is not None or allSessions:
typer.echo(
"[colab] Error: --endpoint cannot be combined with --session or --all.",
err=True,
)
raise typer.Exit(1)

sessions, assignments = state.sync_sessions()
for name, s in sessions.items():
if s.endpoint == endpoint:
_stopOne(name, s)
typer.echo("[colab] Session terminated.")
return

match = next((a for a in assignments if a.endpoint == endpoint), None)
if match is None:
typer.echo(
f"[colab] Backend assignment '{endpoint}' not found. "
"Run 'colab sessions' to list active assignments.",
err=True,
)
raise typer.Exit(1)

_stop_untracked_assignment(
match.endpoint,
match.runtime_proxy_info.url,
match.runtime_proxy_info.token,
)
typer.echo("[colab] Session terminated.")
return

if allSessions:
sessions, _ = state.sync_sessions()
if not sessions:
Expand Down
58 changes: 58 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,64 @@ def test_cli_stop_all_no_sessions(mock_common_state):
assert "No active sessions" in result.output


def test_cli_stop_by_endpoint_untracked_assignment(
mock_client, mock_store, mock_common_state
):
orphan = MagicMock()
orphan.endpoint = "gpu-l4-s-orphan-123"
orphan.runtime_proxy_info.url = "https://orphan-backend"
orphan.runtime_proxy_info.token = "orphan-token"
mock_common_state.sync_sessions.return_value = ({}, [orphan])

result = runner.invoke(app, ["stop", "--endpoint", "gpu-l4-s-orphan-123"])
assert result.exit_code == 0
assert "Stopping untracked assignment 'gpu-l4-s-orphan-123'" in result.output
mock_client.unassign.assert_called_once_with("gpu-l4-s-orphan-123")
mock_store.remove.assert_not_called()


def test_cli_stop_by_endpoint_tracked_session(
mock_client, mock_store, mock_common_state
):
tracked = MagicMock()
tracked.endpoint = "e1"
tracked.name = "s1"
tracked.url = "http://url"
tracked.token = "token"
tracked.kernel_id = None
mock_common_state.sync_sessions.return_value = ({"s1": tracked}, [])

result = runner.invoke(app, ["stop", "--endpoint", "e1"])
assert result.exit_code == 0
mock_client.unassign.assert_called_once_with("e1")
mock_store.remove.assert_called_once_with("s1")


def test_cli_stop_by_endpoint_not_found(mock_client, mock_store, mock_common_state):
mock_common_state.sync_sessions.return_value = ({}, [])

result = runner.invoke(app, ["stop", "--endpoint", "missing-ep"])
assert result.exit_code == 1
assert "Backend assignment 'missing-ep' not found." in result.output
mock_client.unassign.assert_not_called()


@pytest.mark.parametrize(
"args",
[
["stop", "--endpoint", "e1", "-s", "s1"],
["stop", "--endpoint", "e1", "--all"],
],
)
def test_cli_stop_endpoint_conflicts_with_session_or_all(
args, mock_client, mock_common_state
):
result = runner.invoke(app, args)
assert result.exit_code == 1
assert "--endpoint cannot be combined" in result.output
mock_client.unassign.assert_not_called()


def test_cli_sessions_prune(mock_common_state):
mock_assignment = MagicMock()
mock_session_state1 = MagicMock()
Expand Down