Metadata-Version: 2.5
Name: nura-campfire
Version: 0.1.0
Summary: Write inference workers for Campfire, Nura's single-host inference control plane.
License: MIT License
        
        Copyright (c) 2026 Nura Studios
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
License-File: LICENSE
Requires-Python: >=3.11
Requires-Dist: aiohttp>=3.12
Requires-Dist: arguably>=1.3.0
Requires-Dist: fastapi
Requires-Dist: httpx>=0.27
Requires-Dist: numpy
Requires-Dist: pathspec>=0.12.1
Requires-Dist: pillow>=11.3.0
Requires-Dist: pydantic>=2
Requires-Dist: requests>=2.32.4
Requires-Dist: soundfile>=0.13.1
Requires-Dist: uvicorn[standard]>=0.30
Provides-Extra: audio
Requires-Dist: scipy; extra == 'audio'
Provides-Extra: fast
Requires-Dist: uvloop>=0.22.1; (sys_platform != 'win32') and extra == 'fast'
Provides-Extra: gpu
Requires-Dist: nvidia-ml-py>=13; extra == 'gpu'
Provides-Extra: tracing
Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.27.0; extra == 'tracing'
Requires-Dist: opentelemetry-instrumentation-fastapi>=0.48b0; extra == 'tracing'
Requires-Dist: opentelemetry-processor-baggage>=0.48b0; extra == 'tracing'
Requires-Dist: opentelemetry-sdk>=1.27.0; extra == 'tracing'
Description-Content-Type: text/markdown

# nura-campfire

The Python worker SDK for Campfire, a single-host inference control plane.
Write a Python class, serve it over HTTP, and package it for deployment.
The SDK supports typed inputs and outputs, batching, progress, cancellation,
and optional OpenTelemetry tracing.

```bash
uv add nura-campfire             # import nura_campfire; console script campfire-cli
```

Requires Python 3.11+. The source distribution includes a complete
`examples/hello-worker` project that you can copy to get started.

## A worker

```python
from pydantic import Field
from nura_campfire import CampfireJob, CampfireWorker, ImageOutput, OutputKind
from nura_campfire import campfire_worker, campfire_function

class Request(CampfireJob):
    prompt: str
    steps: int = Field(default=20, ge=1, le=100)

@campfire_worker(name="my-worker", max_batch_size=4)
class MyWorker(CampfireWorker[Request, OutputKind.IMAGE]):
    def warm_up(self, device: str):
        self.model = load_model().to(device)      # once per process

    def execute(self, job: Request) -> ImageOutput:
        return ImageOutput(self.model(job.prompt, job.steps))
```

- **`CampfireJob`** is a pydantic model. Its JSON Schema is published with the
  worker. `PIL.Image.Image` fields arrive as base64 data URLs and are decoded
  for you; use `FileUrl` for files referenced by URL.
- **`CampfireWorker[Job, OutputKind]`** declares the request type and the
  result kind (`IMAGE`, `VIDEO`, `AUDIO`, `TENSOR`, `TEXT`, `JSON`, `GSPLAT`,
  `ARCHIVE`). Override `execute(job)` or, for true batch inference,
  `execute_batch(jobs)`.
- **`@campfire_worker`** publishes the metadata Campfire reads:

  | Argument | Default | Meaning |
  |---|---|---|
  | `name` | required | Deployment name; `worker_name` in client requests |
  | `synchronous` | `False` | Return the result in the response instead of through the job queue |
  | `max_batch_size` | `8` | Jobs per `execute_batch` call |
  | `batch_max_wait_ms` | `5` | How long to wait to fill a batch |
  | `max_concurrent_jobs_per_replica` | `1` | Jobs run at once; raise it for IO-bound workers |
  | `execution_timeout_sec` | `600` | Per-request timeout |

- **Outputs.** `execute` and every `@campfire_function` return a typed
  output and the runtime serializes it: a pydantic model becomes JSON shaped
  exactly like the model; `ImageOutput`, `VideoOutput`, `AudioOutput`,
  `TensorOutput`, `TextOutput`, `GSplatOutput` and `ArchiveOutput` become raw
  bytes with the right content type (a PIL image is a PNG). Each wrapper
  takes `headers=` for result headers a client should see (a content hash, a
  filename). The wire form is the runtime's, not part of the API.
- **Errors.** Raise. The runtime answers that job, and only that job, with a
  structured error (`{"error": <type>, "detail": <message>, "worker": ...}`,
  status 500); the rest of the batch proceeds.
- **`@campfire_function`** declares named entry points. Clients pick one with
  the `X-Inferno-Function-Name` header. The method's single pydantic
  parameter is its input; its return annotation is its output, as above.

### Inside a job

Every worker carries per-job helpers on `self`:

- `self._storage.download_blobs(urls)` / `download_image(url)` /
  `download_to_files({...})`: fetch inputs by URL (or data URL) through a
  content-keyed disk cache, so a reference image is never fetched twice.
- `self._progress.report(0.5, "halfway")`: progress for the client; delivered
  through the control plane's callback.
- `self._job.id()` and `self._job.cancelled()`: the job id, and whether a
  cancel arrived; `self._job.register_child(proc)` makes a subprocess you
  spawned stop with the job.
- `self._request.id()`: the correlation id for your logs.

### Catalog metadata

A function tagged `model="vendor/model-id"` must take a `CatalogJob` subclass
that declares `__model__` and `__model_meta__` (`nura_campfire.catalog`:
the model's type and display); Campfire lists it under `GET /models`. That is
the whole public catalog: billing and policy fields are the hosting
platform's own. Asset fields declare their media constraints with
`image_asset(...)`, `video_asset(...)` and `audio_asset(...)`, and the
runtime checks them before the job runs.

## Serving

```bash
campfire-cli serve               # from the project directory; FLARE_PORT or --port
```

One process, one replica: `warm_up(device)` runs once (`--device`, else
`FLARE_DEVICE`, else `cuda:0` when torch sees a GPU, else `cpu`), then:

| Route | Purpose |
|---|---|
| `POST /infer` | Run a job. Sync: the response is the result. Async: send `X-Inferno-Callback-Url` and `X-Inferno-Job-Id`, get 202, and progress/result/failure are POSTed to the callback. `X-Inferno-Function-Name` picks a function. |
| `POST /cancel/{job_id}` | Cooperative cancel; 202 if the job is here, 404 otherwise. |
| `GET /x/info` | Contract version, queue depth, inflight count, capacity, disk fill. |
| `GET /`, `/ping`, `/x/alive` | Health. |

Requests queue and run in mini-batches (`max_batch_size` within
`batch_max_wait_ms`, never mixing functions). A platform with its own process
model implements `nura_campfire.serve.Executor` and builds a `ServeRuntime`
with it.

### The contract

What a worker and Campfire agree on is numbered: `nura_campfire.CONTRACT_VERSION`
(1 today) is written into `WORKER-META.json` and reported by `GET /x/info`,
and Campfire refuses a worker outside the range it supports with an error
that names the version to upgrade to, before the first request. Contract 1,
every header the runtime reads or sends:

| Where | Headers |
|---|---|
| `POST /infer`, read | `X-Inferno-Function-Name`, `X-Inferno-Callback-Url`, `X-Inferno-Job-Id`, `X-Request-ID`, `traceparent`, `tracestate`, `baggage` |
| sync response | `Content-Type`, `X-Elapsed-MS`, `X-Request-ID`, plus the output's own headers (`X-Tensor-Shape`, `X-Tensor-Dtype`, `X-File-Name`, any you set) |
| async accept (202) | `X-Inferno-Job-Id`, `X-Request-ID` |
| every callback POST | `X-Inferno-Status` (`progress`, `completed`, `failed`, `requeue`), `X-Inferno-Job-Id`, `X-Request-ID`, the trace headers |
| `completed` callback | the result body with `Content-Type`, `X-Elapsed-MS`, `X-Inferno-Result-Index` and `X-Inferno-Result-Count` for a multi-result job, and the output's own headers, named in `X-Inferno-Result-Headers` |

Callback bodies: `progress` is `{"progress": 0.5, "message": "..."}`,
`failed` is `{"error": "..."}`, `requeue` is `{"reason": "..."}`.
`GET /x/info` reports `contract_version`, `sdk_version`, `queue_depth`,
`inflight_http`, `capacity`, `max_batch_size`, `overload_events`,
`last_overload_at` and the `disk_*` gauges. The record in
`WORKER-META.json` carries `contract_version`, `id`, `class_name`,
`package_name`, `kind`, `deployed_at` and `metadata` (`name`, `synchronous`,
`max_batch_size`, `max_concurrent_jobs_per_replica`, `job_schema`,
`output_schema`, `functions`). Anything not listed here may change in any
release.

### Versions

Pin `nura-campfire>=0.1,<0.2` (the example does). A patch release (0.1.x)
never breaks a worker: it may add fields and headers, never remove or rename
them, and the contract version does not move. Only a minor release (0.2.0)
may break, and it deprecates first: the old form keeps working for one minor
release with a warning. Use a lockfile to reproduce the SDK and dependency
versions you tested. An image worker runs the SDK it was built with; whether
an archive worker re-resolves dependencies at boot depends on its runtime
image.

Environment the runtime reads: `FLARE_PORT`, `FLARE_DEVICE`, `HF_HOME` (the
cache the disk gauge reports on), `OTEL_EXPORTER_OTLP_ENDPOINT` (with the
`tracing` extra). The hosting control plane supplies callback URLs in request
headers and can set `FLARE_WORKER_CLASS_NAME` and `FLARE_PORT`.

Extras: `nura-campfire[tracing]` exports OpenTelemetry spans; `[gpu]`
reports GPU memory in `/x/info`; `[fast]` installs uvloop; `[audio]` enables
WAV encoding.

### Request diagnostics

Request bodies are omitted from SDK logs and trace attributes by default,
including when tracing is enabled. Set `CAMPFIRE_CAPTURE_REQUEST_PAYLOADS=1`
to include bounded previews in request spans and async job failure logs.
Credential fields, URLs (including signed URLs and inline media), and
authorization strings are redacted before truncation. Invalid JSON bodies
are omitted. Ordinary text such as prompts remains visible when capture is
enabled; enable it only when that text is appropriate for your diagnostics.
This setting controls SDK request previews, not logging inside your worker.

## Deploying to Campfire

A worker ships as a Docker image that is the whole worker (the default), or
as a tarball that a stock runtime image fetches and installs at every boot
(`source: archive`, for hosts that run many workers on one runtime image).

### As an image

Build an image with the project installed, the record written into it, and
`campfire-cli serve` as its command
([`examples/hello-worker/Dockerfile`](examples/hello-worker/Dockerfile)):

```dockerfile
RUN uv run --no-sync campfire-cli meta -o /campfire/WORKER-META.json
CMD ["campfire-cli", "serve"]
```

`campfire-cli meta` writes the deployment record (stdout without `-o`).
List the image in `campfire.yaml`; the key there is the worker's name,
whatever `name=` says. Rebuilding the image redeploys it. What you built is
exactly what runs: nothing is re-resolved at boot. Keep model weights out of
the image, on a volume mounted at `HF_HOME`.

### As a tarball (`source: archive`)

```bash
campfire-cli pack -o /path/to/deployments            # this project
campfire-cli pack my-worker -o /path/to/deployments  # a project by path
```

The project's worker is discovered automatically and announced
(`notice: packing worker MyWorker`); a project that declares several needs
`-w MyWorker`. `pack` writes `<name>.tar.gz` into `-o` (default: the current
directory): the packed project (`code/` plus any local path dependencies,
transitively) with the deployment record as its first member,
`WORKER-META.json`. A path dependency may live anywhere relative to the
project (`../../libs/my-sdk`): it is vendored next to `code/`
under its directory name, and the packed `pyproject.toml` and `uv.lock` are
rewritten to `../my-sdk` so `uv sync` resolves it on the host; the
checkout is not modified. The tarball alone describes the worker: Campfire reads
up to that member, and nothing past it, from every tarball in its registry
directory (`deployments_dir` in `campfire.yaml`). The file is swapped in
atomically, so redeploying while a worker is booting is safe. Then list the
worker in `campfire.yaml` under its `name=`, with `source: archive` and a
runtime image that installs the packed project's dependencies and starts
`campfire-cli serve`.

Packing honors repository and nested `.gitignore` rules, including for local
dependencies. It also always excludes environment files (`.env`, `.env.*`,
`.envrc`), common credential files and directories (`.aws`, `.ssh`, `.netrc`,
`.pypirc`, `credentials.json`, SSH identity files, `*.pem`, `*.key`), backup
files, internal maintainer notes, caches, and symlinks. Negated ignore rules
cannot override these exclusions. Supply deployment secrets separately at
runtime. Add project-specific sensitive files to `.gitignore`; filenames
alone cannot identify every possible secret.
