Metadata-Version: 2.4
Name: qupai-lab
Version: 0.6.3
Summary: The QuPai Lab SDK: work a QuPai lab's instruments from Python scripts through InstruCore's REST API.
Author: QuSpect
License-Expression: MIT
Project-URL: Homepage, https://github.com/QuSpect/qupai-lab-plugin
Project-URL: Repository, https://github.com/QuSpect/qupai-lab-plugin
Keywords: qupai,lab,instruments,instrucore
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Classifier: Topic :: Scientific/Engineering
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: moku
Requires-Dist: moku==4.3.0.1; extra == "moku"
Dynamic: license-file

# QuPai Lab SDK (`qupai-lab`)

Work a QuPai lab's instruments from Python: the lab's machines, sessions on simulated copies, instruments by
role, the files an experiment keeps, and live runs in the lab's queue. It calls InstruCore's own REST API (not
MCP), so one script runs in a QuPai lab project's sandbox, at the lab PC, and outside QuPai with your own `qupai`
sign-in on a lab you may work directly ([below](#outside-qupai-with-your-own-sign-in)). Python 3.10 or later,
standard library only.

## Install

```
pip install qupai-lab
```

A QuPai sandbox has it already; on your own machine or a lab workstation, install it as above. From a checkout of
this repository instead: `pip install ./sdk/python`.

**Releasing.** A tag `sdk-vX.Y.Z` on this repository, equal to `qupai_lab.__version__`, runs
`.github/workflows/sdk-release.yml`: it tests the SDK on Python 3.10 and 3.13, builds the sdist and the wheel, checks
the tag against them, and publishes to PyPI through Trusted Publishing (no token is kept anywhere).

Then check that this sandbox (or PC) reaches its lab:

```
$ qupai-lab machines
Lab http://door.example/lab/lab-sim
MACHINE               KIND       STATE        INSTRUMENTS BY ROLE
signal-bench-sim      pool       3 of 4 free
  signal-bench-sim-1  simulated  free         generator=signal_bench_sim_1_generator, scope=signal_bench_sim_1_scope
  …
```

`qupai-lab machines --json` prints the same as JSON; `qupai-lab --version` the version. Outside QuPai,
`qupai-lab machines --lab magnetic` is the same check for a lab you may work directly ([below](#outside-qupai-with-your-own-sign-in)).

## Where the lab is

`Lab.from_env()` reads `QUPAI_LAB_URL` and `QUPAI_LAB_KEY` from the environment, else from the nearest `.env` up
from the working directory, else from `/workspace/project/.env`. In a QuPai lab project the project's `.env`
holds both: the lab's address at the sandbox door and the project key. At a lab PC, give InstruCore's address and
a local key: `Lab("http://127.0.0.1:59220", "ick_…")`.

### Outside QuPai, with your own sign-in

`Lab.from_qupai("magnetic")` works a lab you may work directly, with no `.env`: a lab QuPai staff granted to your
account, or to the lab workstation you sit at (QuPai staff may work every lab). It takes `record` and `runs` as
`from_env` does, and the rest of the script is the same as in a QuPai sandbox, except that `lab.machine()` holds
a live machine for its block as your own session ([below](#what-holds-a-machine)).

1. It reads your `qupai` sign-in (`qupai login`): the file `QUPAI_CREDENTIALS` names, else
   `qupai/credentials.json` in your configuration directory (`~/Library/Application Support` on macOS,
   `$XDG_CONFIG_HOME` or `~/.config` on Linux, `%AppData%` on Windows). Its `server` is the platform and its
   `api_key` your personal API key, which goes only into `Authorization` and is never printed or recorded. A device
   sign-in has no key: run `qupai login` again.
2. It asks the platform which labs you may work directly from where you are (`GET /v1/me/lab-access`) and finds the
   lab there, by its id (`magnetic`) or its listing (`lab-magnetic`). A lab it does not list raises
   `NO_DIRECT_ACCESS`, naming the labs you may work directly. For any other lab, ask its agent
   (`qupai ask -lab <lab> "…"`, or the `ask` tool of `qupai mcp`): the agent does the lab work in QuPai.
3. It speaks InstruCore's REST API at `<platform>/rest/<listing>/` with your key, as `Lab(url, key)` does
   (`QUPAI_GATEWAY` names another gateway, as for `qupai mcp`). QuPai's gateway checks your grant at every call, and
   the lab applies its own limits and roles, as for anyone.

**On a lab workstation** every call, the first question included, goes through the workstation's door: a local
socket, `QUPAI_WORKSTATION_LAB_SOCKET`, else `/Library/QuPai/workstation/lab.sock` when it exists. The door adds the
workstation's own credential, which no seat can read, so a grant to the workstation counts on the workstation and
nowhere else; your key on another machine carries no such grant. `m.moku()`'s calls take the same way.
`Lab(url, key, unix_socket=…)` sends a `Lab`'s requests through any such socket.

## A script

```python
import sys
from qupai_lab import Lab

lab = Lab.from_env(record="calls.jsonl")      # this run's folder: <experiment>/runs/<id>/
sweep = lab.input("sweep.json")                # inputs/sweep.json: {"frequencies_hz": [100, 300, …]}
with lab.machine(sys.argv[1]) as m:            # a pool: holds a free copy, or waits in its queue for one
    gen, scope = m.role("generator"), m.role("scope")
    rows = []
    for f in sweep["frequencies_hz"]:
        gen.write("set_waveform", channel=1, shape="sine", frequency_hz=f, amplitude_v=1.0)
        scope.write("set_timebase", scale_s=0.5 / f, offset_s=0.0)
        trace = scope.read("acquire", channel=1, points=2000)
        rows.append({"frequency_hz": f, **lab.save(f"data/raw/trace_{f:g}.json", trace)})
lab.table("data/response.csv", rows)
lab.changes("changes.json")                    # the writes above, for a live run's card
```

`python run.py signal-bench-sim` runs it on a simulated copy; its files land in its own run folder (below). The roles are the machine's: `qupai-lab machines`
lists them. A script addresses instruments by role, so the same script works on any copy of a pool and on the
machine the pool simulates, when their roles have the same names.

**Name the bench.** One lab PC may serve several benches of the lab, each a live machine of its own (with its own
instruments, holder and queue) named by its public id, such as `rydberg-a`; a lab with only one bench calls it
`bench`. `lab.machine()` always takes the id: there is no default machine, so take it from the command line, as
above, and never write `bench` into a script that may meet another lab. `lab.machines()` lists only the benches
the key's member holds a role on; another bench answers `NOT_FOUND`.

| Call | What it does |
| --- | --- |
| `lab.machines()` | Each live machine (a bench) and simulated copy the member may see: `id` (public id), `internal_id`, `name`, `kind`, `state`, `status`, `pool`, `roles` (role → instrument id) |
| `lab.machine(id, *, purpose="", wait_s=None)` | A machine for a `with` block (below), by id or public id; there is no default |
| `m.role(name)` | The instrument in that role |
| `m.moku(device)` | The keyword arguments for the official `moku` package on that Moku of the machine, through the lab ([below](#a-moku-with-the-official-sdk)) |
| `inst.read(op, **args)` | A read op; answers its result. Anyone may read |
| `inst.write(op, **args)` | A write op in the machine's session; the lab checks its limits first |
| `inst.check(op, **args)` | Would this write pass policy, arguments and limits? `{"ok": true, "kind": "write"}` or the refusal, without a session |
| `inst.reference()`, `m.reference()` | The reference document (`mhs-reference/0`): ops, units, limits, notes |
| `m.renew()` | Restarts the held session's time limit, unless someone waits |
| `lab.save(path, value, **meta)` | Writes `value` as JSON (folders made as needed); answers `{"file": path, **meta}` |
| `lab.table(path, rows)` | Writes a list of dicts as CSV; answers `{"file": path, "rows": n}` |
| `lab.changes(path)` | Writes the writes made through this `Lab` as JSON (below) and answers it |
| `declare_changes(experiment, changes)` | Writes `<experiment>/changes.json` with a live run's changes declared, not rehearsed: for a lab with no simulated copy ([below](#declaring-a-live-runs-changes-without-a-rehearsal)) |
| `lab.input(name)` | `inputs/<name>` of the experiment: parsed when it is `.json`, else its text |
| `lab.out`, `lab.experiment`, `lab.inputs` | This run's folder, the experiment's folder, its `inputs/` (paths) |
| `lab.request(method, path, body)` | Any other InstruCore route, with the same headers, record and errors; an instrument's op call (`/v1/instruments/<id>/read\|write\|check/<op>`) counts in the run's `calls` like a role's |

## Where a script's outputs go

Each execution of an experiment's script has its own **run folder**, `<experiment>/runs/<id>/`. A live run's id is
its job; a rehearsal's is the UTC time it started and four random hex digits (`20261122-021116-a3f9`), so the
folders sort by time. `Lab.from_env()` makes it for a script run as `python run.py …`, at the script's first call
or output, and a relative path given to `record`, `lab.save`, `lab.table` or `lab.changes` is inside it. The
experiment's own folder keeps only what a person writes, and the latest rehearsal's `changes.json` (or the
[declared](#declaring-a-live-runs-changes-without-a-rehearsal) one), which a live run's card reads:

```
experiments/
├── INDEX.md                          every experiment and its runs, from their manifests (written, not edited)
└── 2026-11-22-freq-response/
    ├── README.md                     what was asked, why, how to run it again, what the runs found
    ├── run.py                        the steps: python run.py <machine>
    ├── analysis.py                   tables and figures of one run: python analysis.py runs/<id>
    ├── inputs/sweep.json             the values run.py reads (lab.input)
    ├── changes.json                  the latest rehearsal's changes, or declared ones: the live run's card
    └── runs/
        ├── 20261122-021116-a3f9/     a rehearsal, on a simulated copy
        │   ├── manifest.json
        │   ├── calls.jsonl  changes.json
        │   └── data/response.csv  data/raw/ (not committed)  figures/
        └── 01a20106-20c6-…/          a live run, its job's id: the same files, and output.log
```

`manifest.json` says what ran and how it ended: `run`, `kind` (`rehearsal` or `live`), `simulated` (every machine
held was a simulated copy), `experiment`, `script` and `script_blob` (its git blob id), `argv`, `commit` and
`dirty` (the experiment differed from the commit, `runs/` aside), `inputs` (each file of `inputs/` with its size and
blob id), `lab` (the listing, from a sandbox door's or the gateway's REST door's address; no address is kept), `machines` (each one used:
`requested`, `machine`, `kind`, `session`, `held`, `held_at`, `released_at`), `official_sdk` (each device worked with
a manufacturer's own package, [`m.moku()`](#a-moku-with-the-official-sdk): `package`, `version`, `machine`, `device`;
the lab records those calls), `started_at`, `ended_at`, `status`
(`running`, `ended`, `failed` after an uncaught exception, `stopped` by a signal), `exit_code` and `error` (a live
run's; `error` is the end of its stderr when it did not end well), `session_ended` and `restore` (a live run whose
session ended under it: [below](#when-the-runs-session-ends-while-it-runs)),
`waits` (each wait in a machine's queue, kept as it goes: `machine`, `for` (`its turn` or `a copy`), `since`,
`position`, `holder` (`name`, `since`, `run` and `ends_in_s`, its longest time left; a pool's `copies` and `free`),
`lab_said`, `waited_s`, `until` and `outcome`: `waiting` while it waits, then `held`, `timeout`, `cancelled`,
`expired`, `stopped` or `failed`; [below](#a-wait-says-what-it-waits-for)), `rate_limited` (the calls' waits for the
platform: `waits`, `waited_s`, `first_at`, `last_at`; [below](#when-the-platform-asks-to-wait)),
`calls`, `outputs` (the files the run itself left, the raw ones counted in `raw_files`; an analysis adds its own
later) and `versions`.

`experiments/INDEX.md` lists each experiment (newest first: its date, from the folder's name, and its README's
title, without a date of its own) and each of its runs: kind,
machine, commit (`*`: it differed), start, status and calls; a run folder without a manifest (from an SDK before
0.3.0) is listed by name. A rehearsal writes it as it ends, `qupai-lab run`
after a live run, and `qupai-lab index` on demand. A script outside a folder named `experiments` leaves it alone.

`Lab.from_env(runs=False)`, or `QUPAI_LAB_RUNS=0`, makes no run folder: paths are then as given, from the working
directory. `python -c`, the interactive interpreter and test runners get none either, and `Lab(url, key)` gets one
only when given (`run_folder=`).

## What holds a machine

| `lab.machine(…)` names | In the `with` block |
| --- | --- |
| A simulated pool (`signal-bench-sim`) | A free copy is held for the block. When none is free the block waits in the pool's queue, asking again when a copy is offered; `wait_s` gives up and leaves the queue. The copy is released at the block's end, also when the block raises, and reset for the next user |
| One simulated copy (`signal-bench-sim-2`) | That copy, the same way |
| The run's live machine, inside a [live run](#live-runs) (`QUPAI_LAB_RUN_MACHINE`, by id or public id) | Held for the block: `POST sessions` with `{"purpose": "run <run id>", "queue": true}`. While others hold or wait for it, the block waits in the machine's queue and asks again when it is offered; the lab holds it for the run's longest time. Released at the block's end, as a copy is. A session that ends while the block runs, not by the run, stops the run ([below](#when-the-runs-session-ends-while-it-runs)) |
| Any other live machine (`signal-bench`) | Nothing is held. The member holds a live machine, in the conversation; the lab answers a script's session there with `RUN_REQUIRED` and a write the member did not allow with `APPROVAL_REQUIRED` |
| A live machine of a lab worked directly ([`Lab.from_qupai`](#outside-qupai-with-your-own-sign-in)) | Held for the block as your own session: `POST sessions` with `{"purpose": <the block's purpose, else the script>, "queue": true}`, waiting in the machine's queue while others hold it. Your role on the bench decides (operate holds it; view is `FORBIDDEN`), and the lab's limits hold. A session you already held when the block began (`start_session` in `qupai mcp`, say) is used and stays held at the block's end |

In a QuPai sandbox, code holds a live machine only as a run the member approved; outside QuPai, only on a lab you
may work directly. Rehearse on a copy first when the lab has one.

### A wait says what it waits for

When the lab puts the block in a queue (`202`), it says on stderr what it waits for, as the lab says it: who holds
the machine and since when, or how many copies of a pool are free, and its place in the queue.

```
qupai-lab: queued for magnetic-bench at position 1; waiting for its turn: held by Wang since 2026-11-26 05:25:19 UTC; its session ends in 25 min at the latest. It says how the wait goes every 30 s; SIGINT or SIGTERM leaves the queue
qupai-lab: still waiting for magnetic-bench (44 s): position 1; held by Wang since 2026-11-26 05:25:19 UTC; …
qupai-lab: magnetic-bench is held after waiting 4 min 12 s in its queue
```

A line comes when its place moves and every 30 s while it waits (the holder looked up again); a member who holds as
many simulated sessions as a member may is told that this is why. It looks at its request every 2 s at first, then
less often while its place does not move, up to every 15 s: a wait never runs in a tight loop. The run's manifest
keeps each wait in `waits` as it goes, so a run folder says what a run that seems stuck is waiting for.

### A long run on a lab workstation: detached

A run that holds a bench for minutes must outlive what started it: a closed browser tab, a dropped connection or the
end of the coding agent's command would otherwise stop it halfway, with the bench's settings changed.

1. Look at the bench first (`qupai-lab machines --lab <lab>`, or the `machines` tool): free, or held by whom. Never
   start a second run while one holds the bench or waits for it, yours included.
2. Start the run detached, in its own session, from the experiment's folder, with its output in a log:

   ```
   lab-detach run.log python3 run.py <bench>      # when the workstation has it (command -v lab-detach)
   nohup python3 -c 'import os,sys; os.fork() and os._exit(0); os.setsid(); os.execvp(sys.argv[1], sys.argv[1:])' \
     python3 -u run.py <bench> > run.log 2>&1 < /dev/null &
   ```

3. Follow the log now and then (`tail -n 20 run.log`), not with a `tail -f` that never returns: the SDK says there
   what it waits for and how the wait goes, and the run's `runs/<id>/manifest.json` has `status` `running` until the
   run ends. To stop it, send SIGTERM (`pkill -TERM -f 'run.py <bench>'`): the script's `finally` puts back what it
   changed and the block releases the bench. Never SIGKILL it: the session would stay held until its idle limit.

SIGTERM and SIGINT while a block holds a machine (a copy, or a run's live machine) release it before the script
exits: the first one raises `SystemExit(143)` (SIGTERM) or `KeyboardInterrupt` (SIGINT) in the block, the block's
end releases the session with the reason `qupai-lab: stopped by SIGTERM`, and a request still in the queue is
withdrawn. A signal that comes while a session starts or ends waits until that call is done; a repeat while the
script stops is ignored. The handlers are installed when the block starts and the script's own are back at its
end (a signal the script ignores stays ignored). Only the main thread installs them.

## A Moku with the official SDK

A lab's Moku can be worked with the manufacturer's own Python package, `moku`, as at the device: code written
against a Moku runs unchanged but for its address, and every call goes through the lab. `m.moku(device)` gives
the keyword arguments for any of the package's instruments, `MultiInstrument` and `Moku`, on the Moku `device` of
the machine in the block:

```python
import sys
from moku.instruments import SpectrumAnalyzer
from qupai_lab import Lab

lab = Lab.from_env()
with lab.machine(sys.argv[1]) as m:
    with SpectrumAnalyzer(**m.moku("moku")) as sa:   # hands the Moku back at the block's end
        sa.set_span(frequency1=0, frequency2=10e6)
        spectrum = sa.get_data()
    lab.save("data/spectrum.json", spectrum)
```

`MultiInstrument(**m.moku("moku"), platform_id=4)` and its `set_instrument` work the same way. The package talks to
a local stand-in for the Moku that `m.moku()` starts in this process (`qupai_lab.moku_forward`, one per device, until
the block ends): it passes every call on to `<QUPAI_LAB_URL>/v1/moku/<machine>/<device>/api/…`, where InstruCore
answers that Moku's own HTTP API behind its checks, with this `Lab`'s key, script header and user agent, and hands
back the lab's answer. `<machine>` is the machine in the block by its public id, as `lab.machines()` lists it: the
live machine, or the simulated copy the block holds, so the same script reaches the copy in a rehearsal and the live
Moku in a run. Every version of the package works through it, whatever it does with its address and headers: 4.3.0.1
(MokuOS 4.0.1 to 4.3) and 4.4.0.0 (MokuOS 4.4 on), whose fast transport keeps only the host and port it is given and
sends only its own `Moku-Client-Key`. Pick the version the device needs (`pip install moku==4.4.0.0` in the project
for a MokuOS 4.4 Moku); InstruCore 0.27.1 or later takes 4.4's calls. `m.moku()` answers:

| Argument | Value |
| --- | --- |
| `ip` | `127.0.0.1:<port>`, the local stand-in |
| `manage_bitstreams` | `False`: the package uploads no FPGA bitstreams (4.3), since InstruCore uploads what the Moku lacks at the lab PC. 4.4 has no such argument and reads the environment instead, so `m.moku()` also sets `MOKU_API_DISABLE_BITSTREAM_MANAGEMENT=1` in the script's environment |
| `session_trust_env`, `session_proxies` | `False` and `{}`: the package's `requests` session reaches 127.0.0.1 directly, whatever proxy the environment names |

- **The lab checks every call** as it checks this SDK's. The key tells the lab whose calls they are, so they belong
  to whatever this `Lab` holds: the block's copy, or a run's live machine. Reads pass; writes need the hold, and on a
  live machine the lab's limits and the member's approval. The package raises its own exceptions
  (`moku.exceptions.MokuException` and its kinds), never `LabError`.
- **The platform's `429`.** The package does not wait and ask again itself. The gateway's own `429` never reached
  the lab, so the stand-in waits for its `Retry-After` and sends the call again while the waits fit in 20 s, under
  the package's own read timeout (30 s by default), and while the package still waits for the answer. Otherwise
  (a minute's `Retry-After`) the package gets the refusal in the Moku's envelope, `RATE`, and raises it: `rate-limited
  by the platform (Too many requests from this address; retry in a minute): this call of the moku package did not
  reach the lab; the platform asks to wait 1 min`, said once on stderr. Any other `429` reaches the package as it
  came.
- **Ownership.** Each instrument's constructor claims the Moku (`claim_ownership`); the lab grants it only while
  this key holds the machine, and `force_connect` takes the Moku from no one. Hand it back with
  `relinquish_ownership()`, or with a `with` block as above.
- **The lab keeps the record.** InstruCore records every call of the package. The `record` file and the manifest's
  `calls` count this SDK's own calls only; the manifest's `official_sdk` (and `changes.json`, when there is any)
  names each device worked this way: `package`, `version`, `machine`, `device`.
- **Its writes are changes.** Each answer of the lab lists the writes it made (`instrucore.writes`), and
  `lab.changes()` lists them with this SDK's own, under the instrument's role, so a rehearsal's `changes.json` lets
  a live run make them. A lab whose InstruCore is older than 0.26.2 lists none: that is said once on stderr,
  `official_sdk` gets `"writes_listed": false`, and a live run of such a script is refused at its first write.
- **Any lab address.** The stand-in makes the calls, so the lab may be at an http or an https address (an address
  that is neither raises `LabError` `INVALID_URL`). A lab that does not answer reaches the package as a refusal in
  the Moku's envelope, code `LAB_UNREACHABLE`. A machine's and a device's id are letters, digits, `_` and `-`
  (`INVALID_MACHINE`, `INVALID_DEVICE` otherwise).
- **Not through the lab:** streaming (`start_streaming`, `get_stream_data`, `stream_to_file`) runs the
  manufacturer's `mokucli` against the device itself. `import moku` warns that it cannot find `mokucli`; nothing
  above needs it.
- The package's other arguments keep their defaults and may be given beside: `SpectrumAnalyzer(**m.moku("moku"),
  read_timeout=60)`. The lab needs an InstruCore that offers `/v1/moku/<machine>/<device>`; an older one answers `404`, which
  the package reports as "Method not found".

`moku` is not a dependency of `qupai-lab`: a QuPai sandbox has 4.3.0.1, and `pip install "qupai-lab[moku]"` installs
that version (MIT). The tests run with 4.3.0.1 and with 4.4.0.0.

## The record and `changes.json`

`record` (a path) gets one JSON line per call, appended: `time`, `method`, `path`, `args`, `ok`, `status`,
`code` (the error code, or null), `message` on a refusal, `req_id`, `retries` and `waited_s` when it waited for
the platform and was sent again, and for an op call `machine`, `role`, `instrument`, `kind` and `op`. A successful call's line carries its `result`, or `file` when the script saved that
result with `lab.save` straight after the call. The line of a call that answered a dict or a list is written with
the next call (or at the block's end), so it can name the file.

`lab.changes(path)` groups the writes by role and op: one numeric argument that moved is a range, several a box,
the rest fixed. `channel` never moves: each channel is its own change.

```json
{"script": "experiments/2026-11-21-frequency-response/run.py@3f2a91c", "machines": ["signal-bench-sim-1"],
 "changes": [
  {"role": "generator", "op": "set_waveform", "calls": 7, "quantity": "frequency_hz", "min": 100, "max": 100000.0,
   "fixed": {"channel": 1, "shape": "sine", "amplitude_v": 1.0}},
  {"role": "scope", "op": "set_timebase", "calls": 7, "quantity": "scale_s", "min": 5e-06, "max": 0.005,
   "fixed": {"offset_s": 0.0}}]}
```

A box reads `"ranges": {"x": [min, max], "y": [min, max]}` in place of `quantity`, `min` and `max`.

With a run folder the answer starts with `run`, the run's id; a rehearsal also writes it to
`<experiment>/changes.json`, where a live run's card reads it. A script that worked a Moku with the official package
gets `official_sdk` after `machines` (the devices, as in the manifest), and the writes the lab listed for those calls
are among the changes ([above](#a-moku-with-the-official-sdk)).

### Declaring a live run's changes without a rehearsal

A lab whose machine has no simulated copy has nothing to rehearse on, so no rehearsal writes `changes.json`, and the
card of a live run there would list no change: the lab then refuses the run's first write (`APPROVAL_REQUIRED`).
Declare the writes the run will make instead, in the form the card reads, and commit the file with the experiment:

```python
from qupai_lab import declare_changes

declare_changes("experiments/2026-11-26-coil-scan", [
    # one argument moves: quantity, min and max; the arguments it keeps are fixed
    {"role": "coil", "op": "set_current", "quantity": "current_a", "min": 0.0, "max": 1.5, "fixed": {"channel": 1}},
    # several move: ranges, each [min, max]
    {"role": "scope", "op": "set_timebase", "ranges": {"scale_s": [5e-6, 5e-3], "offset_s": [0.0, 1e-3]}},
    # nothing moves: exactly these arguments, as often as the run needs, for the whole session
    {"role": "moku", "op": "vendor.begin_control", "fixed": {}},
])
```

It writes `<experiment>/changes.json` as `{"declared": true, "written_at": …, "changes": […]}` and answers it. `role`
is the instrument's role on the machine (`qupai-lab machines`), `op` the write op's name (`describe`, or the
`instrucore.writes` the lab lists for a Moku's calls). A change the card would not take raises `LabError`
`INVALID_CHANGE` saying which and why (an unknown key such as `args`, a range with min above max, an argument both
moving and fixed, more than 32 changes), and nothing is written. The card reads a declared file as a rehearsed one:
each change with the lab's answer for it (`grants/evaluate`), marked `declared` and not `rehearsed`, and in the run the
lab allows exactly these writes and refuses any other. A later rehearsal's `lab.changes()` replaces the file, and so
does a later declaration. Declare only what the script writes, no wider than it needs: the member approves the card
as it reads.

Every request sends `Authorization: Bearer <key>` and `X-InstruCore-Script: <script>@<commit>`: the running
script's path in its git repository and the short commit, so the lab's record shows the code behind each call.
Outside a git repository the header is left out; `Lab(…, script_ref="…")` sets it, `script_ref=""` sends none.

## Live runs

When the member approves a live run (QuPai's `lab_run`, or Run on an experiment folder), QuPai writes the run's key
file into the place's repository and starts, in the repository's root:

```
qupai-lab run --key-file .qupai/runs/<run>/key.env --commit <sha> experiments/2026-11-21-freq signal-bench
```

1. It reads `QUPAI_LAB_URL`, `QUPAI_LAB_KEY` (the run's key), `QUPAI_LAB_RUN` (the run's id) and
   `QUPAI_LAB_RUN_MACHINE` from the key file (`KEY=VALUE` lines) and deletes it at once, whatever it holds. The
   machine must be the one named on the command line.
2. It checks the commit out into `/tmp/qupai-run-<run>` (`git worktree add --detach`, in the repository found from
   the working directory). Any committed `data/`, `figures/`, `calls.jsonl` and `changes.json` beside `run.py` (a
   rehearsal's, from before run folders) are removed from that checkout, so what the run keeps is its own.
3. It runs `python run.py <machine>` in `<checkout>/<experiment>` with the Python it runs in, with the four
   settings in place of any other `QUPAI_*` variable and `PYTHONUNBUFFERED=1`. The script's output is the
   command's own, as it is printed, and is also kept as the run's `output.log` (stdout and stderr, the first
   MiB). The script's `Lab.from_env()` gets the run's key and its run folder (`runs/<run>/`), and
   `lab.machine(<machine>)` holds the live machine (above).
4. When the script ends it copies the run folder, and any `data/`, `figures/`, `calls.jsonl` and `changes.json`
   the script wrote beside `run.py` itself, to `<experiment>/runs/<run>/` in the repository. The manifest gets
   the approved commit, the exit code and the status from it, and for a script that did not end well the last
   lines of its stderr as `error` unless the SDK said why already (a short manifest is written when the script left
   none), `experiments/INDEX.md` is written again, and the checkout is removed, also when the script failed.
5. It prints the run's answer as the last line of its stdout, one JSON object, which QuPai's Runtime hands the run's
   job as its output: `{"run": "<run>", "status": "ended" | "failed" | "stopped", "exit_code": n, "error": "…" | null}`
   (`error`: why it did not end well). It exits with the script's exit code (128 + the signal's number when a signal
   ended the script; 1 when the script exited 0 although the run's session ended while it ran).

SIGTERM and SIGINT are passed to the script, which releases the machine and exits; a script that has not ended
20 s later is killed. What it left is still copied and the checkout removed. A run that cannot start (a key file
without the four settings, another machine, no repository, no such commit, no `run.py` in the experiment at that
commit) says why on stderr and in its answer (`"error": "the run could not start: …"`) and exits with 2, after
deleting the key file.

### When the run's session ends while it runs

The run's session is the run's while its block runs, and only the lab ends it early: someone who may end it (the
member from the bench page, the lab's admin), or the lab itself at the run's longest time or after the session's idle
limit. The lab then refuses the run's next write, and every call of the official `moku` package, with `BENCH_NOT_HELD`
(`SESSION_REQUIRED` on a copy, `BENCH_HELD` or `MACHINE_IN_SESSION` once another holds it). Inside a run the SDK looks
at the machine on such a refusal, and when the session there is no longer the run's, the run stops at once:

- It says why on stderr, in a sentence the manifest keeps as `error` (and the machine as `ended`, the run as
  `session_ended`): the machine, since when the run held it, what ended it as far as the run can tell (its longest
  time, its idle limit, or someone other than the run: the bench page or the lab's admin), when the lab refused, and
  who holds the machine now when someone does.
- It tells QuPai `held` 0 and `session_ended` (below), and raises `RunSessionEnded`, a `SystemExit` with exit status 1,
  so `except Exception` (or `except LabError`) does not catch it; from the `moku` package's calls, it is raised in the
  script's main thread as a signal is. Every later call through the same `Lab` raises it again without reaching the
  lab, and the `moku` stand-in refuses every later call (`SESSION_ENDED`) but handing the Moku back.
- The block's end ends nothing: the session is not the run's to end. The manifest's `status` is `failed`, and
  `qupai-lab run` fails the run (exit 1) even when the script caught the exception and exited 0.

A refusal while the session there is still the run's is the lab's own, raised as `LabError` as always.

**Putting the run's settings back** (0.6.1). A script that changes a setting puts it back in a `finally` inside the
machine's block. When the session ended under the run, a call on the run's machine that the script makes while it
stops (in a `finally`, an `except` or a `with` block's exit, as `RunSessionEnded` or the script's own error goes by)
is its clean-up, and the SDK lets it through a session the run takes for it, once, when:

- the machine's block is still open (a clean-up after the block finds it ended),
- the session did not end at the run's longest time (the run's approved time is over then),
- and the machine is free and nobody waits for it (`GET /v1/machines/<id>`: no `session`, an empty `queue`).

That session is `{"purpose": "run <id>: putting back its settings", "queue": false, "max_s": 120}` (the lab gives the
smaller of that and its own limits), the lab checks the run's key and its approved changes in it as in the run, and the
block's end ends it. Otherwise each such call reaches nothing and raises `LabError` `NOT_PUT_BACK`, saying why, so the
script's `except LabError` goes on with the rest of its clean-up. A call outside a handler still raises
`RunSessionEnded` without reaching the lab: a script that swallows the end and carries on with its scan takes nothing.
The official `moku` package's calls after the end are refused by its stand-in as before: put a Moku's settings back
with the lab's own ops (`m.role(...).write(...)`).

The manifest's `restore` says what became of the run's settings: `machine`, `session` (the one taken to put them back,
or null) and `why_not` (why none could be taken), `after_end` (each change of the clean-up after the end: its `role`,
`op` and `args`, `put_back`, and `why` when it did not reach the instrument; for the `moku` package, its `device` and
`call`), and `left_set`, what the run set on the machine and did not put back: the last write of each setting (by role,
op and the argument that says which: `channel`, `slot`, `output`, `port`, `axis`, `index`, `input`, `source`). The
`error` adds what was put back, what did not reach the machine and why, and what is still set, so the run's answer and
its job say it too.

### Points for QuPai (`QUPAI_METRIC`)

Inside a run (`QUPAI_LAB_RUN` set) the SDK prints the run's progress on stdout as lines QuPai's Runtime takes from
a background job's output, one point each:

```
QUPAI_METRIC {"key": "queue_position", "value": 2}
QUPAI_METRIC {"key": "held", "value": 1}
QUPAI_METRIC {"key": "held_since", "value": 1795670719.0}
QUPAI_METRIC {"key": "calls", "value": 14}
QUPAI_METRIC {"key": "held", "value": 0}
```

| Key | When |
| --- | --- |
| `queue_position` | The request's position in the machine's queue, when it is queued and each time it moves |
| `held` | 1 when the run's session starts, 0 when it is released or ended while the run ran |
| `held_since` | With `held` 1: when the session started, as the lab says (`started_at`), in seconds since the epoch |
| `calls` | The instrument calls made so far (reads, writes and checks, refused ones too), at most every 5 s, and when the session is released or ended and the script exits |
| `session_ended` | When the run learned that its session ended while it ran, not by the run (seconds since the epoch; [above](#when-the-runs-session-ends-while-it-runs)) |

They are the run's own machine's: a simulated copy the run's script holds tells nothing. Outside a run nothing is
printed on stdout but the runner's answer.

## Errors

A refusal raises `LabError`, with `code`, `message` (the lab's sentence as it sent it), `detail` and `status`
(the HTTP status, 0 when no answer came). It reads InstruCore's `{"error": {code, message, detail}}` and the QuPai
gateway's problem documents (`urn:qupai:problem:rate` becomes `RATE`, `invalid-key` `INVALID_KEY`).

### When the platform asks to wait

QuPai's gateway answers `429 Too Many Requests` before it passes a call on to the lab: too many calls from one
address in the minute (`Retry-After: 60`, until the minute ends; a lab workstation's seats share one address, MCP and
REST together), or too many of the member's calls to the lab. InstruCore answers no `429` itself. The SDK then waits
and sends the same call again, said once on stderr:

```
qupai-lab: rate-limited by the platform; waiting 1 min, then asking again (GET /v1/machines: Too many requests from this address; retry in a minute). One call waits 5 min at most
```

- **What is sent again**: a call that may be sent again whatever became of the first, after any `429` and after a
  `503` that names a `Retry-After`: every GET (the machine list, a machine, a queue request, a reference), an
  instrument's `read` and `check` ops, a session's start, renewal and end, withdrawing a queue request; and a write
  after the gateway's own `429` (its `urn:qupai:problem:rate` document), which never reached the lab. A write refused
  any other way is never sent twice, since it may have reached the instrument: it raises at once, and says so.
- **How long**: the `Retry-After` the answer names (seconds or an HTTP date), else 2 s doubling with each try; at
  least 1 s and at most 60 s each time, 5 minutes in all for one call. Then the refusal is raised, with `retries` and
  `waited_s` in its `detail`, and said on stderr. The record's line has `retries` and `waited_s` too, and the manifest
  counts the waits (`rate_limited`).
- A signal while a session's start waits stops the script at once: nothing was started. The block's end (`sessions/end`)
  waits as long as it must, within the 5 minutes, so a bench is not left held because the platform was busy.
- `Lab.from_qupai`'s first question (`GET /v1/me/lab-access`) waits the same way, and so do the official `moku`
  package's calls at their stand-in, within the package's patience ([above](#a-moku-with-the-official-sdk)).

| Code | What it means |
| --- | --- |
| `LIMIT_EXCEEDED`, `POLICY_DENIED`, `FORBIDDEN` | The lab refuses this value or op. Save what you have and report the limit; never retry with another value or through another op |
| `APPROVAL_REQUIRED` | A write on a live machine the member has not allowed |
| `RUN_REQUIRED` | A script asked to hold a live machine: only a run the member approved holds one |
| `SESSION_REQUIRED`, `BENCH_NOT_HELD`, `MACHINE_IN_SESSION`, `BENCH_HELD` | The write needs your session on that machine, or someone else holds it. Inside a run, on the run's machine, they mean the run's session ended: `RunSessionEnded` (below) |
| `SESSION_ENDED` (`RunSessionEnded`, a `SystemExit`) | Inside a live run: the run's session ended while it ran, not by the run; the run stops ([above](#when-the-runs-session-ends-while-it-runs)) |
| `NOT_PUT_BACK` | Inside a live run whose session ended: a call of the script's clean-up that could not be put through a session of the run's own, and why; the manifest's `restore` lists it ([above](#when-the-runs-session-ends-while-it-runs)) |
| `INVALID_KEY`, `FORBIDDEN`, `RATE`, `UNAVAILABLE` (the gateway's) | The key, your role on the lab, too many calls (still, after 5 minutes of waiting: [above](#when-the-platform-asks-to-wait)), the lab not reachable through QuPai |
| `NOT_FOUND` | No such machine or instrument, or a bench you hold no role on |
| `UNREACHABLE`, `NOT_CONFIGURED` | No answer from the address; no address or key found |
| `UNKNOWN_ROLE`, `NOT_HELD`, `WAIT_TIMEOUT`, `REQUEST_EXPIRED`, `REQUEST_CANCELLED` | The SDK's own: no such role, the machine used outside `with`, no copy offered in `wait_s`, the queue request ended |
| `INVALID_MACHINE`, `INVALID_DEVICE`, `INVALID_URL` | `m.moku()`'s own: not a plain machine or device id; the lab's address is not http(s)://host[:port][/path] |
| `INVALID_CHANGE` | `declare_changes`'s own: a change the card would not take |
| `NOT_SIGNED_IN`, `NO_DIRECT_ACCESS`, `NOT_OFFERED` | `Lab.from_qupai`'s own: no `qupai` sign-in with a personal key here (run `qupai login`); a lab you may not work directly from here (the message names the labs you may; ask the lab's agent for the others); a platform that does not say which labs yet (`GET /v1/me/lab-access` answered 404) |

## Tests

```
cd sdk/python
python3 -m venv .venv && .venv/bin/pip install -e ".[moku]" pytest
.venv/bin/pytest -q
```

They run against a fake InstruCore in a thread (`tests/test_direct.py`: the same fake as the platform's REST door,
over TCP and over a Unix socket as a workstation's door); `tests/test_moku_official.py` drives the official `moku` package
through `m.moku()` against the fake's stand-in for InstruCore's Moku endpoint, and is skipped when the package is not
installed (`pip install -e . pytest` without the extra); `qupai-lab run`'s tests make git repositories under the test's
temporary folder and checkouts in `/tmp/qupai-run-<run>`, and send signals to scripts in subprocesses. `tests/test_integration.py` also runs against a real InstruCore
with a simulated pool when `QUPAI_LAB_IT_URL` and `QUPAI_LAB_IT_KEY` (a read-write key) are set;
`QUPAI_LAB_IT_POOL` picks the pool.

## License

MIT
