# zc2 Usage Guide
This guide covers the complete usage of `zc` (built from `zc2`), the Zakuro AI command-line tool. `zc` is a P2P compute broker that routes compute requests to workers across a distributed network, with yen-denominated billing settled through the Zakuro hub HTTP API (ADR ZC-0005), P2P broker-to-broker communication, write-ahead logging, automatic worker discovery, and real-time monitoring.
---
## Table of Contents
- [Prerequisites](#prerequisites)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Broker](#broker)
- [Starting the Broker](#starting-the-broker)
- [Foreground Mode](#foreground-mode)
- [Daemon Mode](#daemon-mode)
- [Worker Discovery](#worker-discovery)
- [Mesh Mode](#mesh-mode)
- [Local Mode](#local-mode)
- [Manual Registration](#manual-registration)
- [API Reference](#api-reference)
- [Health & Status](#health--status)
- [Worker Management](#worker-management)
- [Compute Execution](#compute-execution)
- [Balance Management](#balance-management)
- [Ledger Administration](#ledger-administration)
- [P2P Broker Endpoints](#p2p-broker-endpoints)
- [Routing Strategies](#routing-strategies)
- [Benchmarking](#benchmarking)
- [Basic Benchmark](#basic-benchmark)
- [Strategy Comparison](#strategy-comparison)
- [Benchmark Options](#benchmark-options)
- [Remote Monitoring](#remote-monitoring)
- [System Diagnostics](#system-diagnostics)
- [Balance System](#balance-system)
- [Hub Ledger (Credit Authority)](#hub-ledger-credit-authority)
- [Reserve-Commit Model](#reserve-commit-model)
- [API Keys](#api-keys)
- [P2P Broker-to-Broker Communication](#p2p-broker-to-broker-communication)
- [Write-Ahead Log (WAL)](#write-ahead-log-wal)
- [Cluster Commands](#cluster-commands)
- [Zakuro Drive Hooks](#zakuro-drive-hooks)
- [Environment Variables](#environment-variables)
- [Configuration Reference](#configuration-reference)
---
## Prerequisites
- **Rust** toolchain (recent stable; the dependency tree's MSRV is 1.88) for building from source
- **Docker** and **Docker Compose** (for containerized deployments)
- **WireGuard** (optional, for P2P network discovery)
- `ZAKURO_API_KEY` environment variable must be set
## Installation
### From Source
```bash
git clone https://github.com/zakuro-ai/zc.git
cd zc
task build:bin
```
This compiles the release binary and installs it to `/usr/local/bin/zc`.
### With Docker
```bash
task build
```
This builds the binary, then builds and starts the Docker services via `docker compose`.
### Verify Installation
```bash
zc --version
```
Prints the version, the commit, and the SHA-256 of the binary itself — the
same hash each broker discloses, so a local install can be matched against
what is running on the mesh.
---
## Quick Start
1. Set your authentication token:
```bash
export ZAKURO_API_KEY="your-token-here"
```
2. Start the broker:
```bash
zc broker
```
3. The broker will automatically discover workers on your network and begin accepting compute requests on port `9000`.
---
## Broker
The broker is the core component of `zc`. It accepts compute requests from clients, selects an optimal worker, forwards the request, and handles billing.
### Starting the Broker
```bash
# Default: foreground mode on 0.0.0.0:9000
zc broker
# Custom port
zc broker 8080
# Custom host and port
zc broker 0.0.0.0 9000
```
### Foreground Mode
```bash
zc broker
```
Foreground mode displays a startup banner listing all API endpoints and then prints a live transaction log to stdout. Each request is shown with its status, user, cost, and latency. Press `Ctrl+C` to stop.
Example output:
```
╔═══════════════════════════════════════════╗
║ Zakuro Compute Broker ║
╚═══════════════════════════════════════════╝
Listening: http://0.0.0.0:9000
API Endpoints:
─────────────────────────────────────────────
GET /health Health check
GET /workers List workers
POST /workers Register worker
POST /workers/heartbeat Worker heartbeat
DEL /workers/:id Unregister worker
POST /execute Execute request
POST /price Estimate price
GET /balance/:user Get balance
POST /balance/:user/add Add funds
─────────────────────────────────────────────
Press Ctrl+C to stop.
```
### Daemon Mode
```bash
zc -d broker
zc --daemon broker
zc -d broker 8080 # Daemon on custom port
```
Daemon mode runs the broker in the background with minimal output. Useful for production deployments or running the broker as a service.
---
## Worker Discovery
The broker automatically discovers compute workers based on the available network interfaces.
### Mesh Mode
**Trigger:** A `zakuro0` or `wg*` interface is detected holding an address in `10.13.13.0/24`, or `ZAKURO_WIREGUARD_IP` is set. See `get_mesh_ip` in `src/broker/discovery.rs`.
**Behavior:**
- Scans the mesh subnet (`10.13.13.2` through `10.13.13.254`) on port `3960` (configurable via `ZAKURO_WORKER_PORT`)
- Also checks extra ports: `3961`, `3962`
- Probes each address for `/health` and `/info` endpoints
- Only registers services that return a valid `worker_type` in their `/info` response
- Refreshes heartbeats for existing workers every 15 seconds (configurable via `ZAKURO_SCAN_INTERVAL`)
- **Balances are enforced** in this mode — all executions are billed
### Local Mode
**Trigger:** No mesh interface is detected.
**Behavior:**
- Scans `127.0.0.1` on ports `3960`, `3961`, `3962` (or `ZAKURO_SCAN_RANGE` if set)
- Same probing logic as mesh mode
- **Execution is free** — no money is charged
- Useful for development and testing
### Manual Registration
Workers can always register themselves via the REST API regardless of discovery mode. When `ZAKURO_WORKER_KEY` is configured, include the key in the `X-Worker-Key` header:
```bash
curl -X POST http://localhost:9000/workers \
-H "Content-Type: application/json" \
-H "X-Worker-Key: $ZAKURO_WORKER_KEY" \
-d '{
"name": "my-worker",
"uri": "http://10.13.13.5:3960",
"worker_type": "zakuro",
"resources": {
"cpus_total": 8.0,
"cpus_available": 8.0,
"memory_total": 17179869184,
"memory_available": 17179869184,
"gpus_total": 1,
"gpus_available": 1
},
"pricing": {
"cpu_price": 0.001,
"memory_price": 0.0001,
"gpu_price": 0.01,
"min_charge": 0.15
},
"tags": ["gpu", "cuda"]
}'
```
Workers must send periodic heartbeats to remain healthy:
```bash
curl -X POST http://localhost:9000/workers/heartbeat \
-H "Content-Type: application/json" \
-H "X-Worker-Key: $ZAKURO_WORKER_KEY" \
-d '{"worker_id": "uuid-of-worker"}'
```
Workers that miss heartbeats for longer than `worker_timeout` (default: 30 seconds) are marked unhealthy and eventually removed.
---
## API Reference
The broker exposes an HTTP API on its configured host and port (default: `0.0.0.0:9000`).
### Health & Status
#### `GET /health`
Returns `200 OK` if the broker is running, plus the identity of the binary
answering — the semver, the commit it was built from, and the SHA-256 of the
executable file:
```json
{
"status": "healthy",
"service": "zakuro-broker",
"node_id": "zc://node-dd715b7f6d94d44e",
"mesh_tunnel": "up",
"build": {
"version": "0.0.33",
"git": "0447049",
"binary_sha256": "0130785371eae09b5816ced91616ce48a4419f912809e757307459eb7dd0b6be"
}
}
```
The hash is what distinguishes two brokers reporting the same version from the
same commit but running different artifacts. A broker built before build
disclosure omits `build` entirely. The same block rides `GET /peer/advert` and
`GET /peer/identity`, and `GET /brokers` reports it per peer as `build`
alongside this broker's own `self_build`.
Run `zc brokers` to reconcile it across the mesh, or `zc --version` to print
the local binary's hash for comparison.
The body also carries the broker-wide settlement backlog, as counts only (no
account ids, amounts or request ids): `settlement_pending` (transactions
charged and not yet delivered to the hub), `settlement_quarantined`
(transactions given up on after 5 failed flushes since start, written to
`wal-rejected.jsonl`), `settlement_retired` (of those, rows the hub refused for good: their WAL entry is retired and nothing re-sends them), `settlement_dropped` (of those, rows that never had a WAL entry of their own, such as requester refunds `<rid>-earn-refund` / `<rid>-unresolved-refund` and infer or serve rows: once quarantined, nothing re-sends them either), `quarantine_records_evicted` (per-account quarantine
records dropped from the bounded `/ledger/status` record since start; non-zero
means some account's view under-reports, see below) and
`settlement_last_flush_secs` (seconds since the flush path last ran).
Every `wal-rejected.jsonl` line says what happens to the row next:
`"retired": true` (refused for good, never re-sent), `"owed": true` (its WAL
entry is still open, so the next restart re-sends it) or `"dropped": true`
(no WAL entry, never re-sent). Retired and dropped rows are also appended to
`wal-retired.jsonl`, which is never rotated, so they can be reconciled with the
hub. That file is at-least-once: a kill between its write and the WAL's group
commit can quarantine and write the same row again after a restart, so
reconcile by `request_id`. `settlement_pending` climbing while
`settlement_last_flush_secs` grows means the broker is charging for work it
is not delivering. `settlement_pending` excludes rows in the batch a flush is
delivering at that moment. To see which of the rows are yours, use
[`GET /ledger/status`](#get-ledgerstatus) with your own key on a broker that
validates keys with the hub.
#### `GET /stats`
Returns broker statistics in JSON format.
**Authentication:** Requires `Authorization: Bearer <key>`. Non-admin callers only see their own transactions; admin callers see all.
**Response fields:** transactions, workers, metrics (request count, RPS, latency percentiles, yen spent).
### Worker Management
#### `GET /workers`
List all registered workers and their current status.
**Response:**
```json
{
"total": 2,
"healthy": 2,
"workers": [
{
"id": "uuid",
"name": "worker-1",
"uri": "http://10.13.13.5:3960",
"status": "Healthy",
"resources": { "cpus_total": 8, "cpus_available": 6, ... },
"pricing": { "cpu_price": 0.001, ... },
"avg_latency_ms": 12.5
}
]
}
```
#### `POST /workers`
Register a new worker. See [Manual Registration](#manual-registration) for the request body schema.
**Authentication:** Requires `X-Worker-Key` header matching `ZAKURO_WORKER_KEY` env var (when configured). Without a configured key, registration is open (local dev).
#### `POST /workers/heartbeat`
Refresh a worker's heartbeat to keep it marked as healthy.
**Authentication:** Same as `POST /workers` — requires `X-Worker-Key` when configured.
#### `DELETE /workers/:id`
Unregister a worker by its UUID.
**Authentication:** Same as `POST /workers` — requires `X-Worker-Key` when configured.
### Compute Execution
#### `POST /execute`
The primary endpoint. Sends a compute request that the broker routes to the best available worker.
**Request headers:**
| Header | Required | Description |
|--------|----------|-------------|
| `Authorization` | Yes (remote mode) | `Bearer <api_key>` — resolves user ID for billing |
| `X-Zakuro-User` | No | Fallback user ID in local mode only (defaults to `anonymous`) |
| `X-Zakuro-Requirements` | No | JSON resource requirements (see below) |
| `Content-Type` | No | `application/octet-stream` for binary payloads |
**Requirements JSON:**
```json
{
"cpus": 1.0,
"memory_bytes": 1073741824,
"gpus": 0,
"estimated_duration_secs": 1.0,
"strategy": "best_price",
"worker_type": "zakuro",
"tags": ["gpu"],
"budget": 150
}
```
All fields are optional and have sensible defaults (1 CPU, 1 GiB memory, 1 second duration, `best_price` strategy), with one exception: `budget`.
**Remote dispatch needs a budget.** When the broker requires vouchers (`ZAKURO_REQUIRE_VOUCHER=1`, which a CLI broker with billing credentials sets by default), a job it offers to a peer broker carries a hub-signed voucher minted for `budget`. A request that would go remote without a positive `budget` fails fast with `400 BUDGET_REQUIRED`; there is no silent default. A job that runs on a local worker does not need one. The default will come from the node's `policy.toml` `[budget]` once ZC-0017 is implemented (`docs/adr/0017-one-sharing-policy.md`).
**Response headers:**
| Header | Description |
|--------|-------------|
| `X-Zakuro-Request-Id` | Unique request ID |
| `X-Zakuro-Cost` | Actual cost in yen |
| `X-Zakuro-Balance` | User's balance after the transaction |
| `X-Zakuro-Duration-Ms` | Total request duration in milliseconds |
#### `POST /price`
Estimate the cost of a request without executing it.
**Request body:** Same `requirements` JSON as `/execute`.
**Response:**
```json
{
"min_cost": 0.15,
"max_cost": 0.005,
"workers_available": 3
}
```
### Balance Management
#### `GET /balance/:user`
Get the balance for a user.
**Authentication:** Requires `Authorization: Bearer <key>`. Non-admin callers can only view their own balance (403 otherwise).
```bash
curl http://localhost:9000/balance/my-user \
-H "Authorization: Bearer $API_KEY"
```
#### `POST /balance/:user/add`
Add funds to a user's account. Requires an `X-Api-Key` header. It is not supported in API mode (`501`; use the dashboard). With `ZAKURO_MASTER_KEY` set, the header must be the master key. With **no** master key set, *any* `X-Api-Key` value is accepted: that is a dev-only convenience for seeding a local broker, where billing is off anyway, so never expose such a broker.
```bash
curl -X POST http://localhost:9000/balance/my-user/add \
-H "Content-Type: application/json" \
-H "X-Api-Key: your-api-key" \
-d '{"amount": 100.0, "description": "Initial deposit"}'
```
### Ledger Administration
#### `GET /ledger/status`
Report which ledger the broker runs: `{"api_mode": true}` when balances go through the hub API (`ZAKURO_API_URL` + `ZAKURO_API_KEY`, no `ZAKURO_MASTER_KEY`), `false` in standalone mode (`ZAKURO_MASTER_KEY` set: local in-memory ledger). There is no database connection to report: the broker has no PostgreSQL client (ADR ZC-0005).
**Authentication:** Requires `Authorization: Bearer <key>`. The master key gets the broker-wide `{"api_mode": ...}` body above. Any other key gets only its **own** account's settlement backlog, and only on a broker that validates keys with the hub (`ZAKURO_API_URL` set, `ZAKURO_TRUST_KEY_SHAPE` off). In local mode or under `ZAKURO_TRUST_KEY_SHAPE`, identity is just the shape of the key, so non-admin keys still get `403`. Rows are filtered on the transaction's account, so other accounts' data never appears:
```json
{
"scope": "account",
"account": "alice",
"api_mode": true,
"settlement_pending": 1,
"settlement_quarantined": 1,
"quarantine_incomplete": false,
"pending": [{"request_id": "r-1", "tx_type": "commit", "amount": 1.25, "attempts": 2}],
"quarantined": [{"request_id": "r-0", "tx_type": "commit", "amount": 2.5, "quarantined_at": "2026-11-07T10:00:00+00:00"}]
}
```
`settlement_pending` counts all of the account's queued rows, but excludes rows in the batch a flush is delivering at that moment (they are counted again if that delivery fails). `pending` lists up to 100 of them. `settlement_quarantined` and `quarantined` (the 50 most recent rows) cover what was quarantined since the broker started. The broker keeps these records for at most 1024 accounts and drops the account that least recently had a quarantine first. Once any account's record has been dropped, `quarantine_incomplete` is `true` on every account's view (the broker does not remember which accounts were dropped): `settlement_quarantined` and `quarantined` are then a lower bound, and `0` does not mean nothing was quarantined. Check `wal-rejected.jsonl` or ask the operator. `earning` rows (your payout for work your worker ran) are listed without `request_id`, because that id belongs to the requester. Worker addresses, balances and the hub's error text are left out, because a batch error can name other accounts' jobs. The full error stays in the operator-only `wal-rejected.jsonl`.
```bash
curl http://localhost:9000/ledger/status \
-H "Authorization: Bearer $ZAKURO_MASTER_KEY" # broker-wide view
curl http://localhost:9000/ledger/status \
-H "Authorization: Bearer $ZAKURO_API_KEY" # your own settlement backlog
```
### P2P Broker Endpoints
These endpoints are **only available when P2P is on** (the default for a CLI-started broker with a mesh route, or `ZAKURO_P2P=true`; see [P2P Broker-to-Broker Communication](#p2p-broker-to-broker-communication)) and are used for broker-to-broker communication.
#### `GET /peer/health`
Check if the peer broker is healthy and reachable.
**Authentication:** Requires `X-Peer-Key` header matching `ZAKURO_PEER_KEY`.
```bash
curl http://peer-broker:9000/peer/health \
-H "X-Peer-Key: $ZAKURO_PEER_KEY"
```
#### `POST /peer/reserve`
Reserve funds for a user owned by this broker (called by non-authoritative brokers).
**Authentication:** Requires `X-Peer-Key` header.
**Request body:**
```json
{
"user_id": "9000000001",
"amount": 0.005,
"reservation_id": "res-uuid-123"
}
```
**Response:**
```json
{
"success": true,
"balance_remaining": 99.995
}
```
#### `POST /peer/commit`
Commit a transaction after worker execution (finalizes the reservation).
**Authentication:** Requires `X-Peer-Key` header.
**Request body:**
```json
{
"reservation_id": "res-uuid-123",
"actual_cost": 0.003,
"worker_id": "worker-uuid",
"duration_ms": 250.0
}
```
#### `POST /peer/cancel`
Cancel a reservation and refund the full amount.
**Authentication:** Requires `X-Peer-Key` header.
**Request body:**
```json
{
"reservation_id": "res-uuid-123"
}
```
#### `GET /peer/balance`
Get the balance for a user owned by this broker.
**Authentication:** Requires `X-Peer-Key` header.
**Query parameters:** `user_id=9000000001`
```bash
curl "http://peer-broker:9000/peer/balance?user_id=9000000001" \
-H "X-Peer-Key: $ZAKURO_PEER_KEY"
```
**Response:**
```json
{
"user_id": "9000000001",
"balance": 99.995
}
```
#### `POST /peer/earn`
Pay earnings to the broker owner's account (used when a remote broker pays for execution on a local worker).
**Authentication:** Requires `X-Peer-Key` header.
**Request body:**
```json
{
"request_id": "req-uuid-123",
"amount": 0.003
}
```
#### `GET /peer/workers`
List workers that are local to this broker (at `127.0.0.1` or `localhost`). Used by peer brokers to discover available workers across the mesh.
**Authentication:** Requires `X-Peer-Key` header.
---
## Routing Strategies
When sending a compute request via `/execute`, you can specify a routing strategy in the `X-Zakuro-Requirements` header. The strategy determines how the broker selects which worker handles the request.
| Strategy | Aliases | Description |
|----------|---------|-------------|
| `best_price` | `price`, `cheap`, `cheapest` | Selects the worker with the lowest estimated cost. **(Default)** |
| `best_latency` | `latency`, `fast`, `fastest` | Selects the worker with the lowest average response time. |
| `best_availability` | `availability`, `available` | Selects the worker with the most available resources and fewest active requests. |
| `round_robin` | `robin`, `rr` | Distributes requests evenly across all healthy workers in order. |
| `random` | `rand` | Selects a random healthy worker. |
| `weighted_capacity` | `weighted`, `capacity` | Randomly selects a worker weighted by available CPU and memory. |
### Adaptive Routing (opt-in)
`ZAKURO_ADAPTIVE_ROUTING` is **off by default**. With `1`/`true`/`yes`/`on` the adaptive policy (`src/broker/policy.rs`: a Thompson sample of each worker's service time, best of `d` draws) makes the routing decision instead of the strategies above. Off, it runs in shadow: it is shown every decision the normal strategy made and keeps its ledger, but routes nothing. See ADR ZC-0011 (`docs/adr/0011-adaptive-scheduler-promotion.md`). On `zc agent`, the variable is forwarded to the broker the agent starts.
### Worker Scoring Algorithm
For the default `best_price` strategy, the overall worker score is computed as:
```
score = price_score * 0.5 + load_score * 0.3 + latency_score * 0.2
```
Where:
- **Price score (50%):** `cpu_price * 0.6 + memory_price * 0.3 + gpu_price * 0.1`
- **Load score (30%):** `(1 - cpus_available/total + 1 - memory_available/total) / 2`
- **Latency score (20%):** `avg_latency_ms / 100`
Lower scores indicate better workers.
---
## Benchmarking
`zc bench` measures the broker's throughput and latency under load.
### Basic Benchmark
```bash
# Default: 10 concurrent workers, 1000 requests, best_price strategy
zc bench
# Benchmark with a specific strategy
zc bench -s best_latency
# High-load benchmark
zc bench -c 100 -n 10000
# Benchmark a remote broker
zc bench zc://node-fd29ea8fe9ffa2e0
```
### Finding where a slow request went
`X-Zakuro-Duration-Ms` is one number for everything up to settlement, so a
broker that spends seconds somewhere can only report that it did. Send
`X-Zakuro-Trace: 1` and the reply carries `X-Zakuro-Phases`: each phase's own
cost in milliseconds, in the order the request crossed them.
```bash
curl -s -o /dev/null -X POST "$BROKER/execute" \
-H 'X-Zakuro-Trace: 1' -H 'Authorization: Bearer $ZAKURO_API_KEY' \
-H 'Content-Type: application/octet-stream' --data-binary @payload.pkl \
-w '%{time_total}s [%header{X-Zakuro-Phases}]\n'
# 0.004s [queue=0.06 auth=0.01 balance=0.06 route=0.07 voucher=0.00
# reserve=0.00 body=0.00 forward=3.44 finish_queue=0.01 settle=0.12]
```
| phase | what it covers |
|---|---|
| `queue` | waiting for a blocking-pool slot before prepare ran — load, not work |
| `auth` | resolving the caller from the Bearer token |
| `balance` | the authority lookup and balance fetch |
| `route` | choosing a worker |
| `voucher` | minting a dashboard voucher, when one is required |
| `reserve` | the reservation and its WAL record |
| `body` | reading the request body |
| `forward` | the worker round trip — the only phase that is the actual job |
| `finish_queue` | waiting for a blocking-pool slot again, after the worker replied |
| `settle` | commit, WAL, ledger, voucher redeem — all of it after `X-Zakuro-Duration-Ms` is taken |
Everything but `forward` is overhead. On a healthy broker they are all under a
millisecond; anything else is the thing to fix.
Tracing is opt-in per request and costs nothing when it is not asked for.
### Benchmarking one node
Naming a node measures **that node**: the run addresses its broker and asks
for the work to stay there, so the "where it ran" table should show one row.
The report says which it was, and names the nodes if the work spread anyway.
```bash
# One node, and only it
zc bench zc://node-fd29ea8fe9ffa2e0
```
Two flags decide where the work may NOT run, and they mean different things:
| Flag | Means | Use it to |
|---|---|---|
| `--remote` | not on **this machine** | keep a run off your laptop. A broker already out on the mesh satisfies it as-is, so it is a no-op there. |
| `--remote-only` | the **broker** must skip its own workers and offer the job to a peer | measure peer dispatch itself. It sends work AWAY from a node you named, so it releases the pin. |
`--remote` used to be sent as the broker-side `remote_only`, which made
`zc bench zc://node-… --remote` scatter its work over every peer of the node
it had just named — slower, mostly timeouts, and never a measurement of that
node.
A pin is only put on the wire for a broker running 0.0.33 or newer; older
brokers mishandle it, and bench relies on their local-first routing instead.
`zc brokers` shows each broker's build.
The benchmark:
1. Verifies broker connectivity via `/health`
2. Checks available workers via `/workers`
3. Sends requests concurrently to `/execute`
4. Displays a progress spinner during execution
5. Prints a detailed report with throughput and latency percentiles
**Example output:**
```
═══════════════════════════════════════════════
◆ Benchmark Results
═══════════════════════════════════════════════
Summary
────────────────────────────────
Total Requests: 1000
Successful: 987 (98.7%)
Failed: 13 (1.3%)
Duration: 4.21s
Throughput: 237.53 req/s
Latency (ms)
────────────────────────────────
Min: 0.84
Avg: 3.21
Max: 42.10
p50: 2.15
p75: 3.80
p90: 6.20
p95: 9.45
p99: 28.30
Latency Histogram
────────────────────────────────
≤1ms [██████ ] 120 ( 12.2%)
≤5ms [██████████████████████████████] 650 ( 65.9%)
≤10ms [████████████ ] 150 ( 15.2%)
≤25ms [██ ] 40 ( 4.1%)
≤50ms [█ ] 27 ( 2.7%)
```
### Strategy Comparison
Compare all six routing strategies side by side:
```bash
zc bench --compare
zc bench --compare -c 50 -n 5000
```
This runs the benchmark separately for each strategy and outputs a comparison table highlighting the best throughput and lowest latency.
### Mesh Warmup / Calibration
`zc bench mesh` probes a worker set and emits a JSON report that mirrors the
Python warmup primitive used by `AdaptiveCompute`.
```bash
zc bench mesh --workers a:3960,b:3960,c:3960 | jq .
```
The report includes per-worker `latency_p95`, `bandwidth_bps`, and a
`recommended_backpressure` threshold for the mesh as a whole.
### Benchmark Options
| Option | Short | Default | Description |
|--------|-------|---------|-------------|
| `--concurrency` | `-c` | `10` | Number of concurrent workers |
| `--requests` | `-n` | `1000` | Total requests to send |
| `--url` | `-u` | `http://127.0.0.1:9000` | Broker URL |
| `--user` | | `bench-user` | User ID for requests |
| `--strategy` | `-s` | `best_price` | Routing strategy to test |
| `--compare` | | | Compare all strategies |
| `--list-strategies` | | | List available strategies |
| `--help` | `-h` | | Show help |
---
## Remote Monitoring
Read a running broker from another machine:
```bash
# Its workers, their health and prices
zc workers localhost:9000
zc workers http://broker.mesh:9000
# Transactions, request rate and latency percentiles, as JSON
curl -s -H "Authorization: Bearer $ZAKURO_API_KEY" http://broker.mesh:9000/stats
```
See [`GET /stats`](#get-stats) for the response.
---
## System Diagnostics
View system information, network status, and detected compute clusters:
```bash
zc info
```
**Output sections:**
| Section | Content |
|---------|---------|
| **Network** | Hostname, operating mode (P2P / Local), local IP, mesh IP |
| **Compute Clusters** | Availability of Ray, Dask, and Spark clusters with version and node count |
| **Configuration** | The hub API URL in use and whether `ZAKURO_API_KEY` is set (the key itself is never printed) |
| **Services** | Reachability of the production hub (`hub.zakuro-ai.com`), the local broker (9000) and the local worker (3960) |
### Resource budget
What a node lends is set by `ZAKURO_BUDGET_CPU`, `ZAKURO_BUDGET_MEMORY` and `ZAKURO_BUDGET_GPU`. The defaults are 50% of the CPUs, 50% of the memory and no GPU (ZC-0017, ZC-0018). On the Docker backend, every container started for someone else runs with explicit limits from the budget:
| Workload | Limits |
|---|---|
| Share workers (`zc share`, `zc up`, the agent) | the budget split evenly across the worker slots, so together they stay within it |
| Deployments | `ZAKURO_DEPLOY_BUDGET_SLICE` of the budget (a percentage, default `25%`): deployments carry no resource request yet |
| Space leases | the lease's requirements, clamped to the budget; a cpu or memory it leaves unset takes what is left of the budget |
A workload gets a GPU only when the budget has one: `ZAKURO_BUDGET_GPU` is on, or `ZAKURO_DEPLOY_GPUS` is set. A device pin from `ZAKURO_DEPLOY_GPUS` is never replaced. An invalid budget refuses the start (reason `budget`). A container never falls back to running unlimited. Host-process workers (`ZAKURO_SHARE_RUNTIME=host`) have no cap.
**One runtime layer (zc#578).** Every container path (Atelier jobs, Spaces leases, deployments, share workers) asks one backend choice, made once per process, in two tiers. `zc doctor` prints both (`engine (jobs): …`, `engine (shared): …`) with the reason each was chosen.
| Tier | What | Used for | Default choice |
|---|---|---|---|
| T0 | host process | the owner's own work only | `ZAKURO_SHARE_RUNTIME=host`, never implicit |
| T1 shared | long-lived containers, on **Docker** | deployments, share workers, Atelier jobs | Docker when it probes OK; the LXC sandbox `zakuro-sandbox` (nerdctl) only if you opt in, or if Docker is absent and Incus/LXD is present |
| T2 per job | one ephemeral LXC instance `zk-job-<id>` cloned from the golden image `zakuro-sandbox-base`, deleted at the end | Spaces leases | whenever an LXC CLI (`incus`, else `lxc`) probes OK; otherwise Docker with limits, reported as the FALLBACK in `zc doctor` |
- Hosts that have LXD or Incus installed keep their long-lived services on Docker. To move them into the LXC sandbox: `ZAKURO_SANDBOX_SHARED=lxc`, or `ZAKURO_RUNTIME_PREFER` listing `lxc` before `docker` (for example `lxc,docker`). With neither Docker nor LXC the start fails naming what to install.
- `ZAKURO_SANDBOX_ISOLATION=job|shared`: `job` (default when LXC probes OK) gives a lease its own instance carrying the admitted cpu, memory and disk limits (`ZAKURO_BUDGET_DISK`), a GPU only if the budget has one and the lease asks (one job per GPU; a `device=GPU-<uuid>` pin is resolved to its PCI address); `shared` runs it on the T1 engine. A reaper removes `zk-job-*` instances whose owner process is gone, at start and every 2 minutes. The golden image is built once per node and rebuilt when the provisioning changes.
- Atelier jobs carry `--cpus`/`--memory` from the job's request (`cpus`, `memory_gb` in the job spec) clamped to the node budget, admitted against everything else running, and refused with a reason when they do not fit or ask for a GPU the budget does not pass through. Admission is serialised across the agent and the broker by a file lock at `<zakuro home>/sandbox/admission.lock`.
- `ZAKURO_SHARE_RUNTIME=auto` (default) never falls back to a host process: without an isolating backend, or without the worker image in it, it fails and says what to install or load. `ZAKURO_SHARE_RUNTIME=host` is the explicit escape and prints that it has NO isolation.
- `verify_image` compares the pinned digest whole (`sha256:<64 hex>`), never as a substring.
**Accounting across workloads (zc#565).** On Docker the budget is also enforced as a sum. Every container carries a `zakuro.budget` label with its own limits, and before each start the node lists the running containers (`docker ps`) and adds up their labels. A start that would take the sum of cpu or memory past the budget is refused with reason `budget`: a deployment fails its rollout (retried when the hub bumps the version), a Space lease backs off, and an agent share worker is restarted later. A workload that stops, crashes or is removed releases its share by no longer running, and a restarted broker or agent rebuilds the sum from what actually runs. A deployment's own earlier versions are left out of its sum, so an upgrade can briefly run beside the version it replaces. Share workers hold their whole slice while they run: with the default `--workers` split they hold the whole budget, and a deployment or lease is refused until the budget is raised or fewer workers run. GPUs are not summed. Foreground `zc share` workers are counted but not admitted. Containers started before this version carry no label and are not counted.
`zc doctor` prints a `sandbox runtime:` section with the selected backend, why each preferred backend was skipped (each backend prints its own probe reason), the budget and the limits it resolves to, and, when Docker responds, what the running containers hold of it (`allocated:`) and what is left.
**macOS: Lima and Colima VMs (zc#511, zc#578).** On macOS the default preference is `lima, colima, docker`, so Docker Desktop is no longer a prerequisite. zc creates and owns one VM, a Lima instance or a Colima profile named `zakuro`, on Apple Virtualization (`vz`, with Rosetta on Apple Silicon). The VM *is* the budget: its cpus, memory and disk come from `ZAKURO_BUDGET_CPU` / `ZAKURO_BUDGET_MEMORY` / `ZAKURO_BUDGET_DISK`, and every workload inside still carries its own `--cpus` / `--memory`. It is created at the first start (the first start downloads the guest image), resized at the next start when the budget changed and nothing runs in it, and only the zakuro work directory (`ZAKURO_HOME`, default `~/.zakuro`) is mounted, writable. zc never uses a VM the owner uses: the name `default` is refused, other instances and profiles are never touched, and an instance or profile that mounts the home directory writable (or, for Colima, still has the default mounts) is refused, not adopted. A GPU request is refused: there is no GPU passthrough to a Linux guest on macOS. A workload mount must be inside the work directory, and a published port needs a fixed host port (the VM forwards the same port to the Mac). Containers cannot reach the Mac (the Lima gateway) or the owner's LAN (private and link-local ranges); DNS and the internet work. The rules are applied inside the guest at every start. IPv6 is not filtered yet.
| Variable | Effect |
|---|---|
| `ZAKURO_RUNTIME_PREFER` | comma list, now also `colima` (for example `colima,docker`) |
| `ZAKURO_LIMACTL` | path of `limactl` (default: `PATH`, then `/opt/homebrew/bin`, `/usr/local/bin`); needs Lima 2.0 or newer |
| `ZAKURO_LIMA_INSTANCE` | the Lima instance name, default `zakuro` (never `default`) |
| `ZAKURO_COLIMA` | path of `colima` (same lookup); needs Colima 0.8 or newer |
| `ZAKURO_COLIMA_PROFILE` | the Colima profile name, default `zakuro` (never `default`) |
Colima workloads run through `colima ssh -p zakuro -- docker …`, the Docker daemon inside the VM, not through the `colima-zakuro` Docker context: that would need a host `docker` CLI and trust `DOCKER_HOST` / the active context to point at the right daemon, so a wrong environment could land a job on Docker Desktop.
---
## Sharing policy (`policy.toml`)
One file, `$ZAKURO_HOME/policy.toml` (default `~/.zakuro/policy.toml`), decides what the node runs for other people (ZC-0017). A new node gets the defaults: squad `public`, `when = "idle"`, budget 50% CPU / 50% memory / GPU on (where the machine has one) / 50G disk, every workload on including every Atelier backend the machine supports, `min_price = "default"`. GPU sharing on by default follows the approved desktop hosted-runners design (D2, 2026-11-10), which amends ZC-0017 §3; `zc budget --no-gpu` (or `budget.gpu = false`) turns it off. A node that already had the old switches gets a policy generated from them on first run (`ZAKURO_P2P=0` becomes `squads = []`, Spaces and hub allocation keep their opt-in and sizes, `agent/hosting.toml` moves over).
```
zc policy [show] # the effective policy and budget
zc policy set sharing.when=always sharing.min_price=2.5 workloads.spaces=false
zc budget [--cpu 4] [--memory 8G] [--gpu [on|off]] [--vram 8G] [--disk 100G]
zc ledger [--by day|product|node] [--from YYYY-MM-DD] [--to YYYY-MM-DD] [--json]
```
`zc policy set` and `zc budget` go through the agent (`PUT /v2/policy`) when it runs and otherwise write the file under the same lock. An unknown key is an error naming it; `revision` goes up on every change and is what the hub compares. `sharing.schedule` takes windows such as `"mon-fri 19:00-08:00"` (local time). `sharing.min_price` is `"default"`, a yen-per-hour number, or `-1` (withdrawn). `workloads.atelier` is `true`, `false`, `"gpu-only"` or a list of backends.
Every job source (peer offers, Spaces, hub allocation, environment guests, Atelier jobs) passes one admission check; a refusal has a reason (`squad`, `workload`, `budget`, `price`, `schedule`, `idle`) and is counted under `admission` on the broker's `GET /health` and in summary v2. `when = "idle"` is enforced for every source, from one owner-activity signal the agent computes and mirrors to `$ZAKURO_HOME/owner.json` every 15 s: on macOS the keyboard/mouse idle time (5 minutes), AC power when `budget.on_ac_only`, and critical memory pressure; on Linux the local logind sessions' idle hint (remote logins do not count; no logind or no session means nobody is there) and memory pressure from PSI. Load is not an input, because the node's own jobs would count as the owner. A refusal for `idle` also covers battery (with `on_ac_only`) and memory pressure, whatever `when` says. The broker treats a signal older than `ZAKURO_OWNER_STALE_SECS` (default 90) as an active owner (fail safe) and a missing file as no signal (a broker with no agent beside it behaves as before). The owner's own account is never made to wait. `ZAKURO_OWNER_SIGNAL=0` stops the agent publishing it.
Agent routes: `GET/PUT /v2/policy`, `GET /v2/ledger?by=&from=&to=` (the hub's provider ledger, yen), event `policy.changed`.
#### Owner revenue (ZC-0025)
```bash
zc earnings [--json] # earned today / 7 days / month, utilisation, eligible-idle time, refusals by reason
```
`zc earnings` reads the hub's provider ledger through the agent (`/v2/ledger`) and the node's own figures from the broker (`revenue` on `GET /health` and in `GET /v2/summary`, mirrored to `revenue.json`). *Eligible idle* is time the node was allowed to take work (policy `when` and schedule, squads, price not withdrawn), had free budget, and a claim loop (Spaces, hub allocation) came back with nothing it could take; overlapping sources count once.
- A peer offer is admitted against what is free: the chosen worker's free CPU, memory and GPUs, and the node budget minus what other admitted offers still hold. A refusal is counted as `budget`; the requester's broker moves to the next peer. When two offers arrive together for the last slot, the one with the better expected revenue per budget-hour wins (waits at most `ZAKURO_OFFER_RANK_WINDOW_MS`, default 20, `0` = first come first served; an offer that leaves room for another never waits).
- The peer advert (`GET /peer/advert`) carries `capacity`: per class (GPU model and VRAM per GPU, CPU cores, memory) `total` / `budget` / `free`. The hub workers sync adds `node_capacity` and `cpu_cores_total` / `ram_gb_total` / `gpus_total` to each worker; the existing fields keep their meaning. The view is pushed when it changes (at most every 15 s) and at least every 60 s.
- The price in the peer advert is the price the node bills: the cheapest healthy local worker's effective price (after the hub's override). `ZAKURO_BROKER_PRICE` and `POST /price` set the broker-wide price, which now only serves as the advert price when the node has no worker.
- Peer offers are admitted against everything the budget lends: besides other offers' holds, what sandboxes (T1/T2), environment guests, Space leases and Atelier jobs hold (the labelled containers, scanned at most every 2 s). With `budget.gpu = false` the advertised GPU budget is zero and GPU offers are refused as `budget` (the node's own account is exempt). An offer may carry `min_vram_gb` (optional; per GPU): it is admitted only when the capacity view has enough free GPUs of at least that VRAM, and the router matches the worker on it. Offers without it behave as before.
- Spaces preemption: when the owner becomes active (`when = "idle"`, battery or memory pressure), every running Space that is not about to finish is stopped; when an offer that pays more than a lease was turned away for want of budget, the cheapest such leases are stopped until it would fit. The container is stopped and the session stops heartbeating, so the hub re-leases the batch after expiry (the hub has no abandon route). A Space expected to finish within `ZAKURO_SPACES_PREEMPT_GRACE_SECS` (default 120) is left to finish. Stops are counted as `preempted` (`owner_active`, `better_offer`) under `revenue` on `GET /health` and in summary v2. A lease whose hub price is not known (the claim reply carries `price_per_hour` only when the hub sends it) is never stopped for an offer.
- Spaces: with a node budget, the number of leases claimed per round is how many leases of the hub's last-seen size fit the free budget (hub maximum 16), and the in-flight count no longer gates claims. `ZAKURO_SPACES_MAX_LEASES` (default 1 without a budget) and `ZAKURO_SPACES_MAX_INFLIGHT` (default 1), when set, stay explicit ceilings.
Deprecated, still working: `ZAKURO_BUDGET_CPU|MEMORY|GPU|DISK` (win over `[budget]` while set, warned once), `ZAKURO_P2P=0` (edits `squads`), `zc spaces enable|disable`, `zc hub allocate` (edit the policy and print a deprecation line).
`ZAKURO_VPN_WATCH=0` turns off the agent's tunnel supervision (checks every 30 s, repairs with backoff when the interface is gone or the last handshake is older than 180 s, raises the `vpn_down` problem).
## Balance System
The broker uses a yen-denominated billing system to charge users for compute requests.
Every amount (balances, prices, charges, earnings, budgets) is yen, a decimal
with up to 6 fractional digits. Default worker price: ¥540/hour (¥0.15/s),
minimum charge ¥0.15 per request.
Peers settle only in the same currency: `/peer/advert` and `/peer/identity`
carry `"currency": "jpy"`, every `/peer/*` call sends `X-Zakuro-Currency: jpy`,
and a node refuses (409 `CURRENCY_MISMATCH`) to reserve, commit or earn with a
peer that does not.
### Hub Ledger (Credit Authority)
The hub is the balance authority (ADR ZC-0005, `docs/adr/0005-hub-balance-authority-and-wal.md`). The broker has **no database client**: it never holds database credentials, so it can run on a user's machine on a public mesh. Every balance read and settlement goes through the hub HTTP API, authenticated with `X-Broker-Api-Key` (`src/broker/ledger.rs`, `src/broker/node_sync.rs`):
| Hub endpoint | Used for |
|--------------|----------|
| `GET /api/broker/balance/{uid}` | Balance read (cached, see below) |
| `POST /api/broker/transaction` | Single settlement |
| `POST /api/broker/batch-sync` | Buffered settlements, flushed in chunks |
| `POST /api/broker/sync-workers` | Worker registry sync |
| `/api/broker/node/register`, `/api/broker/node/roster` | Node registration and mesh roster |
| `/api/broker/mesh/owner-ips` | Owner IPs on the mesh |
| `POST /api/broker/voucher`, `GET /api/broker/voucher/pubkey` | Hub-signed job vouchers (ADR ZC-0006) |
| `/api/broker/config/mesh`, `/api/broker/config/wireguard` | Mesh and WireGuard profile configuration |
The ledger runs in one of three modes:
| Mode | Selected by | Balances |
|------|-------------|----------|
| **API mode** | `ZAKURO_API_URL` + `ZAKURO_API_KEY`, no `ZAKURO_MASTER_KEY` | The hub. Reads are cached, settlements are buffered and flushed asynchronously |
| **Standalone** | `ZAKURO_MASTER_KEY` set (wins over API mode) | Local in-memory ledger, billing still enforced; lost on restart |
| **Local / free** | Neither | No billing: local execution is free |
**Balance reads** are cached for `ZAKURO_BALANCE_TTL_MS` (default 1000 ms; `0` asks the hub every time), served stale while a single in-flight refresh runs. For 120 s after a user last spent on this broker (`SPEND_GRACE`), a refresh may lower the cached balance but not raise it, because the hub may not have seen the spend yet; a hub top-up can therefore take up to two minutes to show.
**Settlement** is buffered in a `TransactionBuffer` (`src/broker/flush.rs`) and flushed to `batch-sync` by a dedicated `zc-flush` thread on every health-check tick (`health_check_interval`, default 5 s) and once more on shutdown. Each POST is chunked to at most `MAX_FLUSH_BATCH = 500` transactions **and** `MAX_FLUSH_BYTES = 512 KiB` of body (the hub's proxy refuses bodies over ~1 MiB with 413, #330); a row larger than the byte cap travels alone. A chunk that fails is re-queued; after `MAX_FLUSH_ATTEMPTS = 5` failures its transactions are quarantined to `wal-rejected.jsonl` next to the WAL (rotated to `.1` past its size cap). The hub deduplicates on `request_id`, so a retried chunk is not charged twice.
### Reserve-Commit Model
Each compute request follows a reserve-commit flow:
1. **Reserve:** The estimated cost is atomically deducted from the user's balance and stored as a reservation (5-minute TTL).
2. **Execute:** The request is forwarded to the selected worker.
3. **Commit:** On success, the reservation is finalized with the actual cost, and any difference is refunded. On failure, the full amount is refunded (cancel).
This ensures users are never overcharged and money is not lost on failures.
### API Keys
- **Master Key:** Set via `ZAKURO_MASTER_KEY`. Has full permissions (admin operations like adding funds, viewing ledger status).
- **User API Keys:** Follow the `zk_{user_id}_{hex}` format. In API mode the broker does not trust the key's shape: it asks the hub who the key belongs to (`GET /api/auth/me/api-key`, `src/broker/key_auth.rs`) and caches the verdict by the key's SHA-256 (positive 300 s, negative 30 s). A hub that cannot answer yields 503, never a fallback to the shape. `ZAKURO_TRUST_KEY_SHAPE=1` restores shape-only resolution as an emergency opt-out for a hub outage. It **suspends per-user billing integrity** while it is on: any caller can act as any non-reserved user by sending `zk_<uid>_anything`. They can spend that user's balance and read `/balance/<uid>`, and `zk_<owner_uid>_x` counts as the broker's own owner, so it executes for free. The broker prints a warning at startup when the opt-out is active. Turn it off as soon as the hub is back.
- **The admin identity:** Only a key that exactly equals `ZAKURO_MASTER_KEY` is the admin (compared in constant time). The uids `admin` and `anonymous` (the keyless sentinel, which `/serve` does not bill) are reserved: a key shaped `zk_admin_…` or `zk_anonymous_…` (any case) is rejected with `401` in every mode, and a hub answer naming a reserved uid is not trusted either.
- **Local / standalone mode and `ZAKURO_TRUST_KEY_SHAPE`:** With no `ZAKURO_API_URL` (or with the opt-out on), the key's shape *is* the identity: nothing checks the `{hex}` part, so a caller can act as any non-reserved uid by sending `zk_<uid>_anything`. That is by design for dev and standalone use. Never run a broker that holds real balances in local mode. On a hub-mode broker, keep `ZAKURO_TRUST_KEY_SHAPE` to a short emergency window (see above).
- **Storage:** The broker stores no API keys; keys are held and checked by the hub.
### Hub Unavailable
There is no database fallback. When the hub cannot be reached, a user whose balance was never loaded gets `BalanceUnavailable` (not a zero balance), key checks fail closed with 503, and settlement flushes fail. A transport error counts as a failed attempt, so a transaction that fails `MAX_FLUSH_ATTEMPTS = 5` flushes in a row (about 25 s at the default 5 s tick) is quarantined to `wal-rejected.jsonl` rather than retried forever. Work already admitted keeps executing.
### Local Mode (Free Execution)
When running in local discovery mode (no mesh), all executions are free and no money is charged.
### Per-Worker Local Detection (P2P Mesh)
In a multi-node P2P mesh, each broker detects its own mesh IP at startup and uses it to distinguish local vs remote workers:
- **Local workers** (at `127.0.0.1` or matching the broker's own mesh IP) execute for **free** — no reservation or billing
- **Remote workers** (on other mesh IPs) are **charged** via the normal reserve-commit flow
This enables a mesh topology where each node acts as both broker and worker. When `best_price` routing is used, the local worker is always preferred (cost=0). Other strategies like `round_robin` distribute across local and remote workers.
### P2P Broker-to-Broker Communication
P2P is on by default for a CLI-started broker with a mesh route, and `ZAKURO_P2P` overrides it (see the table below). This mode adds broker-to-broker communication for money operations, so the authoritative broker for a user answers reserve/commit from memory instead of asking the hub on the hot path.
**Architecture:**
Each user is assigned an **authoritative broker** using a consistent hash (FNV-1a):
```
authority_index = hash(zakuro_user_id) % num_brokers
```
**Authority modes:**
| Mode | Trigger | Hot Path | Behavior |
|------|---------|----------|----------|
| **Authority::Local** | User owned by this broker | **No hub call** | DashMap in-memory money ops (reserve, commit, balance) |
| **Authority::Peer(url)** | User owned by remote broker | **~1ms HTTP** | Forward money ops to authoritative broker via `/peer/*` endpoints |
| **Authority::Standalone** | Peer broker unreachable | **Hub API** | Falls back to the hub ledger path |
**Transaction flow (P2P authoritative):**
1. Auth (DashMap cache) → 2. Balance (DashMap) → 3. Reserve (DashMap atomic deduct)
4. WAL: RESERVED → 5. Forward to worker → 6. WAL: EXECUTED
7. Commit (DashMap refund diff) → 8. Queue in flush buffer → 9. WAL: COMMITTED → 10. Return
**Transaction flow (P2P non-authoritative):**
1. Auth (DashMap cache) → 2. HTTP `/peer/reserve` to authoritative (~1ms)
3. WAL: RESERVED → 4. Forward to worker → 5. WAL: EXECUTED
6. HTTP `/peer/commit` to authoritative (~1ms) → 7. WAL: COMMITTED → 8. Return
**Peer endpoints:**
All peer endpoints require `X-Peer-Key` header authentication:
| Endpoint | Method | Purpose |
|----------|--------|---------|
| `/peer/health` | GET | Peer broker health check |
| `/peer/reserve` | POST | Reserve funds for remote user (body: `{user_id, amount, reservation_id}`) |
| `/peer/commit` | POST | Commit transaction (body: `{reservation_id, actual_cost, worker_id, duration_ms}`) |
| `/peer/cancel` | POST | Cancel reservation (body: `{reservation_id}`) |
| `/peer/earn` | POST | Pay earnings to broker owner (body: `{request_id, amount}`) |
| `/peer/balance` | GET | Get balance (query: `?user_id=...`) |
| `/peer/workers` | GET | List this broker's local workers |
**Flush thread:**
In P2P mode, authoritative brokers maintain a `TransactionBuffer` that batches writes every **5 seconds** (every health-check tick) to the hub `batch-sync` API, chunked as described in [Hub Ledger](#hub-ledger-credit-authority):
- Pending transactions (all state transitions)
- Balance snapshots (for dashboard/audit)
This keeps the hub round trip off the hot path; balances are eventually consistent with the hub.
**Environment variables:**
| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `ZAKURO_P2P` | No | on with a mesh route, else off | Unset: `zc broker` / `zc share` / `zc up` enable P2P when the machine reaches the mesh (local mesh interface or `zc connect` proxy sidecar), see `p2p_default_from` in `src/broker/mod.rs`. `true`/`1` forces it on, any other value forces it off. |
| `ZAKURO_PEER_KEY` | Yes (in P2P) | — | Shared secret for `X-Peer-Key` auth |
| `ZAKURO_OWNER_ID` | Yes (in P2P) | — | This broker's unique ID (used in authority hash) |
| `ZAKURO_PEERS` | Yes (in P2P) | — | Comma-separated peer broker URLs: `http://10.13.13.5:9000,http://10.13.13.6:9000` |
**Resilience:**
- If authoritative peer is down → `Authority::Standalone` → hub ledger API
- WAL replay on crash: `reserved→cancel`, `executed→commit` (same as before)
- Peer discovery via `ZAKURO_PEERS` + health probes on startup
---
## Write-Ahead Log (WAL)
The broker maintains a write-ahead log for crash recovery. Candidate paths (first writable wins): `ZAKURO_WAL_PATH` env → `$HOME/.zakuro/wal.jsonl` → `/tmp/zakuro-wal.jsonl`. Each transaction progresses through these states (`WalStatus` in `src/broker/wal.rs`):
| Status | Description |
|--------|-------------|
| `Reserved` | Funds reserved, request sent to worker |
| `Executed` | Worker returned successfully, actual cost calculated |
| `Earned` | A peer earning applied in memory and queued for the hub, not yet confirmed flushed |
| `Committed` | Charge committed and settled |
| `Failed` | Request failed; reservation refunded |
**Implementation:**
- **Append-only JSONL file** — one JSON object per line, never modified in-place
- **DashMap in-memory index** — O(1) lookup by `request_id` for status checks and updates
- **Group commit off the request path** — `append` only pushes the serialized line onto a lock-free queue (`SegQueue`); it never takes the file lock or calls `fsync`. A dedicated flush worker (`run_flush_worker`) drains the queue and `fsync`s when the oldest entry reaches **100 ms** (`WRITE_BUFFER_MAX_AGE_MS`) or sooner once **1024 entries** are buffered (`WRITE_BUFFER_MAX_ENTRIES`), and drains once more on shutdown
Durability is time-bounded (an acknowledged entry reaches disk within about 100 ms) while no request thread ever blocks on `fsync`.
### Crash Recovery
On startup, the broker replays any uncommitted WAL entries via `recovery.rs`:
- **Reserved** entries: closed without a refund. The job never finished, and the hold existed only in the crashed process's memory, so there is nothing to give back. Replay seeds no balance: the next read loads the hub's balance where the broker reads balances from the hub (not under `ZAKURO_MASTER_KEY`, which skips that read even with a hub URL set), and otherwise starts from the fresh in-memory ledger, uncredited
- **Executed** entries: charges are committed at the actual cost and published to the hub (worker succeeded but broker crashed before committing)
- **Earned** entries: re-delivered to the hub through the normal flush
**P2P mode:** WAL replay works seamlessly with P2P — authoritative brokers apply state changes to their DashMap, non-authoritative brokers skip or retry peer calls.
The WAL is **automatically compacted** every ~5 minutes: committed and failed entries are removed from disk, keeping only uncommitted entries. The in-memory index is also cleared of completed entries.
### WAL Format
Append-only JSONL file. Each line is a JSON object:
```json
{"request_id":"uuid","user_id":"user","reservation_id":"res-id","estimated_cost":0.15,"actual_cost":0.12,"worker_id":"worker-uuid","duration_ms":250.0,"timestamp":"2024-01-01T00:00:00Z","status":"Committed","unit":"jpy"}
```
`unit` is always `"jpy"`: every amount is yen, a decimal with up to 6 fractional
digits (ADR 0027 in zak-marketplace). A line without `unit` was written before
the switch; on start the broker multiplies its amounts by 150 once, tags it
`jpy` and rewrites the WAL, so it is never converted twice.
---
## P2P Mesh Deployment
Deploy a multi-node mesh where each node runs a broker + worker pair reachable
over WireGuard.
### Architecture
```
Node 1 (zk0-node01) Node 2 (zk0-node02)
┌─────────────────────┐ ┌─────────────────────┐
│ Broker (:9000) │◄══ WireGuard ════►│ Broker (:9000) │
│ ├ WAL + DashMap │ 10.13.13.0/24 │ ├ WAL + DashMap │
│ ├ hub API client │ │ ├ hub API client │
│ └ Discovery │ │ └ Discovery │
│ │ │ │
│ Worker (:3960) │ │ Worker (:3960) │
│ type: standard │ │ type: premium │
│ (free to self) │ │ (free to self) │
└─────────────────────┘ └─────────────────────┘
```
The tunnel is brought up on the **host**, not in a sidecar container: each host
holds a `zakuro0` (or `wg*`) interface with an address in `10.13.13.0/24`, and
the broker finds it through `get_mesh_ip` (`src/broker/discovery.rs`).
`zc vpn` manages that interface, and the dashboard hands out a per-user peer
profile via `GET /api/broker/config/wireguard`.
### Prerequisites
- A WireGuard peer profile per host (see `zc vpn --help`, or fetch one from the
dashboard with your broker API key)
- Docker and Docker Compose
### How discovery works in the mesh
1. Each broker resolves its own mesh IP — `ZAKURO_WIREGUARD_IP` if set,
otherwise the `zakuro0`/`wg*` interface address
2. Discovery scans localhost ports first (finds the local worker)
3. Then probes explicit `ZAKURO_PEERS` (finds remote workers across the tunnel)
4. Existing workers get their heartbeat refreshed by TCP connect only, with no
full HTTP probe
5. Workers are deduplicated by name, so the same worker never appears twice
### Environment Variables (Mesh)
| Variable | Description |
|----------|-------------|
| `ZAKURO_WIREGUARD_IP` | This node's mesh IP (for local worker detection). Named for the mesh we used to run; it applies to WireGuard too. |
| `ZAKURO_PEERS` | Comma-separated `ip:port` of remote workers or brokers to probe |
> **The two-node Docker recipe was removed.** It stood up a VPN sidecar per
> node under `zak-zakuro/docker/` and shared its network namespace with the
> broker and worker, which only worked on the mesh we no longer run. There is
> no drop-in Compose replacement yet: bring WireGuard up on each host, then run
> the brokers and workers with `ZAKURO_PEERS` pointing at the other host's mesh
> address.
---
## Cluster Commands
| Command | Description |
|---------|-------------|
| `zc up` | Start 1 worker + broker locally (foreground) |
| `zc up --workers N` | Start N workers + broker (ports 3960–3960+N) |
| `zc up --workers N -d` | Start N workers + broker in the background (daemon) |
| `zc down` | Stop all workers + broker started by `zc up` |
| `zc workers` | List workers registered with the local broker |
| `zc me` / `zc balance` | Show authenticated user info and money |
| `zc update` | Update the `zc` CLI from `get.zakuro-ai.com` |
| `zc pull` | Pull updated Docker images |
| `zc images` | List Zakuro images built on the machine |
| `zc ps` | List currently running Zakuro containers |
| `zc kill` | Stop and remove running Zakuro containers |
| `zc restart` | Restart containers with updated images |
---
## Unattended Jobs (`zc job`) and Receipts (`zc verify`)
`zc job` sends a container job to the hub's Spaces queue and keeps it: the zc agent writes the job to a durable outbox, drives it to the end (retrying through hub outages and agent restarts, never creating a second Space or publishing twice) and collects the outputs. It needs the agent running (`zc agent run`, or `zc agent install` to keep it at login); without one every verb refuses and says so. `zc jobs` (plural) is a different command: the jobs this node *ran*.
| Command | Description |
|---------|-------------|
| `zc job submit <spec.toml\|spec.json\|->` | Validate the spec and queue the job. Prints the job id and the most the hub will hold (`max_price_per_batch` x batches). |
| `zc job ls` | The submitted jobs, newest first, with progress. |
| `zc job status <id>` | State, batch counts, image digest, price ceiling, results and receipt status. |
| `zc job watch <id>` | Follow the job on the agent's event stream until it ends; exit 0 only for `done`. |
| `zc job results <id> [--out <dir>]` | Where the outputs are (`$ZAKURO_HOME/results/<id>/<batch>/`), or copy them to `<dir>`. |
| `zc job cancel <id>` | Cancel; the hub refunds what was not used. Not possible once the work is finished and being collected. |
All take `--json`. States: `queued -> uploading -> publishing -> running -> collecting -> done`, or `failed` / `cancelled`. A job that cannot reach the hub stays in its state and retries with backoff; it fails only when the hub refuses (a 4xx other than 408/429), a digest does not match, or a batch failed on the hub.
A spec (TOML or JSON; relative input paths are relative to the spec file):
```toml
name = "digest-run"
image = "registry.example/app@sha256:..." # or a tag: recorded as given, pinned to the digest the hub resolves
max_price_per_batch = 50 # yen; the hub holds exactly this x batches
squad = "public" # public | private | a squad id (optional)
require_receipts = false # fail the job when a batch receipt cannot be fetched
[resources]
cpus = 1
memory_gb = 1
gpus = 0
min_vram_gb = 0
max_runtime_s = 180
[[batch]] # one entry per unit of work
inputs = { "part.txt" = "./data/part-001.txt" } # name inside the container = local file
```
Unknown keys are refused (a typo must not drop the price ceiling). `cmd` is refused: the hub's Spaces API has no command override, so bake the command into the image's entrypoint. Each input file is hashed at submit and must still match when uploaded; at most 512 MiB each.
The hub's Spaces publisher routes take a hub **session token**. The agent sends the credential `zc login` saved; if the hub refuses it (401) the job fails with `hub_credential_refused`.
Finished jobs and their results are kept for `ZAKURO_OUTBOX_KEEP_DAYS` (default 30) and at most `ZAKURO_OUTBOX_KEEP_MAX` (default 200) jobs; the oldest go first, and a job that is not finished is never removed.
`zc verify <receipt-file | receipt-hash | -> [--pubkey <hex|base64>]... [--json]` checks a hub receipt offline: the Ed25519 signature over `zakuro-receipt:v1\n` + the exact signed bytes, then prints what it binds (payer commitment, executor, cost, output digests, the hub's own `trust_level`). A hash is fetched from `GET /api/receipts/<hash>` and must hash to itself. Keys come from `--pubkey`, otherwise from the hub's `GET /api/receipts/pubkeys` over HTTPS and are labelled *fetched, not pinned*. Exit 0 only when everything verifies. `receipt.json` beside each batch's outputs is a file it accepts.
---
## Zakuro Drive Hooks
`zc hooks` manages file-event hooks on a running [zakuro-drive](https://github.com/zakuro-ai/zakuro-drive) daemon (`zakurod`) over its QUIC API (default `127.0.0.1:4719`; override with `--daemon HOST:PORT` or the `ZAKURO_DRIVE_DAEMON` env var). A hook fires on file events matching a glob and either POSTs an HMAC-signed JSON payload to a webhook or runs a local command.
| Command | Description |
|---------|-------------|
| `zc hooks add` | Create a hook (see flags below) |
| `zc hooks get <id\|name>` | Show full config for a hook (secrets redacted by the daemon) |
| `zc hooks list [--all]` | List hooks; `--all` includes disabled ones |
| `zc hooks update <id\|name>` | `--enable`/`--disable`, or tune `--retry-*` options |
| `zc hooks remove <id\|name>` | Delete a hook |
| `zc hooks logs [<id\|name>]` | Delivery history; `--dead` (dead letters), `--failed`, `--from 2h`, `--to`, `--limit N`, `--verbose` |
### `zc hooks add` flags
- `--name NAME` (required), `--glob GLOB` (required)
- `--on EVENT` (repeatable, required): `file.created` | `file.modified` | `file.deleted`
- Exactly one handler: `--webhook URL` or `--exec CMD`
- Webhook secret, exactly one of: `--secret-stdin` (recommended — reads one line from stdin), `--secret-from-env VAR`, `--secret VALUE` (discouraged: visible in `ps`/shell history)
- Optional: `--timeout SECS` (default: webhook 30, exec 60), `--tls-insecure` (webhook only; prints a warning), `--retry-attempts N`, `--retry-initial-delay MS`, `--retry-max-delay MS`, `--disabled`
```bash
echo "$WEBHOOK_SECRET" | zc hooks add --name slack-notify \
--on file.created --glob "reports/**/*.pdf" \
--webhook https://hooks.example.com/zakuro --secret-stdin
zc hooks logs slack-notify --from 7d --verbose
```
`--from`/`--to` accept relative durations (`90s`, `30m`, `2h`, `7d`), ISO dates (`2026-06-01`), or RFC3339 timestamps.
---
## Environment Variables
| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `ZAKURO_OUTBOX_KEEP_DAYS` | No | `30` | `zc agent`: how long a finished `zc job` and its results are kept. |
| `ZAKURO_OUTBOX_KEEP_MAX` | No | `200` | `zc agent`: the most finished `zc job`s kept; the oldest are removed first. |
| `ZAKURO_API_KEY` | Yes | — | Authentication token. Also used for dashboard API calls in API mode. |
| `ZAKURO_API_URL` | No | — | Dashboard API URL (e.g., `https://hub.zakuro-ai.com`). When set with `ZAKURO_API_KEY`, enables API mode: the hub is the balance authority. |
| `ZAKURO_MASTER_KEY` | No | — | Master API key for admin operations (adding funds, ledger status). When set, the broker runs the standalone in-memory ledger even if `ZAKURO_API_URL` is set. |
| `ZAKURO_BALANCE_TTL_MS` | No | `1000` | How long a hub balance read is cached, in ms. `0` asks the hub on every request. |
| `ZAKURO_WAL_PATH` | No | `$HOME/.zakuro/wal.jsonl` | WAL location; falls back to `/tmp/zakuro-wal.jsonl` when the default is not writable. |
| `ZAKURO_WORKER_KEY` | No | — | Shared secret for worker management endpoints (`POST/DELETE /workers`, heartbeat). When unset, these endpoints are open to loopback. A broker started by the agent or `zc up` runs with one regardless: when unset, a random per-node key is made once and kept `0600` at `<zakuro home>/worker.key`; `zc serve` sends it (`X-Worker-Key`) to a loopback broker, and an explicit `ZAKURO_WORKER_KEY` is sent to whichever broker `zc serve` is given. The key is not passed to worker processes or containers: they run job code and never register themselves. |
| `ZAKURO_REQUIRE_WORKER_KEY` | No | off | `1`/`true`/`yes`/`on` refuses `/workers` registrations that carry no key from a non-loopback address when `ZAKURO_WORKER_KEY` is unset (loopback stays allowed). Keyless non-loopback registrations are counted either way (`zero_trust.keyless_worker_nonloopback` on `/health`). |
| `ZAKURO_EARN_AFTER_RECEIPT` | No | off | Requester side. `1`/`true`/`yes`/`on` holds the payout of a remote job whose debit this broker tracks (`/execute`, `/execute/batch`) until the hub has committed the debit and answered its `receipt_hash`, then sends `/peer/earn` with the receipt attached. The owed-payout loop delivers it (every 30 s), so the executor is paid a little later. Off: the payout goes out right after the job with no receipt, as before. |
| `ZAKURO_ENFORCE_NODE_SIG` | No | on with a hub and a loaded roster | `/peer/*` node-signature enforcement. An explicit `1`/`true`/`yes`/`on` or `0`/`false`/`no`/`off` wins; unset enforces iff a hub is configured (`ZAKURO_API_URL` and `ZAKURO_API_KEY`) AND a roster has been loaded (hub or disk cache). Hubless brokers stay permissive. |
| `ZAKURO_REQUIRE_VOUCHER` | No | on with a hub | Require a hub-signed voucher on foreign jobs (`402 VOUCHER_INVALID` otherwise, also when the voucher was issued for a different requester than the offer names). Explicit value wins; unset requires it iff a hub is configured. A voucher redeem that fails is queued in `voucher-redeem-queue.jsonl` beside the WAL and retried (depth on `/health`). |
| _voucher binding_ | — | — | A requester mints with its node fingerprint (`requester_node`) and, on the offer path, the SHA-256 of the offer (`offer_hash`, see `TaskOffer::binding_hash`: task id, payload digest, price cap, duration, requester, currency). A hub that signs them puts them in the voucher JSON; the executor then refuses (`402 VOUCHER_INVALID`) a voucher presented by another node than the one authenticated as the sender (HTTP node signature, QUIC `node_sig`, or the `zk-quic/2` peer) or for another offer. A voucher without the fields (an older hub or requester) is accepted and counted (`zero_trust.voucher_binding.unbound_seen`; refusals under `.refused`). A redeem the hub answers 409 (it never minted the nonce) is dropped, not retried (`zero_trust.voucher_redeem_refused`); `already_redeemed` counts as done. |
| `ZAKURO_REQUIRE_SIG_V2` | No | off | Refuse `/peer/*` requests that carry only the v1 node signature (`401`). Senders sign v1 and, once the recipient's fingerprint is known, v2 (`X-Node-Sig2`, `X-Node-Aud`), which also covers the query string and the recipient. v1-only requests are counted as `zero_trust.sig_v1_only_seen`. |
| `ZAKURO_EARN_BINDING` | No | `observe` | `/peer/earn` binding. An earn is `bound` (this executor ran the job: `/peer/tasks/offer`, two-phase commit, QUIC one-shot and task-feed offers, each recorded with the requester its transport authenticated), `bound_by_receipt` (no record, but the requester attached the hub's `receipt_hash` for its debit; the executor fetches it from the hub with a 5 s bound, verifies it offline against the hub keys, and checks it is a settled `transaction` receipt, the earn is at most its settled amount, it names one of this node's workers, and it backs no other earn), or not bound: `unknown_job` / `over_amount` / `wrong_requester`. `observe` books every earn and counts each class (and, per reason, the receipts that did not bind: `receipt_rejected.{fetch_failed,unverified,not_settled,wrong_executor,reused}`) under `zero_trust.earn_binding` on `/health`; `enforce` refuses non-bound earns with `409 EARN_NOT_BOUND_*` (`503 EARN_RECEIPT_UNAVAILABLE`, retried by the requester, when the hub could not be asked; a resend of an already booked earn is still answered `duplicate`). `enforce` is safe once `unknown_job` stays 0 on the mesh. Requesters need `ZAKURO_EARN_AFTER_RECEIPT=1` for direct `/execute` jobs to carry a receipt; `/infer` payouts have no logged debit to attach one to and stay `unknown_job`; a hub that issues no `receipt_hash` leaves today's classification. The receipt does not carry the request id (the hub signs it only as a commitment the account owner opens) nor the executor node (the debit's `source_node` is the requester's), so the binding is to a real, settled debit of enough money for one of this node's workers, once. |
| `ZAKURO_ROSTER_MAX_AGE` | No | `86400` | Seconds. With a hub and enforcement on, a roster not refreshed for longer refuses money routes and task offers with `503 ROSTER_STALE`. Age is `zero_trust.roster_age_secs` on `/health`: measured from the hub's `X-Roster-Generated-At` when it sends one (else from the fetch). `zc brokers` shows the `zc_build` a node registered with the hub (marked `(hub)`) for a broker that does not answer. |
| `ZAKURO_MESH_PEER_KEY` | No | random, kept in `~/.zakuro/mesh_peer_key` | Peer key of a local `zc mesh`. Previously the literal `zakuro-mesh`. |
| `ZAKURO_WIREGUARD_IP` | No | — | Override mesh IP detection. Named for the mesh we used to run; it applies to WireGuard too. |
| `ZAKURO_PEERS` | No | — | Comma-separated `ip:port` peers for worker discovery, or `http://host:port` for broker peers in P2P mode. |
| `ZAKURO_P2P` | No | on with a mesh route, else off | P2P broker-to-broker communication. Unset, a CLI-started broker enables it when the machine reaches the mesh (local mesh interface or `zc connect` proxy sidecar); `true`/`1` forces it on, any other value forces it off. |
| `ZAKURO_ADAPTIVE_ROUTING` | No | off | `1`/`true`/`yes`/`on` lets the adaptive (Thompson-sampling) policy route (`adaptive_routing_enabled`, `src/broker/server.rs`; ADR ZC-0011). Off, it runs in shadow and only observes the normal strategy's decisions. Set on `zc agent`, it is forwarded to the broker the agent starts. |
| `ZAKURO_PEER_KEY` | No (Yes in P2P) | — | Shared secret for P2P broker authentication (`X-Peer-Key` header). |
| `ZAKURO_QUIC_LEGACY` | No | allowed | `0`/`false` turns off the legacy `zk-quic` QUIC protocol (shared-key pinned certificate), on both the serving and the dialling side, leaving only `zk-quic/2` (node-key mutual TLS) and HTTP. Legacy is also off on a broker without `ZAKURO_PEER_KEY`. See `docs/QUIC_TRANSPORT.md`. |
| `ZAKURO_OWNER_ID` | No (Yes in P2P) | — | This broker's unique ID for authority assignment (FNV-1a hash). Auto-derived from `ZAKURO_API_KEY` if in `zk_{user}_{hex}` format. |
| `ZAKURO_NODE_NAME` | No | Auto-detected | Human-readable node name (mesh hostname → system hostname). |
| `ZAKURO_WORKER_PORT` | No | `3960` | Primary port workers listen on (discovery). |
| `ZAKURO_SCAN_RANGE` | No | — | Port range for discovery scan, e.g. `3960-3999`. |
| `ZAKURO_SCAN_INTERVAL` | No | `15` | Seconds between discovery scans. |
| `ZAKURO_AUTO_UPDATE` | No | off | Opt-in broker self-update from crates.io (crate `zc2`). `1`/`true`/`yes`/`on` enables it; anything else is off. Never set it on k8s fleets (their image is managed by CD). When on, the broker reads the crates.io sparse index; for a strictly newer non-yanked release it runs `cargo install zc2 --version X --locked` into a scratch dir next to the executable while it keeps serving, checks the built binary runs and reports exactly X, waits until idle (no in-flight requests, local workers or pending settlements, on 3 polls 5 s apart), swaps it in atomically and exits with code 75 so systemd (`Restart=always`) starts it. Needs `cargo` (see `ZAKURO_CARGO`) and a writable executable directory; failures are logged and retried next interval. Status (`source`, `building`, `last_error`, ...) is in `GET /health` under `auto_update`. `zc update` still uses the release mirror. |
| `ZAKURO_AUTO_UPDATE_INTERVAL` | No | `600` | Time between index checks, in seconds or with an `s`/`m`/`h` suffix (`10m`, `1h`). Minimum 300 s. +up to 10% jitter; the first check is after a random 60 s..interval delay. |
| `ZAKURO_AUTO_UPDATE_INDEX` | No | `https://index.crates.io/3/z/zc2` | Sparse-index URL for `zc2` (https; http only for `127.0.0.1`/`localhost`). For tests. |
| `ZAKURO_CARGO` | No | `cargo` on PATH, else `$HOME/.cargo/bin/cargo` | The cargo used by auto-update builds. |
| `ZAKURO_ENV` | No | `prod` | Environment profile: `lab`, `staging` (`stg`, `stage`) or `prod`. Sets the hub API, the get/update mirror, the registry and the trust roots together (`zc doctor` prints them). `lab` = `http://hub.lab.zakuro.internal`, `http://get.lab.zakuro.internal`, `registry.lab.zakuro.internal:5000`, and skips the legacy `/env` fetch into `/opt/zakuro/etc/zk0.env`. Also read from `env=` in `~/.zakuro/credentials` or `ZAKURO_ENV=` in `~/.zakuro/env`. `ZAKURO_API_URL`, `ZAKURO_UPDATE_URL` and `ZAKURO_REGISTRY` still override their part. |
| `ZAKURO_REGISTRY` | No | the profile's | OCI registry override for the active `ZAKURO_ENV` profile. |
| `ZAKURO_UPDATE_URL` | No | the profile's (`https://get.zakuro-ai.com/zc`) | Mirror base for `zc update` (the manual path; broker auto-update uses crates.io). Either a bare host base (`https://stg.get.zakuro-ai.com`) or one ending in `/zc`; trailing `/` is trimmed and `/zc` appended when missing. Must be `https://` (plain `http://` only for `127.0.0.1`/`localhost`); an invalid value is an error, never silently ignored. |
---
## Configuration Reference
### BrokerConfig
| Field | Default | Description |
|-------|---------|-------------|
| `host` | `0.0.0.0` | Host to bind the broker server |
| `port` | `9000` | Port to bind the broker server |
| `health_check_interval` | `5` | Worker health check interval in seconds |
| `worker_timeout` | `30` | Seconds before marking a worker unhealthy |
| `min_balance` | `0.15` | Minimum balance (yen) required for any request |
| `daemon` | `false` | Run in daemon (background) mode |
| `verbose` | `true` | Show live transaction logs (foreground mode) |
| `enable_discovery` | `true` | Enable automatic worker discovery |
### DiscoveryConfig
| Field | Default | Description |
|-------|---------|-------------|
| `subnet` | `10.13.13` | Mesh subnet to scan |
| `worker_port` | `3960` | Primary port workers listen on (from `ZAKURO_WORKER_PORT` env) |
| `extra_ports` | `[3961, 3962]` | Additional ports to scan |
| `scan_port_range` | `None` | Full port range scan, e.g. `(3960, 3999)` (from `ZAKURO_SCAN_RANGE` env) |
| `interval_secs` | `15` | Seconds between discovery scans (from `ZAKURO_SCAN_INTERVAL` env) |
| `enable_scan` | `true` | Enable active network scanning |
| `enable_dns` | `true` | Enable DNS-based discovery |
| `peers` | `[]` | Explicit peer addresses from `ZAKURO_PEERS` env var |
### Ledger configuration
There is no ledger config struct or database URL. `Ledger::new(api_url, api_key)` (`src/broker/ledger.rs`) takes the broker's `api_url` / `api_key`, which come from the environment:
| Input | Source | Effect |
|-------|--------|--------|
| `api_url` | `ZAKURO_API_URL` (or the `ZAKURO_ENV` profile's hub) | Hub base URL for balance and settlement calls |
| `api_key` | `ZAKURO_API_KEY` | Sent as `X-Broker-Api-Key`; with `api_url`, selects API mode |
| master key | `ZAKURO_MASTER_KEY` | Standalone in-memory ledger; overrides API mode |
| balance cache | `ZAKURO_BALANCE_TTL_MS` | Balance read cache window (default 1000 ms) |
### Worker Pricing Model
Workers advertise their pricing when registering:
| Field | Description |
|-------|-------------|
| `cpu_price` | Cost per CPU-core per second |
| `memory_price` | Cost per GiB of memory per second |
| `gpu_price` | Cost per GPU per second |
| `min_charge` | Minimum charge per request |
The estimated cost for a request is:
```
cost = max(
cpu_price * cpus * duration_secs +
memory_price * memory_gib * duration_secs +
gpu_price * gpus * duration_secs,
min_charge
)
```