Metadata-Version: 2.4
Name: runlab-client
Version: 0.4.3
Summary: Did my change actually help? Verdicts over seeds with confidence intervals, for AI researchers, ML engineers and their coding agents. Python client and CLI for RunLab; standard library only.
Author: omer-nachman
License-Expression: MIT
Project-URL: Homepage, https://github.com/omer-nachman/runlab-python
Project-URL: Documentation, https://omer-nachman.github.io/runlab-python/api.html
Project-URL: Changelog, https://github.com/omer-nachman/runlab-python/blob/main/CHANGELOG.md
Project-URL: Issues, https://github.com/omer-nachman/runlab-python/issues
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: yaml
Requires-Dist: PyYAML>=6; extra == "yaml"
Dynamic: license-file

# runlab-client

[![PyPI](https://img.shields.io/pypi/v/runlab-client)](https://pypi.org/project/runlab-client/)
![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue)
![Status: public preview](https://img.shields.io/badge/status-public%20preview-orange)
[![License: MIT](https://img.shields.io/badge/license-MIT-blue)](https://github.com/omer-nachman/runlab-python/blob/main/LICENSE)

**Did my change actually help?**

RunLab compares a change (an augmentation, loss, prompt, or learning rate) against its baseline
across random seeds and returns a verdict you can quote — built for AI researchers, ML engineers,
and their coding agents. Your training stays where it runs today; the Python client and `runlab`
CLI require Python 3.10+ and **zero dependencies** (standard library only).

[API reference](https://omer-nachman.github.io/runlab-python/api.html) · [Examples](https://github.com/omer-nachman/runlab-python/tree/main/examples) · [Coding agents](https://github.com/omer-nachman/runlab-python/blob/main/AGENTS.md) · [Changelog](https://github.com/omer-nachman/runlab-python/blob/main/CHANGELOG.md)

## Get started

```bash
pip install -U runlab-client   # Python 3.10+, zero dependencies; upgrades an older copy
runlab demo                    # signs in with GitHub, then runs a 10-seed demo
```

The first time, a browser opens to sign in with GitHub. The demo plans, records 10 simulated seeds
per arm, compares them, and prints a verdict in seconds:

```text
treatment vs baseline on acc (higher is better): treatment is better
  paired_t: diff +0.01868 [95% CI +0.01371, +0.02365], p=1.37e-05, n=10 (A 10, B 10)
  ...
quotable: treatment − baseline on acc = +0.01868 (95 % CI [+0.01371, +0.02365]; ...)
The verdict page: https://runlab.tools/v/...
```

To sign in without running the demo, run `runlab login`.

<details>
<summary>No venv, Python &lt; 3.10, or pip says "externally-managed-environment"?</summary>

Install the CLI with [uv](https://docs.astral.sh/uv/) — it fetches Python 3.10+ itself (`--force`
replaces an older `runlab` executable):

```bash
uv tool install -U --force runlab-client
```

If uv is not installed, install it first with its standalone installer, then open a new terminal:

```bash
# On macOS and Linux.
curl -LsSf https://astral.sh/uv/install.sh | sh

# On Windows.
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
```

To also import `runlab_client` inside your training script, run `pip install -U runlab-client` in
your training environment; one sign-in serves both.

</details>

## Quickstart

Four calls take an experiment from plan to quotable verdict:

```python
from runlab_client import RunLab

rl = RunLab()  # uses `runlab demo` / `runlab login` credentials, or RUNLAB_TOKEN

# 1. Pre-register before any seed runs.
rl.plan("resnet-aug", "mixup", "baseline", "acc",
        hypothesis="mixup raises top-1 accuracy",
        n_max=10, stopping="fixed")  # fixed: compare once after all 10 seeds

# 2. Record each seed's metric for both arms (same seeds for both).
for seed in range(10):
    rl.result("resnet-aug", "mixup", acc=train("mixup", seed), seed=seed)
    rl.result("resnet-aug", "baseline", acc=train("baseline", seed), seed=seed)

# 3. Compare once, after all planned seeds finish.
v = rl.compare("resnet-aug", "mixup", "baseline", "acc")
print(v["verdict"], v["prereg"]["status"])  # a_better ok
print(v["text"])

# 4. Check which wins a write-up may quote (adjusted across all pairs in the project).
for c in rl.report("resnet-aug")["claims"]:
    print(c["status"], c["quote"])  # quotable mixup − baseline on acc = ...
```

Replace `train` with your training function. See
[examples/quickstart.py](https://github.com/omer-nachman/runlab-python/blob/main/examples/quickstart.py)
for a runnable script and
[examples/curl.sh](https://github.com/omer-nachman/runlab-python/blob/main/examples/curl.sh) for
plain HTTP.

## How verdicts work

### What keeps a verdict honest

| Guard | Why | What RunLab does |
|---|---|---|
| **Plan first** | Picking metrics or seed counts after seeing results inflates false wins. | Checks `prereg.status` (`ok`, `deviation`, `missing`, `tampered`). Amendments need a reason; every version is kept. |
| **Look once** | Re-testing a fixed-n p-value as seeds arrive breaks alpha. | Calling `compare` on grown data warns `peeking` and marks the pair `not_quotable`. Re-comparing unchanged data is fine. To stop early validly, use a [study](#studies-stop-early-as-seeds-run). |
| **Equal budgets** | Tuning one arm harder than the baseline measures tuning, not the change. | Refuses the verdict (`refused_by: equal_budget`) if one arm has > 1.25× as many parameter configs. |
| **Multiple testing** | At alpha 0.05, ~1 in 20 null pairs looks like a win. | `report()` applies Benjamini-Hochberg across the project (`quotable`, `quotable_with_caveat`, or `not_quotable`). |
| **Stale inputs** | Bad seeds or datasets undermine verdicts built on them. | `verdicts()` reports `stale` counts; `verdicts(recheck=True)` re-judges pairs (`unchanged`, `inputs_changed`, or `flipped`). |

### Verdicts and metric direction

`a` is the treatment and `b` is the baseline; `diff` is the mean of `a − b` over shared seeds
(paired t-test, or Welch's test if fewer than 2 seeds are shared). Common lower-is-better metrics
(`loss`, `error`, `perplexity`, `latency`, `mse`, `fid`, …) are detected automatically; pass
`better="lower"` or `better="higher"` whenever unsure. Always check `prereg["status"]` and
`warnings` next to `verdict`.

| `verdict` | Meaning |
|---|---|
| `a_better` / `b_better` | `p < alpha` (default `0.05`) and the difference favours that arm. |
| `no_detectable_difference` | `p >= alpha`. Not proof of equality — pass `margin` to test equivalence. |
| `equivalent` / `non_inferior` | With `margin`: 95% CI lies within `±margin`, or `a` is worse by less than `margin`. |
| `insufficient` | Fewer than 2 seeds in an arm; no test ran. |
| `refused` | A guardrail blocked the verdict; `refused_by` and `why` say what to fix. |

<details>
<summary>Full list of lower-is-better metric names</summary>

Lower is better when the metric name contains any of these as a whole word (between `_`, `.`, `/`
or `-`): `loss`, `error`, `err`, `perplexity`, `ppl`, `wer`, `cer`, `mse`, `mae`, `rmse`, `nll`,
`latency`, `fid` (also `fid50k`, `fid10k`), `kid`, `regret`, `bpb`, `bpc`, `bpd`, `bits_per_byte`,
`bits_per_char`, `bits_per_dim`, `cross_entropy`, `xent`, `kl`, `ece`, `fpr`, `fnr`, `eer`.
Everything else defaults to higher-is-better unless `better` is passed.

</details>

### Recording results from logs

Prefer `rl.result(...)` from Python. If your training script prints logs instead, emit `RESULT:`
lines and pass the whole log to `rl.record(project, log_text)`:

```text
RESULT: <arm> <metric>=<number> seed=<n> [<param>=<value> ...]
```

Non-`RESULT:` lines are ignored; duplicate lines are skipped (`already`), so retries are safe. Any
malformed `RESULT:` line (or none) fails with 400 and stores nothing. Names use letters, digits,
`_`, `.`, `-` (arms start with a letter); project names are case-insensitive and cannot contain
`~`. Optional `param=value` pairs track tuning configs (keep them constant across an arm's seeds).

### Known limits

Every test is checked by simulation (10,000 synthetic datasets per case at 3, 5, 10, and 30 seeds;
failures must reproduce on a second run). RunLab does **not** yet warn about these cases in the
verdict (a skewness warning was tested and dropped because it missed most false wins):

| Case | What goes wrong | Measured (target) | What to do |
|---|---|---|---|
| Skewed per-seed diffs (latency, cost, perplexity, losses with blow-ups) in `compare` | Too many false wins; 95% CI too narrow | false wins 0.12–0.18 (0.05); CI coverage 0.82–0.88 (0.95) | Before running seeds, `plan(..., scale="log")` or `scale="rank"` |
| Skewed per-seed diffs in a sequential study (one look per seed) | Stops early on false wins; stopping interval too narrow | false wins 0.15 / 0.21 at 10 / 30 seeds (0.05); coverage 0.79–0.93 (0.95) | Record `log(metric)` as its own metric and run the study on that |
| Skewed per-seed diffs with `margin` (equivalence) | Calls arms equivalent too often when true gain equals margin | false equivalence 0.16–0.24 (0.05) | Before running seeds, `plan(..., scale="log")` or `scale="rank"` |

## Studies: stop early as seeds run

A sequential study tests after each seed pair with an always-valid sequential test (mSPRT) and
stops as soon as the evidence decides, `n_max` is reached, or the next pair would pass your dollar
cap.

### Run seeds on your own machine (`runlab worker`)

1. Register a sequential plan (`stopping="msprt"` is the default):

   ```python
   from runlab_client import RunLab

   RunLab().plan("resnet-aug", "mixup", "baseline", "acc",
                 hypothesis="mixup raises top-1 accuracy", n_max=20)
   ```

2. Run `runlab worker` on your laptop, GPU box, or cluster node. Your command prints
   `<metric>=<value>` to stdout; `{arm}`, `{seed}`, and param placeholders are substituted without
   a shell:

   ```bash
   runlab worker --project resnet-aug --a mixup --b baseline --metric acc \
       --max-usd 5 --usd-per-hour 0.8 --param epochs=10 \
       --cmd "python train.py --arm {arm} --seed {seed} --epochs {epochs}"
   # seed 0: mixup acc=0.853, baseline acc=0.801 (412.3 s)
   # ...
   # study st_...: decided (A, winner mixup) after 6 pairs, $0.5496
   ```

- `--usd-per-hour` prices wall time toward `--max-usd` (and records `wall_s` and `usd` per run).
- Add workers with `--study st_...`; pass `--worker NAME` to resume an open pair after a restart.
- Non-zero exit, missing metric, or `--timeout` marks a run failed and skips the pair.
- From Python: `s = rl.start_worker_study(...)`, then `rl.run_worker(s["id"], cmd)`.

### Hosted studies

When named training commands are enabled, RunLab can run the seed pairs for you (using the same
`stopping="msprt"` plan):

```python
s = rl.start_study("resnet-aug", command="train", a="mixup", b="baseline", metric="acc",
                   max_usd=5, arm_params={"mixup": {"alpha": "0.2"}})
s = rl.wait_study(s["id"])
print(s["state"], s["winner"], s["pairs"], s["usd"])  # e.g. decided mixup 6 0.84
```

All checks run before anything starts (a refusal raises 400 and costs nothing). Placeholder values
in `params` and `arm_params` allow letters, digits, and `_.:+=-` only.

<details>
<summary>Study states (<code>running</code>, <code>decided</code>, <code>budget</code>, …)</summary>

| `state` | Meaning |
|---|---|
| `running` | Still running seed pairs. |
| `decided` | Sequential test stopped: `decision` is `A` or `B` (`winner` names the arm), `futile`, or `equivalent` (`winner` is null). |
| `undecided` | Reached `n_max` seed pairs without a decision. |
| `budget` | Stopped undecided before the next pair would exceed `max_usd`. |
| `killed` | Stopped hard when the time `max_usd` buys ran out. |
| `failed` | Command failed or printed no result; see `detail`. |
| `lost` | Stopped reporting well past its deadline. |
| `refused` | Refused before starting (that call raised 400); listed for the record. |

</details>

## Pull-request check: `runlab verdict`

`runlab verdict` turns a comparison into a GitHub pull-request check (difference, 95% CI, and
pass/fail status). On GitHub, [runlab-action](https://github.com/omer-nachman/runlab-action) runs
it in ~5 lines of workflow YAML.

1. Commit `.runlab/verdict.yml` to your default branch:

   ```yaml
   paths: ["train/**", "configs/**"]   # other changes get a neutral check
   project: my-model
   checks:
     - a: "pr-{pr}-{sha7}"             # this PR's seeds
       b: "base-{pr}-{sha7}"           # base branch's seeds, from the same job
       metric: val_acc
       expect: better
   ```

2. Train both arms in CI (printing `RESULT:` lines with `seed=`), then run:

   ```bash
   pip install -U "runlab-client[yaml]"
   runlab verdict --post \
     --results "out/pr/*.txt --arm pr-{pr}-{sha7}" \
     --results "out/base/*.txt --arm base-{pr}-{sha7}"
   ```

**Keyless in GitHub Actions:** grant `permissions: id-token: write` and omit `RUNLAB_TOKEN`. The
client signs in with GitHub's short-lived OIDC token as the RunLab user bound to the repository
owner's GitHub login (scoped to `runlab verdict` calls only, at most role `agent`). Organization
repos set `RUNLAB_TOKEN` from a secret instead; fork PRs receive no token or verdict.

The spec is read from the PR's **base** commit so a PR cannot loosen its own bar; `{sha7}` gives
each push fresh arm names to avoid `peeking`; and `refused`, `insufficient` (< 2 seeds), and
unknown spec keys always fail. Note that the check is only as trustworthy as the CI job that trains
the seeds.

<details>
<summary>Spec keys, flags, and exit codes</summary>

`runlab verdict` writes a table to the job summary; `--post` also updates a `runlab verdict` check
run and one PR comment. Use `--spec-from head` to test a spec before merging. Placeholders `{pr}`,
`{sha}`, `{sha7}`, and `{branch}` expand in arm names and `--results` specs (which also accept
`--project P` and `--arm A`). JSON specs work without the `[yaml]` extra.

| Spec key | Default | Meaning |
|---|---|---|
| `paths` | all paths | Globs (`*`, `**`, `dir/`). PRs touching none get a neutral check and record nothing. |
| `project` | none | Default project for rows that omit `project`. |
| `a`, `b` | required | Treatment and baseline arm names. |
| `metric` | required | Metric to compare. |
| `expect` | `better` | `better` (`a_better`), `not_worse` (`a_better`/`equivalent`/`non_inferior`, needs `margin`), or `different` (`a_better`/`b_better`). |
| `margin` | none | Smallest difference that matters, in metric units. |
| `better` | `auto` | `higher`, `lower`, or `auto`. |
| `alpha` | `0.05` | Significance level (CI is `1 − alpha`). |
| `missing` | `failure` | Result when an arm has no results yet: `failure` or `neutral`. |

Exit codes: `0` every row met `expect` (or no verdict needed), `4` a row failed, `2` spec, results
file, RunLab, or GitHub error.

</details>

### Without a workflow: the RunLab GitHub App

When your RunLab has a GitHub App and it is installed on the repository, the App posts the same
`runlab verdict` check on each pull request with no workflow: from the spec on the base branch
and the results you record (`record()`, `result()` or `runlab worker`, from wherever you
train). Link the repository to your projects once:

```bash
pip install -U runlab-client
runlab login                       # sign in with GitHub
runlab link acme/resnet            # every project of yours; or --project "resnet-*"
```

- A repository owned by your own GitHub account needs no link: signing in links it.
- An organization's repository is linked by someone with full control of it on GitHub (its top
  role, the one that changes its settings). RunLab asks GitHub, as the App, whether the App is
  installed on it and whether your GitHub account has that role: nothing to store or rotate.
- The check reads only your projects: `project: my-model` in the spec is your `my-model`, and
  a row naming a project outside the link fails as not granted, without reading it. The check
  and the comment show your project names as you wrote them.
- One link per repository: linking it again changes its projects; another user's link stays
  unless you pass `--replace` (after the same check).
- `runlab link` with no repository lists your links; `runlab unlink acme/resnet` removes one.
  An unlinked repository's pull requests get a neutral "Not set up" check with these steps;
  it never blocks a merge.

## Reference

### CLI commands

All commands also run as `runlab-client` or `python -m runlab_client`.

| Command | What it does |
|---|---|
| `runlab demo [--project P] [--url URL] [--no-browser]` | Sign in if needed, then run a 10-seed simulated comparison in `runlab-demo`. |
| `runlab login [--url URL] [--no-browser]` | Sign in with GitHub and save a key on this machine. |
| `runlab login --rotate` | Replace this machine's key; the old key stops working at once. |
| `runlab whoami [--url URL] [--keys]` | Show your signed-in identity; `--keys` lists live keys (`*` = this machine). |
| `runlab logout [--key ID \| --all]` | Sign out here, revoke one key (`--key ID`), or revoke all keys and web sessions (`--all`). |
| `runlab worker ...` | Run a sequential study's seed pairs on this machine. |
| `runlab verdict [--results "GLOB [--project P] [--arm A]"] [--spec PATH] [--spec-from base\|head] [--post]` | Record results, compare spec arms, and pass or fail a PR check. |
| `runlab link [owner/name] [--project P]... [--replace]` | Link a repository to your projects for the GitHub App's check (see above); with none, list your links. |
| `runlab unlink owner/name` | Remove your link of a repository. |
| `runlab --version` | Print the installed version. |

### Python client

`RunLab(url=None, token=None, *, timeout=30, retries=3, backoff_s=0.5)` — with no arguments, reads
`RUNLAB_TOKEN` / `RUNLAB_URL`, else saved `runlab login` credentials, else GitHub Actions OIDC.
Each method returns the decoded JSON of one operation in
[openapi.json](https://github.com/omer-nachman/runlab-python/blob/main/openapi.json).

| `RunLab` method | Returns / notes |
|---|---|
| `me()` | `name`, `role` |
| `plan(project, a, b, metric, hypothesis, n_max, **options)` | `plan`, `power_check`, `text` (options: `better`, `alpha`, `n_min`, `stopping`, `scale`, `amend`) |
| `result(project, arm, *, seed=None, params=None, **metrics)` | `stored`, `already` (one `RESULT:` line per metric) |
| `record(project, results)` | `stored`, `already` (string or list of `RESULT:` lines) |
| `compare(project, a, b, metric, **options)` | `verdict`, `diff`, `ci`, `p`, `test`, `n`, `prereg`, `warnings`, `text` (options: `better`, `alpha`, `margin`) |
| `report(project, *, arm="", metric="", q=0.05)` | `claims`, counts per status, `text` |
| `verdicts(project="", limit=50, recheck=False)` | `verdicts`, `stale`, and `recheck` when requested |
| `verdict(id)` | Full verdict: `seeds`, `check`, `now` |
| `start_worker_study(project, a, b, metric, max_usd, usd_per_hour, *, params=None, arm_params=None)` | Worker study (`mode: worker`) |
| `run_worker(id, cmd, *, worker=None, cwd=None, timeout=None, lease_s=None, log=None)` | Runs seed pairs locally until ended; returns the study |
| `work(id, *, seed=None, results=None, failed=None, wall_s=None, worker=None, lease_s=None)` | Low-level worker loop: `study`, `pair` (or null), `retry_after_s` |
| `start_study(project, command, a, b, metric, max_usd, *, params=None, arm_params=None)` | Hosted study |
| `study(id)`, `studies(project="", limit=50)`, `wait_study(id, timeout=86400, poll_s=30)` | One study, list of studies, or poll until ended |
| `link(repo, projects=None, *, replace=False)` | `id`, `repo`, `projects`, `replaced` |
| `links()`, `unlink(id)` | a list of your links; `unlinked` |

Module-level helpers (`from runlab_client import ...`): `result_line(arm, metric, value, *, seed=None, **params)`
builds one `RESULT:` line; `login(url=None, *, browser=True, host=None, show=None)` runs the
interactive login flow and saves the key; `saved_login()` and `config_dir()` inspect the saved
`(url, key)` and its directory.

### Errors and retries

Failures raise `RunLabError` with `.status` (HTTP code, or `0` if unreachable), `.message`, and
`.request_id` (quote it when reporting an issue): `400` bad input or refused action (suggests close
matches for typos), `401` missing/invalid token, `403` role too low, `404` unknown verdict or study
id, `413` body too large (split large result batches across calls).

Reads and idempotent writes (`plan`, `record`/`result`, `compare`, `work`) retry up to 3 times on
connection errors and 429/502/503/504, respecting `Retry-After` (up to 60 s) or backing off 0.5,
1, and 2 s. `start_study` and `start_worker_study` are never retried.

## Coding agents

[AGENTS.md](https://github.com/omer-nachman/runlab-python/blob/main/AGENTS.md) is the short guide
for Claude Code, Codex, and other coding agents.
[llms.txt](https://github.com/omer-nachman/runlab-python/blob/main/llms.txt) indexes this repo for
LLM tools.

## Versioning and 1.0

`runlab-client` is in **public preview (0.x)** and follows
[semantic versioning](https://semver.org/): minor releases (`0.4 → 0.5`) may include breaking
changes (listed first in
[CHANGELOG.md](https://github.com/omer-nachman/runlab-python/blob/main/CHANGELOG.md)); patch
releases never do. Pin `runlab-client~=0.4.0` to take fixes only.

1.0 ships once all of these hold: no breaking API or CLI changes for 8 weeks, RunLab uptime
≥ 99.5% over 30 days, and every [known limit](#known-limits) fixed or flagged in `warnings`. From
1.0 onward, breaking changes require a new major version with at least 3 months of deprecation
warnings.

## Support & license

Questions and bug reports:
[GitHub Issues](https://github.com/omer-nachman/runlab-python/issues).
Licensed under MIT ([LICENSE](https://github.com/omer-nachman/runlab-python/blob/main/LICENSE)).
