Skip to content
Open
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ Run `colab <command> --help` to view specific options, defaults, and detailed he
### Session Management
| Command | Description |
| --- | --- |
| `colab new [-s NAME] [--gpu GPU] [--tpu TPU] [--high-mem]` | Allocate a new CPU, GPU, or TPU VM runtime (optionally high-RAM) |
| `colab new [-s NAME] [--gpu GPU] [--tpu TPU] [--high-mem] [-v]` | Allocate a new CPU, GPU, or TPU VM runtime (optionally high-RAM, or `-v`/`--verify` runtime type) |
| `colab sessions` | List all active sessions currently active on the backend |
| `colab status [-s NAME]` | Display hardware, machine shape, status, and local metadata for active sessions |
| `colab restart-kernel [-s NAME]` | Restart the active session's Jupyter kernel |
Expand Down
5 changes: 4 additions & 1 deletion docs/01_session_management.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
---
log:
2026-12-01: Extracted `assign_runtime` in `session.py` (shared by `colab new` and `colab run`) to translate exhausted `HTTP 502/503/504` and `ReadTimeout` allocation failures into actionable CLI messages (including the browser Colab Terms of Service acceptance hint for first-time/newly entitled accounts, `colab sessions`, and `COLAB_CLI_REQUEST_TIMEOUT`) with exit code 1 instead of raw tracebacks (#273).
2026-11-30: Added `-v`/`--verify` to `colab new` (and optional `machineShape` parsing to `PostAssignmentResponse`) to verify server-reported `variant`, `accelerator`, and `machineShape` against the requested runtime type, falling back to `list_assignments()` when fields are absent; stops the session and exits 1 on mismatch or verification failure.
2026-11-23: `colab stop -s <name>` now exits 1 when the named session does not exist (or has already vanished from the backend), delegating missing-session handling to `State.get_session` (#251).
2026-11-13: Documented `--auth {oauth2,adc}` (default `oauth2`) and required ADC `gcloud` scopes under Global Flags.
2026-11-04: `--gpu` and `--tpu` now reject unknown values instead of silently selecting `A100` (GPU) or `v6e1` (TPU). `resolve_runtime_options()` uses the new `GPU_ACCELERATORS` / `TPU_ACCELERATORS` maps and raises a `typer.BadParameter` that names the flag and the supported list; `--help` is generated from the same maps so it cannot drift. Validation runs before any assignment request, in both `colab new` and `colab run`.
Expand Down Expand Up @@ -111,6 +112,7 @@ end to end; mocked timeouts alone do not establish backend compatibility.
- `accelerator`: Selected from the list above.
- **State Persistence**: The response contains a `token` and potentially a backend URL or identifier. We will store this in a local JSON file (default `~/.config/colab-cli/sessions.json`), readable only by its owner (mode 0600).
- Format: `{ "session_name": { "token": "...", "backend_url": "...", "hardware": "..." } }`
- **Runtime Verification (`-v` / `--verify`)**: Checks the server-reported assignment metadata (`variant`, `accelerator`, and `machineShape`) from `PostAssignmentResponse` (falling back to `GET /tun/m/assignments` / `list_assignments()` when `machineShape` is absent or when an existing `Assignment` was recovered). If the server's runtime does not match the requested type (or cannot be confirmed), the CLI prints the mismatch to stderr, stops/unassigns the session (`reason="verification_failed"`), and exits with status 1.

### 2. Session Status (`colab status`)
- **Session lines**: Local metadata per tracked session — hardware, shape, variant, IDLE/BUSY (from CLI bookkeeping), and optional last-execution detail. Syncs with `GET /tun/m/assignments` to prune stale entries.
Expand Down Expand Up @@ -161,7 +163,8 @@ The runtime proxy token (`runtimeProxyInfo.token`) authenticates every request t
TDD is mandatory for all session management features.

### 1. Mock Assignment API
- **Test Case**: Verify `colab new` correctly parses a `PostAssignmentResponse` and stores it in the local `StateStore`.
- **Test Case**: Verify `colab new` correctly parses a `PostAssignmentResponse` (including optional `machineShape`) and stores it in the local `StateStore`.
- **Test Case**: Verify `colab new -v`/`--verify` succeeds when server metadata matches (including single-shape accelerators where `--high-mem` is ignored), falls back to `list_assignments()` when `PostAssignmentResponse` lacks `machineShape` or an `Assignment` is recovered, and stops the session and exits 1 on mismatch or verification error.
- **Test Case**: Verify `colab stop` sends a `POST` request with the correct XSRF token to the unassign endpoint.
- **Test Case**: Verify `colab stop -s <missing>` prints a not-found error and exits with status 1 without calling unassign.
- **Test Case**: Verify that the path provided via `-c` is correctly passed to the authentication flow.
Expand Down
1 change: 1 addition & 0 deletions src/colab_cli/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,7 @@ class PostAssignmentResponse(BaseModel):
endpoint: str
runtime_proxy_info: RuntimeProxyInfo = Field(..., alias="runtimeProxyInfo")
variant: AssignmentVariant
machine_shape: Optional[Shape] = Field(default=None, alias="machineShape")


class GetAssignmentResponse(BaseModel):
Expand Down
134 changes: 132 additions & 2 deletions src/colab_cli/commands/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
from colab_cli.client import (
Accelerator,
Assignment,
AssignmentVariant,
ColabRequestError,
HIGH_MEM_ONLY_ACCELERATORS,
PostAssignmentResponse,
Expand Down Expand Up @@ -116,6 +117,112 @@ def resolve_runtime_options(
return variant, accelerator, shape


def _format_runtime_spec(
accelerator: str, variant: str, machine_shape: Optional[Shape]
) -> str:
shape_label = (
"Unknown" if machine_shape is None else shape_display_label(machine_shape)
)
return (
f"Hardware: {_hardware_label(accelerator)}"
f" | Shape: {shape_label}"
f" | Variant: {variant}"
)


def _extract_actual_runtime(
res,
endpoint: str,
client,
expected_variant: Variant,
expected_accelerator: Accelerator,
) -> Optional[tuple[AssignmentVariant, Accelerator, Optional[Shape]]]:
if isinstance(res, PostAssignmentResponse):
if (
res.variant.name != expected_variant.value
or res.accelerator != expected_accelerator
or res.machine_shape is not None
):
return res.variant, res.accelerator, res.machine_shape

for assignment in client.list_assignments():
if assignment.endpoint == endpoint:
return (
assignment.variant,
assignment.accelerator,
assignment.machine_shape,
)
return None


def _stop_unverified(name: str, session_state: SessionState) -> None:
try:
_stopOne(name, session_state, reason="verification_failed")
except Exception as e:
typer.echo(f"[colab] Failed to stop session '{name}': {e}", err=True)


def _verify_created_session(
name: str,
session_state: SessionState,
res,
expected_variant: Variant,
expected_accelerator: Accelerator,
expected_shape: Shape,
) -> None:
from colab_cli.common import state

try:
actual = _extract_actual_runtime(
res,
session_state.endpoint,
state.client,
expected_variant,
expected_accelerator,
)
except Exception as e:
typer.echo(
f"[colab] Runtime verification failed for session '{name}': {e}",
err=True,
)
_stop_unverified(name, session_state)
raise typer.Exit(code=1)

if actual is None:
typer.echo(
f"[colab] Runtime verification failed for session '{name}': "
f"assignment '{session_state.endpoint}' not found on server.",
err=True,
)
_stop_unverified(name, session_state)
raise typer.Exit(code=1)

actual_variant, actual_accelerator, actual_shape = actual
if (
actual_variant.name != expected_variant.value
or actual_accelerator != expected_accelerator
or actual_shape != expected_shape
):
expected_desc = _format_runtime_spec(
expected_accelerator.value, expected_variant.value, expected_shape
)
actual_desc = _format_runtime_spec(
actual_accelerator.value, actual_variant.name, actual_shape
)
typer.echo(
f"[colab] Runtime verification failed for session '{name}': "
f"expected {expected_desc}, got {actual_desc}.",
err=True,
)
_stop_unverified(name, session_state)
raise typer.Exit(code=1)

verified_desc = _format_runtime_spec(
actual_accelerator.value, actual_variant.name, actual_shape
)
typer.echo(f"[colab] Verified session '{name}': {verified_desc}.")


def assign_runtime(
client,
*,
Expand Down Expand Up @@ -209,6 +316,18 @@ def new(
),
),
] = False,
verify: Annotated[
bool,
typer.Option(
"-v",
"--verify",
help=(
"Verify the created session matches the requested runtime "
"type (variant, accelerator, and machine shape). Stops the "
"session and exits 1 on mismatch."
),
),
] = False,
):
"""Create a new session"""
from colab_cli.common import state
Expand Down Expand Up @@ -269,6 +388,17 @@ def new(
"machine_shape": s.machine_shape,
},
)
if verify:
_verify_created_session(
name=name,
session_state=s,
res=res,
expected_variant=variant,
expected_accelerator=accelerator,
expected_shape=(
Shape.HIGH_RAM if shape == Shape.HIGH_RAM else Shape.STANDARD
),
)
typer.echo("[colab] Session READY.")


Expand Down Expand Up @@ -377,7 +507,7 @@ def status(
_print_status_for(s)


def _stopOne(name: str, s: SessionState) -> None:
def _stopOne(name: str, s: SessionState, *, reason: str = "user_requested") -> None:
"""Terminate a single session (kernel, backend, local store)."""
from colab_cli.common import state

Expand All @@ -388,7 +518,7 @@ def _stopOne(name: str, s: SessionState) -> None:
pass
state.client.unassign(s.endpoint)
state.store.remove(name)
state.history.log_event(name, "session_terminated", {"reason": "user_requested"})
state.history.log_event(name, "session_terminated", {"reason": reason})


def stop(
Expand Down
Loading