Metadata-Version: 2.5
Name: shadowset-runtime
Version: 0.1.0a0
Summary: Shadowset agent memory runtime: loopback daemon exposing the /v1 wire contract
Author: Shadowset contributors
License-Expression: Apache-2.0
Requires-Python: >=3.12
Requires-Dist: fastapi>=0.115
Requires-Dist: opentelemetry-api>=1.45.2
Requires-Dist: opentelemetry-instrumentation-asgi>=0.66b2
Requires-Dist: opentelemetry-sdk>=1.45.2
Requires-Dist: pillow>=13.0.0
Requires-Dist: pydantic-settings>=2.6
Requires-Dist: pydantic>=2.9
Requires-Dist: pyyaml>=6.0.3
Requires-Dist: uvicorn[standard]>=0.32
Provides-Extra: otlp
Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.45.2; extra == 'otlp'
Description-Content-Type: text/markdown

# shadowset-runtime

Python reference implementation of the Shadowset daemon. The supported product
boundary is the HTTP `/v1` contract in
[`../openapi/shadowset-v1.yaml`](../openapi/shadowset-v1.yaml); Python objects
are not public API. [`../docs/wire-contract.md`](../docs/wire-contract.md) is
the tour of that contract.

## Run

Requires Python 3.12 or later and [uv](https://docs.astral.sh/uv/). The
package is not on PyPI yet, so run it from the clone:

```sh
cd runtime
uv sync
uv run shadowset serve --data-dir ./.shadowset
# listens on http://127.0.0.1:7337
```

`shadowset serve` takes `--data-dir`, `--port`, `--host` and `--log-level`.
Flags override `SHADOWSET_*` environment variables, which override defaults.
Stop it with SIGINT or SIGTERM; the daemon finishes the derivation job in
flight (up to the shutdown timeout), closes the stores and releases its lock.
`shadowset --version` prints the package version. `shadowset inspect` and
`shadowset stats` are reserved names that answer "not implemented in v0.1".

## Configuration

Every setting is an environment variable with the `SHADOWSET_` prefix.
Defaults come from `shadowset/settings.py`.

| Variable | Default | Meaning |
|---|---|---|
| `SHADOWSET_HOST` | `127.0.0.1` | Address to bind. Must be loopback (`127.0.0.1`, `::1` or `localhost`); anything else is a startup error. Remote exposure and authentication are deliberately unsupported in v0.1. |
| `SHADOWSET_PORT` | `7337` | TCP port. |
| `SHADOWSET_DATA_DIR` | `.shadowset` | Directory for the lock file, the metadata database and the object store; created if missing. |
| `SHADOWSET_LOG_LEVEL` | `INFO` | `DEBUG`, `INFO`, `WARNING` or `ERROR`, case-insensitive. Logs are one JSON object per line on stderr, with `request_id` and, inside a span, `trace_id`/`span_id`. |
| `SHADOWSET_TELEMETRY_ENABLED` | `true` | `false` switches OpenTelemetry off entirely (no tracer provider, no ASGI middleware). Exporters are chosen by the standard `OTEL_TRACES_EXPORTER` (`none`, `console`, `otlp`; the `otlp` extra `shadowset-runtime[otlp]` is needed for OTLP) and `OTEL_METRICS_EXPORTER` (`none`, `console`). |
| `SHADOWSET_DERIVATION_WORKER` | `on` | `off` disables the background derivation thread. Jobs are still queued and kept for a later daemon; observations stay `pending`. |
| `SHADOWSET_DERIVATION_MAX_ATTEMPTS` | `3` | Attempts per derivation job before it is marked `failed`. |
| `SHADOWSET_DERIVATION_LEASE_SECONDS` | `60` | How long a claimed job stays `processing` before another daemon may reclaim it (crash recovery). |
| `SHADOWSET_DERIVATION_SHUTDOWN_TIMEOUT_SECONDS` | `10.0` | How long shutdown waits for the job in flight before leaving it to the next daemon's lease sweep. |
| `SHADOWSET_IDEMPOTENCY_TTL` | `86400` | Seconds a stored `Idempotency-Key` response stays replayable. Expiry is judged at read time; a background purger reclaims the rows. `0` disables idempotency: keys are validated but never stored or replayed. |
| `SHADOWSET_EXPAND_SYNC_BUDGET_MS` | `300` | Milliseconds `POST /v1/expand` may spend producing a crop in the request before answering 409 `derivation_not_ready`. |
| `SHADOWSET_EXPAND_MAX_PIXELS` | `50000000` | Largest image (width times height) `expand` will decode for a crop, checked from the header before any pixel is decoded; bigger images are a terminal 404 with `reason: image_too_large`. |
| `SHADOWSET_COMPILE_RELEVANCE_FLOOR` | `0.05` | Relevance (0 to 1) below which `POST /v1/compile` rejects a candidate as `low_utility` before spending budget on it. |
| `SHADOWSET_MAX_RUN_METADATA_BYTES` | `65536` | Largest run `metadata` object accepted, measured on its compact JSON encoding. |
| `SHADOWSET_MAX_ARTIFACT_BYTES` | `67108864` (64 MiB) | Largest artifact body `PUT /v1/artifacts` accepts, checked against `Content-Length` before the body is read. |

## Data directory

```
<data-dir>/
  LOCK                 exclusive flock held by the running daemon; owner metadata inside (see below)
  metadata.sqlite      the metadata database (SQLite, WAL mode)
  metadata.sqlite-wal  write-ahead log; present while the daemon is open
  metadata.sqlite-shm  WAL index; present while the daemon is open
  objects/
    sha256/
      <aa>/            shard: the first two hex characters of the digest
        <64 hex>       one read-only (0444) file per object, named by its SHA-256
    tmp/               uploads in flight (<random>.part); emptied as each finishes
```

**Object store.** Artifacts and binary derived representations (crops) are
objects, keyed by the SHA-256 of their bytes. An upload is streamed into
`objects/tmp/` while being hashed, fsynced, then hard-linked into its final
path; the link fails rather than overwrites, so an object can never change
once written and concurrent uploaders of the same bytes agree without
coordination. When `PUT` returns, the object is both visible and on stable
storage (the shard directory is fsynced too). Rows in the metadata database
point at objects with relative URIs (`file://objects/sha256/<aa>/<digest>` for
artifacts, `object:sha256:<digest>` for representations), so a data directory
can be moved as a whole. An S3-backed store has an agreed interface
(`shadowset/artifacts/store.py`) but is not implemented.

**Metadata database.** `metadata.sqlite` holds runs, observations, artifact
rows and their links, representations, the derivation job queue, stored
idempotency responses, the FTS5 retrieval index and the compile decision
traces. The schema is versioned by numbered SQL migrations in
`shadowset/metadata/migrations/` (0001 to 0005 today), applied on open, each
in its own transaction. A database written by a newer daemon (a higher
recorded version) is refused rather than downgraded.

**SQLite WAL.** The database runs with `journal_mode=WAL`, `synchronous=NORMAL`,
`foreign_keys=ON` and a 5 s busy timeout. WAL means readers never block the
writer and the file stays consistent across a crash or power loss;
`synchronous=NORMAL` makes committed transactions durable across application
crashes. The daemon holds one connection guarded by a lock, so SQLite sees one
statement at a time, and every write runs inside `BEGIN IMMEDIATE`. Opening the
file with another tool while the daemon runs is safe for reading; writing to it
is not supported. Copy all three files (`metadata.sqlite`, `-wal`, `-shm`) or
stop the daemon first when taking a backup.

## One daemon per data directory

Many SDK processes may talk to one daemon, but two daemons must never own the
same data directory. On startup the daemon takes an exclusive, non-blocking
`flock` on `<data-dir>/LOCK` and writes its pid, hostname, URL and start time
into the file. A second `shadowset serve` on the same directory exits with
status 1:

```
shadowset serve: data directory .shadowset is owned by shadowsetd pid 4242 (http://127.0.0.1:7337)
```

The flock is the single source of truth; the JSON inside is informational. An
orderly stop empties the file while still holding the lock, so metadata found
under a lock nobody holds identifies a daemon that died without releasing
(SIGKILL, power loss). The next daemon logs that, takes the lock and carries
on: nothing in the data directory needs repair, because every write was
transactional. The Milestone 0 acceptance test exercises exactly this path.

`fcntl.flock` is POSIX-only; v0.1 does not support Windows.

## The OpenAPI snapshot

`openapi/shadowset-v1.yaml` is generated from the FastAPI routes and committed.
It is never hand-edited. After changing a route, a wire model, a header or an
error response:

```sh
cd runtime
uv run shadowset openapi --write    # rewrite openapi/shadowset-v1.yaml
uv run shadowset openapi --check    # exit 1 with a diff when the committed file is stale
uv run shadowset openapi            # print the document to stdout
```

Commit the regenerated file with the Python change, then regenerate the SDK
types (`pnpm --filter @shadowset/sdk generate`). [`../openapi/README.md`](../openapi/README.md)
documents the exporter; [`../docs/versioning.md`](../docs/versioning.md)
documents the review policy, including breaking changes.

## Checks

The same checks CI runs in its "Python runtime" and "OpenAPI snapshot" jobs:

```sh
cd runtime
uv sync --locked
uv run ruff check .
uv run ruff format --check .
uv run mypy
uv run pytest
uv run shadowset openapi --check
```

The TypeScript integration tests and the Milestone 0 acceptance test spawn this
runtime through `uv run --project runtime shadowset serve`, so `uv sync` here is
a prerequisite for `pnpm test` to exercise a real daemon and for `pnpm test:e2e`
to run at all.

## Layout

```
shadowset/
  cli.py            shadowset serve / openapi; lock acquisition, settings resolution
  settings.py       every SHADOWSET_* setting
  lock.py           the data-directory flock
  api/              FastAPI app, wire models, error envelope, idempotency, routes/
  artifacts/        content-addressed object store (filesystem; S3 placeholder)
  metadata/         SQLite store, migrations, repository
  derivation/       job queue, background worker, generators
  index/            FTS5 retrieval index
  context/          budgeted context compilation and its decision trace
  openapi.py        the snapshot exporter
  telemetry.py      OpenTelemetry spans and instruments
  logging.py        JSON logging with request and trace ids
```
