# 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.
#### `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 API key.
```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 <master_key>` (admin only).
```bash
curl http://localhost:9000/ledger/status \
-H "Authorization: Bearer $ZAKURO_MASTER_KEY"
```
### 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) |
---
## 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.
- **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: funds are refunded (worker may have crashed before responding)
- **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 |
---
## 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_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. |
| `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_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
)
```