Skip to content
Merged
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
26 changes: 26 additions & 0 deletions docs/01_session_management.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
---
log:
2026-10-14: Added configurable HTTP request timeouts and bounded allocation retries. Uncertain allocation POSTs are reconciled by GET using the same notebook hash before resubmission.
2026-09-25: Runtime proxy tokens are now refreshed before expiry. `SessionState` persists `token_expires_at`, and `State.get_session` re-fetches the token via `GET /tun/m/assignments` when it's within 5 minutes of expiring.
2026-09-25: Removed the keep-alive background daemon and related client/CLI ping functions. VM liveness is automatically maintained by the Colab backend based on kernel activity.
2026-08-10: Added `colab usage` for account-level compute-unit rate/balance via `GET /tun/m/ccu-info` on the session backend (same bearer token as `colab new`).
Expand Down Expand Up @@ -53,6 +54,31 @@ The CLI maps user flags to these backend parameters:

## Approach

### HTTP Timeout and Allocation Recovery

`COLAB_CLI_REQUEST_TIMEOUT` sets the HTTP request timeout in seconds. If unset,
the session's existing default applies (AuthorizedSession defaults to 120 seconds).
An explicit `timeout=` passed by a caller takes precedence. This does not change
kernel execution timeouts, Colab runtime lifetime, or benchmark job timeouts.

Allocation POSTs retry `ReadTimeout` and HTTP 502/503/504 at most
`COLAB_CLI_ASSIGN_RETRIES` times (default 3; 0 disables retries). Between attempts,
the client waits `COLAB_CLI_RETRY_BACKOFF * 2**attempt` seconds (default 10, 20, 40).
It then queries the same notebook hash: an existing allocation is returned directly;
otherwise the refreshed XSRF token is used for the next POST. HTTP 412 still raises
`TooManyAssignmentsError`; other errors are not retried. Failed initial/recovery
GETs and exhausted POST retries propagate to the caller. There is no unlimited wait.

```bash
COLAB_CLI_REQUEST_TIMEOUT=300 COLAB_CLI_ASSIGN_RETRIES=3 COLAB_CLI_RETRY_BACKOFF=10 \
colab new --session kernel-benchmark-v6e --tpu v6e1
```

Regression tests cover timeout precedence, same-request recovery, refreshed
tokens, retry limits, exponential backoff and permanent-error handling. A live
allocation/recovery test is also required before declaring the behavior verified
end to end; mocked timeouts alone do not establish backend compatibility.

### 1. New Session (`colab new`)
- **API**: `GET https://colab.sandbox.google.com/tun/m/assign` (based on HAR).
- **Parameters**:
Expand Down
62 changes: 45 additions & 17 deletions src/colab_cli/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,23 +13,26 @@
# limitations under the License.

import abc
import json
import logging
import os
import time
import uuid
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from enum import Enum
import json
import logging
from typing import Dict, List, Optional, Union
from urllib.parse import urljoin, urlparse
import uuid

import requests
from pydantic import BaseModel, Field, TypeAdapter

from colab_cli.consumption import (
CcuInfo,
ConsumptionUserInfo,
consumption_user_info_from_tunnel,
)
from colab_cli.utils import get_status_code
from pydantic import BaseModel, Field, TypeAdapter
import requests

# Standard Colab Headers
ACCEPT_JSON_HEADER = {"key": "Accept", "value": "application/json"}
Expand Down Expand Up @@ -214,6 +217,12 @@ def _issue_request(
"value"
]

# Slow allocations may outlive AuthorizedSession's default read timeout.
if "timeout" not in kwargs:
timeout = os.getenv("COLAB_CLI_REQUEST_TIMEOUT")
if timeout:
kwargs["timeout"] = float(timeout)

self.logger.debug(f"Request: {method} {endpoint}")
self.logger.debug(f"Params: {params}")

Expand Down Expand Up @@ -269,20 +278,40 @@ def assign(
accelerator: Optional[Accelerator] = None,
shape: Optional[Shape] = None,
) -> Union[PostAssignmentResponse, Assignment]:
assignment = self._get_assignment(
notebook_hash, variant, accelerator, shape
)
assignment = self._get_assignment(notebook_hash, variant, accelerator, shape)
if isinstance(assignment, Assignment):
return assignment

try:
res = self._post_assignment(
notebook_hash, assignment.token, variant, accelerator, shape
)
except ColabRequestError as e:
if get_status_code(e) == 412:
raise TooManyAssignmentsError(str(e))
raise e
retries = max(0, int(os.getenv("COLAB_CLI_ASSIGN_RETRIES", "3")))
backoff = max(0.0, float(os.getenv("COLAB_CLI_RETRY_BACKOFF", "10")))
for attempt in range(retries + 1):
try:
res = self._post_assignment(
notebook_hash, assignment.token, variant, accelerator, shape
)
break
except (ColabRequestError, requests.exceptions.ReadTimeout) as e:
status = (
get_status_code(e) if isinstance(e, ColabRequestError) else None
)
if status == 412:
raise TooManyAssignmentsError(str(e))
retryable = isinstance(
e, requests.exceptions.ReadTimeout
) or status in (502, 503, 504)
if not retryable or attempt >= retries:
raise
delay = backoff * (2**attempt)
self.logger.warning(
"Assignment request failed; retrying in %.0fs", delay
)
time.sleep(delay)
# Reconcile an uncertain POST before submitting the same request again.
assignment = self._get_assignment(
notebook_hash, variant, accelerator, shape
)
if isinstance(assignment, Assignment):
return assignment

return res

Expand Down Expand Up @@ -329,4 +358,3 @@ def _post_assignment(
return self._issue_request(
url, method="POST", headers=headers, schema=PostAssignmentResponse
)

167 changes: 162 additions & 5 deletions tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,21 @@
# See the License for the specific language governing permissions and
# limitations under the License.

import uuid
import json
import pytest
import uuid
from unittest.mock import MagicMock

import pytest
import requests

from colab_cli.client import (
Accelerator,
Assignment,
Client,
Prod,
ColabRequestError,
GetAssignmentResponse,
PostAssignmentResponse,
Assignment,
Accelerator,
Prod,
Shape,
TooManyAssignmentsError,
Variant,
Expand All @@ -39,6 +44,158 @@ def client(mock_session):
return Client(Prod(), mock_session)


def test_request_timeout_override_and_explicit_precedence(
client, mock_session, monkeypatch
):
monkeypatch.setenv("COLAB_CLI_REQUEST_TIMEOUT", "300")
mock_session.request.return_value.text = ""
client._issue_request("https://colab.research.google.com/test")
assert mock_session.request.call_args.kwargs["timeout"] == 300
client._issue_request("https://colab.research.google.com/test", timeout=12)
assert mock_session.request.call_args.kwargs["timeout"] == 12


def test_request_default_timeout_is_preserved(client, mock_session, monkeypatch):
monkeypatch.delenv("COLAB_CLI_REQUEST_TIMEOUT", raising=False)
mock_session.request.return_value.text = ""
client._issue_request("https://colab.research.google.com/test")
assert "timeout" not in mock_session.request.call_args.kwargs


def pending_assignment(token="initial"):
return GetAssignmentResponse(acc="NONE", nbh="same", token=token, variant="DEFAULT")


def allocated_assignment():
return Assignment(
endpoint="recovered",
runtimeProxyInfo={
"token": "proxy",
"tokenExpiresInSeconds": 3600,
"url": "http://backend",
},
)


@pytest.mark.parametrize("status", [None, 502, 503, 504])
def test_assign_recovers_before_another_post(client, mocker, monkeypatch, status):
monkeypatch.setenv("COLAB_CLI_ASSIGN_RETRIES", "3")
monkeypatch.setenv("COLAB_CLI_RETRY_BACKOFF", "10")
recovered = allocated_assignment()
get = mocker.patch.object(
client, "_get_assignment", side_effect=[pending_assignment(), recovered]
)
error = (
requests.exceptions.ReadTimeout("allocation pending")
if status is None
else ColabRequestError(
"transient", request=None, response=MagicMock(status_code=status)
)
)
post = mocker.patch.object(client, "_post_assignment", side_effect=error)
sleep = mocker.patch("time.sleep")
notebook = uuid.uuid4()
assert client.assign(notebook) is recovered
assert get.call_count == 2
assert all(call.args[0] == notebook for call in get.call_args_list)
post.assert_called_once()
sleep.assert_called_once_with(10)


def test_assign_refreshes_token_and_uses_bounded_backoff(client, mocker, monkeypatch):
monkeypatch.setenv("COLAB_CLI_ASSIGN_RETRIES", "3")
monkeypatch.setenv("COLAB_CLI_RETRY_BACKOFF", "10")
mocker.patch.object(
client,
"_get_assignment",
side_effect=[pending_assignment(str(i)) for i in range(4)],
)
post = mocker.patch.object(
client,
"_post_assignment",
side_effect=requests.exceptions.ReadTimeout("pending"),
)
sleep = mocker.patch("time.sleep")
notebook = uuid.uuid4()
with pytest.raises(requests.exceptions.ReadTimeout):
client.assign(notebook)
assert [call.args[:2] for call in post.call_args_list] == [
(notebook, str(i)) for i in range(4)
]
assert [call.args[0] for call in sleep.call_args_list] == [10, 20, 40]


@pytest.mark.parametrize("status", [400, 401, 403])
def test_assign_does_not_retry_nontransient_errors(client, mocker, status):
get = mocker.patch.object(
client, "_get_assignment", return_value=pending_assignment()
)
post = mocker.patch.object(
client,
"_post_assignment",
side_effect=ColabRequestError(
"permanent", request=None, response=MagicMock(status_code=status)
),
)
sleep = mocker.patch("time.sleep")
with pytest.raises(ColabRequestError):
client.assign(uuid.uuid4())
get.assert_called_once()
post.assert_called_once()
sleep.assert_not_called()


def test_assign_succeeds_after_recovery_refreshes_token(client, mocker, monkeypatch):
monkeypatch.setenv("COLAB_CLI_ASSIGN_RETRIES", "1")
monkeypatch.setenv("COLAB_CLI_RETRY_BACKOFF", "0")
get = mocker.patch.object(
client,
"_get_assignment",
side_effect=[pending_assignment("first"), pending_assignment("fresh")],
)
result = PostAssignmentResponse(
accelerator="NONE",
endpoint="new",
variant=0,
runtimeProxyInfo={
"token": "proxy",
"tokenExpiresInSeconds": 3600,
"url": "http://backend",
},
)
post = mocker.patch.object(
client,
"_post_assignment",
side_effect=[requests.exceptions.ReadTimeout("pending"), result],
)
mocker.patch("time.sleep")
notebook = uuid.uuid4()
assert client.assign(notebook) is result
assert get.call_count == 2
assert [call.args[:2] for call in post.call_args_list] == [
(notebook, "first"),
(notebook, "fresh"),
]


def test_assign_retries_can_be_disabled(client, mocker, monkeypatch):
monkeypatch.setenv("COLAB_CLI_ASSIGN_RETRIES", "0")
get = mocker.patch.object(
client, "_get_assignment", return_value=pending_assignment()
)
post = mocker.patch.object(
client,
"_post_assignment",
side_effect=requests.exceptions.ReadTimeout("pending"),
)
sleep = mocker.patch("time.sleep")
with pytest.raises(requests.exceptions.ReadTimeout):
client.assign(uuid.uuid4())
get.assert_called_once()
post.assert_called_once()
sleep.assert_not_called()


def test_client_assign_new(client, mock_session):
# Mock _get_assignment (GET)
get_resp = MagicMock()
Expand Down
Loading