From 82b260b7ed737e2165d9a4ec62460331f02fbe96 Mon Sep 17 00:00:00 2001 From: Seth Troisi Date: Mon, 30 Nov 2026 13:07:57 -0800 Subject: [PATCH] feat(session): add -v/--verify flag to colab new --- README.md | 2 +- docs/01_session_management.md | 5 +- src/colab_cli/client.py | 1 + src/colab_cli/commands/session.py | 134 +++++++++++++- tests/test_cli.py | 281 ++++++++++++++++++++++++++++++ tests/test_client.py | 26 +++ 6 files changed, 445 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 90b49ea8..2b82863c 100644 --- a/README.md +++ b/README.md @@ -68,7 +68,7 @@ Run `colab --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 | diff --git a/docs/01_session_management.md b/docs/01_session_management.md index 9ae719d6..b028b06a 100644 --- a/docs/01_session_management.md +++ b/docs/01_session_management.md @@ -1,5 +1,6 @@ --- log: +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 ` 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`. @@ -104,6 +105,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. @@ -154,7 +156,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 ` 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. diff --git a/src/colab_cli/client.py b/src/colab_cli/client.py index f32d3598..0addec6f 100644 --- a/src/colab_cli/client.py +++ b/src/colab_cli/client.py @@ -203,6 +203,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): diff --git a/src/colab_cli/commands/session.py b/src/colab_cli/commands/session.py index 8f208535..769e57b5 100644 --- a/src/colab_cli/commands/session.py +++ b/src/colab_cli/commands/session.py @@ -19,6 +19,7 @@ from colab_cli.client import ( Accelerator, + AssignmentVariant, ColabRequestError, HIGH_MEM_ONLY_ACCELERATORS, PostAssignmentResponse, @@ -113,6 +114,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 new( session: Annotated[ Optional[str], typer.Option("-s", "--session", help="Session name") @@ -148,6 +255,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 @@ -240,6 +359,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.") @@ -347,7 +477,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 @@ -358,7 +488,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( diff --git a/tests/test_cli.py b/tests/test_cli.py index 085a61f4..85037304 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -26,10 +26,14 @@ from colab_cli.cli import app from colab_cli.state import SessionState, Settings from colab_cli.client import ( + Accelerator, Assignment, + AssignmentVariant, ColabRequestError, + ListedAssignment, PostAssignmentResponse, RuntimeProxyInfo, + Shape, TooManyAssignmentsError, ) from colab_cli.consumption import ConsumptionUserInfo @@ -457,6 +461,283 @@ def test_cli_new_default_is_cpu(mock_client, mock_store): assert added_state.accelerator == "NONE" +def _make_post_response( + endpoint="e1", + variant=AssignmentVariant.DEFAULT, + accelerator=Accelerator.NONE, + machine_shape=Shape.STANDARD, +): + payload = { + "endpoint": endpoint, + "variant": variant, + "accelerator": accelerator, + "runtimeProxyInfo": { + "token": "t1", + "tokenExpiresInSeconds": 3600, + "url": "https://u1", + }, + } + if machine_shape is not None: + payload["machineShape"] = machine_shape + return PostAssignmentResponse.model_validate(payload) + + +def _make_listed_assignment( + endpoint="e1", + variant=AssignmentVariant.DEFAULT, + accelerator=Accelerator.NONE, + machine_shape=Shape.STANDARD, +): + return ListedAssignment( + endpoint=endpoint, + variant=variant, + accelerator=accelerator, + machineShape=machine_shape, + runtimeProxyInfo=RuntimeProxyInfo( + token="t1", tokenExpiresInSeconds=3600, url="https://u1" + ), + ) + + +@pytest.mark.parametrize( + "flags,variant,accelerator,machine_shape", + [ + (["-v"], AssignmentVariant.DEFAULT, Accelerator.NONE, Shape.STANDARD), + ( + ["--verify", "--high-mem"], + AssignmentVariant.DEFAULT, + Accelerator.NONE, + Shape.HIGH_RAM, + ), + ( + ["-v", "--gpu", "A100", "--high-mem"], + AssignmentVariant.GPU, + Accelerator.A100, + Shape.HIGH_RAM, + ), + ( + ["--verify", "--gpu", "L4", "--high-mem"], + AssignmentVariant.GPU, + Accelerator.L4, + Shape.STANDARD, + ), + ( + ["-v", "--tpu", "v5e1"], + AssignmentVariant.TPU, + Accelerator.V5E1, + Shape.STANDARD, + ), + ], +) +def test_cli_new_verify_succeeds_on_matching_response( + mock_client, mock_store, flags, variant, accelerator, machine_shape +): + mock_client.assign.return_value = _make_post_response( + variant=variant, accelerator=accelerator, machine_shape=machine_shape + ) + + result = runner.invoke(app, ["new", "-s", "verified-sess", *flags]) + + assert result.exit_code == 0, result.output + assert "Verified session 'verified-sess'" in result.output + assert "Session READY." in result.output + mock_client.list_assignments.assert_not_called() + mock_client.unassign.assert_not_called() + mock_store.remove.assert_not_called() + + +@pytest.mark.parametrize( + "flags,actual_variant,actual_acc,actual_shape", + [ + ( + ["-v", "--gpu", "A100"], + AssignmentVariant.GPU, + Accelerator.T4, + Shape.STANDARD, + ), + ( + ["--verify", "--gpu", "T4"], + AssignmentVariant.DEFAULT, + Accelerator.NONE, + Shape.STANDARD, + ), + ( + ["-v", "--gpu", "A100", "--high-mem"], + AssignmentVariant.GPU, + Accelerator.A100, + Shape.STANDARD, + ), + ( + ["--verify"], + AssignmentVariant.GPU, + Accelerator.T4, + Shape.STANDARD, + ), + ( + ["-v", "--tpu", "v5e1"], + AssignmentVariant.TPU, + Accelerator.V6E1, + Shape.STANDARD, + ), + ], +) +def test_cli_new_verify_mismatch_stops_session_and_exits_1( + mock_client, + mock_store, + mock_history, + flags, + actual_variant, + actual_acc, + actual_shape, +): + mock_client.assign.return_value = _make_post_response( + endpoint="ep-bad", + variant=actual_variant, + accelerator=actual_acc, + machine_shape=actual_shape, + ) + + result = runner.invoke(app, ["new", "-s", "bad-sess", *flags]) + + assert result.exit_code == 1 + assert "verification failed" in result.output.lower() + assert "Session READY." not in result.output + mock_client.unassign.assert_called_once_with("ep-bad") + mock_store.remove.assert_called_once_with("bad-sess") + mock_history.log_event.assert_any_call( + "bad-sess", "session_terminated", {"reason": "verification_failed"} + ) + + +def test_cli_new_verify_falls_back_to_list_assignments_when_shape_missing( + mock_client, mock_store +): + mock_client.assign.return_value = _make_post_response( + endpoint="ep1", + variant=AssignmentVariant.GPU, + accelerator=Accelerator.A100, + machine_shape=None, + ) + mock_client.list_assignments.return_value = [ + _make_listed_assignment( + endpoint="ep1", + variant=AssignmentVariant.GPU, + accelerator=Accelerator.A100, + machine_shape=Shape.STANDARD, + ) + ] + + result = runner.invoke( + app, ["new", "-s", "hm-sess", "--gpu", "A100", "--high-mem", "-v"] + ) + + assert result.exit_code == 1 + mock_client.list_assignments.assert_called_once_with() + mock_client.unassign.assert_called_once_with("ep1") + mock_store.remove.assert_called_once_with("hm-sess") + + +def test_cli_new_verify_accelerator_mismatch_without_shape_skips_list_assignments( + mock_client, mock_store +): + mock_client.assign.return_value = _make_post_response( + endpoint="ep-nos", + variant=AssignmentVariant.GPU, + accelerator=Accelerator.T4, + machine_shape=None, + ) + + result = runner.invoke(app, ["new", "-s", "acc-sess", "--gpu", "A100", "-v"]) + + assert result.exit_code == 1 + assert "Shape: Unknown" in result.output + mock_client.list_assignments.assert_not_called() + mock_client.unassign.assert_called_once_with("ep-nos") + mock_store.remove.assert_called_once_with("acc-sess") + + +def test_cli_new_verify_falls_back_to_list_assignments_for_recovered_assignment( + mock_client, mock_store +): + mock_client.assign.return_value = Assignment( + endpoint="ep-rec", + runtimeProxyInfo=RuntimeProxyInfo( + token="t1", tokenExpiresInSeconds=3600, url="https://u1" + ), + ) + mock_client.list_assignments.return_value = [ + _make_listed_assignment( + endpoint="ep-rec", + variant=AssignmentVariant.GPU, + accelerator=Accelerator.T4, + machine_shape=Shape.STANDARD, + ) + ] + + result = runner.invoke(app, ["new", "-s", "rec-sess", "--gpu", "T4", "--verify"]) + + assert result.exit_code == 0, result.output + mock_client.list_assignments.assert_called_once_with() + mock_client.unassign.assert_not_called() + + +def test_cli_new_verify_missing_in_list_assignments_stops_and_exits_1( + mock_client, mock_store +): + mock_client.assign.return_value = Assignment( + endpoint="ep-ghost", + runtimeProxyInfo=RuntimeProxyInfo( + token="t1", tokenExpiresInSeconds=3600, url="https://u1" + ), + ) + mock_client.list_assignments.return_value = [] + + result = runner.invoke(app, ["new", "-s", "ghost-sess", "-v"]) + + assert result.exit_code == 1 + assert "ep-ghost" in result.output + mock_client.unassign.assert_called_once_with("ep-ghost") + mock_store.remove.assert_called_once_with("ghost-sess") + + +def test_cli_new_verify_list_assignments_error_stops_and_exits_1( + mock_client, mock_store +): + mock_client.assign.return_value = Assignment( + endpoint="ep-err", + runtimeProxyInfo=RuntimeProxyInfo( + token="t1", tokenExpiresInSeconds=3600, url="https://u1" + ), + ) + mock_client.list_assignments.side_effect = RuntimeError("network error") + + result = runner.invoke(app, ["new", "-s", "err-sess", "-v"]) + + assert result.exit_code == 1 + assert "network error" in result.output + mock_client.unassign.assert_called_once_with("ep-err") + mock_store.remove.assert_called_once_with("err-sess") + + +def test_cli_new_verify_unassign_failure_still_exits_1_and_keeps_local_state( + mock_client, mock_store +): + mock_client.assign.return_value = _make_post_response( + endpoint="ep-stuck", + variant=AssignmentVariant.DEFAULT, + accelerator=Accelerator.NONE, + machine_shape=Shape.STANDARD, + ) + mock_client.unassign.side_effect = RuntimeError("unassign failed") + + result = runner.invoke(app, ["new", "-s", "stuck-sess", "--gpu", "T4", "-v"]) + + assert result.exit_code == 1 + assert "Failed to stop session 'stuck-sess'" in result.output + mock_client.unassign.assert_called_once_with("ep-stuck") + mock_store.remove.assert_not_called() + + def test_cli_help(): result = runner.invoke(app, ["--help"]) assert result.exit_code == 0 diff --git a/tests/test_client.py b/tests/test_client.py index 5868fa96..c4859bb9 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -432,6 +432,32 @@ def test_client_assign_url_omits_shape_for_standard(client, mock_session): assert "shape=" not in get_url +@pytest.mark.parametrize( + "raw_shape,expected_shape", + [ + (0, Shape.STANDARD), + (1, Shape.HIGH_RAM), + (None, None), + ], +) +def test_post_assignment_response_parses_machine_shape(raw_shape, expected_shape): + payload = { + "accelerator": "A100", + "endpoint": "ep1", + "variant": 1, + "runtimeProxyInfo": { + "token": "t1", + "tokenExpiresInSeconds": 3600, + "url": "https://backend", + }, + } + if raw_shape is not None: + payload["machineShape"] = raw_shape + + res = PostAssignmentResponse.model_validate(payload) + assert res.machine_shape == expected_shape + + @pytest.mark.parametrize( "accelerator,high_mem,expected", [