# Development Guide

## Prerequisites

| Component | Minimum version | Purpose |
| --- | --- | --- |
| Python | \>= 3.15 | Server Runtime |
| Python | \>= 3.8 | Worker Runtime |
| MongoDB | mongod service | Data store |
| uv | \-- | Python package manager |

nginx is not required for single-instance development. For multi-instance local testing, see the [nginx development config](<#nginx-development-config>) section below.

## Installation

```
cd server && uv sync && uv sync --group test
```

This installs all runtime and test dependencies into a virtual environment at `server/.venv`.

## Running the development server

```
cd server
FISHTEST_INSECURE_DEV=1 uv run uvicorn fishtest.app:app --reload --port 8000
```

No concurrency flags are needed in development. The async event loop handles concurrent requests natively.

Setting `FISHTEST_INSECURE_DEV=1` enables an insecure fallback secret key for cookie signing. This must never be used in production.

### Running the worker with the development server

The worker must authenticate against `/api/request_version`, so the username must exist in the local MongoDB and must not be `pending` or `blocked`.

After starting the server with the command above, run the worker in a second terminal:

```
cd worker
uv run worker.py USERNAME PASSWORD --protocol http --host 127.0.0.1 --port 8000
```

### OpenAPI documentation

To enable the interactive OpenAPI docs (`/docs`, `/redoc`, `/openapi.json`) during development:

```
OPENAPI_URL=/openapi.json FISHTEST_INSECURE_DEV=1 uv run uvicorn fishtest.app:app --reload --port 8000
```

OpenAPI docs are disabled in production (`openapi_url` defaults to `None`, which prevents FastAPI from registering the `/openapi.json`, `/docs`, and `/redoc` routes). Setting `OPENAPI_URL=/openapi.json` re-enables them and exposes the `/api` routes in the Swagger UI; the UI routes are registered with `include_in_schema=False`.

## Environment variables

The full environment variables table is in [Deployment](<http://official-stockfish.github.io/fishtest/deployment/index.md>). The following subset is relevant during development:

| Variable | Default | Description |
| --- | --- | --- |
| `FISHTEST_INSECURE_DEV` | \-- | `1`, `true`, `yes` or `on` to use the insecure fallback signing secret |
| `FISHTEST_AUTHENTICATION_SECRET` | \-- | The cookie signing secret, in place of the insecure fallback |
| `FISHTEST_CAPTCHA_SECRET` | \-- | reCAPTCHA secret key; `/signup` refuses every signup without it |
| `OPENAPI_URL` | (empty) | Set to `/openapi.json` to enable `/docs` and `/redoc` |
| `FISHTEST_PORT` | `-1` | Defaults to primary when unset |
| `FISHTEST_PRIMARY_PORT` | `-1` | Defaults to primary when unset |
| `FISHTEST_JINJA_TEMPLATES_DIR` | auto | Override Jinja2 templates directory |

When `FISHTEST_PORT` or `FISHTEST_PRIMARY_PORT` is unset or negative, the instance is primary -- the expected mode for single-instance development.

## Linting

Run Ruff from the repo root so it uses the tracked dev tool and shared config.

```
uv run ruff check server worker --config pyproject.toml
```

## Running tests

Start local MongoDB, run the server test suite, then stop MongoDB:

```
mkdir -p .local/mongo-data
mongod --dbpath .local/mongo-data --fork --logpath .local/mongod.log
(cd server && uv run python -m unittest discover -s tests -v)
mongod --shutdown --dbpath .local/mongo-data
```

For a focused server-only loop when MongoDB is already running:

```
(cd server && uv run python -m unittest discover -s tests -v)
```

See [Home](<http://official-stockfish.github.io/fishtest/index.md>) for pre-commit hooks and CI workflows.

## vtjson rules

Use vtjson for all server-side validation.

Core rules:

- Define persisted document schemas in `server/fishtest/schemas.py`.
- Treat persisted vtjson schemas as both documentation and the final server-side gate for stored data.
- Keep vtjson as the only server-side data validation layer. Do not introduce Pydantic models or a second schema system for the same contracts.
- Use different schemas when raw input and persisted data intentionally allow different values.
- Canonicalize benign user input in Python before validating the persisted document shape.
- Keep field-specific contracts in the relevant reference page instead of freezing them into this guide.
- Name schemas by boundary or purpose, not by convenience.
- Update `RUN_VERSION` when the stored run schema contract changes.
- Add focused tests for both the schema rule and the changed behavior.
- Run the relevant lint checks and test suite after schema changes.

Boundary split pattern:

- a route may accept a broader raw-input value than the stored document allows
- canonicalization narrows the value before the persisted document is validated and written
- the persisted schema describes the final stored form, not every accepted input variant

## nginx development config

For local multi-instance testing with nginx, use the development-only HTTP config below. This mirrors the production routing topology without TLS and works on local VMs where the IP may change between boots. Leave `FISHTEST_URL` and `FISHTEST_NN_URL` empty in the systemd units to allow dynamic host/IP usage.

File: `/etc/nginx/sites-available/fishtest.conf`

```
upstream backend_8000 {
    server 127.0.0.1:8000;
    keepalive 256;
    keepalive_requests 10000;
    keepalive_timeout 60s;
}

upstream backend_8001 {
    server 127.0.0.1:8001;
    keepalive 256;
    keepalive_requests 10000;
    keepalive_timeout 60s;
}

upstream backend_8002 {
    server 127.0.0.1:8002;
    keepalive 256;
    keepalive_requests 10000;
    keepalive_timeout 60s;
}

upstream backend_8003 {
    server 127.0.0.1:8003;
    keepalive 256;
    keepalive_requests 10000;
    keepalive_timeout 60s;
}

map $uri $backends {
    /tests                                 backend_8001;
    ~^/api/(actions|active_runs|calc_elo)  backend_8002;
    ~^/api/(nn|pgn|run_pgns)/              backend_8002;
    ~^/api/upload_pgn                      backend_8003;
    ~^/tests/(finished|machines|user)      backend_8002;
    ~^/(actions/|contributors)             backend_8002;
    ~^/(api|tests)/                        backend_8000;
    default                                backend_8001;
}

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name _;
    server_tokens off;

    location = /nginx_status {
        stub_status  on;
        allow        127.0.0.1;
        allow        ::1;
        deny         all;
    }

    location = /        { return 308 /tests; }
    location = /tests/  { return 308 /tests; }

    location = /robots.txt {
        alias       /var/www/fishtest/static/robots.txt;
        access_log  off;
    }

    location = /favicon.ico {
        alias       /var/www/fishtest/static/favicon.ico;
        access_log  off;
        expires     1y;
        add_header  Cache-Control "public, max-age=31536000, immutable";
    }

    location ^~ /static/ {
        alias       /var/www/fishtest/static/;
        try_files   $uri =404;
        access_log  off;
        etag        on;
        expires     1y;
        add_header  Cache-Control "public, max-age=31536000, immutable";
    }

    location /nn/ {
        root         /var/www/fishtest;
        gzip_static  always;
        gunzip       on;
    }

    location / {
        # Canonical upstream identity
        proxy_set_header Host               $http_host;
        proxy_set_header X-Real-IP          $remote_addr;

        # Forwarded chain
        proxy_set_header X-Forwarded-For    $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto  $scheme;
        proxy_set_header X-Forwarded-Host   $host;
        proxy_set_header X-Forwarded-Port   $server_port;
        proxy_set_header Connection         "";

        # Custom metadata
        proxy_set_header X-Country-Code     $region;

        # Timeouts
        proxy_connect_timeout    2s;
        proxy_send_timeout       30s;
        proxy_read_timeout       60s;

        # Buffering
        proxy_request_buffering  on;
        proxy_buffering          on;
        proxy_next_upstream      off;

        client_max_body_size     200m;
        client_body_buffer_size  512k;

        proxy_redirect           off;
        proxy_http_version       1.1;

        # Decompression
        gunzip                   on;

        proxy_pass http://$backends;
    }
}
```

The `$region` variable comes from the `geo $region` block in `/etc/nginx/conf.d/cidr.conf`, generated by `server/utils/nginx_cidr_builder.py`; see [Deployment](<http://official-stockfish.github.io/fishtest/deployment/index.md#nginx-configuration>).

## Documentation site

The pages under `docs/` are published as a site built by [zensical](<https://zensical.org/docs/>) from `mkdocs.yml`. The `docs` dependency group of the root project holds the tool. From the repository root:

```
uv sync --group docs
uv run zensical serve -a localhost:8008   # live preview; 8000 is the dev server
uv run zensical build --strict            # what CI runs
```

`--strict` fails the build on a link to a page or an anchor that does not exist and on a page that no `nav` entry in `mkdocs.yml` lists. A new page goes into `nav`, and into the `llmstxt` sections that generate `/llms.txt` and `/llms-full.txt`. A link to a file outside `docs/` uses its full GitHub URL, since the site serves only the pages.

A push to `master` publishes the site to the GitHub Pages of the upstream repository. A fork previews the site on its own GitHub Pages: allow the branch in the `github-pages` environment and name it in the `DOCS_PAGES_BRANCH` repository variable. A push to that branch publishes the site there.

The publishing repository sets Settings -\> Pages -\> Build and deployment -\> Source to "GitHub Actions". The "Deploy from a branch" source runs a Jekyll build of the whole repository on every push, which publishes to the same site and stops on the Jinja tags the pages quote. While that source is set, a push to the publishing branch fails the docs check.
