Metadata-Version: 2.4
Name: onyx-site
Version: 0.1.0
Summary: Onyx site-runner: runs onyx-app's jobs on a customer's units (builders, sims, rigs)
Author: Max Palay
Author-email: Max Palay <maximiliano@onyx-robotics.com>
License-Expression: Apache-2.0
License-File: LICENSE
Requires-Dist: httpx>=0.28
Requires-Dist: cryptography>=44
Requires-Dist: pydantic>=2.10
Requires-Python: >=3.12
Description-Content-Type: text/markdown

# onyx-site

The Onyx **site-runner**: a long-running service on the customer's machine that runs onyx-app's
jobs on the site's units (builders, simulators, rigs). It is a runner in onyx-app's jobs protocol
(`typescript/onyx-app/docs/jobs.md`): it calls `POST /api/v1/runners/sync` once a tick, over
plain HTTPS, with the site's API key. Each sync offers the site's units and reports on its jobs;
each answer assigns, cancels or forgets jobs. Every assignment is checked against the site's own
policy, then run by a customer **driver** (each in its own process). Result files stay on the
site and are served through signed download links. A local SQLite journal means a restart or a
lost response loses nothing and does nothing twice.

**Setting up a site, step by step: [SETUP.md](https://github.com/onyx-robotics/onyx-agent/blob/main/docs/sites/SETUP.md).**

It runs as a packaged service, not in a container, because drivers need USB, CAN and serial.
Its drivers run as the site's user, without a sandbox, and run code from the experiment's commit,
which agents may have written: give that user only what the site needs, and make a driver that
moves hardware safe whatever it's asked to do.

## Install

```bash
uv tool install onyx-site   # or: pip install --user onyx-site
# from a checkout of the Onyx repository instead: uv tool install ./python/site-runner
```

Production layout: a dedicated `onyx-site` user, the site file at `/etc/onyx-site/site.toml`,
state in `/var/lib/onyx-site` (mode 0700), `onyx-site run` under systemd (or launchd). The key is
a 0600 file only the service user reads. Drivers don't get it in their environment, but they run
as that user, so they could read it.

## Enrol

```bash
onyx-site enrol --server https://app.onyx.dev
```

This is onyx-app's device flow with scope `site`: it prints a link and a code, an org admin
approves the machine on `/device` and names the site, and the site-runner stores the site's API
key (an `onyx_sk_…` key with only the `run` scope) in `<state_dir>/token`, mode 0600. The key is only ever sent to the
server it enrolled with, over verified TLS (`http://` only to localhost), in the `Authorization`
header, never following redirects. It is never put in an environment variable, the site file or
a log line. The site-runner replaces it every `rotate_days` (30) through `POST /sites/me/rotate`;
the old key works ten more minutes, so a lost response costs nothing.

## Run

```bash
onyx-site run                                   # the service
onyx-site status                                # units, jobs, and the sync with onyx-app
onyx-site stop --job <id>                       # stop a job now, reported cancelled (works offline)
onyx-site hold --unit motor-3 --reason "belt"   # no new jobs on the unit
onyx-site release --unit motor-3                # a held or quarantined unit
onyx-site rotate                                # a new key now
onyx-site conformance my_drivers.rig:MotorRig --config '{"port": "/dev/ttyACM0"}'
```

`onyx-site init` writes a site file to start from (`src/onyx_site/templates/site.toml`: onyx-app's
address, the file server (off until it has a certificate), and commented example units on the placeholder driver). By default the
site file is `~/.config/onyx-site/site.toml` and the state `~/.local/state/onyx-site` (root, or a
user whose site is already in `/etc/onyx-site`, keeps the system layout below).
`--site` / `ONYX_SITE_CONFIG` pick the site file; `--state-dir` / `ONYX_SITE_STATE_DIR` the state
folder. Stop, hold and release talk to the running service over `<state_dir>/control.sock`; with
the service down, hold and release are written to the journal.

## What it reports

Each sync carries every unit (`key` = its id in the site file, `type` = its unit type, which must
be an asset type in the org's registry, `free`, `ok`), every job it holds, and its reports:

| What happened | Report |
| --- | --- |
| a run started | `started`, with nothing else |
| it finished | `ended`, `succeeded`, with its props, metrics and files |
| the driver raised `JobFault` | `failed`, `job` (never retried) |
| it ran, but its data is missing or malformed (`RunResult(valid=False)`, bad metrics) | `failed`, `invalid`, keeping what it left |
| onyx-app refused an end's results (say, a metric its registry doesn't know) | the end again without them: `failed`, `invalid`, with onyx-app's reason |
| the site's policy refused it | `failed`, `refused`; it never started |
| the driver raised `UnitFault` | `failed`, `unit`; onyx-app holds the unit until someone resumes it |
| anything around the run (`InfraFault`, a fetch, the site-runner restarting mid-run) | `failed`, `infra` |
| onyx-app said `cancel`, or `onyx-site stop` | `cancelled` |

`unknown` and `lost` are onyx-app's to decide, never the site's. Files are refs
`{system: "onyx-site", locator: "<job>/<attempt>/<path>", contentHash, sizeBytes}`; onyx-app
records which site holds them and hands out links. A unit failing its health check is offered
`ok: false` with the reason: offline after one failure, and checked again every minute until it
passes; quarantined after two in a row (no more checks, until `onyx-site release`), but only if it
has been healthy since it was added: one that never has isn't set up yet, and stays offline.

A job with retries left stops when no sync has succeeded for `leaseMs` (onyx-app may run it
elsewhere); one without finishes under local supervision. A key onyx-app no longer accepts (401,
or 403/404 on sync) stops syncing; jobs in flight finish, and `onyx-site enrol` resumes.

## The site file

`onyx-site init` writes a commented site file to start from (in a checkout of the Onyx repository, `examples/site.toml` has every option). In short:

| Table | What |
| --- | --- |
| `[site]` | `server` (onyx-app), `state_dir`, `health_interval_s` (60), `stop_timeout_s` (10), `rotate_days` (30) |
| `[files]` | the file server: `bind` (`0.0.0.0:7443`), `public_url` (reported to onyx-app as `filesUrl`), `cert`/`key`, or `insecure_http = true` for development |
| `[retention]` | `days`, `max_gb`: whole jobs are deleted, oldest first |
| `[policy]` | `unit_types` (default: all below), `max_deadline_s`. onyx-app can't loosen it |
| `[repos."<name>"]` | what a job's `git` prop may name: `url`, and a read-only `ssh_key` or `token_file`. Nothing else is ever fetched |
| `[drivers.<name>]` | `ref = "module:Class"` (Python) or `program = "/path"`; `config = {…}` for the driver; `process = "driver"` or `"unit"` (one worker per unit); `python_path` |
| `[unit_types."<asset type>"]` | `driver`, `fidelity` (sim, hil, hardware, build), `physical` (default: hardware and hil) |

Units come from the drivers' `describe()`. The site file is watched: a change re-offers the units
and restarts changed drivers once their jobs end.

## Writing a driver

The full guide is [DRIVERS.md](https://github.com/onyx-robotics/onyx-agent/blob/main/docs/sites/DRIVERS.md): what the site-runner sends a driver, when, and what
becomes of what it returns. In short, a driver is written for **one** resource, and the site-runner
runs one instance of it per entry in its site-file section's `instances`, each in its own process,
handing it a job only when the resource is able to run it:

```python
import json
from pathlib import Path
from onyx_site import Driver, Unit, Health, RunContext, RunResult, JobFault, UnitFault, InfraFault


class MotorRig(Driver):
    protocol = 1
    version = "1.2.0"

    def describe(self) -> Unit:  # required: what this resource is
        return Unit(self.id, "bench.motor_rig", {"rev": "B"}, exclusive_group="psu-a")

    def health(self) -> Health:  # required; between jobs, after failures
        return Health(True)

    def run(self, inp: Path, out: Path, ctx: RunContext) -> RunResult:  # required
        params = json.loads((inp / "params.json").read_text())
        while not ctx.cancelled:
            ctx.progress(rpm=812.0)
            ctx.log("streaming")
            ...
        (out / "recording.csv").write_text(...)
        return RunResult(conditions={"temperature_c": 31.5}, metrics={"bench.final_rpm": 998.0})

    def stop(self) -> None: ...  # required: any time, twice, during run
    def reset(self) -> RunResult: ...  # required for physical units

    def check(self, inp: Path) -> None: ...  # optional: raise JobFault to refuse
```

* `self.config` is the instance's config: the section's `config` with its own `instances`
  entry over it, which always has its `id` (also `self.id`).
* `inp` holds the job's props as `params.json`, and the fetched commit when its props name one
  (`git: {url, commit}`). Write results to `out`: every file there is offered for download.
* Metric names must be metrics in the org's registry: an org's own pack names them
  `<pack>.<key>`.
* Raise `JobFault(code, message)` for the job's own fault, `UnitFault` when the unit failed,
  `InfraFault` for everything around it. `RunResult(valid=False)` reports `invalid`.
* `ctx.cancelled` turns true on stop or at the deadline; `ctx.wait(s)` sleeps but wakes on stop.
* The site-runner calls `stop()` with its own timeout (`stop_timeout_s`), then kills the
  driver's process. Each Python driver runs in `python -m onyx_site.worker module:Class` and
  speaks JSON lines; `print()` goes to the service log, not the protocol.

**Program drivers** (any language) answer subcommands instead, one process per call, for one
instance: `driver describe`, `driver health`, `driver run --in in/ --out out/ --deadline-s N`,
`driver stop`, `driver reset`, `driver check --in in/`. Exit code 0 ok, 10 job
fault, 11 unit fault, 12 infrastructure fault. Stdout lines are JSON (`{"log": …}`,
`{"progress": {…}}`, `{"result": {…}}`, `{"fault": {"code", "message"}}`) or plain text
(logged). `describe` prints `{"result": {"version", "calls": ["reset", …], "unit": {id,
unit_type, labels}}}`; the instance's config arrives as JSON in `ONYX_DRIVER_CONFIG`.

Before a driver gets real jobs, run `onyx-site conformance <module:Class | program>` (or
`onyx-site conformance <name> --from-site`): it runs every call, including stop during a run.
`--input` and `--long-input` give it a short job and one that runs until stopped.

Shipped examples: `onyx_site.drivers.local_build:LocalBuild` (runs the source's `build.sh` on this
host, as you, so only for code you trust) and
`onyx_site.drivers.sim_motor:SimMotor` (a simulated motor rig; `metrics_prefix` names its metrics
for an org's pack), and `onyx_site.drivers.local_program:LocalProgram`: a slot on this computer,
running a program from each job's commit (`command`), with the job's props in `$ONYX_PARAMS`,
everything it writes to `$ONYX_OUT` kept, and `$ONYX_OUT/metrics.json` recorded as its metrics.
It runs the program directly, so it's for code you trust; it's also the shortest complete driver
to start your own from. **Writing a driver, step by step: [DRIVERS.md](https://github.com/onyx-robotics/onyx-agent/blob/main/docs/sites/DRIVERS.md).**

## Running locally against onyx-app

1. Start onyx-app (`bun run dev` in `typescript/onyx-app`). The org needs an asset type for the
   units and, for results to be recorded, the metrics the driver reports (a pack).
2. Enrol, keeping state in the project folder:

   ```bash
   cd python/site-runner
   uv run onyx-site --site examples/site.toml enrol
   ```

   Approve the code on `http://localhost:3000/device` as an admin, and name the site.
3. Run it: `uv run onyx-site --site examples/site.toml run`. Its units show up as runner units in
   onyx-app.
4. Submit a job for one of its unit types (`POST /api/v1/jobs`, or `onyx run --on <type>` from
   onyx-app's CLI). `GET /api/v1/jobs/{id}/files` gives a signed link to each file on
   `http://localhost:7443/files/{job}/{attempt}/`.

## Develop

```bash
uv sync
uv run ruff check && uv run ruff format --check && uv run ty check && uv run pytest
```

The tests run the service against a fake onyx-app that speaks the runner protocol: lost
responses, rejections, cancel and stale, the lease, rotation and revocation, and signed
downloads.

## Layout

| Module | |
| --- | --- |
| `driver.py` | the driver contract: `Driver`, `Unit`, `Health`, `RunContext`, `RunResult`, faults |
| `worker.py` | the process a Python driver runs in (JSON lines on stdin/stdout) |
| `driverhost.py` | starting, calling, killing drivers (Python workers and programs) |
| `service.py` | units, assignments, runs, reports, health, recovery after restart |
| `sync.py` | the runner protocol: the sync loop, `/sites/me`, key rotation, backoff |
| `journal.py` | SQLite: jobs, unacknowledged reports, unit holds |
| `policy.py` | the site's check of every assignment |
| `fetch.py` | git mirrors per repository |
| `store.py` | the site result store and retention |
| `fileserver.py` | signed download links, range requests |
| `auth.py`, `enrol.py` | the site's key and the device flow |
| `control.py`, `cli.py` | local control socket and the `onyx-site` command |
| `conformance.py` | the driver check |

## License

Apache-2.0 (see the `LICENSE` file in the package).
