Metadata-Version: 2.5
Name: goaly-looper
Version: 0.1.0b2
Summary: Looper's SDK: the client and the typed values of Looper's API, looper.v1.
Requires-Python: >=3.12
Requires-Dist: httpx<1,>=0.28.1
Requires-Dist: protobuf<7,>=6.33.5
Description-Content-Type: text/markdown

# goaly-looper

Looper's SDK: the client and the typed values of Looper's API, `looper.v1`.
Looper is Goaly's hosted post-training service: a user's own program holds the
data, the rewards and the loop, and calls a few primitives that Looper runs on
GPUs it manages ([the design](../docs/README.md), [the API and the
SDK](../docs/sdk.md)).

Its import package is `looper_sdk`. It imports nothing of ours, so it installs
and runs on its own. It is a project of its own, with this `pyproject.toml`,
to be published as `goaly-looper` and open-sourced
([monorepo.md](../docs/monorepo.md) §4, §9).

Status: `looper.v1`'s messages for P1's calls; the values, losses, results
and errors, with the module that maps them onto the wire; and the clients
over httpx: `ServiceClient`, `TrainingClient` and `Operation` (sdk.md §3,
§6). Publishing, sampling and suspension join with their verbs
(server.md §14).

| Path | What lives there |
|---|---|
| `pyproject.toml` | The project: its version, read from `looper_sdk/_version.py`, and its dependency ranges |
| `looper_sdk/` | The import package |
| `looper_sdk/values.py`, `losses.py`, `optimizers.py`, `results.py` | What a client sends and what an operation computed: frozen values that validate themselves, with `_checks.py`'s checks |
| `looper_sdk/checkpoints.py` | `Checkpoint`, as a `StateCheckpoint` (from `save_state`) or a `WeightsCheckpoint` (from `save_weights`): a named registry value with expiry, identity and source-version provenance, and its `CheckpointState`: `uploading`, `ready_to_use` or `failed` ([sdk.md §4.6](../docs/sdk.md#46-checkpoints-and-exports)) |
| `looper_sdk/errors.py` | A class for each of §4.9's codes; retry semantics come with each error, as data |
| `looper_sdk/wire.py` | The values, results and errors as `looper.v1`'s messages, and back |
| `looper_sdk/proto/` | `looper.v1`'s protos and their generated modules |
| `looper_sdk/service.py`, `training.py`, `operations.py` | The clients: a program's session, a run's writer, and an accepted operation |
| `looper_sdk/transport.py` | httpx, the retries every call takes, and the session's heartbeats and closure |
| `looper_sdk/unit_tests/` | The SDK's unit tests, which import only what the SDK declares |

## Client lifetime

Use an async context manager when the program's work has a bounded scope:

```python
from looper_sdk import ServiceClient

config = ServiceClient.Config(project="research")
async with await config.build() as service:
    training = await service.create_training_client(training_config)
    status = await training.status()
```

The default API root is `https://api.looper.goaly.ai`, exported as
`looper_sdk.DEFAULT_BASE_URL`. Pass `base_url="http://127.0.0.1:8080"` for a
local service, or another root for an alternate deployment. Omit `/v1` from
the root: the SDK adds it to requests.

Exit closes the session and HTTP client and stops heartbeats, including when
the body raises or is cancelled. It invalidates local clients and records
termination of session-owned runs; the coordinator retires workers
asynchronously. Checkpoints and historical results retain their storage policy.

For an application-managed lifetime, keep the client and explicitly call
`await service.close()` in the application's shutdown path.

Raw requests and detailed results stay on service SSD until lifecycle
cleanup. After a training run ends or a sampler retires, cleanup can make
the original detailed result unavailable even if it was never downloaded.
Retrieval then raises non-retryable `ResultExpired`; it never reruns the
computation. Operation status and aggregate training metrics survive
indefinitely. Checkpoints retain their separate lifetime.

## API key

Every request sends `Authorization: Bearer <key>`: the config's `api_key`,
or `$LOOPER_API_KEY` when that is None. With neither, the client sends no
credential, which only local mode accepts (looper/docs/sdk.md §3). The key
never appears in the config's repr.

## Rules

- **Ranges, never pins.** Each dependency runs from the oldest version we
  test to the next major. An exact pin in a published wheel would conflict
  with the rest of a user's environment. protobuf's floor is the version of
  the generator that wrote `looper_sdk/proto/` (monorepo.md §4).
- **It imports nothing of ours.** `looper_server`'s import-rules test fails
  on any import of `goaly_rl`, `looper_server` or `looper_cookbook`, or
  through `looper.`.
- **Its tests import only what it declares,** so they pass outside this
  repository.

## Alone

CI's `looper-isolated` job builds the SDK's sdist, and a wheel from it. It
installs the wheel in a fresh environment, with the declared dependencies at
the lowest versions their ranges allow. It then runs the unit tests copied out
of the checkout, so `import looper_sdk` finds only the wheel (monorepo.md §7).
From the repository's root:

```bash
uv build looper/sdk --out-dir /tmp/looper-sdk
uv venv /tmp/looper-sdk/env --python 3.12
uv pip install --python /tmp/looper-sdk/env --resolution lowest-direct -r looper/sdk/pyproject.toml /tmp/looper-sdk/goaly_looper-*.whl pytest==9.1.1
cp -r looper/sdk/looper_sdk/unit_tests /tmp/looper-sdk/unit_tests
cd /tmp/looper-sdk && env/bin/python -m pytest -q unit_tests
```

## Publish a beta release to PyPI

[`publish.sh`](publish.sh) builds the SDK's sdist and a wheel from it, tests the
installed wheel in isolation at its dependency floors, then publishes both
artifacts to public PyPI as `goaly-looper`. It publishes only this standalone
SDK, never the server or the root project. PyPI distributions are publicly
accessible and discoverable; hosted API access still requires a Looper API key.

The version comes from `looper_sdk/_version.py`. Use beta versions such as
`0.1.0b1`, then `0.1.0b2`; never replace a release with different contents.

One-time setup: create a [PyPI account](https://pypi.org/account/register/), enable
2FA, and create an [API token](https://pypi.org/manage/account/token/). The first
upload creates the project, so its token initially needs account-wide scope.
Once the project exists, replace it with a token scoped to `goaly-looper`.
The name must be available, or the account must already have publishing access.

With `uv` and Python 3 installed, run from the repository root:

```bash
# Read the token without echoing it or storing its literal value in shell history.
read -r -s -p "PyPI API token: " UV_PUBLISH_TOKEN
printf '\n'
export UV_PUBLISH_TOKEN
bash looper/sdk/publish.sh
unset UV_PUBLISH_TOKEN
```

The hidden-prompt example uses Bash; in zsh use
`read -r -s 'UV_PUBLISH_TOKEN?PyPI API token: '` instead of its `read` line.
Never put the token in a notebook or commit it. `uv` uses a temporary Python 3.12
virtual environment for the SDK tests. No GCS credentials or bucket settings
are needed. The script works from any directory when called by its path.

Uploads use PyPI's check URL so retrying an unchanged release can complete a
partial upload without replacing existing files. An upload failure exits
nonzero; completed uploads may remain on PyPI. After uploading, the script
checks PyPI's release metadata, downloads both public artifacts and verifies
their SHA-256 against the local build. Only then does it print `SUCCESS`, the
project URL and an exact-version Colab/Jupyter install command. Verification
failure exits nonzero and leaves the release in place for investigation.
Temporary local artifacts are removed on exit. These checks prove SDK unit
behavior and artifact availability, not compatibility with a deployed service.

Users install the beta in Colab or local Jupyter with:

```python
%pip install "goaly-looper==0.1.0b2"
```

An exact prerelease pin does not require `--pre`. Future automation can use
PyPI Trusted Publishing; the local release script needs no CI configuration.

## Readiness and explicit closure

`create_training_client(config, key=..., timeout_s=...)` returns after the
training node is ready. The default wait has no overall deadline.
`CreationTimeout` carries the originating session ID, creation key and run ID
when known; accepted work remains intact. Service failures raise `CreationError`
with the original typed error in `.cause` and `__cause__`, preserving its
traceback and retry semantics.
An existing handle can `await training.wait_until_ready(timeout_s=...)`.

Explicit service closure, including context exit, rejects new calls with
`SessionClosed`. Pending calls have up to 60 seconds to finish while heartbeats
continue. Cleanup then stops heartbeats, cancels remaining calls and closes the
session and HTTP client. A call interrupted by shutdown raises `SessionClosed`;
caller cancellation remains `CancelledError`. The default close wait is 70
seconds; cancellation or a caller deadline leaves shared cleanup running while
the event loop remains alive. A later `close()` can wait again. Backend runs
end on session closure or expiry; workers retire asynchronously. Continuation
uses a new service and run, optionally from a saved checkpoint. Session identity
is immutable and expiry never renews it. Sampling clients, once added, must
borrow the same session lifetime.

`await training.save_state(name)` accepts a save; `await operation.result()`
answers once the step is on the worker group's local storage, with the
checkpoint `uploading`, while the run trains on. `await
service.wait_checkpoint(checkpoint.id)` waits until it is `ready_to_use`:
uploaded, named and loadable; it raises `CheckpointFailed` if the upload
never finished ([sdk.md §4.6](../docs/sdk.md#46-checkpoints-and-exports)).
`await training.save_weights(name)` takes the same stages for an export of
the weights alone, a `WeightsCheckpoint` that a sampler loads as it is and
`create_run(init=...)` refuses. Registry lookup, list and delete methods use
`ServiceClient`, and answer either kind.

## Checkpoint model metadata

Every checkpoint includes `model_spec: ModelSpec`, exported from
`looper_sdk`: the source run's `model` name and exact `Full()` or `Lora(...)`
configuration, including rank and target switches. It excludes workload sizing
and does not resolve a Hugging Face revision. Save results, registry lookups and
lists return this metadata; historical save results are completed by the server
from the immutable source run.

The updated SDK requires an updated server: missing or malformed model metadata
raises `InvalidArgument`. Older SDKs can ignore the additive binary protobuf
field. Clients using strict JSON schemas must allow the new response field.
