# Fishtest > The distributed testing framework of the Stockfish chess engine. Fishtest is the distributed testing framework of the Stockfish chess engine. Developers submit patches as test runs; volunteer workers build both engines, play games with fastchess and report the results; the server schedules tasks, computes SPRT and Elo statistics, and stops a test once it is statistically decided. The server is a FastAPI and Starlette application with Jinja2 templates and htmx, backed by MongoDB. # Home # Fishtest Server Documentation ## Overview Fishtest is a distributed chess engine testing system. The server assigns testing tasks to volunteer workers, collects game results, and computes statistical analyses (SPRT, ELO) to determine whether code changes improve Stockfish. The web interface provides dashboards for managing test runs, viewing results, and administering users and workers. ## Documents The pages fall into three groups: guides for a task, explanations of how the system is shaped, and reference tables to look a fact up in. | Section | Document | Audience | Description | | --- | --- | --- | --- | | Guides | [Development]() | All developers | Dev setup, validation workflows, vtjson rules, OpenAPI, this site | | Guides | [Deployment]() | Operators | systemd, nginx, kernel tuning, capacity audit | | Explanation | [Architecture]() | All contributors | Server structure, module map, request flow, startup/shutdown | | Explanation | [Threading model]() | Backend contributors | Async/sync boundaries, threadpool usage, rules for new code | | Explanation | [Worker]() | Worker contributors | Worker architecture, task lifecycle, API usage | | Reference | [Worker API reference]() | Worker and integration developers | Worker API endpoints, protocol invariants, error shapes | | Reference | [UI routes]() | UI contributors | UI routes, view dispatch pipeline, htmx fragment dispatch, session/CSRF/auth | | Reference | [Templates]() | UI contributors | Jinja2 environment, template catalog (page + fragment), context contracts | | Reference | [External references]() | All developers | FastAPI, Starlette, Jinja2, htmx, Python, MongoDB, and tooling references | The site serves [`llms.txt`](), a manifest of these pages, and [`llms-full.txt`](), their full text, for tools that read documentation. ## Quick start ``` # Install server dependencies (from repo root) (cd server && uv sync --group test) # Start the development server (from server/) (cd server && FISHTEST_INSECURE_DEV=1 uv run uvicorn fishtest.app:app --reload --port 8000) ``` For OpenAPI docs, worker setup, local validation workflows, and vtjson validation rules, see [Development](). ## Technology stack | Layer | Technology | | --- | --- | | Web framework | FastAPI + Starlette (ASGI) | | Application server | Uvicorn | | Templates | Jinja2 (`.html.j2`, `StrictUndefined`) | | Client interactivity | htmx 4.0.1 (CDN, fragment polling/swaps, OOB updates) | | Session management | itsdangerous `TimestampSigner` cookie sessions | | Database | MongoDB (pymongo) | | Validation | vtjson (schema-first validation; no Pydantic) | | Statistics | scipy, numpy (SPRT, ELO calculations) | | Python (server) | \>= 3.15 | | Python (worker) | \>= 3.8 | ## Project layout ``` fishtest/ |-- pyproject.toml -- Root: dev tools (ruff, ty, pre-commit), docs tools (zensical) |-- uv.lock -- Locked dependency set for the root project |-- mkdocs.yml -- Docs site configuration |-- .pre-commit-config.yaml -- Pre-commit hooks (file checks, ruff, uv-lock) |-- .github/workflows/ -- CI: lint, server tests, worker tests (POSIX + MSYS2), docs site |-- docs/ -- Architecture and reference documentation |-- server/ | |-- pyproject.toml -- Server package: runtime + test dependencies | |-- uv.lock -- Locked dependency set for the server | |-- fishtest/ -- FastAPI application (Python >= 3.15) | |-- tests/ -- Focused unit and HTTP contract tests | `-- utils/ -- Operational utilities (backup, indexes, migration, analysis) `-- worker/ |-- pyproject.toml -- Worker package: runtime dependencies (Python >= 3.8) |-- uv.lock -- Locked dependency set for the worker |-- worker.py -- Main worker script |-- games.py -- Engine compilation, game execution |-- updater.py -- Self-update mechanism |-- sri.txt -- SRI hashes of the worker files |-- tests/ -- Worker tests `-- packages/ -- Vendored packages ``` ### Why three `pyproject.toml` files The root `pyproject.toml` defines **development-only tools** (ruff, ty, pre-commit) shared across the repo. The server and worker each have their own `pyproject.toml` with independent dependency sets and Python version constraints -- the server requires Python \>= 3.15 while the worker supports Python \>= 3.8 to run on contributor machines with older distributions. ### Build system Both the server and worker use **hatchling**, a standards-compliant PEP 517 build backend. ### Dependency management with uv [uv]() is the package manager. The root, the server and the worker are three independent projects, each with its own `uv.lock`; run `uv` in the directory of the project it should change. ``` # Install the server's runtime and test dependencies cd server && uv sync --group test # Add a dependency uv add # runtime dependency uv add --group test # test-only dependency # Remove a dependency uv remove # Update a dependency uv lock --upgrade-package # Regenerate the lock file from scratch uv lock ``` After any dependency change, commit both the modified `pyproject.toml` and the updated `uv.lock`. ### Pre-commit hooks The `.pre-commit-config.yaml` runs on every commit: - **pre-commit-hooks** -- large file check, TOML and YAML validation (YAML with `--unsafe`, for the Python tag in `mkdocs.yml`), end-of-file fixer, trailing whitespace - **ruff** -- lint with `--fix --exit-zero`, which applies the fixes it can and never fails the commit, and format - **uv-lock** -- re-lock the root `uv.lock` when the root `pyproject.toml` changes; `server/uv.lock` and `worker/uv.lock` are not checked Install with: `uv run pre-commit install` ### CI workflows | Workflow | File | Trigger | What it does | | --- | --- | --- | --- | | Lint | `lint.yaml` | push, PR, manual | ruff check, import sort and format; Prettier check of the static CSS, HTML and JS; zizmor security audit of the workflows | | Server | `server.yaml` | push, PR, manual | Server test suite (MongoDB required) | | Worker POSIX | `worker_posix.yaml` | push, PR, manual | Worker tests on Linux/macOS | | Worker MSYS2 | `worker_msys2.yaml` | push, PR, manual | Worker tests on Windows (MSYS2) | | Docs | `docs.yaml` | push, PR, manual | Build this site with `zensical build --strict`; a push to `master`, or on a fork to the branch named by the `DOCS_PAGES_BRANCH` variable, publishes it to GitHub Pages | # Guides # 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](). 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]() 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](). ## Documentation site The pages under `docs/` are published as a site built by [zensical]() 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. # Production Deployment ## Prerequisites | Component | Minimum version | Purpose | | --- | --- | --- | | Python | \>= 3.15 | Runtime | | MongoDB | mongod service | Data store, on `localhost`, database `fishtest_new` | | nginx | \>= 1.25.1 (`http2 on`) | Reverse proxy, TLS, static files | | uv | \-- | Python package manager | The server creates no MongoDB index. Run `server/utils/create_indexes.py` once on a new database, and again when it changes. Two directories under `/var/www/fishtest` are shared with nginx: | Path | Content | | --- | --- | | `/var/www/fishtest/nn` | Uploaded networks, written by the server as `.gz`; writable by the service user | | `/var/www/fishtest/static` | The static files nginx serves; a copy of `server/fishtest/static`, since the server derives the asset cache-busting tokens from the package copy | ## Environment variables | Variable | Required | Default | Description | | --- | --- | --- | --- | | `FISHTEST_PORT` | Yes | `-1` | Port for this instance | | `FISHTEST_PRIMARY_PORT` | Yes | `-1` | Fixed primary port (typically 8000) | | `FISHTEST_URL` | No | the first request's origin | Public URL (e.g., `https://tests.stockfishchess.org`) the server writes into run links in its log | | `FISHTEST_NN_URL` | No | (unset =\> request host; empty =\> same-host) | Base URL workers use to download neural networks (see below) | | `FISHTEST_AUTHENTICATION_SECRET` | Yes | \-- | Cookie signing secret (itsdangerous) | | `FISHTEST_CAPTCHA_SECRET` | For signup | \-- | reCAPTCHA secret key; without it every signup fails | | `FISHTEST_CAPTCHA_SITE_KEY` | No | built-in | reCAPTCHA site key for signup | | `FISHTEST_INSECURE_DEV` | No | \-- | `1`, `true`, `yes` or `on` for development mode (insecure secret) | | `FISHTEST_JINJA_TEMPLATES_DIR` | No | auto | Override Jinja2 templates directory | | `FISHTEST_STATIC_DIR` | No | the package's `static/` | Override the directory mounted at `/static` | | `GH_TOKEN` | No | \-- | GitHub token sent with the server's GitHub API calls, for a higher rate limit | | `OPENAPI_URL` | No | (empty) | Set to `/openapi.json` to enable `/docs` and `/redoc` (development-only) | | `UVICORN_WORKERS` | No | \-- | On the primary, an integer other than `1` stops the server at startup | | `WEB_CONCURRENCY` | No | \-- | Read in place of `UVICORN_WORKERS` when that is unset | The startup check reads these variables, not Uvicorn's `--workers` argument, so the systemd unit passes `--workers $UVICORN_WORKERS`. **Session invalidation**: deploying a new `FISHTEST_AUTHENTICATION_SECRET` invalidates all existing sessions. Users must re-authenticate once. ### Primary instance detection If `FISHTEST_PORT == FISHTEST_PRIMARY_PORT`, the instance is primary. If either value is unset, not an integer, or negative, the instance is primary too. ## Primary / secondary instance model | Instance | Port | Responsibilities | | --- | --- | --- | | Primary | 8000 | Scheduler, GitHub master SHA refresh, aggregated data, cache flush; the worker API except PGN uploads; the run actions (`/tests/run`, `modify`, `stop`, `approve`, `purge`, `delete`); every other `/api/` and `/tests/` path | | Secondary | 8001 | The `/tests` homepage and every path no other backend takes | | Secondary | 8002 | `/api/actions`, `/api/active_runs`, `/api/calc_elo`; the `/api/nn/`, `/api/pgn/` and `/api/run_pgns/` downloads; `/tests/finished`, `/tests/machines`, `/tests/user`; `/contributors` | | Secondary | 8003 | PGN uploads (`/api/upload_pgn`) -- 3 Uvicorn workers (production override) | A secondary answers the worker API except `/api/upload_pgn`, and the run actions, with HTTP 503. Four systemd units (ports 8000-8003), seven OS processes: one each on 8000, 8001 and 8002, and on 8003 the Uvicorn supervisor and its three workers. The primary (8000) must be a single process (`UVICORN_WORKERS=1`) because it holds in-process mutable state (run cache, scheduler, task locks). As a single-core async process, the primary saturates at roughly 15,000 concurrent workers -- this is the practical scaling ceiling. Port 8003 runs 3 Uvicorn workers via a systemd drop-in override (see below); the workers share one listening socket, and the kernel hands each connection to the worker that accepts it. The extra workers absorb the long-tail latency of large PGN writes (p95 approx 30 s at peak load). High-level routing topology: ``` flowchart LR clients[Browsers and workers] --> nginx[nginx reverse proxy] nginx -->|/static and /nn| static[Direct file serving] subgraph cluster[Uvicorn cluster] primary[8000 primary] tests[8001 tests homepage] readonly[8002 read-only UI and API] pgn["8003 upload_pgn (3 workers)"] end nginx -->|Worker API| primary nginx -->|/tests| tests nginx -->|Read-only UI and API| readonly nginx -->|/api/upload_pgn| pgn ``` ## Starting the server Managed via a systemd service template (one unit per port): ``` sudo systemctl enable fishtest@{8000..8003} sudo systemctl start fishtest@{8000..8003} sudo journalctl -u fishtest@8000 # useful flags: -f, --since, --until, --no-pager ``` ## systemd unit template File: `/etc/systemd/system/fishtest@.service` Copy the following file as-is. Replace `USER_NAME` with the actual user, `SERVER_NAME` with the actual domain, `OPTIONAL_NN_URL` with one of the values below, and `CHANGE_ME` with the production cookie signing secret and the reCAPTCHA secret. `OPTIONAL_NN_URL` -- base URL workers use to download neural networks: | Value | Meaning | | --- | --- | | (unset) | Server falls back to the request origin (`{scheme}://{host}`) for redirects | | (empty) | Server uses same-host relative redirects (`/nn/`) | | `https://SERVER_NAME` | Workers download directly from this origin | | `https://CDN_HOSTNAME` | Workers download via a CDN in front of this origin | | `https://data.stockfishchess.org` | Workers download via the official fishtest CDN | Note: `systemd` `Environment="FISHTEST_NN_URL=..."` always sets the variable. If you want the (unset) behavior, omit that `Environment=` line. When a `CDN_HOSTNAME` is used, it must also appear in the nginx `server_name` directive (see site configuration below). `CDN_HOSTNAME` resolves to Cloudflare edge servers, not to the origin; Cloudflare proxies requests back to `SERVER_NAME` and caches the immutable net files at the edge. ``` [Unit] Description=Fishtest Server port %i After=network.target mongod.service [Service] Type=simple Environment="UVICORN_WORKERS=1" Environment="FISHTEST_URL=https://SERVER_NAME" Environment="FISHTEST_NN_URL=OPTIONAL_NN_URL" # Cookie-session signing secret (required in production). # Development-only insecure fallback requires explicit opt-in: Environment="FISHTEST_INSECURE_DEV=1" Environment="FISHTEST_AUTHENTICATION_SECRET=CHANGE_ME" Environment="FISHTEST_CAPTCHA_SECRET=CHANGE_ME" # Port of *this* instance Environment="FISHTEST_PORT=%i" # Fixed primary port for the cluster Environment="FISHTEST_PRIMARY_PORT=8000" WorkingDirectory=/home/USER_NAME/fishtest/server User=USER_NAME # At 20k workers the primary needs ~15k fds; 32768 provides 2x headroom. LimitNOFILE=32768 ExecStart=/home/USER_NAME/fishtest/server/.venv/bin/python -m uvicorn fishtest.app:app --host 127.0.0.1 --port %i --proxy-headers --forwarded-allow-ips=127.0.0.1 --backlog 16384 --log-level warning --workers $UVICORN_WORKERS Restart=on-failure RestartSec=3 [Install] WantedBy=multi-user.target ``` ### PGN upload worker override In production, port 8003 handles PGN uploads which have long-tail latency. Running 3 Uvicorn workers on this port prevents slow uploads from blocking fast ones. Create a per-instance drop-in override: ``` sudo mkdir -p /etc/systemd/system/fishtest@8003.service.d ``` Create the file `/etc/systemd/system/fishtest@8003.service.d/override.conf`: ``` [Service] Environment="UVICORN_WORKERS=3" ``` Then reload and restart: ``` sudo systemctl daemon-reload sudo systemctl restart fishtest@{8000..8003} ``` ### Uvicorn flags **`--backlog 16384`** -- Sets the kernel TCP listen queue size. This absorbs connection bursts from large worker fleets without dropping connections. The value must exceed the peak burst arrival rate during restarts (when all backed-off workers reconnect simultaneously). **Do NOT use `--limit-concurrency`.** This flag rejects connections beyond the specified limit with HTTP 503 (plain text "Service Unavailable"). Workers receiving this non-JSON response trigger a `JSONDecodeError` and enter exponential backoff (15 s -\> 900 s), effectively removing themselves from the active pool. Under Uvicorn's ASGI async model, connection acceptance is handled by the event loop and costs negligible resources per idle connection. Application-level throttling (`task_semaphore` and `request_task_lock` in `rundb.py`) governs the critical scheduling path. Their sizes, `THREADPOOL_TOKENS` and `TASK_SEMAPHORE_SIZE`, live in `http/settings.py`; see [Threading model]() for the full analysis. There is no need for an HTTP-layer concurrency cap. **OpenAPI docs** (`/docs`, `/redoc`, `/openapi.json`) are disabled in production (`openapi_url` defaults to `None`). Set `OPENAPI_URL=/openapi.json` in the environment to re-enable during development. ## nginx configuration The nginx setup uses three configuration files: 1. **`/etc/nginx/conf.d/default.conf`** -- catch-all server that handles HTTP-\>HTTPS redirects and rejects TLS handshakes for unrecognized hostnames. This prevents certificate leaks when multiple vhosts share one IP address. 2. **`/etc/nginx/sites-available/fishtest.conf`** -- the named fishtest vhost with upstream routing, static file serving, and reverse proxy. 3. **`/etc/nginx/conf.d/cidr.conf`** -- the `geo $region` block that maps a client address to its country code, which the vhost forwards as `X-Country-Code`. Generate it from the ipverse country blocks with `server/utils/nginx_cidr_builder.py -o /etc/nginx/conf.d/cidr.conf`. Without it `nginx -t` fails on the unknown `$region` variable. The server shows a missing code or `ZZ` as `?`. ### Default server configuration File: `/etc/nginx/conf.d/default.conf` This file replaces the stock nginx `default.conf`. It owns the `default_server` designation for both ports 80 and 443, handling infrastructure concerns (redirects, monitoring, and unknown-hostname rejection) so that named vhosts stay focused on application routing. ``` # --- HTTP catch-all --- server { listen 80 default_server backlog=16384; listen [::]:80 default_server backlog=16384; server_name _; server_tokens off; # Monitoring (localhost only) location = /nginx_status { stub_status on; allow 127.0.0.1; allow ::1; deny all; } # Everything else -> HTTPS (permanent redirect, preserves method) location / { return 308 https://$host$request_uri; } } # --- HTTPS catch-all: reject unknown SNI --- server { listen 443 ssl default_server backlog=16384; listen [::]:443 ssl default_server backlog=16384; http2 on; server_name _; # Reject the TLS handshake for unrecognized hostnames. # No certificate is sent -- the client sees a connection reset. # Requires nginx >= 1.19.4. ssl_reject_handshake on; } ``` `backlog=16384` on the `default_server` listen directives sets the kernel TCP listen queue for the shared socket. All server blocks on the same address:port inherit this socket parameter. The value matches the Uvicorn `--backlog` and absorbs thundering-herd reconnection bursts from large worker fleets. ### Site configuration File: `/etc/nginx/sites-available/fishtest.conf` Copy the following file as-is. Replace every occurrence of `SERVER_NAME` with the actual domain name (e.g. `tests.stockfishchess.org`) and `CDN_HOSTNAME` with the Cloudflare-proxied CDN hostname (e.g. `data.stockfishchess.org`). Omit `CDN_HOSTNAME` from the `server_name` directive if no CDN is used. Adjust Let's Encrypt certificate paths if needed. ``` 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 443 ssl; listen [::]:443 ssl; http2 on; server_tokens off; server_name SERVER_NAME CDN_HOSTNAME; # TLS certificates (Let's Encrypt) ssl_certificate /etc/letsencrypt/live/SERVER_NAME/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/SERVER_NAME/privkey.pem; include /etc/letsencrypt/options-ssl-nginx.conf; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # Security headers add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always; add_header X-Content-Type-Options "nosniff" always; add_header X-Frame-Options "SAMEORIGIN" always; add_header Referrer-Policy "strict-origin-when-cross-origin" always; add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always; # block bad actors at the server level (early access phase) # deny xxx.xxx.xxx.xxx; 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 named vhost does **not** use `default_server` -- that designation belongs exclusively to the catch-all in `default.conf`. This separation ensures correct SNI-based certificate selection when multiple vhosts share one IP on both IPv4 and IPv6. ### Neural network CDN (`CDN_HOSTNAME`) `CDN_HOSTNAME` appears in the `server_name` directive so that nginx routes CDN traffic to this vhost instead of rejecting it via the `ssl_reject_handshake` catch-all. The `location /nn/` block already serves the net files -- no additional location is needed. **Certificate mismatch (known trade-off).** The Let's Encrypt certificate covers `SERVER_NAME` only. Cloudflare receives a cert whose hostname does not match `CDN_HOSTNAME`. This is accepted under Cloudflare SSL mode "Full", which verifies only that a valid TLS connection is established. Mode "Full (Strict)" checks the hostname and would reject it. Expanding the certificate to cover both hostnames requires Cloudflare dashboard access (DNS-01 or Origin CA), which is outside the scope of this server configuration. ### Maintenance mode configuration File: `/etc/nginx/sites-available/fishtest-maintenance.conf` During planned maintenance (major upgrades, database migrations), swap the active site symlink so that all requests receive a friendly 503 maintenance page while static assets (logos, icons) remain available. The procedure: ``` sudo ln -sfn /etc/nginx/sites-available/fishtest-maintenance.conf /etc/nginx/sites-enabled/fishtest.conf sudo nginx -t && sudo systemctl reload nginx ``` To restore normal operation: ``` sudo ln -sfn /etc/nginx/sites-available/fishtest.conf /etc/nginx/sites-enabled/fishtest.conf sudo nginx -t && sudo systemctl reload nginx ``` Copy the following file as-is. Replace every occurrence of `SERVER_NAME` with the actual domain name. Security headers and TLS settings match the production vhost exactly. ``` server { listen 443 ssl; listen [::]:443 ssl; http2 on; server_tokens off; server_name SERVER_NAME; # TLS certificates (Let's Encrypt) ssl_certificate /etc/letsencrypt/live/SERVER_NAME/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/SERVER_NAME/privkey.pem; include /etc/letsencrypt/options-ssl-nginx.conf; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # Security headers add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always; add_header X-Content-Type-Options "nosniff" always; add_header X-Frame-Options "SAMEORIGIN" always; add_header Referrer-Policy "strict-origin-when-cross-origin" always; add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always; # Static assets remain available during maintenance location ^~ /img/ { root /var/www/fishtest/static; try_files $uri =404; 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; expires 1y; add_header Cache-Control "public, max-age=31536000, immutable"; } 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 = /robots.txt { alias /var/www/fishtest/static/robots.txt; access_log off; } # Everything else -> maintenance page (HTTP 503) error_page 503 @maintenance; location / { return 503; } location @maintenance { root /var/www/fishtest/static/html; rewrite ^(.*)$ /maintenance.html break; } } ``` No port 80 block is needed -- `default.conf` already redirects all HTTP traffic to HTTPS regardless of hostname. ### nginx worker tuning The following directives belong in `/etc/nginx/nginx.conf` (not in the site config). They raise the per-worker fd limit and connection capacity for high worker counts: ``` user www-data; worker_processes 2; error_log /var/log/nginx/error.log notice; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; # must exceed worker_connections (32768); 40k allows headroom for connections + misc worker_rlimit_nofile 40000; events { # total capacity = worker_connections * worker_processes = 65536 # at 20k workers each process handles ~20k connections (client + upstream) worker_connections 32768; # efficiently handle multiple new connections at once multi_accept on; use epoll; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for" $upstream_response_time'; access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; # combined headers into one packet tcp_nodelay on; # good for small API bursts keepalive_timeout 65; gzip on; gzip_vary on; gzip_min_length 256; gzip_comp_level 5; gzip_types text/plain text/css application/json application/javascript text/xml; gzip_proxied any; # compress responses from upstream python backends include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*.conf; } ``` At 20,000 workers each nginx worker process handles approximately 10,000 client connections plus 10,000 upstream proxy connections (\~20,000 total). `worker_connections 32768` provides 1.6x headroom per worker. `keepalive 256` sets the maximum number of idle keepalive connections retained per upstream block. At 9,400 workers the sustained request rate is \~150 req/s with most requests completing in \<100 ms. The value 256 is generous for localhost backends but harmless -- idle TCP connections consume negligible memory. ### nginx proxy timeout rationale Proxy timeouts are set aggressively low to fail fast on unresponsive backends rather than accumulating stale connections: | Directive | Value | Rationale | | --- | --- | --- | | `proxy_connect_timeout` | 2 s | Backend connect should succeed in \< 1 ms (localhost) | | `proxy_send_timeout` | 30 s | Request bodies (PGN uploads) rarely exceed 10 s | | `proxy_read_timeout` | 60 s | Accommodates slow DB queries and streaming PGN downloads | ## Kernel tuning (sysctl) For the 20,000-worker target, verify the following `sysctl` values. Add to `/etc/sysctl.d/99-fishtest.conf` if needed: ``` # fishtest production tuning (target: 20,000 workers) # must be >= uvicorn --backlog (16384); 32768 absorbs thundering-herd reconnections net.core.somaxconn = 32768 net.core.netdev_max_backlog = 32768 net.ipv4.tcp_max_syn_backlog = 32768 # 20k client + 20k upstream + mongodb + misc approx 45k peak; 120k provides ~2.5x headroom fs.file-max = 120000 # each proxied request consumes an ephemeral port; default range (~28k) is too narrow net.ipv4.ip_local_port_range = 1024 65535 # fast socket recycling under high connection churn net.ipv4.tcp_tw_reuse = 1 # handle high-frequency socket churn from 20k workers; prevents 'time wait bucket table overflow' net.ipv4.tcp_max_tw_buckets = 65536 ``` Apply with `sudo sysctl --system`. `net.core.somaxconn` must be \>= the Uvicorn `--backlog` value (16384). Otherwise the kernel silently truncates the listen queue. The value 32768 provides 2x headroom and absorbs a full thundering-herd reconnection burst. ## User limits systemd `LimitNOFILE` only applies to services started by systemd. For interactive sessions (SSH maintenance, cron jobs), set PAM limits so the USER\_NAME user inherits the same file-descriptor ceiling: ``` sudo mkdir -p /etc/security/limits.d ``` File: `/etc/security/limits.d/99-fishtest.conf` ``` # interactive fd ceiling for the USER_NAME user. # soft (8192) covers SSH maintenance; hard (32768) matches systemd LimitNOFILE. USER_NAME soft nofile 8192 USER_NAME hard nofile 32768 ``` ## Capacity audit script Run on the production host to verify that kernel, nginx, and process limits are correctly sized for the 20,000-worker target: ``` #!/usr/bin/env bash # fishtest capacity audit -- verify system tuning for the 20,000-worker target. # Run on the production host after applying sysctl, nginx, and systemd settings. set -euo pipefail readonly target=20000 readonly expected_nofile=32768 readonly expected_backlog=16384 readonly expected_tw=65536 readonly red=$'\033[0;31m' readonly ylw=$'\033[0;33m' readonly grn=$'\033[0;32m' readonly rst=$'\033[0m' pass() { echo "${grn}pass${rst} ($1)"; } warn() { echo "${ylw}WARN${rst} ($1)"; } fail() { echo "${red}FAIL${rst} ($1)"; } echo "fishtest capacity audit (target: ${target} workers)" echo "----------------------------------------------------" # kernel: somaxconn must be >= uvicorn --backlog printf " %-25s " "somaxconn:" somax=$(cat /proc/sys/net/core/somaxconn) [[ "${somax}" -ge "${expected_backlog}" ]] \ && pass "${somax} >= ${expected_backlog}" \ || fail "${somax} < ${expected_backlog}" # kernel: tw_buckets must handle high connection churn printf " %-25s " "tcp_max_tw_buckets:" tw_buckets=$(cat /proc/sys/net/ipv4/tcp_max_tw_buckets) [[ "${tw_buckets}" -ge "${expected_tw}" ]] \ && pass "${tw_buckets} >= ${expected_tw}" \ || fail "${tw_buckets} < ${expected_tw}" # kernel: ephemeral port range (need ~40k for proxied connections + headroom) printf " %-25s " "ephemeral ports:" read -r port_low port_high < /proc/sys/net/ipv4/ip_local_port_range range=$((port_high - port_low)) [[ "${range}" -ge 40000 ]] \ && pass "${range} (${port_low}-${port_high})" \ || fail "${range} too narrow" # nginx: total capacity must handle client + upstream connections printf " %-25s " "nginx capacity:" w_proc=$(grep -E '^\s*worker_processes' /etc/nginx/nginx.conf \ | awk '{print $2}' | tr -d ';') [[ "${w_proc}" == "auto" ]] && w_proc=$(nproc) w_conn=$(grep -E '^\s*worker_connections' /etc/nginx/nginx.conf \ | awk '{print $2}' | tr -d ';') total=$((w_proc * w_conn)) need=$((target * 2)) [[ "${total}" -ge "${need}" ]] \ && pass "${total} >= ${need}" \ || fail "${total} < ${need}" # listen backlogs (nginx front door + each uvicorn port) echo " listen backlogs (>= ${expected_backlog}):" for port in 443 8000 8001 8002 8003; do printf " port %-18s " "${port}:" bl=$(ss -ltn | awk -v p=":${port}" '$4 ~ p {print $3}' | sort -rn | head -1) [[ -n "${bl:-}" && "${bl}" -ge "${expected_backlog}" ]] \ && pass "${bl}" \ || fail "${bl:-not listening}" done # per-process file-descriptor limits echo " fd limits (>= ${expected_nofile}):" for port in 8000 8001 8002 8003; do printf " port %-18s " "${port}:" pid=$(pgrep -f "port ${port}" | head -1 || true) if [[ -z "${pid}" ]]; then fail "no process" continue fi lim=$(awk '/Max open files/ {print $4}' "/proc/${pid}/limits") [[ "${lim}" -ge "${expected_nofile}" ]] \ && pass "${lim}" \ || fail "${lim} < ${expected_nofile}" done # mongodb: fd limit for data files + connections printf " %-25s " "mongodb fd limit:" mongo_pid=$(pgrep -x mongod || true) if [[ -n "${mongo_pid}" ]]; then mongo_fd=$(awk '/Max open files/ {print $4}' "/proc/${mongo_pid}/limits") [[ "${mongo_fd}" -ge 4096 ]] \ && pass "${mongo_fd} >= 4096" \ || fail "${mongo_fd} < 4096" else fail "mongod not running" fi # mongodb: active connections vs pool capacity printf " %-25s " "mongo active conns:" if command -v mongosh &>/dev/null; then curr_conns=$(mongosh --quiet --eval "db.serverStatus().connections.current") [[ "${curr_conns}" -lt 2048 ]] \ && pass "${curr_conns}" \ || warn "${curr_conns} (approaching pool limit)" else fail "mongosh not found" fi # disk: I/O wait (high values signal MongoDB or PGN write pressure) printf " %-25s " "disk iowait:" if command -v iostat &>/dev/null; then iowait=$(iostat -c 1 2 | awk '/^ / {v=$4} END {print v}') if awk "BEGIN {exit !(${iowait} < 5.0)}"; then pass "${iowait}%" else warn "${iowait}% (high)" fi else fail "iostat not found (install sysstat)" fi echo "----------------------------------------------------" ``` # Explanation # Server Architecture ## What fishtest does Fishtest is a distributed chess engine testing infrastructure. The server: 1. Accepts test submissions from developers (new Stockfish patches). 2. Assigns work units (tasks) to volunteer worker machines. 3. Collects game results and computes statistical tests (SPRT, ELO). 4. Publishes results through a web dashboard and a JSON API. A single MongoDB instance is the system of record. All run state, user accounts, action logs, and neural network metadata are stored there. ## Repository layout ``` server/ |-- pyproject.toml -- Package metadata, dependencies |-- uv.lock -- Locked dependency set |-- fishtest/ | |-- app.py -- ASGI application factory, lifespan, middleware, routers | |-- api.py -- API router (9 worker and 11 read-only endpoints) | |-- views.py -- UI router (33 routes, data-driven dispatch, | | routing hub) | |-- views_helpers.py -- Pure stateless helpers extracted from views.py | |-- views_actions.py -- Actions-page helpers (row building, sorting, query strings) | |-- views_finished.py -- Finished-runs page helpers (pagination, filtering) | |-- views_machines.py -- Machines-page helpers (normalization, filter state) | |-- views_run.py -- Run creation/modification helpers (validation, lifecycle) | |-- rundb.py -- RunDb: run lifecycle, task distribution, caching | |-- userdb.py -- UserDb: authentication, groups, registration | |-- actiondb.py -- ActionDb: audit log | |-- workerdb.py -- WorkerDb: worker blocking | |-- kvstore.py -- KeyValueStore: key-value metadata (books, legacy usernames, | | worker runs, GitHub API cache, official master SHA) | |-- scheduler.py -- Periodic task scheduler (primary instance only) | |-- schemas.py -- vtjson validation schemas | |-- run_cache.py -- In-memory run cache with dirty-page flush | |-- lru_cache.py -- Generic LRU cache | |-- spsa_workflow.py -- Pure classic SPSA lifecycle helpers | |-- spsa_handler.py -- SPSA worker orchestration, request/update flow, history buffering | |-- github_api.py -- GitHub integration (commit metadata, branch resolution) | |-- util.py -- Shared utilities (formatting, validation helpers) | |-- constants.py -- Shared constants (supported compilers and architectures) | |-- __init__.py -- Minimal package init | |-- http/ -- HTTP support modules | |-- templates/ -- Jinja2 templates (54 files, .html.j2) | |-- static/ -- Static assets (JS, CSS, images) | `-- stats/ -- Statistical computation modules |-- tests/ -- Focused unit and HTTP contract tests `-- utils/ -- Operational scripts (backup, indexes, migration, nginx CIDR) ``` `views.py` remains the stable UI routing hub. The extracted `views_*.py` modules hold domain logic, but route registration, `_dispatch_view`, and the request shim stay centralized there. Each extracted `views_*.py` module keeps a matching dedicated test file under `server/tests/`. User-facing route-family UI tests reuse `ui_user_test_case.py` and stay grouped by route family or one focused UI motif. Classic SPSA server ownership is split deliberately. `spsa_workflow.py` holds the pure classic SPSA helpers reused by the run form, the detail page, and the worker lifecycle. `spsa_handler.py` stays attached to `RunDb` and owns the stateful worker request/update path, flip packing, buffering, and history timing. ### HTTP support modules (`server/fishtest/http/`) ``` http/ |-- __init__.py -- Package init |-- boundary.py -- API request adapter (ApiRequestShim), session commit, | template context builder (build_template_context) |-- cookie_session.py -- CookieSession class, secret key management, session helpers |-- csrf.py -- CSRF token validation (CookieSession generates the token) |-- dependencies.py -- Request-state accessors (get_rundb, get_userdb, etc.), called directly |-- errors.py -- Centralized error handler installation (API/UI routing) |-- jinja.py -- Jinja2 Environment, Jinja2Templates instance, static_url |-- middleware.py -- Pure ASGI middleware (5 middleware classes) |-- open_graph.py -- Open Graph metadata for shared links |-- session_middleware.py -- FishtestSessionMiddleware (itsdangerous cookie signing) |-- settings.py -- AppSettings (environment variable parsing) |-- template_helpers.py -- Jinja2 filters and global functions |-- template_renderer.py -- Template rendering helper (render_template_to_response) |-- ui_cookies.py -- Browser-readable UI preference cookies |-- ui_errors.py -- HTML error page rendering (404, 403) `-- ui_pipeline.py -- HTTP cache header application ``` ### Statistical modules (`server/fishtest/stats/`) ``` stats/ |-- __init__.py |-- LLRcalc.py -- Log-likelihood ratio computation |-- brownian.py -- Brownian motion model for SPRT |-- sprt.py -- Sequential probability ratio test `-- stat_util.py -- ELO calculation, SPRT_elo, get_elo ``` ## Application startup The entrypoint is `uvicorn fishtest.app:app`. The `create_app()` function in `app.py` builds the FastAPI instance with a lifespan context manager that handles startup and shutdown. OpenAPI docs (`/docs`, `/redoc`) are disabled in production (`openapi_url` defaults to `None`). Set `OPENAPI_URL=/openapi.json` to enable the full interactive API documentation during development. ### Async concurrency model The server uses Uvicorn (ASGI) with an async event loop. The event loop accepts and dispatches HTTP connections; all blocking work runs in the Starlette threadpool via `run_in_threadpool()`. | Aspect | Description | | --- | --- | | Concurrency model | Async event loop + threadpool (200 tokens, configurable) | | Connection capacity | 9,400+ concurrent workers proven in production | | Blocking I/O | Occupies a threadpool slot only during the blocking call | | Memory per connection | Coroutine frame (\~KBs), not a full thread stack | | Overload behavior | Connections queue in the kernel backlog (`--backlog 16384`) | All blocking work (MongoDB queries, file I/O, CPU-bound stats, GitHub API calls) is offloaded to the threadpool. The event loop stays free to accept new connections and dispatch lightweight work (session cookie signing, JSON parsing, CSRF checks). Application-level throttling (`task_semaphore(TASK_SEMAPHORE_SIZE)` + `request_task_lock` in `rundb.py`) governs the scheduling critical path. Both `THREADPOOL_TOKENS` and `TASK_SEMAPHORE_SIZE` are defined in `http/settings.py`; see [Threading model]() for the full analysis. Do **not** use Uvicorn's `--limit-concurrency` flag -- it rejects excess connections with HTTP 503 instead of queuing them, which triggers exponential backoff in workers (see [Deployment]() for details). ### Startup sequence 1. `AppSettings.from_env()` reads `FISHTEST_PORT`, `FISHTEST_PRIMARY_PORT` and `OPENAPI_URL`; the result is stored as `app.state.settings`. 2. The threadpool limiter is set to `THREADPOOL_TOKENS`. 3. On the primary instance, `_require_single_worker_on_primary()` stops the startup when `UVICORN_WORKERS` (or `WEB_CONCURRENCY`) is an integer other than 1 (prevents duplicated scheduler side effects). 4. `RunDb(port, is_primary_instance)` is constructed in the threadpool. This connects to MongoDB and initializes all domain adapters (UserDb, ActionDb, WorkerDb, KeyValueStore). 5. Domain adapters are stored on `app.state` for request-scoped access: `app.state.rundb`, `app.state.userdb`, `app.state.actiondb`, `app.state.workerdb`. 6. The SIGUSR1 thread-dump handler is installed. 7. `schemas.legacy_usernames` is populated from the key-value store. 8. `gh.init()` initializes the GitHub API client on every instance; only the primary refreshes the official master SHA. 9. On the primary instance only: 10. `rundb.update_aggregated_data()` refreshes cached statistics. 11. `rundb.schedule_tasks()` starts the periodic scheduler. ### Shutdown sequence 1. `rundb._shutdown = True` -- signals middleware to reject new requests. 2. `asyncio.sleep(0.5)` -- brief drain period. 3. Scheduler is stopped (`rundb.scheduler.stop()`). 4. On primary: run cache is flushed, persistent data is saved. 5. A `system_event` action is logged when the instance has a port. 6. MongoDB connection is closed. ## Middleware stack Middleware is installed in `create_app()` and executes in reverse installation order (outermost first in the request path): | Order | Middleware | Responsibility | | --- | --- | --- | | 1 | `FishtestSessionMiddleware` | Reads/writes signed session cookie (itsdangerous) | | 2 | `RedirectBlockedUiUsersMiddleware` | Redirects blocked users to `/tests` (302) | | 3 | `RejectNonPrimaryWorkerApiMiddleware` | Returns 503 for worker API on non-primary instances | | 4 | `AttachRequestStateMiddleware` | Copies `app.state` handles to `request.state`; stamps `request_started_at` | | 5 | `ShutdownGuardMiddleware` | Returns 503 for all requests during shutdown | | 6 | `HeadMethodMiddleware` | Converts HEAD to GET and strips response body (RFC 9110 Section 9.3.2) | All middleware classes are pure ASGI (`__call__(self, scope, receive, send)`). None use Starlette's `BaseHTTPMiddleware`. ## Request flow High-level request path: ``` flowchart LR client[Client] --> nginx[nginx] nginx --> uvicorn[Uvicorn] uvicorn --> middleware[ASGI middleware stack] middleware --> router[FastAPI router] router -->|HTML pages and fragments| ui[views_router] router -->|Worker and user API| api[api_router] router -->|/static| static[StaticFiles] ``` - **Worker API**: `api_router` handles all `/api/*` endpoints. Worker endpoints require authentication: `password` and `worker_info.username` in the POST body. - **UI**: `views_router` handles all HTML-rendering endpoints. Routes are registered from the `_VIEW_ROUTES` table via `_register_view_routes()`. - **Static assets**: `StaticFiles` mount serves `/static/*`. ### htmx integration UI templates load htmx 4.0.1 from CDN in `base.html.j2`. The server remains fully server-rendered (Jinja2 + HTML responses). The test detail page also loads a page-scoped diff renderer for the inline Diff panel. htmx adds three capabilities without client-side rendering or a JavaScript build step: | Capability | Mechanism | | --- | --- | | Fragment polling | `hx-get` + `hx-trigger="every Ns"` fetches a fragment endpoint; server returns partial HTML | | In-place content swap | `hx-get` + `hx-target` + `hx-swap="innerHTML"` replaces a page section (filters, pagination) | | Out-of-band updates | `hx-swap-oob="innerHTML"` attributes in the response update multiple DOM elements in one response | **Swapping and morphing.** A swap style of `innerHTML` replaces the children of its target, so every node inside it is a new node. Anything the browser attached to the old nodes goes with them, keyboard focus first of all: focus on a link inside the panel returns to `` on each tick. The two panels that refresh on a timer, `#machines` on the homepage and `#tasks-content` on the test detail page, use `innerMorph`, which patches the existing nodes in place and keeps their identity. Both panels keep their filter form outside the swap target either way. **Response swapping.** htmx swaps every response whose status is not listed in `htmx.config.noSwap`, which holds `204` and `304`. This server answers errors with whole pages rather than partials sized for a swap target, so the `` element in `base.html.j2` carries `hx-status:4xx:inherited="swap:none push:false"` and the `5xx` equivalent: every descendant inherits them, and an error response neither swaps nor moves the address bar. **Settling.** An `htmx-config` meta tag sets `htmx.config.defaultSettleDelay` to `0`. Settling copies the attributes of each replaced element onto its replacement and restores the response's own attributes a tick later, and it never rewrites the `value` property of a focused input, so a filter field typed into while its own subtree is swapped would keep the value it was served with. Nothing styles the `htmx-settling` or `htmx-added` classes. **Out-of-band-only responses.** A response whose body holds only out-of-band elements leaves an empty fragment for the main swap, and htmx skips that swap: `htmx.config.allowEmptySwapAfterOOB` is `false`. Emptying a swap target requires a response that carries empty main content. The poll drivers that send only out-of-band fragments, `#run-tables-poller`, `#live-elo-poller` and `#tests-view-detail-poller`, declare `hx-swap="none"`. `#tests-stats-poller` and the pollers that swap into themselves (see Polling lifecycle) receive main content with every response. The `` policy stops the main content swap and, through `push:false`, the history entry. htmx still applies out-of-band elements from the body and still adopts the response's ``, neither of them gated on the status. For any status at or above 400, `application.js` therefore clears the response title and empties the task list that carries the swaps on `htmx:before:swap`. A failed request cannot move the address bar, rename the tab, or write an id from an error page over live content. **Dual-mode endpoints.** Several UI routes serve either a full page or an HTML fragment from the same URL. The view handler calls `_is_hx_request(request)`, then returns the appropriate template via the `_render_hx_fragment()` helper. `HX-Request: true` opens the door, and three independent signals close it, each rejecting the case it identifies: `HX-History-Restore-Request: true` for a back navigation, `HX-Request-Type: full` for a swap scoped to the whole document, and `Sec-Fetch-Mode: navigate` for a real top-level navigation. A request that announces none of them is a fragment request. `HX-Request-Type` states the scope of the swap: `partial` targets a region of the current page, `full` replaces the document, which is what a boosted navigation asks for. The check rejects `full` rather than requiring `partial`, so a rename of that header degrades to treating every htmx request as a fragment request, instead of swapping whole pages into every fragment target on the site. `_dispatch_view()` appends one `Vary` token per header the decision above reads: `HX-Request, HX-History-Restore-Request, HX-Request-Type, Sec-Fetch-Mode`, listed once in `FRAGMENT_REQUEST_HEADERS`. RFC 9111 section 4.1 requires the selecting header fields to be named there, or a shared cache may hand a stored fragment to a request the server would answer with a whole page. UI GET responses also emit `Cache-Control`: the default is `no-cache, private`, auth-sensitive pages use `no-store`, and explicit route-level overrides such as `/tests/machines` can still set a short `max-age`. This keeps dynamic cache policy server-authoritative and prevents shared caches such as nginx `proxy_cache` from storing personalized UI responses. **Reverse-proxy cache boundary.** nginx should respect those application headers for dynamic content and should not add `proxy_cache` in front of UI routes. Aggressive proxy/browser caching remains appropriate for immutable static assets only. **Server-authoritative table state.** The htmx list pages (`/nns`, `/contributors`, `/user_management`, `/workers/show`, `/tests/machines`, `/actions`, `/tests/finished`) keep sort, search, page, and view state in the URL and render the active control state server-side on every response. Where the htmx target contains stateful controls, the swapped boundary is the full content fragment, not just table rows. The shared active-search debounce is projected into templates as `htmx.input_changed_delay_ms`. **Request coordination.** The poll-driven panels below a filter form, `#machines` and `#tasks-content`, use `hx-sync` to name the form as their request queue. The form itself declares no `hx-sync`, so submitting it aborts an in-flight poll tick; the poll and the sort/pagination links use `abort`, which drops a request while another is in flight on that queue rather than pre-empting it. Sort and pagination links carry their own query string and inherit nothing: htmx applies an ancestor's attributes only where that ancestor marks them `:inherited`, and a `GET` collects the enclosing form only when the requesting element is the form itself. **Fragment templates.** Fragment responses use standalone `.html.j2` files (named `*_fragment.html.j2`) that do not extend `base.html.j2`; `/rate_limits/server` returns its short fragment as inline HTML. This avoids the need for block-level partial rendering and keeps fragments self-contained. See [Templates](<http://official-stockfish.github.io/fishtest/templates/index.md>) for the full catalog. **OOB table rows.** A `<tr>` cannot stand on its own in parsed HTML, so fragments that update table bodies send their rows inside a `<template>`. The `id` and `hx-swap-oob` attributes go on the `<template>` element itself, never on an element inside it: htmx locates out-of-band elements with `querySelectorAll`, which does not descend into template content, so a nested `hx-swap-oob` is silently ignored. htmx strips the wrapper before the swap and applies the rows to the live `<tbody>` named by the `id`. **Polling lifecycle.** A poll that ends runs on a dedicated driver element that carries the `hx-trigger="every Ns"` attribute and is not its own swap target. htmx clears a poll interval only when its driver leaves the document, so the lifecycle is expressed in the response body: - **200** -- swap the response content and keep polling. - **204** -- no content; htmx skips the swap and keeps polling. - **200 with a driver-removing element** -- terminal state. The response includes `poll_stop_fragment.html.j2`, which renders `<div id="{poller_id}" hx-swap-oob="delete"></div>` and removes the driver. The drivers are `#run-tables-poller`, `#live-elo-poller`, `#tests-stats-poller`, and `#tests-view-detail-poller`. Four pollers swap into the element that carries the trigger and poll for the life of the page: `#machines` and `#tasks-content` (`innerMorph`; the tasks panel renders the periodic trigger only for an unfinished run), `#server_rate_limit` and `#pending-users-nav` (`innerHTML`). The test detail page uses one visibility-aware OOB poller for live summary and detail data: - `/tests/view/{id}/detail` refreshes the ELO block, run status, active-worker totals, detail table, time block, compact chi-square block, and the embedded SPSA chart payload. The merged detail poller uses `hx-swap="none"`, so the poller element stays stable while htmx still applies the response's out-of-band section updates. The tasks table keeps its own conditional `/tests/tasks/{id}` poller because it has a separate shell/body + OOB-controls contract. Run-list and detail polling intentionally use different data shapes. The `/tests` and `/tests/user/{username}` run-table path rebuilds from `aggregate_unfinished_runs()` and the lightweight unfinished-run query, which omits `tasks`, `bad_tasks`, and `args.spsa.param_history`. Detail routes use full run data via `get_run()` and the dedicated tasks poller. **Visibility-aware polling policy.** Every periodic htmx poller follows a three-part trigger policy: 1. A periodic trigger gated on `document.visibilityState === 'visible'`, written `every[<condition>] Ns`, the form htmx parses natively; the templates use no other spelling. 2. An immediate focus-return trigger using `visibilitychange[document.visibilityState === 'visible'] from:document`. 3. Section-scoped pollers (machines, tasks) additionally gate on the section's expanded state (`classList.contains('show')`). This ensures background tabs do not generate server load and that returning to the tab produces an immediate refresh. ## Primary instance model Multiple Uvicorn instances run behind nginx (ports 8000-8003). Exactly one is designated the **primary** via the `FISHTEST_PRIMARY_PORT` environment variable. ### Primary responsibilities - Periodic scheduler: buffer flush, cache cleanup, dead-task scavenging, throughput, nps and games-per-minute updates, run and data-structure validation, worker-map cleanup, book updates, and the official master SHA refresh. - Aggregated data updates. - The official master SHA refresh at startup, and the GitHub API cache save at shutdown. - Run cache flush and persistent data save on shutdown. - The worker API, except `/api/upload_pgn`, and the run actions (`/tests/run`, `modify`, `stop`, `approve`, `purge`, `delete`). ### Secondary instances - Serve UI pages, the read-only `/api/*` endpoints and `/api/upload_pgn`. - Worker API requests other than `/api/upload_pgn` return 503 (via `RejectNonPrimaryWorkerApiMiddleware`), and so do the run actions. - nginx routes worker API traffic to the primary and PGN uploads to their own instance; the rest is distributed across the instances. ## Signals | Signal | Behavior | | --- | --- | | SIGINT / SIGTERM | Uvicorn initiates graceful shutdown -\> lifespan cleanup runs | | SIGUSR1 | Dumps all thread stacks to stderr via `faulthandler.register()` | To trigger a thread dump on a systemd-managed instance, run `sudo systemctl kill -s SIGUSR1 fishtest@8000`. During shutdown, `ShutdownGuardMiddleware` rejects new requests with HTTP 503. ## Core domain adapters These are not HTTP modules. They encapsulate business logic and MongoDB access. | Adapter | Module | Responsibility | | --- | --- | --- | | `RunDb` | `rundb.py` | Run lifecycle, task assignment, result aggregation, run cache | | `UserDb` | `userdb.py` | User CRUD, authentication, group membership | | `ActionDb` | `actiondb.py` | Audit trail for user and system actions | | `WorkerDb` | `workerdb.py` | Worker ban list management | | `KeyValueStore` | `kvstore.py` | Lightweight key-value pairs in MongoDB | | `Scheduler` | `scheduler.py` | Periodic background tasks on primary instance | A single `RunDb` instance is created per process at startup and stored on `app.state.rundb`. It owns all other adapters (`rundb.userdb`, `rundb.actiondb`, `rundb.workerdb`, `rundb.kvstore`). ## Validation vtjson is the sole validation layer. The `schemas.py` module defines the repository's vtjson schemas for plain Python dict validation. Schemas are used in: - API endpoints (request body validation). - Domain adapters (run, user, action document validation before MongoDB writes). - Form input validation (username format, worker name format). When raw form input and persisted document data intentionally have different contracts, fishtest uses different vtjson schemas for those boundaries. Raw-input schemas may be broader than the persisted-data schema, while the persisted schema describes the canonical stored form validated before MongoDB writes. For contributor-facing vtjson rules and schema-change guidance, see [Development](<http://official-stockfish.github.io/fishtest/development/index.md>). No Pydantic models are used anywhere in the codebase. ## Framework usage: FastAPI as a thin wrapper This project uses FastAPI as a thin routing convenience layer on top of Starlette. The FastAPI-exclusive features in use are: 1. **`FastAPI()`** -- the application class (inherits `starlette.Starlette`). 2. **`APIRouter`** -- decorator-style route registration and data-driven `add_api_route()`. 3. **Exception handlers** -- two fallback handlers from `fastapi.exception_handlers`. 4. **`HTTPException` and `RequestValidationError`** -- raised by the API and CSRF code, and handled by `install_error_handlers`. The following FastAPI features are **not used**: - Pydantic request/response models (`BaseModel`, `response_model`). - Dependency injection (`Depends()`) in route signatures. - Parameter declarations (`Body`, `Query`, `Path`, `Header`, `Cookie`). - Security schemes (`OAuth2`, `HTTPBasic`, `APIKey`). All middleware is pure ASGI (Starlette pattern). Session handling, CSRF protection, authentication, and request validation use custom implementations -- not FastAPI's built-in machinery. Contributors should not expect Pydantic, DI, or security scheme patterns in this codebase. When importing classes that FastAPI re-exports from Starlette (`Request`, `Response`, `JSONResponse`, `StaticFiles`, etc.), prefer importing from `starlette` directly. ## Error handling Error handlers are installed via `install_error_handlers(app)` in `app.py`. They route errors differently based on the request path: | Path prefix | HTTP 404 | HTTP 401/403 | Validation error | Unhandled exception | | --- | --- | --- | --- | --- | | `/api/*` (worker) | JSON `{"error": "...", "duration": N}` | JSON | 400 `{"error": "<path>: invalid request", "duration": N}` | 500 `{"error": "<path>: Internal Server Error", "duration": N}` | | `/api/*` (other) | the handler's `{"error": "...", "duration": N}`; `{"detail": "Not Found"}` for an unknown path | JSON | 400 `{"detail": "Invalid request", "errors": [...]}` | 500 `{"detail": "Internal Server Error"}` | | UI routes | HTML 404 page (Jinja2) | the login page with HTTP 403 and a "Please login" message | FastAPI's 422 JSON | Plain text 500 | A handler's error dict is returned as the response body, so worker API errors carry `duration`. The one exception is shutdown: `ShutdownGuardMiddleware` answers every path with an empty 503. # Threading Model ## Principle The ASGI event loop is a thin HTTP dispatcher. All blocking work runs in Starlette's default threadpool via `run_in_threadpool()`. The async event loop holds all concurrent connections (thousands) while only a fraction simultaneously occupy threadpool slots for blocking MongoDB/lock work. Connection acceptance is decoupled from handler execution -- Uvicorn can accept 10,000+ worker connections natively. The threadpool size is configured by `THREADPOOL_TOKENS` in `http/settings.py` (currently 200). This is set during lifespan startup via `current_default_thread_limiter().total_tokens`. The value must be large enough to avoid queuing under sustained load (9,400+ concurrent workers proven in production), but not so large that it overwhelms MongoDB or CPU resources. Application-level throttling (`task_semaphore(TASK_SEMAPHORE_SIZE)` + `request_task_lock` in `rundb.py`) governs the scheduling critical path, not the HTTP layer. Both `THREADPOOL_TOKENS` and `TASK_SEMAPHORE_SIZE` are defined in `http/settings.py`. Do **not** use Uvicorn's `--limit-concurrency` flag. It rejects excess connections with HTTP 503 instead of queuing them. See [Deployment](<http://official-stockfish.github.io/fishtest/deployment/index.md>) for the correct Uvicorn flags. Blocking work includes: - **MongoDB queries** -- pymongo is synchronous. - **File I/O** -- template rendering, PGN uploads, neural network files. - **CPU-bound computation** -- ELO calculations, SPRT, SPSA. - **Network calls** -- GitHub API via the `requests` library. ## Execution domains ### Event loop `[LOOP]` Code that runs directly in the `async def` coroutine on the event loop. Must complete quickly (microseconds to low milliseconds). - All ASGI middleware `__call__` methods. - FastAPI route dispatch (before entering the handler body). - Lifespan startup/shutdown orchestration. - Session cookie signing/unsigning (HMAC + base64 + JSON; small payloads). - CSRF token generation (`secrets.token_hex`). ### Threadpool `[THREAD]` Code offloaded to the default anyio threadpool via `run_in_threadpool()`. - All API endpoint handler bodies (each `async def` route wrapper awaits `run_in_threadpool(api.<method>)`). - All UI endpoint handler bodies (via `_dispatch_view` -\> `run_in_threadpool`). - `RunDb` construction and shutdown (MongoDB connect/close). - Scheduler start/stop. - GitHub API initialization and calls. - Jinja2 template rendering. - Aggregated data updates. ### Streaming `[STREAM/THREAD]` Async generators that yield chunks, with each chunk read in the threadpool. - PGN file downloads (`download_pgn`, `download_run_pgns`): `StreamingResponse` wraps `iterate_in_threadpool(_iter_filelike(...))`. ## Component inventory ### Lifespan (`app.py`) | Function | Domain | Notes | | --- | --- | --- | | `create_app()` / `lifespan()` | `[LOOP]` | Orchestrates startup/shutdown | | `RunDb(...)` | `[THREAD]` | MongoDB connect via `run_in_threadpool` | | `gh.init(...)` | `[THREAD]` | GitHub API setup | | `rundb.update_aggregated_data()` | `[THREAD]` | Refreshes cached statistics (primary) | | `rundb.schedule_tasks()` | `[THREAD]` | Starts periodic scheduler | | `_shutdown_rundb(...)` | `[LOOP]` | Coordinates threadpool shutdown calls | | `rundb.scheduler.stop()` | `[THREAD]` | Stops scheduler | | `rundb.run_cache.flush_all()` | `[THREAD]` | Flushes dirty pages | | `rundb.save_persistent_data()` | `[THREAD]` | Saves persistent data (primary) | | `rundb.actiondb.system_event(...)` | `[THREAD]` | Logs the stop event | | `rundb.conn.close()` | `[THREAD]` | Closes MongoDB connection | ### Middleware (`http/middleware.py`, `http/session_middleware.py`) | Class | Domain | Notes | | --- | --- | --- | | `FishtestSessionMiddleware` | `[LOOP]` | Signs/unsigns cookie, enforces size limits | | `ShutdownGuardMiddleware` | `[LOOP]` | Checks `_shutdown` flag, returns 503 | | `AttachRequestStateMiddleware` | `[LOOP]` | Copies state references, stamps start time | | `RejectNonPrimaryWorkerApiMiddleware` | `[LOOP]` | Checks primary flag, returns 503 | | `RedirectBlockedUiUsersMiddleware` | `[LOOP]` + `[THREAD]` | Session read on loop; blocked-user DB lookup offloaded | | `HeadMethodMiddleware` | `[LOOP]` | Converts HEAD to GET, strips response body | ### API router (`api.py`) | Component | Domain | Notes | | --- | --- | --- | | Route wrappers (`async def`) | `[LOOP]` | Parse JSON body, construct shim | | `WorkerApi` handler methods | `[THREAD]` | All 9 worker endpoints | | `UserApi` handler methods | `[THREAD]` | All 11 user/read-only endpoints | | PGN streaming | `[STREAM/THREAD]` | `iterate_in_threadpool` over file chunks | ### UI router (`views.py`) | Component | Domain | Notes | | --- | --- | --- | | `_dispatch_view()` | `[LOOP]` | Form parsing, CSRF check, then `run_in_threadpool` | | All UI view handler bodies (every route except direct `home`) | `[THREAD]` | Via `_dispatch_view` | | Template rendering | `[THREAD]` | Pages: `_dispatch_view` renders the route's `renderer` in its own `run_in_threadpool` call after the handler returns; fragments: `_render_hx_fragment` renders inside the handler body | ### Error handlers (`http/errors.py`, `http/ui_errors.py`) | Component | Domain | Notes | | --- | --- | --- | | `_http_exception_handler` | `[LOOP]` | Routes to JSON or HTML | | `render_notfound_response` | `[LOOP]` + `[THREAD]` | Session load and context on the loop; the 404 page render offloaded | | `render_forbidden_response` | `[LOOP]` + `[THREAD]` | Session load and context on the loop; the login page render offloaded | ## Event-loop CPU hotspots These are the known points where CPU work runs on the event loop rather than in the threadpool. They are acceptable because they process small payloads: | Hotspot | Location | Payload size | | --- | --- | --- | | JSON decode | `await request.json()` in API routes | Typically \< 10 KB; a `/api/upload_pgn` body carries the base64 games of a task | | Form parse | `await request.form()` in `_dispatch_view` | Typically \< 200 MB max (PGN uploads are API, not UI) | | Cookie decode | `itsdangerous.unsign()` in session middleware | \< 4 KB (cookie size limit enforced) | ## Rules for adding new code 1. **New endpoints**: follow the existing routes. An API route is an `async def` wrapper that builds the request shim and awaits `run_in_threadpool(api.<method>)`; a UI route is a `_VIEW_ROUTES` entry, which `_dispatch_view` runs in the threadpool. Any other blocking call in an `async def` must be offloaded explicitly. 2. **New middleware**: write as pure ASGI (`__call__(self, scope, receive, send)`). Never use `BaseHTTPMiddleware` -- it buffers the entire response body and blocks streaming. 3. **Blocking code in async context**: wrap in `await run_in_threadpool(fn, *args)`. Import from `starlette.concurrency`. 4. **Never block the event loop**: do not call pymongo, `requests.get()`, file read/write, or CPU-intensive computation directly inside an `async def` function body. 5. **Streaming responses**: use `iterate_in_threadpool()` to wrap synchronous iterators for `StreamingResponse`. ## Task scheduling throttle `/api/request_task` is the highest-contention endpoint. It is serialised internally by `request_task_lock` (a mutex), so only **1 thread** does useful scheduling work at any time. Every thread that enters `request_task()` holds one AnyIO threadpool token for its full duration -- **including** while blocked on the mutex. ### Call chain (per request) ``` flowchart TD loop[Event loop] --> offload[Offload request_task to threadpool] offload --> token[One AnyIO token is held] token --> gate[task_semaphore gate] gate --> lock[request_task_lock mutex] lock --> work[sync_request_task] work --> data[MongoDB plus task iteration] ``` Exact call chain: ``` event loop -> run_in_threadpool(api.request_task) [1 AnyIO token] threadpool -> validate_request() [auth, schema, run lookup] threadpool -> task_semaphore.acquire(False) [non-blocking gate] threadpool -> request_task_lock [blocking mutex] sync_request_task(...) [MongoDB + iteration] ``` ### The problem: burst-driven token starvation At steady state (\~200 workers) `request_task` traffic is negligible. But worker reconnection bursts change the picture dramatically. Observed burst in tests: | Time | Workers | Delta workers | Delta time | | --- | ---: | ---: | --- | | 14:47 | 205 | \-- | \-- | | 15:05 | 4,608 | \+4,403 | 18 min | | 15:20 | 9,116 | \+4,508 | 15 min | | 15:23 | 9,418 | \+302 | 3 min | During these bursts hundreds of workers call `/api/request_task` simultaneously. Without a cap **all 200 tokens** could fill with mutex-waiters doing zero useful work -- and **starve** the endpoints that *must* proceed promptly: | Endpoint | Rate at 10k workers | Starvation impact | | --- | ---: | --- | | `/api/beat` | \~83 req/s (10k x 1/120 s) | Missed beats -\> server reclaims active tasks | | `/api/update_task` | \~7.4 req/s (observed) | Lost game results -\> spurious dead-task scavenges | The `task_semaphore` gates entry so that at most `TASK_SEMAPHORE_SIZE` threads can wait on the lock at any time. The next caller, after its request is validated, gets an immediate `{"task_waiting": false, "info": "...too busy..."}` without waiting on the lock, and retries after a short backoff -- harmless because `task_duration` is 30 minutes. ### Why `TASK_SEMAPHORE_SIZE = 5` when `THREADPOOL_TOKENS = 200` The value is grounded in production measurements from the 9,423-worker run. **Measured endpoint latencies**: | Endpoint | Observed p50 | Tokens held (Little's Law: L = lambda \* W) | | --- | ---: | --- | | `/api/beat` | 6 ms | 83 req/s \* 0.006 s = **0.5** | | `/api/update_task` | 7 ms | 7.4 req/s \* 0.007 s = **0.05** | | `/api/request_version` | 4 ms | 18.1 req/s \* 0.004 s = **0.07** | | `/api/request_task` | 15 ms | serialised -\> **\<= 1 active** | Under steady state all endpoints together occupy \< 1 token. The risk is entirely in **bursts**. **Token budget during a reconnection burst (worst case):** ``` THREADPOOL_TOKENS 200 - TASK_SEMAPHORE_SIZE (request_task cap) 5 (2.5 %) ----------------------------------------------- Tokens available for everything else 195 (97.5 %) ``` Of those 5 tokens: - **1** is inside the lock doing actual work (\~15 ms per call). - **4** are a standing queue absorbing arrival jitter. **Why not fewer (e.g. 2)?** During the observed Phase 3 burst, `request_task` arrival rate spiked to \~20 req/s. With a lock hold time of 15 ms, the probability of \> 1 arrival during a single lock hold is \~26%. A queue depth of 4 absorbs this jitter without rejecting the majority of callers. **Why not more (e.g. 10)?** The lock is the throughput bottleneck -- only 1 thread executes regardless of queue depth. 10 slots would pin 10 tokens (5 %) on mutex-waiters for zero throughput gain, and double the worst-case starvation exposure for beat/update\_task. **Production validation** (9,423 workers, 63+ min stable): - "Too busy" rejections: **3** total (was 729 before THREADPOOL\_TOKENS=200) - HTTP 503s from Uvicorn: **0** - Process crashes: **0** - Dead tasks (server-side): **0** ### Where the constants live Both `THREADPOOL_TOKENS` and `TASK_SEMAPHORE_SIZE` are defined in `fishtest/http/settings.py`, which imports only the standard library, so `app.py` and `rundb.py` both import it without an import cycle. # Worker architecture ## Overview The worker is a standalone Python application (Python \>= 3.8) that runs on contributor machines. It fetches testing tasks from the fishtest server, compiles Stockfish from source, runs games via fastchess, and reports results back. Source files: | File | Purpose | | --- | --- | | `worker/worker.py` | Main control loop, configuration, signal handling, heartbeat | | `worker/games.py` | Engine compilation, game execution, fastchess output parsing | | `worker/updater.py` | Self-update mechanism | | `worker/sri.txt` | SRI hashes of the three files above, checked against the server's copy | The worker writes its configuration to `worker/fishtest.cfg` on first start; the file is not part of the repository. ## Constants | Constant | Value | Location | | --- | --- | --- | | `WORKER_VERSION` | the protocol version the server compares | `worker.py` | | `FASTCHESS_SHA` | the fastchess commit the worker builds | `worker.py` | | `HTTP_TIMEOUT` | 30.0 s | `worker.py`, `games.py` | | `INITIAL_RETRY_TIME` | 15.0 s | `worker.py` | | `MAX_RETRY_TIME` | 900 s (15 min) | `worker.py` | | `THREAD_JOIN_TIMEOUT` | 15.0 s | `worker.py` | | `UPDATE_RETRY_TIME` | 15.0 s | `games.py` | | `FASTCHESS_KILL_TIMEOUT` | 15.0 s | `games.py` | | `MIN_GCC_MAJOR.MINOR` | 10.2 | `worker.py` | | `MIN_CLANG_MAJOR.MINOR` | 11.0 | `worker.py` | ## Control flow High-level worker control flow: ``` flowchart TD start[worker] --> init[Setup parameters and verify worker] init --> toolchain[Verify toolchain and setup fastchess] toolchain --> heartbeat[Start heartbeat thread] heartbeat --> fetch[fetch_and_handle_task] fetch --> assigned{Task assigned} assigned -- No --> retry[Wait and retry] --> fetch assigned -- Yes --> prep[Build engines and stage inputs] prep --> batch[Run fastchess batch] batch --> report[POST /api/update_task] report --> more{More games needed} more -- Yes --> batch more -- No --> upload[POST /api/upload_pgn unless SPSA] --> fetch prep -- Failure --> stop[POST /api/failed_task or /api/stop_run] batch -- Failure --> stop stop --> upload ``` ### `worker()` -- entry point 1. Acquire a file lock (`fishtest_worker.lock`) to prevent multiple instances in the same directory. 2. Install signal handlers (SIGINT, SIGTERM, SIGQUIT, SIGBREAK). 3. Call `setup_parameters()` to read/validate `fishtest.cfg`, probe hardware, parse CLI arguments, validate credentials, and write config back. 4. Write SRI hashes (`sri.txt`). 5. If `--only_config` was passed, exit. 6. Create `testing/`. 7. Verify the worker version with the server (may trigger self-update). 8. Verify the toolchain (`make`, `strip`). 9. Build fastchess from source if not already cached, and run its tests. 10. Verify worker integrity via remote SRI comparison. 11. Assemble `worker_info` (username, concurrency, compiler, UUID, and the `worker_arch` that Stockfish's `get_native_properties.sh` reports). 12. Start the heartbeat thread (daemon). 13. Enter the main loop: call `fetch_and_handle_task()` repeatedly, and stop when `fish.exit` exists in the worker directory. ### `fetch_and_handle_task()` 1. Re-verify worker version (may trigger self-update). 2. Clean up old files in `testing/`. 3. Check remaining GitHub API calls. 4. POST `/api/request_task` to get a task assignment. 5. If a task is assigned, call `run_games()`. 6. On exception, POST `/api/stop_run` for a `RunException` and `/api/failed_task` for any other. 7. For a run that is not SPSA, upload the recorded games via POST `/api/upload_pgn` when the PGN file is non-empty and its CRC matches, whether the task finished or failed. ### `run_games()` 1. Set up `result` dict with existing stats (supports resume). 2. Download the opening book if missing or corrupted (SRI check). 3. Build both `new` and `base` engines from source via `setup_engine()`. 4. Download neural networks via `establish_validated_net()`. 5. Verify engine bench signatures. 6. Compute NPS, derive CPU scaling factor. 7. Reject if the machine is too slow. 8. Adjust time control based on CPU scaling factor. 9. Construct the fastchess command line. 10. Call `launch_fastchess()` in a loop (one iteration per batch for SPSA, one call for SPRT/NumGames). ### `launch_fastchess()` 1. For SPSA: POST `/api/request_spsa` to get tuning parameters. 2. Insert SPSA option values into the fastchess command line (stochastic rounding). 3. Start fastchess as a subprocess. 4. Call `parse_fastchess_output()` to monitor stdout/stderr. 5. On exit, send SIGINT to fastchess and wait for graceful shutdown. ### `parse_fastchess_output()` 1. Read fastchess stdout/stderr via background threads feeding a queue. 2. Parse WLD and pentanomial results from fastchess output blocks. 3. Detect crashes, time losses, and fastchess errors. 4. After each batch of games, POST `/api/update_task` with accumulated stats. 5. Respect `task_alive` flag from server response. 6. Enforce a time limit (`tc_limit`). ## Heartbeat A daemon thread sends POST `/api/beat` once 120 seconds pass without a successful `update_task` or beat, and skips the beat while no task is assigned. If the server responds with `task_alive: false`, the current task is abandoned. ## Signal handling | Signal | Behavior | | --- | --- | | SIGINT | Set `current_state["alive"] = False`, raise `FatalException` | | SIGTERM | Same as SIGINT | | SIGQUIT | Same as SIGINT (Unix only) | | SIGBREAK | Same as SIGINT (Windows only) | A `fish.exit` file in the worker directory stops the worker. It is checked after every successful `update_task`, which ends the task with `WorkerException("Task stopped by 'fish.exit'.")` and posts `failed_task`, and after every task. The worker removes the file on exit. ## Configuration file File: `worker/fishtest.cfg` -- INI format, managed by `ConfigParser`. ### Sections and options ``` [login] username = myuser password = mypassword [parameters] protocol = https ; http or https host = tests.stockfishchess.org port = 443 concurrency = max(1,min(3,MAX-1)) ; expression using MAX = cpu_count max_memory = MAX/2 ; expression using MAX = total_ram_MiB uuid_prefix = _hw ; _hw = hardware-derived, or alphanumeric min_threads = 1 ; reject tasks with fewer threads fleet = False ; True = quit on error or empty queue global_cache = ; shared cache path for multi-worker setups compiler = g++ ; g++ or clang++ [private] hw_seed = 3418512882 ; random seed for UUID derivation ``` The `concurrency` and `max_memory` fields accept expressions with `MAX` as a variable and `min`/`max` as functions. They are evaluated at startup. On every start the worker also: - sets the port to 80 for `http` on 443, and to 443 for `https` on 80; - lowers `concurrency` until an STC test fits in `max_memory`, and refuses to start when `max_memory` cannot hold one; - removes sections and options it does not know. Every `[parameters]` option has a command line flag (e.g., `--concurrency`, `--max_memory`, `--fleet`), and the `[login]` values are the positional `USERNAME PASSWORD`. `[private] hw_seed` has no flag. A flag's value is written back to `fishtest.cfg`, so it persists to later starts. ## Command line flags Usage: `python worker.py [USERNAME PASSWORD] [OPTIONS]` Each flag defaults to the value in `fishtest.cfg`; the defaults below are those of a first start. | Flag | Short | Type | Default | Description | | --- | --- | --- | --- | --- | | `--protocol` | `-P` | `{http,https}` | `https` | Protocol for server communication | | `--host` | `-n` | string | `tests.stockfishchess.org` | Server hostname | | `--port` | `-p` | int | `443` | Server port | | `--concurrency` | `-c` | expression | `max(1,min(3,MAX-1))` | Max cores to use (`MAX` = cpu\_count) | | `--max_memory` | `-m` | expression | `MAX/2` | Max memory in MiB (`MAX` = total RAM) | | `--uuid_prefix` | `-u` | string | `_hw` | UUID prefix (`_hw` = hardware-derived) | | `--min_threads` | `-t` | int | `1` | Reject tasks with fewer threads | | `--fleet` | `-f` | `{False,True}` | `False` | Quit on error or empty queue | | `--global_cache` | `-g` | path | (empty) | Shared cache directory for multi-worker setups | | `--compiler` | `-C` | a detected compiler | `g++` when usable, else the first detected | Compiler for engine builds | | `--only_config` | `-w` | flag | \-- | Write config and SRI hashes, then exit | | `--no_validation` | `-v` | flag | \-- | Skip username/password validation with server | The `concurrency` and `max_memory` flags accept expressions using `MAX` as a variable and `min`/`max` as functions. ## Self-update mechanism When `verify_worker_version()` learns from the server that a newer version exists: 1. `updater.py:update()` downloads the master branch zip from GitHub. 2. Extracts the `worker/` directory to a temp folder. 3. Verifies SRI hashes of the downloaded files. 4. Replaces the local worker files with the new ones. 5. Renames `testing/` to `_testing_<timestamp>` and migrates cached files. 6. Calls `do_restart()` which uses `os.execv()` to replace the current process with a fresh invocation. ## Engine build pipeline `setup_engine()` in `games.py`: 1. Check if a cached engine binary exists in `testing/` (keyed by SHA + compiler version + environment hash). 2. If cached and healthy (verified by running bench), return the cached path. 3. Otherwise, download the source zip from GitHub (with global cache support). 4. Extract, download default neural networks from source headers. 5. Determine the best CPU architecture target via `find_arch()`. 6. Run `make profile-build` (or `make build` for Apple Silicon). 7. Strip the binary. 8. Move to `testing/` with the canonical name. ## Compiler detection `detect_compilers()` probes `g++` and `clang++` by running them with `-E -dM -` and parsing version macros. It rejects: - g++ \< 10.2 - clang++ \< 11.0 - clang++ masquerading as g++ - clang++ without `llvm-profdata` ## UUID generation Each worker instance gets a unique key: `uuid_prefix[:8] + uuid4()[8:]` When `uuid_prefix = _hw`, the prefix is derived from: `hw_seed XOR fingerprint(machine_id) XOR fingerprint(worker_path)` Machine ID sources: `/etc/machine-id`, then `/var/lib/dbus/machine-id` (Linux), registry `MachineGuid` (Windows), `ioreg IOPlatformExpertDevice` (macOS). ## Fleet mode When `fleet = True`, the worker exits immediately if: - No tasks are available - An error occurs during task execution - The server is unreachable This allows fleet orchestrators to spin workers up/down based on queue depth. ## Global cache When `global_cache` points to an existing directory, multiple workers on the same machine share downloaded artifacts (source zips, fastchess zips, neural networks). Writes use atomic `link()` to avoid partial-file races. ## File management `trim_files()` runs before each task to clean up old files in `testing/`: | Pattern | Keep | Expiration | | --- | --- | --- | | `fastchess` | 1 | never | | `stockfish-*-old` | 0 | immediately, during a self-update only | | `stockfish-*` | 50 | 30 days | | `nn-*.nnue` | 10 | 30 days | | `results-*.pgn` | 10 | 30 days | | `*.epd` | 4 | 365 days | | `*.pgn` | 4 | 365 days | Files are sorted by access time; the most recently accessed are preserved. ## API endpoints used by the worker Every fishtest endpoint except `/api/nn/{id}`, a plain GET, takes a JSON-encoded POST body with `password` and `worker_info` fields. Responses are JSON dicts that may contain an `error` key. ### Fishtest server endpoints | Endpoint | Method | Phase | Purpose | | --- | --- | --- | --- | | `/api/request_version` | POST | Setup | Check worker version, trigger update | | `/api/request_task` | POST | Setup | Request a task assignment | | `/api/nn/{id}` | GET | Setup | Download a neural network file | | `/api/update_task` | POST | Main loop | Report game results (batch updates) | | `/api/request_spsa` | POST | Main loop | Get SPSA tuning parameters | | `/api/beat` | POST | Heartbeat | Keep the task alive after 120 s without an update | | `/api/failed_task` | POST | Finish | Report task failure | | `/api/stop_run` | POST | Finish | Request early run termination | | `/api/upload_pgn` | POST | Finish | Upload compressed PGN game records | | `/api/worker_log` | POST | Main loop | Log a fastchess warning on the server | ### External endpoints | Endpoint | Method | Purpose | | --- | --- | --- | | `https://api.github.com/rate_limit` | GET | Check remaining API quota | | `https://api.github.com/repos/Disservin/fastchess/zipball/{sha}` | GET | Download fastchess source | | `https://api.github.com/repos/{user}/{repo}/zipball/{sha}` | GET | Download engine source | | `https://raw.githubusercontent.com/official-stockfish/books/master/<book>.zip` | GET | Download an opening book | | `https://api.github.com/repos/official-stockfish/books/contents/<book>.zip?ref=master` | GET | Download an opening book (fallback) | | `https://github.com/official-stockfish/fishtest/archive/master.zip` | GET | Download the worker for a self-update | ## Exception hierarchy | Exception | Effect | | --- | --- | | `FatalException` | Post `failed_task`, upload the games, stop the worker | | `RunException` | Stop the current run (POST `/api/stop_run`), continue to next | | `WorkerException` | Fail the current task, continue to next | | any other exception | Post `failed_task` with the traceback, stop the worker | `WorkerException.__new__` forwards existing `WorkerException` subclass instances (including `FatalException`) unchanged, preventing exception type downgrade during re-wrapping. ## Logging The worker writes `api.log` in its install directory, beside `worker.py`. Each API call records the server-side and worker-side latency, and each task start records the run, the task and its size: ``` 2025-01-15 12:00:00.123456+00:00 : 1.23 ms (s) 45.67 ms (w) https://tests.stockfishchess.org:443/api/update_task ``` On self-update, the log is rotated to `api.log.previous`. ## Developer: regenerating SRI hashes When modifying SRI-monitored files (`worker.py`, `games.py`, `updater.py`), the `sri.txt` file must be regenerated before committing. Use the `--only_config` flag to write the config and update SRI hashes without starting the worker: ``` cd worker uv run worker.py a a --only_config --no_validation ``` The dummy `a a` arguments satisfy the positional username/password parameters. `--no_validation` skips server contact. The command needs a usable compiler (g++ \>= 10.2 or clang++ \>= 11.0), writes updated hashes to `worker/sri.txt` and `worker/fishtest.cfg`, and exits. Delete the generated `fishtest.cfg` afterwards: the worker tests expect none. # Reference # Worker API Reference The `/api` routes serve two clients: workers, which authenticate on every call and drive a task from assignment to its last batch, and readers such as the web UI and external tools, which need no account. ## Protocol invariants - A successful response is a JSON object. `POST /api/actions` returns a JSON array. - Every worker endpoint response carries `duration`, the seconds the server spent on the request. - A request the handler refuses returns a non-2xx status with `{"error": "<path>: <message>", "duration": N}`, the message prefixed with the endpoint path: - 400: a body that is not JSON, a body the schema refuses, an unknown `run_id` or `task_id`, a missing field, a bad query parameter. - 401: a wrong username or password, a blocked or pending account, and every refused `stop_run`. - 404: a run, task, network or PGN a read-only endpoint cannot find. - An outcome the run database decides returns HTTP 200 with a status flag: `"task_waiting": false` from `request_task`, `"task_alive": false` from `update_task`, `beat`, `request_spsa` and `failed_task`. An `info` or `error` string may come with it, worded by the scheduler and not prefixed with the path. - A worker endpoint other than `/api/upload_pgn` called on a non-primary instance returns HTTP 503 with `{"error": "<path>: primary instance required", "duration": N}`. - While the server shuts down, every request returns HTTP 503 with an empty `text/plain` body. - Every GET route also answers HEAD. - The protocol version is `WORKER_VERSION` in `api.py`. A worker whose own version is lower updates itself before it asks for work. ## Authentication Every worker endpoint reads the credentials from the POST body: `password` at the top level and `username` inside `worker_info`. `UserDb.authenticate()` checks them. - Wrong credentials: HTTP 401, `{"error": "/api/<endpoint>: Invalid username or password.", "duration": N}`. A blocked or pending account gets a message naming its state. - A body that is not JSON: HTTP 400. ## Protocol lifecycle ``` sequenceDiagram actor W as Worker participant S as Fishtest server participant F as Fastchess W->>S: POST /api/request_version alt Server version is newer S-->>W: version W->>W: Self-update and restart else Same version S-->>W: version W->>S: POST /api/request_task alt No task ready S-->>W: task_waiting false W->>W: Back off and retry else Task assigned S-->>W: run and task_id W->>W: Build engines and stage inputs par Task execution loop Each batch opt SPSA run W->>S: POST /api/request_spsa S-->>W: parameters, or task_alive false end W->>F: Run games F-->>W: WLD and pentanomial results W->>S: POST /api/update_task S-->>W: task_alive true or false end and Heartbeat loop After 120 s without an update W->>S: POST /api/beat S-->>W: task_alive end end opt Task failed W->>S: POST /api/failed_task or /api/stop_run end opt Not SPSA, PGN recorded W->>S: POST /api/upload_pgn end end end ``` 1. **Version check**: `POST /api/request_version`. A newer server version makes the worker update itself and restart. 2. **Task request**: `POST /api/request_task`. The server assigns a task or returns `"task_waiting": false`, and the worker retries after a delay. 3. **Engine build**: the worker downloads the opening book, then builds both Stockfish binaries from source. 4. **Game execution**: the worker runs fastchess. For an SPSA run, `POST /api/request_spsa` fetches the parameters of each batch. 5. **Progress reporting**: `POST /api/update_task` sends the results so far after each batch. `"task_alive": false` stops the task. 6. **Heartbeat**: a daemon thread sends `POST /api/beat` once 120 seconds pass without an `update_task` or a beat for the current task. The server marks a task inactive when it has not heard from it for 360 seconds; its unplayed games go to the next task `request_task` creates. 7. **Failure**: the worker posts `POST /api/failed_task` when the task fails, and `POST /api/stop_run` when the run itself is broken (a wrong bench signature, a fastchess error). 8. **Games upload**: for a run that is not SPSA, `POST /api/upload_pgn` sends the recorded games once the task ends, whether it finished or failed. 9. **Loop**: the worker returns to step 2. `POST /api/worker_log` posts a fastchess warning to the event log while games run. ## Worker API paths These 9 paths are the worker API (`WORKER_API_PATHS` in `api.py`). On a non-primary instance all of them except `/api/upload_pgn` return HTTP 503: ``` /api/request_version /api/request_task /api/update_task /api/beat /api/request_spsa /api/failed_task /api/stop_run /api/upload_pgn /api/worker_log ``` ## Request body `/api/request_version` reads only the credentials: ``` { "password": "string", "worker_info": { "username": "string" } } ``` Every other worker endpoint validates the whole body against `api_schema`: | Field | Required | Content | | --- | --- | --- | | `password` | yes | the account password | | `worker_info` | yes | the worker description below, every key required, no other key | | `run_id` | no | the run, 24 hexadecimal digits | | `task_id` | no | the task's index in the run; requires `run_id` | | `stats` | no | game results, see [`update_task`](<#post-apiupdate_task>) | | `spsa` | no | SPSA batch results, see [`update_task`](<#post-apiupdate_task>) | | `message` | no | free text for `failed_task`, `stop_run` and `worker_log` | | `pgn` | no | base64 of the gzip-compressed games, for `upload_pgn` | With a `task_id`, the request's `worker_info.unique_key` and `worker_info.username` must equal the task's. `worker_info`: | Key | Content | | --- | --- | | `uname` | operating system name and release | | `architecture` | `platform.architecture()`, two strings | | `concurrency` | cores the worker uses, a positive integer | | `max_memory` | memory the worker may use, in MiB | | `min_threads` | the fewest threads a task may ask for, a positive integer | | `username` | the account name | | `version` | the worker's `WORKER_VERSION` | | `python_version` | three integers | | `gcc_version` | the compiler version, three integers | | `compiler` | `g++` or `clang++` | | `unique_key` | the worker's UUID | | `modified` | `true` when the worker's files differ from the release | | `worker_arch` | the Stockfish architecture the worker builds for, or `unknown` | | `ARCH` | the CPU features the engine reports | | `nps` | the measured nodes per second, a non-negative number | | `near_github_api_limit` | `true` when the worker is close to the GitHub API rate limit | ## Authenticated endpoints ### POST /api/request\_version Returns the worker protocol version: `{"version": N, "duration": N}`, where `version` is `WORKER_VERSION`. ### POST /api/request\_task Assigns a task to the worker. **Task assigned**: ``` { "run": { "_id": "run_id", "args": { "...": "the run arguments, with book_sri when the book is known" }, "my_task": { "num_games": 200, "start": 0, "stats": { "...": "..." } } }, "task_id": 0, "duration": 0.05 } ``` **No task**: `{"task_waiting": false, "duration": N}`, with an `info` string when the server is too busy or the chosen run needs no more games, and an `error` string when the worker is blocked, its name is already in use, or the account's machine limit is reached. ### POST /api/update\_task Reports the results of the task so far. `stats` carries the cumulative counts: ``` { "wins": 10, "losses": 5, "draws": 15, "crashes": 0, "time_losses": 0, "pentanomial": [0, 1, 9, 4, 1] } ``` The counts must agree with the pentanomial: wins, losses and draws add up to twice the game pairs, and the win-loss difference and the draws follow from the pairs. An SPSA run also sends `spsa`, `{"wins", "losses", "draws", "num_games", "sig"}`, the batch's results, where `num_games` is even and equals the sum of the three counts, and `sig` is the signature `request_spsa` returned. **Response**: `{"task_alive": true, "duration": N}` while the task runs, and `"task_alive": false` once the task is finished, inactive or stopped, with an `info` or `error` string where the server explains why. ### POST /api/beat Keeps the task alive between updates. **Response**: `{"task_alive": true | false, "duration": N}`. ### POST /api/request\_spsa Returns the parameters for the next SPSA batch: ``` { "w_params": [{ "name": "string", "value": 0.0, "...": "the step values" }], "b_params": [{ "name": "string", "value": 0.0, "...": "the step values" }], "sig": 0, "task_alive": true, "duration": 0.01 } ``` For an inactive task: `{"task_alive": false, "info": "...", "duration": N}`. ### POST /api/failed\_task Marks the task failed and records `message` on the event log. **Response**: `{"duration": N}`, or `{"task_alive": false, "info": "...", "duration": N}` when the task is already inactive. ### POST /api/stop\_run Stops the run and records `message` on the event log. The account needs at least 1000 CPU hours. **Response**: `{"duration": N}`. The refusals return HTTP 401: an account under 1000 CPU hours (the request is still logged, marked `(not authorized)`, and the task is made inactive) and a run that is already finished. ### POST /api/upload\_pgn Stores the gzip-compressed games of the task, `pgn` in base64. The decoded data must start with the gzip signature. **Response**: `{"duration": N}`. This endpoint runs on a non-primary backend and is outside `PRIMARY_ONLY_WORKER_API_PATHS`. ### POST /api/worker\_log Records `message` on the event log. A `run_id` requires a `task_id`, so the server can check that the worker holds that task. **Response**: `{"duration": N}`. ## Read-only endpoints These endpoints need no authentication. ### GET /api/active\_runs Returns every unfinished run as a JSON object keyed by run ID, without `tasks`, `bad_tasks` and the SPSA parameter history. ### GET /api/finished\_runs Returns 50 finished runs per page, keyed by run ID. | Parameter | Content | | --- | --- | | `page` | required, 1-based | | `username` | only this submitter's runs | | `success_only` | any non-empty value keeps only accepted runs | | `yellow_only` | any non-empty value keeps only yellow runs | | `ltc_only` | any non-empty value keeps only long time control runs | | `timestamp` | a UNIX timestamp, 10 digits with optional fraction; keeps the runs updated since then | ### POST /api/actions Returns up to 200 event-log entries matching the MongoDB filter in the JSON body, in the collection's natural order. A body that is not a valid filter returns `[]`. The response allows any origin. ### GET /api/get\_run/{id} Returns the run without `tasks`, `bad_tasks` and the SPSA parameter history. The response allows any origin. ### GET /api/get\_task/{id}/{task\_id} Returns one task. `task_id` is the task's index, or the index followed by `bad` for a task in `bad_tasks`. The worker's `unique_key` is cut to its first 8 characters and `remote_addr` is masked. ### GET /api/get\_elo/{id} Returns the run, stripped as `get_run` strips it, with the SPRT analysis under `elo`. A run without SPRT returns `{}`. ### GET /api/calc\_elo Computes Elo from game counts. | Parameter | Content | | --- | --- | | `LL`, `LD`, `DDWL`, `WD`, `WW` | pentanomial counts; take precedence over W/D/L | | `W`, `D`, `L` | win, draw and loss counts | | `elo0`, `elo1` | SPRT bounds, both or neither; each at most 10 in magnitude, `elo1` at least `elo0 + 0.5` | | `elo_model` | `BayesElo`, `logistic` or `normalized` (default); read only with SPRT bounds | Without SPRT bounds it returns `{"elo", "ci", "LOS"}`; with them, the SPRT analysis with `alpha` and `beta` fixed at 0.05. At most 2^32 games. ### GET /api/nn/{id} Counts a download of the network and redirects (HTTP 302) to `<base>/nn/<id>`, where `<base>` is `FISHTEST_NN_URL`, or the request's own scheme and host when the variable is unset. ### GET /api/pgn/{id} Downloads the games of one task, `id` being `<run_id>-<task_id>.pgn`, served with `Content-Encoding: gzip`. ### GET /api/run\_pgns/{id} Downloads the games of every task of a run as one gzip file. `id` must be `<run_id>.pgn.gz`. ### GET /api/rate\_limit Returns the server's GitHub API rate limit. ## Validation Request bodies are validated against vtjson schemas in `schemas.py`: - `api_access_schema`: the credentials, `password` and `worker_info.username`; other keys are allowed. - `api_schema`: the whole body of every worker endpoint except `request_version`. - `gzip_data`: the decoded PGN upload starts with the gzip signature. A failed validation returns HTTP 400. ## Adding a new API endpoint 1. Add the route in `api.py` with `@router.post(...)` or `@router.get(...)`. 2. Write the handler as an `async def` that wraps the request in an `ApiRequestShim` (`get_request_shim(request)` for a POST body), builds a `WorkerApi` or `UserApi` on it, and runs the method with `run_in_threadpool`. 3. Return a dict with `"duration"` (`GenericApi.add_time()`). 4. Refuse a request with `GenericApi.handle_error()`, which raises `HTTPException` with the error dict as its detail. 5. Add a vtjson schema in `schemas.py` if the endpoint accepts structured input. 6. Add a contract test in `tests/test_api.py`. 7. If the endpoint requires worker authentication, add its path to `WORKER_API_PATHS` in `api.py`. # UI Routes and View Dispatch ## Overview All UI routes are defined in `views.py`. The server uses a **data-driven registration model**: `_VIEW_ROUTES` is a list of route descriptors, and `_dispatch_view()` is the centralized dispatch function that handles cross-cutting concerns for every UI request. `views.py` is intentionally organized into stable top-level sections: authentication (with the htmx helpers), home redirect, login and signup, lists, workers, neural networks, users, contributors, homepage and run lists, run mutation, run creation, run administration, run detail, and router registration. ## Route table Routes are declared in `_VIEW_ROUTES` as tuples of: ``` (handler_function, path, config_dict) ``` Config keys: | Key | Type | Description | | --- | --- | --- | | `renderer` | string | Jinja2 template name (e.g., `"tests.html.j2"`) | | `require_csrf` | bool | Enforce CSRF validation on POST | | `require_primary` | bool | Reject POST on non-primary instance (503) | | `request_method` | string or tuple | Allowed HTTP methods (default: GET) | | `http_cache` | int | `Cache-Control: max-age=` seconds | | `direct` | bool | Bypass `_dispatch_view` (for pure redirects) | At module load time, `_register_view_routes()` iterates over `_VIEW_ROUTES`, wraps each handler with `_dispatch_view()` (unless `direct=True`), and registers it on the FastAPI router. When `request_method` is omitted, the route is read-only and registered as `GET` only. The small set of endpoints that render a form on `GET` and process it on `POST` opt into `GET, POST` explicitly, while pure mutations stay `POST` only. `HEAD` works on `GET` routes through middleware compatibility, but generic `OPTIONS` is not part of the UI route contract and returns `405`. ## Registered routes | Path | Method(s) | Handler | Template | Notes | | --- | --- | --- | --- | --- | | `/` | GET | `home` | \-- | Redirects to `/tests` (direct) | | `/login` | GET, POST | `login` | `login.html.j2` | CSRF | | `/logout` | POST | `logout` | \-- | CSRF | | `/signup` | GET, POST | `signup` | `signup.html.j2` | CSRF | | `/tests` | GET | `tests` | `tests.html.j2` | Main dashboard; page 1 live run tables poll the same route via `?live=run_tables` | | `/tests/run` | GET, POST | `tests_run` | `tests_run.html.j2` | CSRF, primary | | `/tests/modify` | POST | `tests_modify` | \-- | CSRF, primary | | `/tests/stop` | POST | `tests_stop` | \-- | CSRF, primary | | `/tests/approve` | POST | `tests_approve` | \-- | CSRF, primary | | `/tests/purge` | POST | `tests_purge` | \-- | CSRF, primary | | `/tests/delete` | POST | `tests_delete` | \-- | CSRF, primary | | `/tests/view/{id}` | GET | `tests_view` | `tests_view.html.j2` | Full detail page; renders server-owned Open Graph metadata with a query-free canonical URL and a Discord-oriented multi-line `og:description`; unfinished runs poll the merged detail fragment endpoint and the dedicated tasks endpoint | | `/tests/view/{id}/detail` | GET | `tests_view_detail` | `tests_view_detail_fragment.html.j2` | Fragment-only; no page-head metadata; OOB refresh for ELO, run status, active-worker totals, detail, time, chi-square, and the retained SPSA data payload | | `/tests/live_elo/{id}` | GET | `tests_live_elo` | `tests_live_elo.html.j2` | Live Elo page + dual-scale gauge | | `/tests/stats/{id}` | GET | `tests_stats` | `tests_stats.html.j2` | HX: `tests_stats_content_fragment.html.j2`; active runs poll with the dedicated stats-page interval and visibility-aware refresh | | `/tests/tasks/{id}` | GET | `tests_tasks` | `tasks_content_fragment.html.j2` | Fragment-only; updates the scrolling task table body and refreshes fixed controls/pagination OOB, with server-side sorting for every visible task column, one combined worker/info search filter, and 25-row pagination | | `/tests/machines` | GET | `tests_machines` | `machines_fragment.html.j2` | Fragment-only, 10s cache | | `/tests/live_elo_update/{id}` | GET | `live_elo_update` | `live_elo_fragment.html.j2` | Fragment-only (OOB) | | `/tests/finished` | GET | `tests_finished` | `tests_finished.html.j2` | HX: `tests_finished_results_fragment` | | `/tests/user/{username}` | GET | `tests_user` | `tests_user.html.j2` | HX: `tests_user_content_fragment`; page 1 live run tables poll the same route via `?live=run_tables` | | `/actions` | GET | `actions` | `actions.html.j2` | Full page plus htmx content fragment; full-page responses render route-specific Open Graph metadata that preserves the current query string in `og:url` and summarizes the first visible action row | | `/contributors` | GET | `contributors` | `contributors.html.j2` | HX: `contributors_content_fragment`; paginated (100/page) | | `/contributors/monthly` | GET | `contributors_monthly` | `contributors.html.j2` | HX: `contributors_content_fragment`; paginated (100/page) | | `/user/{username}` | GET, POST | `user` | `user.html.j2` | CSRF | | `/user` | GET, POST | `user` | `user.html.j2` | CSRF | | `/user_management` | GET | `user_management` | `user_management.html.j2` | HX: `user_management_content_fragment` | | `/user_management/pending_count` | GET | `user_management_pending_count` | `pending_users_nav_fragment.html.j2` | Sidebar status fragment; the stable wrapper and poll triggers live in `base.html.j2`, and this route returns only the `Users` anchor HTML | | `/workers/{worker_name}` | GET, POST | `workers` | `workers.html.j2` | CSRF; HX: `workers_content_fragment` | | `/upload` | GET, POST | `upload` | `nn_upload.html.j2` | CSRF | | `/nns` | GET | `nns` | `nns.html.j2` | HX: `nns_content_fragment` | | `/sprt_calc` | GET | `sprt_calc` | `sprt_calc.html.j2` | | | `/rate_limits` | GET | `rate_limits` | `rate_limits.html.j2` | | | `/rate_limits/server` | GET | `rate_limits_server` | inline HTML response | Fragment-only | ## Sidebar status links The sidebar contains two visibility-aware status links: - `Users` is rendered inside the stable `#pending-users-nav` wrapper in `base.html.j2`. Full pages include the current count server-side, and that same wrapper mounts the visibility-aware htmx poll to `/user_management/pending_count`; the fragment route itself returns only the anchor HTML. - `GitHub Rate Limits` uses separate cadences: `POLL_RATE_LIMITS_GITHUB_S` for the browser-side GitHub rate-limit poll in shared JavaScript, which updates the sidebar link on full pages and also updates the `/rate_limits` client row when that page is open, and `POLL_RATE_LIMITS_SERVER_S` for the `/rate_limits/server` htmx row. The sidebar link itself is rendered directly in `base.html.j2`. Route notes: - **Fragment-only**: endpoint always returns a fragment template (no full page). - **HX**: dual-mode endpoint; returns the named fragment when `HX-Request: true` is present and the request does not announce itself as a history restore, a full-document swap, or a top-level navigation; otherwise renders the full-page template. - **OOB**: fragment contains `hx-swap-oob` attributes for multi-element updates. ## Tests Repository URL Contract The `Tests Repository` field used on `/signup`, `/user`, and `/tests/run` accepts a GitHub repository URL with or without a trailing slash. Server-side behavior: - raw form validation accepts either `https://github.com/<user>/<repo>` or `https://github.com/<user>/<repo>/` - user profile data is canonicalized to the slash-free form - persisted user and run validation requires the slash-free canonical form - run data uses the slash-free form in `run["args"]["tests_repo"]` Canonical stored value: - `https://github.com/<user>/<repo>` This keeps GitHub compare links and worker download URLs stable even when the submitted form value includes a trailing slash. ## `/tests/view/{id}/detail` live detail contract The test detail page keeps its live summary and detail data synchronized through the fragment-only `/tests/view/{id}/detail` endpoint. This endpoint is the live detail-page poll contract. The full detail page uses a visibility-aware htmx poller with: - `hx-get="/tests/view/{id}/detail"` - `hx-include="#tests-view-detail-expected"` - `hx-swap="none"` The response updates these regions out of band: - `#tests-view-detail-expected`, the hidden input the next poll sends back - `#elo-<run_id>` - `#run-status-<run_id>` - `#tasks-totals` - `#tests-view-details` - `#tests-view-time` - `#tests-view-stats` for non-SPSA runs - `#spsa-data-<run_id>` for SPSA runs Page-head metadata contract: - The full `/tests/view/{id}` page owns `<title>`, Open Graph tags, and the optional `theme-color` meta tag. - The `/tests/view/{id}` `og:description` is emitted as plain multi-line text so Discord previews preserve the run-summary layout without literal backticks. - The fragment-only `/tests/view/{id}/detail` endpoint never renders or updates page-head metadata. - Shared links and social preview clients must fetch the full page URL, not the fragment URL. For SPSA runs, the detail fragment updates the existing `#spsa-data-<run_id>` node in place. The page-owned `spsa.js` controller keeps the chart shell mounted, draws the chart at a fixed 1000x500 size inside the scrollable container, skips redraws when the embedded JSON payload is unchanged, and redraws changed payloads in place without replacing the chart shell. The full `/tests/view/{id}` page also remembers the `% c` checkbox with a browser cookie, so the checkbox reopens in its previous mode while live detail polling continues to update only the embedded SPSA data node. The full `/tests/view/{id}` page also loads a dedicated client-side diff renderer for the inline Diff panel. That asset is page-scoped and is not part of the `/tests/view/{id}/detail` fragment contract. The request submits the page's current canonical `expected` state from a server-owned hidden input: - `active` - `paused` - `pending` Server behavior for htmx polling: - `200` returns fresh OOB detail content. - `204` keeps the current DOM when the run is still paused or pending. - When the run is terminal, the `200` response also carries `<div id="tests-view-detail-poller" hx-swap-oob="delete"></div>`, which removes the poller and stops the poll. ## `/tests/live_elo/{id}` gauge scale contract The Live Elo page renders three Google gauges (LOS, LLR, Elo) and keeps the details table in sync through `/tests/live_elo_update/{id}` OOB swaps. The Elo gauge supports two display modes: - Fixed mode (default without a saved choice): fixed gauge range `[-4, +4]` for visual consistency. - Dynamic mode: auto range chosen from the smallest symmetric power-of-two interval that covers the current Elo value and confidence interval. Switching modes: - Clicking the Elo gauge toggles between fixed and dynamic mode. - Keyboard activation on the Elo gauge (`Enter` or `Space`) also toggles modes. - The chosen mode is saved in the `live_elo_mode` cookie. Value display rule: - The gauge reports the real uncapped Elo value from the server. - In fixed mode, the gauge needle is visually limited by the selected range. ## `/tests/stats/{id}` raw statistics contract The raw statistics page is dual-mode: - Full-page navigation renders `tests_stats.html.j2`. - A fragment request (see [Detection](<#detection-_is_hx_requestrequest>)) renders `tests_stats_content_fragment.html.j2`. The page shell keeps a visibility-aware poller for unfinished non-SPSA runs: - `every[document.visibilityState === 'visible'] {{ poll.tests_stats }}s` - `visibilitychange[document.visibilityState === 'visible'] from:document` Server behavior for htmx polling: - `200` when the run is active, returning the refreshed stats fragment. - `204` when the run is not active but not terminal, keeping the current DOM. - When the run is terminal (`finished` or `failed`), the `200` response also carries `<div id="tests-stats-poller" hx-swap-oob="delete"></div>`, which removes the poller and stops the poll. Layout contract: - the shared fragment preserves the original heading-and-table statistics presentation from the page shell; - genuinely tabular data, such as SPRT bounds, remains a table; - SPSA runs render an informational message instead of raw statistics. ## htmx fragment dispatch Dual-mode endpoints (marked **HX** in the route table) serve either a full HTML page or a fragment, from the same URL, based on request headers. ### Detection: `_is_hx_request(request)` Returns `True` when the request carries `HX-Request: true` and announces none of the following, case-insensitively: 1. `HX-History-Restore-Request: true` -- a back navigation. htmx 4 keeps no page snapshots, so it refetches the pushed URL and swaps the response into `<body>`. The restore passes its own request object, which replaces the core headers: the request carries `HX-History-Restore-Request: true` and `HX-Request-Type: full`, and no `HX-Request`, `HX-Source` or `Accept`. The missing `HX-Request` already rejects it; this check names the case. 2. `HX-Request-Type: full` -- a swap scoped to the whole document, which is what a boosted navigation asks for. 3. `Sec-Fetch-Mode: navigate` -- a real top-level navigation. htmx never issues one, so this catches a browser prefetch or a proxy replaying `HX-Request`. It is the only signal here that page script cannot forge. The check rejects `full` rather than requiring `partial` on purpose. Requiring it would tie every dual-mode endpoint to one htmx 4 header keeping its name, and the failure would be silent and total: whole pages swapped into the `<div>`s that asked for a fragment. ### Rendering: `_render_hx_fragment(request, template_name, context)` Convenience wrapper that checks `_is_hx_request()` and, when true, renders the fragment template via `render_template_to_response()`. Returns `None` for non-htmx requests, allowing the caller to fall through to full-page rendering. Typical usage: ``` return ( _render_hx_fragment(request, "my_fragment.html.j2", context) or context ) ``` Or, when the htmx context differs from the full-page context: ``` hx = _render_hx_fragment(request, "my_fragment.html.j2", hx_context) if hx: return hx return full_page_context ``` ### `Vary` header `_dispatch_view()` appends `Vary: HX-Request, HX-History-Restore-Request, HX-Request-Type, Sec-Fetch-Mode` to every GET response, fragment and full-page alike. The tokens are the four headers `_is_hx_request()` reads, declared once in `FRAGMENT_REQUEST_HEADERS`, so adding a signal to the decision is one edit rather than two that can drift. Every one of them selects a representation: drop a token and a shared cache may serve a stored fragment to a request that the same URL answers with a whole page. RFC 9111 section 4.1 requires the selecting header fields to be named. ## `_dispatch_view()` pipeline For every UI request (except `direct` routes), `_dispatch_view()` handles the following steps in order: 1. **Request context assembly** -- calls `get_request_context(request)` to load the session and DB handles. 2. **POST body parsing** -- `await request.form()` with configured limits (`max_files=2`, `max_fields=200`, `max_part_size=200MB`). 3. **CSRF enforcement** -- if `require_csrf` is set, validates the token from the form field or `X-CSRF-Token` header against the session token. 4. **`_ViewContext` construction** -- bundles request, session, POST data, path params, and DB handles into a single object passed to the handler. 5. **Primary-instance guard** -- if `require_primary` is set and the instance is not primary, returns a 503 HTML response. 6. **Handler execution** -- `await run_in_threadpool(fn, shim)` runs the sync handler body in the threadpool. 7. **Response passthrough** -- if the handler returns a `Response` (a redirect, an htmx fragment, an `HTMLResponse`), it is returned as is, with the session commit, the HTTP cache headers, and on GET the `Vary` tokens and a default `Cache-Control: no-cache, private`. 8. **Template rendering** -- a `response_status` of 204 returns an empty 204; otherwise, if `renderer` is set, `render_template_to_response()` renders the Jinja2 template with the handler's dict, and a route without a renderer returns an empty 204. 9. **Session commit** -- `commit_session_response()` applies remember/forget flags to the cookie. 10. **HTTP cache headers** -- `apply_http_cache()` sets `Cache-Control` if configured. 11. **Vary header** -- one token per header the fragment decision reads is appended to every GET response (see htmx fragment dispatch above), with a default `Cache-Control: no-cache, private`. 12. **Response headers** -- custom headers from the handler are propagated. ## Session handling ### Storage `FishtestSessionMiddleware` (pure ASGI) manages session persistence. Session data lives in `request.scope["session"]` as a plain dict, wrapped by `CookieSession` for helper access. ### Cookie format - Signed with `itsdangerous.TimestampSigner`. - Cookie name: `fishtest_session`. - Encoding: base64(JSON(session\_data)), signed. - Maximum cookie size: 3800 bytes (enforced; flash messages are trimmed if exceeded). - SameSite: `lax`. Cookie ownership is split intentionally: - `http/settings.py` owns cookie policy values such as size limits and persistence windows. - `http/cookie_session.py` owns the session cookie transport contract such as the cookie name, SameSite default, secret resolution, and request-scope override helpers. - `http/ui_cookies.py` owns browser-readable non-auth UI cookie names, shared low-level parsing helpers, and the raw `Set-Cookie` formatting reused by UI views. ### Session keys | Key | Type | Description | | --- | --- | --- | | `user` | string | Authenticated username | | `csrf_token` | string | CSRF token (generated on first access) | | `flashes` | dict | Flash message queues (`error`, `warning`, default) | | `created_at` | string | ISO timestamp of session creation | | `remember_max_age` | int | Cookie max-age in seconds after a "remember me" login | ### Per-request overrides - `scope["session_max_age"]` -- overrides cookie `Max-Age` (used by "remember me": 400 days, `SESSION_REMEMBER_ME_MAX_AGE_SECONDS`). - `scope["session_secure"]` -- overrides the `Secure` flag. - `scope["session_force_clear"]` -- forces an expired cookie on the response (used by logout). ## Cookie workflow The UI uses two cookie families with different ownership and lifecycles: - **Session/auth cookie** -- `fishtest_session`, emitted by `FishtestSessionMiddleware`. - **UI state cookies** -- lightweight browser-side preferences such as `theme`, `contributors_findme`, `machines_state`, and the homepage workers filters. These non-auth UI cookies use the shared `400 days` max-age policy from `UI_STATE_COOKIE_MAX_AGE_SECONDS` and stay separate from the signed session payload. ### Session cookie lifecycle 1. `FishtestSessionMiddleware` reads `fishtest_session` at request start and decodes the signed JSON payload into `scope["session"]`. 2. `load_session()` wraps that dict in `CookieSession` and sets `created_at` when it is missing; the CSRF token is created on first access. 3. `build_template_context()` calls `session.get_csrf_token()` on every render, pages and fragments alike. The middleware emits `Set-Cookie` whenever the session dict is non-empty, so every `_dispatch_view` response sets the session cookie. 4. On login, `remember()` writes `session["user"]` and optionally stores a persistent max-age marker for "remember me" behavior. 5. On logout, `forget()` clears the session and marks the response to emit an expired cookie. 6. `commit_session_response()` translates those flags into request-scope overrides, and `FishtestSessionMiddleware` finally appends the `Set-Cookie` header on the outbound response. ### UI state cookie lifecycle UI state cookies are intentionally separate from the signed session payload. They are written through shared server or browser helpers because they do not carry authentication state: - `theme` is written through `writeUiCookie()` in `static/js/application.js` and controls light or dark presentation. The same cookie is read during full-page renders so the server can emit the matching theme before first paint. - `login_remember_me` is written by `POST /login` and mirrored by `static/js/application.js` through the shared browser cookie helper when the checkbox changes. It keeps the login form's explicit opt-out state across browser restarts without changing the signed auth-cookie lifetime. - `master_only` is mirrored by the shared checkbox-cookie handler in `static/js/application.js` using `data-ui-cookie-*` attributes from `nns_content_fragment.html.j2`. The `/nns` form also submits an explicit false fallback so unchecked htmx requests do not depend on cookie timing. - `contributors_findme` is written by `static/js/contributors.js` and preserves rank-jump mode across contributors pages. - `machines_state` is written by `static/js/tests_homepage.js` and preserves whether the homepage workers panel is expanded. Opening the panel also triggers an immediate `/tests/machines` refresh instead of waiting for the next periodic poll. - `machines_sort`, `machines_order`, `machines_page`, `machines_q`, and `machines_my_workers` are written server-side through `http/ui_cookies.py` from `views_machines.py` when `/tests/machines` normalizes the current filter state. - `active_run_filters` is written by `static/js/active_run_filters.js` and preserves the Active runs filter selection across the three dimensions (test type, time control, and threads). - `active_run_filters_panel` is written by `static/js/active_run_filters.js` and preserves whether the expandable Active runs filter controls are shown. - `<prefix>pending_state`, `<prefix>paused_state`, `<prefix>failed_state`, `<prefix>active_state` and `<prefix>finished_state` are written by the toggle handler in `static/js/application.js` and preserve which run-table panels are collapsed. - `live_elo_mode` is written by `static/js/live_elo.js` and preserves the Elo gauge mode. - `spsa_percentage` is mirrored by the shared checkbox-cookie handler from the `% c` checkbox of the SPSA section. - `tasks_state` preserves whether the tasks panel of the detail page is collapsed; `tasks_sort`, `tasks_order`, `tasks_view` and `tasks_q` are written server-side when `/tests/tasks/{id}` normalizes its controls. This split keeps auth/session semantics on the server-controlled signed cookie while letting low-risk UI preferences remain simple, readable browser state. ## CSRF protection - A token is generated per session on first access (`CookieSession.get_csrf_token()`). - Validated on every UI POST when `require_csrf` is set in the route config. - The token can be submitted as: - A form field `csrf_token`. - An HTTP header `X-CSRF-Token`. - Validation uses `secrets.compare_digest()` for timing-safe comparison. - Failure raises HTTP 403. ## Authentication ### Login flow 1. `GET /login` renders the Remember me checkbox checked by default. 2. If the `login_remember_me` UI cookie stores an explicit opt-out, the same page renders the checkbox unchecked on later visits. 3. User submits username/password to `POST /login`. 4. `UserDb.authenticate()` validates credentials. 5. On success, `remember(request, username)` sets `session["user"]`. 6. Checked Remember me emits a persistent signed session cookie using the shared remember-me lifetime. Unchecked login keeps the auth cookie scoped to the current browser session. 7. `POST /login` also refreshes `login_remember_me` so the user's explicit checkbox choice survives later browser starts. 8. Redirect to the `next` parameter, else the `came_from` parameter, else the current URL (`/` when that is the login page itself). ### Logout flow 1. `POST /logout` calls `forget(request)`. 2. Session dict is cleared and `session_force_clear` is set. 3. Redirect to `/tests`. ### Access control - `ensure_logged_in(request)` checks `session["user"]`. If absent, redirects to `/login` with a flash message. - Group-based authorization: `userdb.get_user_groups(username)` returns group memberships. The `has_permission("approve_run")` method checks for `"group:approvers"`. ## URL generation - Templates write route paths literally and read `request.url` where they need the current address; no route carries a `name=`, and no template calls `url_for`. - `static_url(path)` maps to `/static/{path}` with a cache-busting query parameter (SHA-384 hash of file content). - Navigation URLs are provided as a `urls` dict in the base template context. ## Navigation behavior - The sidebar `Users` link shows `Users (N)` when `N` users are pending approval. - With JavaScript enabled, that link refreshes its pending-user count periodically while the tab is visible and refreshes again when the tab becomes visible via `visibilitychange`. - The sidebar `GitHub Rate Limits` link keeps its text fixed and reflects the browser-side GitHub client budget used by pages that read the token from local storage. - When the client budget falls below the current warning threshold, the link switches to the same red status styling used by the pending-users sidebar item. - The sidebar reuses the last known client warning state from local storage on first paint, so page navigation does not flash the link back to its normal color before the client poll completes. - The browser-side GitHub poll runs on every page that renders the sidebar, pauses while the tab is hidden, refreshes immediately on `visibilitychange`, window `focus`, and bfcache `pageshow`, and then resumes its normal cadence from that activation point. - When JavaScript is unavailable, the same link still works as normal navigation and the count refreshes on the next full-page render. ## Adding a new UI route 1. Write a sync handler function that receives a `_ViewContext` and returns either a dict (for template rendering) or a `RedirectResponse`. 2. Add an entry to `_VIEW_ROUTES`: ``` (my_handler, "/my/path", {"renderer": "mypage.html.j2", "require_csrf": True}) ``` 3. Create the Jinja2 template in `templates/`. 4. Add a contract test in the route family's `tests/test_views_*.py` module (for example `test_views_actions.py`), and the route's methods in `test_views_routes.py`. ## Homepage workers (`/tests/machines`) query parameters The homepage workers fragment (`/tests/machines`) supports URL-driven state for server sorting, paging, and lightweight filtering. | Parameter | Values | Default | | --- | --- | --- | | `sort` | `last_active`, `machine`, `cores`, `uuid`, `mnps`, `ram`, `system`, `arch`, `compiler`, `python`, `worker`, `running_on` | `last_active` | | `order` | `asc`, `desc` | column default | | `page` | integer `>= 1` | `1` | | `q` | free-text filter matched against any displayed machine column | empty | | `my_workers` | `1`, `true`, `on`, `yes` | absent/false | Behavior notes: - Sorting is server-authoritative and stable with username asc tie-breaks. - Pagination is enabled with page size `500`; links are omitted for one-page result sets. - `my_workers` only applies for authenticated users; anonymous requests ignore this filter. - `q` performs case-insensitive substring matching across all displayed table columns (machine, cores, UUID, MNps, RAM, system, arch, compiler, python, worker, running-on, and last-active text). - Polling includes the current homepage filter-form state (`hx-include`), so sort/filter/page settings persist across periodic refreshes, including while the `q` search filter remains active. - Filter controls (`q`, `my_workers`) are rendered on `/tests` outside the swapped machines fragment to avoid input focus/caret glitches during table refresh swaps. - `/tests/machines` responses persist the effective `sort`, `order`, `page`, `q`, and `my_workers` values in cookies, so returning to `/tests` restores the last machines filter state. - Workers counter semantics are stable across `/tests`, `/tests/machines`, and the page-1 `/tests?live=run_tables` OOB updates: - no active filters: `Workers - <total>` - active `q` and/or `my_workers`: `Workers - <total> (<filtered>)` - When workers filters are active and the Workers panel is collapsed, `/tests` and its page-1 live run-table fragment recompute the filtered value from the current machine snapshot instead of reusing the last cookie-backed filtered count. - Machines sorting is fully server-authoritative; there is no client-side header sorter. ## Active runs type filter The Active runs panel on `/tests` provides client-side checkboxes for filtering visible runs. The controls use a compact ellipsis toggle plus three independent dimensions matching the new-test submission page: | Dimension | Checkboxes | Classification | | --- | --- | --- | | Test type | SPRT, SPSA, NumGames | `spsa` if SPSA params present; `sprt` if SPRT bounds present; `numgames` otherwise | | Time control | STC, LTC | `get_tc_ratio(tc, threads) > 4` → LTC; else STC | | Threads | ST, SMP | `threads > 1` → SMP; else ST | An "All" master checkbox checks or unchecks all dimension checkboxes. Filtering uses AND between dimensions and OR within each dimension: a row is visible when it matches at least one checked value in **every** dimension. Behavior notes: - Each table row carries three `data-*` attributes (`data-test-type`, `data-time-control`, `data-threads`) with a single value per dimension, computed by the server template. - After the page is loaded, filtering remains client-side and uses those server-rendered attributes. - The filter controls sit inside the Active panel's collapse section (matching the workers table filter placement). - The Active filter bar remains visible even when there are zero active runs, so users can inspect or change persisted filter state before new runs appear. - The ellipsis toggle shows or hides the filter controls without leaving the Active panel. - Checkboxes are grouped by dimension with small text labels (Type, TC, Threads). On desktop the controls stay on one inline row. On mobile the ellipsis stays pinned at the left while the filter grid opens beside it, with the All checkbox on the first row and aligned checkbox columns. - The "All" checkbox uses the indeterminate state when some (but not all) checkboxes are checked. - The Active header keeps parentheses whenever a non-`All` filter state is active, even when the filtered count equals the total. Parentheses disappear only when the effective filter state is truly `All`. - The panel header count updates to show both total and filtered counts when a filter is active: "Active - N (M) tests". - Filter state is persisted in the `active_run_filters` cookie using the shared long-lived UI-cookie policy (`path=/`, `SameSite=Lax`). When all checkboxes are checked the cookie is cleared. - On page reload, `/tests` restores the cookie-backed filter state in the first HTML response, including the checkbox state, filtered count text, and initial row-hide CSS. Hidden categories therefore do not flash briefly before the browser restores the filter logic. - Active-row zebra striping follows the same visible-row pattern as the other filtered tables. The Active filter logic keeps the visible rows contiguous in tbody order, so the normal alternating darker or lighter `table-striped` pattern stays correct after checkbox changes and after homepage polling replaces the Active tbody. The striping contract does not depend on hidden categories retaining their original sibling positions. - Clearing every checkbox persists as an explicit empty selection, so reloads keep the Active panel empty until categories are enabled again. - The filter panel open/closed state is persisted in the `active_run_filters_panel` cookie. - Filters are re-applied after htmx OOB swap updates to the active runs tbody, so periodic poll refreshes respect the current filter state. - Notification bell buttons initialize from browser-local follow state after page load and stay hidden until that state is known, which avoids transient wrong bell icons during reload. ## User management (`/user_management`) query parameters The user-management page supports URL-driven server-authoritative table state. | Parameter | Values | Default | | --- | --- | --- | | `group` | `all`, `pending`, `blocked`, `idle`, `approvers` | `pending` | | `sort` | `username`, `registration`, `groups`, `email` | `registration` | | `order` | `asc`, `desc` | column default | | `page` | integer `>= 1` | `1` | | `q` | free-text filter matched against username column | empty | | `view` | `paged`, `all` | `paged` | Behavior notes: - Sorting is server-authoritative and stable with username tie-breaks. - Pagination uses page size `25` in paged view. - `view=all` returns all matching rows up to a hard cap (`5000`) and hides pagination controls. - `q` performs case-insensitive substring matching on username only. - User-management filtering stays on the userdb path: the base list comes from `request.userdb.get_users()`, while pending/blocked subsets come from the cached `get_pending()` / `get_blocked()` helpers. - htmx requests target `#user-management-content` and keep URL state via `hx-push-url="true"`. - The outer GET form keeps `sort`, `order`, and `view` in hidden inputs. htmx fragment responses refresh those hidden inputs out of band so later group or filter changes preserve the current table state. - Table sorting is fully server-authoritative; there is no client-side header sorter. ## Workers management (`/workers/show`) query parameters The blocked-workers table supports URL-driven server-authoritative state. | Parameter | Values | Default | | --- | --- | --- | | `filter` | `all-workers`, `le-5days`, `gt-5days` | `le-5days` | | `sort` | `worker`, `last_changed`, `events`, `email` | `last_changed` | | `order` | `asc`, `desc` | column default | | `page` | integer `>= 1` | `1` | | `q` | free-text filter matched against worker column | empty | | `view` | `paged`, `all` | `paged` | Behavior notes: - `filter` keeps the server-side time-window behavior. - Sorting is server-authoritative and stable with worker-name tie-breaks. - Pagination uses page size `25` in paged view. - `view=all` returns all matching rows up to a hard cap (`5000`) and hides pagination controls. - `q` performs case-insensitive substring matching on worker name only. - Non-approver users cannot sort by `email`; unsupported values fall back to default server sort. - htmx requests target `#workers-content` and keep URL state via `hx-push-url="true"`. - Sort-header links are dual-mode (`href` + `hx-get`): workers sorting swaps `#workers-content` with `hx-push-url="true"` when htmx is active, and still degrades to full-page navigation. - The outer GET form keeps `sort`, `order`, and `view` in hidden inputs. htmx fragment responses refresh those hidden inputs out of band so later filter changes preserve the current table state. - Table sorting is fully server-authoritative; there is no client-side header sorter. ## Contributors query parameters The contributors pages (`/contributors` and `/contributors/monthly`) support URL-driven state for server sorting, search, paging, full view, and rank jump. | Parameter | Values | Default | | --- | --- | --- | | `search` | one-shot go-to query (exact username first, then first substring match) | empty | | `sort` | `cpu_hours`, `username`, `last_updated`, `games_per_hour`, `games`, `tests`, `tests_repo` | `cpu_hours` | | `order` | `asc`, `desc` | column default | | `page` | integer `>= 1` | `1` | | `view` | `paged`, `all` | `paged` | | `findme` | any non-empty value (`findme=0` included) | absent | | `highlight` | username | empty | Behavior notes: - Sorting is server-authoritative and stable with username asc tie-breaks. - Rank is global for the filtered+sorted dataset (not page-local loop index). - `findme=1` redirects authenticated users to the page containing their row and sets `highlight=<username>#me`. - `view=all` returns all rows up to a hard cap (`5000`) and hides pagination. - `search` is consumed as one-shot navigation intent and is not preserved in pagination/sort/view links, preventing repeated jumps during later browsing. - `/contributors` and `/contributors/monthly` stay on the userdb fast path: the all-time page reads from `userdb.user_cache`, and the monthly page reads from `userdb.top_month`, a rolling cache rebuilt from unfinished runs (pending and active) plus finished runs started within the last 30 days. - Sort-header links are dual-mode (`href` + `hx-get`): contributors sorting swaps `#contributors-content` with `hx-push-url="true"` when htmx is active, and still works as normal navigation when JavaScript is unavailable. - The outer search form keeps `sort`, `order`, and `view` as hidden inputs. htmx fragment responses refresh those inputs out of band so later search or rank-jump requests do not replay stale table state. ## Neural networks (`/nns`) query parameters The neural network repository page (`/nns`) supports URL-driven state for search and paging. | Parameter | Values | Default | | --- | --- | --- | | `network_name` | literal network name substring (case-insensitive) | empty | | `user` | literal uploader username substring (case-insensitive) | empty | | `master_only` | `1`, `true`, `on`, `yes` | absent/false | | `sort` | `time`, `name`, `user`, `first_test`, `last_test`, `downloads` | `time` | | `order` | `asc`, `desc` | `desc` | | `view` | `paged`, `all` | `paged` | | `page` | integer `>= 1` | `1` | Behavior notes: - The page renders four summary cards above the table for the current filtered result set: Nets, Master nets, Contributors, and Downloads. - The explanatory CC0 and default-net copy is rendered under the summary cards and above the paged or all view controls. - Sorting is server-authoritative and deterministic. - Sort-header links are dual-mode (`href` + `hx-get`): sorting swaps `#nns-content` with `hx-push-url="true"` when htmx is active, with plain-link fallback preserved. - Pagination links follow the same dual-mode contract. - Search inputs are htmx-triggered (`input changed delay`) and also support explicit submit for keyboard and non-JS flows. - `network_name` and `user` are treated as literal substring filters; regex metacharacters have no special meaning. - htmx updates target `#nns-content` and push updated query URLs for back/forward and shareable links. - The filter form is rendered inside `#nns-content`, under the explanatory copy and above the paged or all switch, so htmx responses keep the full page order aligned with the other card pages: cards, text, filters, view switch, pagination, table, pagination. - `master_only` checkbox preference is persisted in a cookie and reused when the query parameter is not present. The form also submits an explicit false fallback so unchecked htmx requests and cookie persistence stay aligned. - Table sorting is fully server-authoritative; there is no client-side header sorter. ## Actions (`/actions`) query parameters The actions log supports URL-driven server-authoritative filtering, paging, and sort state on the canonical `/actions` route. | Parameter | Values | Default | | --- | --- | --- | | `action` | action name filter | empty | | `user` | username substring | empty | | `text` | Mongo text-search query | empty | | `run_id` | run id | empty | | `page` | integer `>= 1` | `1` | | `max_count` | positive integer, capped by auth state | route policy | | `sort` | `time`, `event`, `source`, `target`, `comment` | `time` | | `order` | `asc`, `desc` | `desc` for `time`, otherwise column default | | `before` | action timestamp cursor for time-link deep links | absent | Behavior notes: - Sorting is server-authoritative. The default `time desc` path stays on the indexed fast query; explicit alternate sorts materialize and sort the capped working set server-side. - Anonymous requests are capped at `5000` actions. Authenticated requests without an explicit `max_count` default to `50000`; explicit `max_count` values are preserved in the URL and hidden form state. - htmx requests target `#actions-content` and keep URL state via `hx-push-url="true"`. - The visible filters auto-submit on select change and search/input events. - The username field follows the same pattern as the other username filters in the UI: it is a plain `<input type="search">` in the main `/actions` GET form. - `user` matches case-insensitive username substrings, not only exact names. - When multiple usernames match a fragment, prefix matches are ranked before inner-substring matches, and ties stay recent-first within each username. - Typing pauses trigger the existing debounced htmx form request, so results refresh from `GET /actions?...` without a separate suggestions endpoint, popup, or second swap target. - To keep that debounced path fast on large historical logs, `/actions` resolves substring matches from a short-lived cached distinct username list built from the actions collection, refreshes it once on a no-match lookup, then fetches the matching rows by exact username query while keeping the active `action`, `text`, `run_id`, and time-cursor filters applied on each exact-username fetch. This differs from `/contributors` and `/user_management`, which can stay on userdb-backed sources because they only need current user records. - The summary line reports both the visible row count on the current page and the total matching row count, so pagination does not imply every match is currently rendered. - The time link remains a normal anchor because it is a shareable deep link into the log timeline, not just a local fragment action. - Full-page `/actions` responses emit server-owned Open Graph metadata. Unlike `/tests/view/{id}`, the preview keeps the current query string in `og:url` because the filters, time cursor, and explicit `max_count` define the shared log slice; the title and description summarize the first visible action row. ## Finished Tests (`/tests/finished`) query parameters The finished tests page supports URL-driven server-authoritative filtering, pagination, and htmx fragment refresh on the canonical `/tests/finished` route. | Parameter | Values | Default | | --- | --- | --- | | `success_only` | `1` to show green results only | absent | | `yellow_only` | `1` to show yellow results only | absent | | `ltc_only` | `1` to show LTC results only | absent | | `sort` | `time` | `time` | | `order` | `desc` | `desc` | | `user` | case-insensitive username substring | empty | | `text` | text search on the run info; `info_regex` is read as an alias | empty | | `mode` | `search` for the search form, which ignores the three filters above | absent | | `max_count` | positive integer, capped by auth state | route policy | | `page` | integer `>= 1` | `1` | Behavior notes: - htmx requests target `#tests-finished-content` and keep URL state via `hx-push-url="true"`. - Finished tests currently use a fixed recent-first order, but still carry the explicit `sort=time` and `order=desc` query parameters so the URL contract stays aligned with the actions page. - htmx tab clicks refresh the results target directly and refresh the tab strip out of band so the active-tab styling stays aligned with the pushed URL. - The username input auto-submits on debounced input and native search clear events. - The run-info text-search input auto-submits on debounced input and native search clear events. - In search mode, the username and free-text fields rely on the shared Bootstrap grid sizing used by the other standalone filter pages. The page does not apply a dedicated width override to the free-text control. - `user` resolves case-insensitive username substrings from a short-lived cached username list on the users collection, then queries the matching usernames through the exact-username finished-run path. - When multiple usernames match a fragment, prefix matches are ranked before inner-substring matches, and ties stay recent-first within each username. - Finished rows without a usable `last_updated` value sort after timestamped rows in the merged recent-first result, and equal fallback rows stay stable by run id. - `text` alone runs a MongoDB `$text` query against the run info of finished runs. With a `user` filter it runs a case-insensitive `$regex` on `args.info` instead, so the username index serves the query. - `/actions` and `/tests/finished` share the same `max_count` query parameter for result caps. `/tests/user/{username}` applies no cap: it carries no filter, so a `max_count` there is stripped by redirect. - Anonymous search requests use the anonymous finished-run search cap. Authenticated search requests use the authenticated finished-run default. Explicit `max_count` values are preserved in the URL and hidden form state. - Navigation mode (no filters active) is uncapped — `max_count` is not used. - Stale `max_count` values in navigation-mode URLs are stripped via redirect. - The summary line reports both the visible row count on the current page and the total matching finished-run count. Deleted runs are excluded from both the displayed rows and the total count. - Oversized `max_count` values are clamped to MongoDB's signed 64-bit integer range before they reach pymongo. # Jinja2 Templates ## Environment configuration | Setting | Value | | --- | --- | | Templates directory | `server/fishtest/templates/` | | File extension | `.html.j2` | | Autoescape | Enabled for HTML, XML, and `.j2` files | | Undefined behavior | `StrictUndefined` (missing variables raise errors) | | Extensions | `jinja2.ext.do` | | Instance | Single `Environment` built by `http/jinja.py` on the first render (`_jinja_templates()` in `http/template_renderer.py` is cached) | Custom filters and global functions are registered via `http/template_helpers.py` and `http/jinja.py`. ### Custom filters | Filter | Description | | --- | --- | | `urlencode` | URL-encodes a value (`quote_plus`) | | `split` | Splits a string (`str.split`) | | `string` | Converts to string (`str()`) | ### Global functions | Global | Source | Description | | --- | --- | --- | | `static_url(path)` | `http/jinja.py` | Static asset URL with cache-buster token | | `diff_url(...)` | `util.py` | GitHub diff URL builder | | `format_bounds(...)` | `util.py` | SPRT bounds formatter | | `format_date(dt)` | `util.py` | Date formatter | | `format_group(groups)` | `util.py` | User group label formatter | | `format_results(...)` | `util.py` | Game results formatter | | `format_time_ago(dt)` | `util.py` | Relative time formatter | | `display_residual(r)` | `util.py` | Chi-squared residual display | | `is_active_sprt_ltc(run)` | `util.py` | Checks if run is active SPRT LTC | | `is_elo_pentanomial_run(run)` | `template_helpers.py` | Checks pentanomial display | | `nelo_pentanomial_summary(...)` | `template_helpers.py` | Pentanomial ELO summary (returns `Markup`) | | `results_pre_attrs(...)` | `template_helpers.py` | HTML attributes for results display (returns `Markup`) | | `run_tables_prefix(username)` | `template_helpers.py` | Toggle prefix for run tables | | `tests_run_setup(...)` | `template_helpers.py` | Test form default values | | `tests_repo(run)` | `util.py` | Extract the canonical tests repo URL from run | | `get_tc_ratio(...)` | `util.py` | Time control ratio of a run | | `worker_name(info)` | `util.py` | Format worker name from info dict | | `list_to_string(values, decimals)` | `template_helpers.py` | Formats a list of floats as a string | | `pdf_to_string(...)` | `template_helpers.py` | Formats a probability density function | | `t_conf(...)` | `template_helpers.py` | Confidence interval formatting | | `poll` | `http/jinja.py` | Shared htmx polling intervals exposed to templates | | `finished` | `http/jinja.py` | Finished-run result caps (`filter_max_count_anon`, `filter_max_count_auth`) | | `htmx` | `http/jinja.py` | Shared htmx timing defaults exposed to templates | | `cookies` | `http/jinja.py` | Shared cookie max-age values for page scripts/templates | | `fishtest` | `fishtest` package | Package module (version, metadata) | | `gh` | `github_api.py` | GitHub API module (commit\_url, etc.) | | `math`, `datetime`, `copy`, `float` | Python stdlib | Standard library access | | `urllib` | Python stdlib | `urllib.parse` | ## Rendering flow 1. The view handler returns a context dict; the template is the route's `renderer` in `_VIEW_ROUTES`. 2. `_dispatch_view()` calls `render_template_to_response()` in the threadpool. 3. `build_template_context()` in `http/boundary.py` constructs the shared base context (CSRF token, current user, flash messages, navigation URLs). 4. The handler-specific context is merged with the base context. 5. `Jinja2Templates.TemplateResponse(request, name, context)` renders the template and returns an HTML response. 6. Rendering is synchronous and executes in the threadpool. ## Shared base context Every template receives these keys from `build_template_context()`: | Key | Type | Description | | --- | --- | --- | | `request` | `Request` | Starlette request object (templates read `request.url`) | | `csrf_token` | string | CSRF token for forms and meta tags | | `current_user` | `{"username": str}` or `None` | Authenticated user | | `open_graph` | dict | Server-owned Open Graph fields rendered by `base.html.j2` | | `theme` | string | `"dark"`, `"light"`, or empty (from cookie) | | `theme_color` | string or `None` | Optional `theme-color` meta value rendered by `base.html.j2` | | `pending_users_count` | int | Pending-user count used by the sidebar `Users` link | | `static_url` | callable | `static_url(path)` function | | `flash` | dict | `{"error": [...], "warning": [...], "info": [...]}` | | `urls` | dict | Navigation URLs (see below) | ## Page metadata contract `base.html.j2` renders the page head from shared context. Full-page handlers may override these keys: - `open_graph`: dictionary with `site_name`, `type`, `title`, `description`, and `url` - `theme_color`: CSS color string or `None` For `/tests/view/{id}`, `open_graph['description']` is plain multi-line text so Discord link previews preserve the run summary layout, including pentanomial lines when present, without shipping literal backticks. For `/actions`, the full page overrides `open_graph` with the first visible action row. Its `og:url` keeps the current query string because filters, timeline cursors, and explicit `max_count` values define the shared events-log slice. Fragment-only templates do not own page-head metadata. The `/tests/view/{id}` detail page follows this rule: the full page renders the head tags, while the live `/tests/view/{id}/detail` fragment updates body content only. `actions_content_fragment.html.j2` follows the same rule: the full `/actions` page owns the Open Graph tags, while the htmx fragment updates only `#actions-content`. ### Navigation URLs (`urls` dict) ``` { "home": "/", "login": "/login", "logout": "/logout", "signup": "/signup", "user_profile": "/user", "tests": "/tests", "tests_finished": "/tests/finished", "tests_run": "/tests/run", "tests_user_prefix": "/tests/user/", "tests_machines": "/tests/machines", "nn_upload": "/upload", "nns": "/nns", "contributors": "/contributors", "contributors_monthly": "/contributors/monthly", "actions": "/actions", "user_management": "/user_management", "workers_blocked": "/workers/show", "sprt_calc": "/sprt_calc", "rate_limits": "/rate_limits", "api_rate_limit": "/api/rate_limit", } ``` ### Shared sidebar status links - `base.html.j2` includes `pending_users_nav_fragment.html.j2` inside a stable htmx poll wrapper. The wrapper owns the `load` and `every` triggers, while the fragment owns only the rendered anchor HTML and current count markup. - `base.html.j2` renders the sidebar `GitHub Rate Limits` anchor directly. `static/js/application.js` updates that link, not a server fragment endpoint, because the browser-side GitHub token lives in local storage and is not part of server session state. - `rate_limits.html.j2` exposes the same browser-side client poll cadence via `data-poll-seconds` on `#client_rate_limit`, so the page row and the sidebar link read the same client limit state. ## Client-side behavior pattern Behavior-heavy page scripts should prefer static assets plus `data-*` configuration over large inline `<script>` blocks. Current examples: - `contributors.html.j2` -\> `static/js/contributors.js` - `tests.html.j2` -\> `static/js/tests_homepage.js` - `user.html.j2` (profile mode) -\> `static/js/user_profile.js` `tests_homepage.js` owns the homepage Workers panel cookie state and triggers an immediate `machines:load` refresh whenever Bootstrap reports that the panel has been opened. Shared behavior that spans multiple pages belongs in shared assets instead of page-local inline scripts. Search/filter inputs remain plain `<input type="search">` controls, and any shared behavior or styling should live in shared assets instead of page-local inline scripts. This keeps templates focused on structure and server-provided state, aligns with MDN separation-of-concerns guidance, and makes the JS contract testable without embedding implementation details in the template body. ## Sortable table accessibility baseline Seven content-fragment templates define inline `sort_header` Jinja2 macros for sortable data tables. All sortable tables must satisfy: 1. **`scope="col"`** on every `<th>` in `<thead>` (including non-sortable column headers like the `#` row number). Helps assistive technologies associate headers with data cells. 2. **`<caption class="visually-hidden">`** as the first child of each `<table>`. Provides a programmatic name for the table so screen readers can announce it before reading cells. 3. **`class="sticky-top"`** on `<thead>` so column headers remain visible when scrolling long tables. 4. **`aria-sort`** only on the currently active sort column header. Values: `ascending` or `descending`. 5. **`aria-hidden="true"`** on the decorative sort-indicator icon span. Templates that follow this contract: | Template | Table ID | Caption text | | --- | --- | --- | | `actions_content_fragment.html.j2` | `actions_table` | Events log results | | `contributors_content_fragment.html.j2` | `contributors_table` | Contributors | | `machines_fragment.html.j2` | `machines_table` | Machines | | `nns_content_fragment.html.j2` | `nns_table` | Neural networks | | `tasks_content_fragment.html.j2` | `tasks_table` | Tasks | | `user_management_content_fragment.html.j2` | `user_management_table` | User management | | `workers_content_fragment.html.j2` | `workers_table` | Workers | Regression tests in `test_http_boundary.py` enforce `scope="col"`, `visually-hidden` caption, and `sticky-top` on `<thead>` for all seven templates. ### Filter and cookie consistency The seven sortable tables split into two architectural patterns that determine their filter form and state-persistence behavior: | Pattern | Pages | Filters | Cookie persistence | Polling | | --- | --- | --- | --- | --- | | **A** (standalone) | contributors, actions, workers, user\_management, nns | `form-control` (full-size) | 0-1 client-side cookies | none | | **B** (embedded panel) | machines, tasks | `form-control-sm` | 4-6 server-side cookies | 60 s | Design rules: - **No custom width overrides** on filter inputs. Let `col-md-auto` size fields naturally across all standalone pages. - This rule also applies to `/tests/finished?mode=search`: its username and free-text controls should size through the shared grid layout, not through a page-specific CSS minimum width. - **`autocomplete="off"`** on search/filter text inputs prevents browser autofill from interfering with htmx-driven filtering. The `/actions` username and text inputs and the `/tests/finished` search inputs do not carry it. - **Cookie max-age** must use `UI_STATE_COOKIE_MAX_AGE_SECONDS` from `settings.py`, never hardcoded values. Client-side cookies must flow through the shared `writeUiCookie()` helper in `application.js` or through template `data-*` attributes consumed by that helper. This is the single max-age owner for non-auth UI cookies; templates should expose `cookies.ui_state_max_age` or a page-specific `cookie_max_age` context instead of introducing literals. `cookies.contributors_findme_max_age` is the one other alias. Known limitations: - Workers and user\_management have zero cookie persistence for filter/sort state (user resets to defaults on page reload). - Contributors has one client-side cookie (`contributors_findme`, the rank-jump mode) but no filter-state cookies. ## Template catalog The live template inventory contains **54** Jinja templates: - **1** base layout template - **19** full-page templates that extend `base.html.j2` - **34** non-base templates used as htmx fragments or shared partials ### Base layout template | Template | Purpose | | --- | --- | | `base.html.j2` | Base layout (navbar, footer, page-head metadata, asset loading, htmx CDN, pending-user nav poll target) | ### Full-page templates (extend `base.html.j2`) | Template | Purpose | | --- | --- | | `actions.html.j2` | Paginated action log | | `contributors.html.j2` | Contributor leaderboard (all-time and monthly) | | `login.html.j2` | Login form | | `nn_upload.html.j2` | Neural network upload form | | `nns.html.j2` | Neural network listing with pagination | | `notfound.html.j2` | 404 error page | | `rate_limits.html.j2` | API rate limit information page | | `signup.html.j2` | User registration form | | `sprt_calc.html.j2` | SPRT calculator page | | `tests.html.j2` | Main tests dashboard | | `tests_finished.html.j2` | Finished tests listing with filters | | `tests_live_elo.html.j2` | Live ELO chart page | | `tests_run.html.j2` | New test / rerun submission form | | `tests_stats.html.j2` | Raw statistics page shell with visibility-aware poller | | `tests_user.html.j2` | Per-user test listing | | `tests_view.html.j2` | Single test detail page | | `user.html.j2` | User profile page | | `user_management.html.j2` | User administration page | | `workers.html.j2` | Worker blocking administration page | ### Non-base templates These templates do not extend the base layout. Some are direct htmx response fragments; others are shared partials included by page or fragment templates. | Template | Kind | Primary use | | --- | --- | --- | | `actions_content_fragment.html.j2` | htmx content fragment | Swaps `#actions-content` | | `active_run_filters_fragment.html.j2` | shared controls partial | Included by `run_table.html.j2` through `filters_template` for the Active panel | | `contributors_content_fragment.html.j2` | htmx content fragment | Swaps `#contributors-content`; includes hidden-input OOB sync | | `contributors_rows_fragment.html.j2` | shared row partial | Included by `contributors_content_fragment.html.j2` | | `tests_run_tables_fragment.html.j2` | OOB poll fragment | Shared run-table OOB payload for `/tests?live=run_tables` and `/tests/user/{username}?live=run_tables` | | `elo_results.html.j2` | shared display partial | Included where ELO summary markup is rendered | | `elo_results_fragment.html.j2` | shared OOB partial | Included by `tests_view_detail_fragment.html.j2` for live ELO summary, status, and task-total updates | | `homepage_stats_fragment.html.j2` | OOB summary fragment | Updates homepage stat targets | | `live_elo_fragment.html.j2` | OOB poll fragment | Poll response for live ELO page updates | | `machines_fragment.html.j2` | htmx content fragment | Swaps `#machines` and updates `#workers-count` OOB | | `nns_content_fragment.html.j2` | htmx content fragment | Swaps `#nns-content` | | `pagination.html.j2` | shared pagination partial | Included by paginated pages and fragments | | `pending_users_nav_fragment.html.j2` | shared nav anchor fragment | Included server-side in `base.html.j2` and returned by `/user_management/pending_count` to refresh `#pending-users-nav` | | `poll_stop_fragment.html.j2` | shared OOB partial | Renders `<div id="{poller_id}" hx-swap-oob="delete">`; included by a terminal poll response to remove its driver element and stop the poll | | `run_table.html.j2` | shared table partial | Renders one run table shell and includes row markup | | `run_table_row_fragment.html.j2` | row fragment | Renders `<tr>` rows; included by `run_table.html.j2`, and by `tests_run_tables_fragment.html.j2` inside the `<template id="<panel>-tbody" hx-swap-oob="innerHTML">` wrappers | | `run_tables.html.j2` | shared table-group partial | Composes pending, active, and finished run tables | | `tasks_content_fragment.html.j2` | htmx content fragment | Swaps `#tasks-content` and updates controls/pagination OOB | | `tasks_controls_fragment.html.j2` | shared controls partial | Included by `tests_view.html.j2` and reused in OOB updates | | `tasks_rows_fragment.html.j2` | shared row partial | Included by `tasks_content_fragment.html.j2` | | `tests_filter_tabs_fragment.html.j2` | shared navigation partial | Renders test-mode tabs for caller-defined targets | | `tests_finished_content_fragment.html.j2` | shared full-page partial | Included by `tests_finished.html.j2` | | `tests_finished_results_fragment.html.j2` | htmx results fragment | Swaps `#tests-finished-content`; can update tab wrapper OOB | | `tests_stats_content_fragment.html.j2` | polled content fragment | Swaps `#tests-stats-content` | | `tests_view_detail_fragment.html.j2` | OOB poll fragment | Poll response for live detail-page summary + detail updates | | `tests_view_details_section.html.j2` | shared detail partial | Included by `tests_view.html.j2` and `tests_view_detail_fragment.html.j2` | | `tests_view_spsa_section.html.j2` | shared SPSA partial | Included by `tests_view.html.j2` | | `tests_view_stats_section.html.j2` | shared stats partial | Included by `tests_view.html.j2` and `tests_view_detail_fragment.html.j2` | | `tests_view_time_section.html.j2` | shared time partial | Included by `tests_view.html.j2` and `tests_view_detail_fragment.html.j2` | | `tests_user_content_fragment.html.j2` | htmx content fragment | Swaps `#tests-user-content` | | `user_management_content_fragment.html.j2` | htmx content fragment | Swaps `#user-management-content`; includes hidden-input OOB sync | | `user_management_rows_fragment.html.j2` | shared row partial | Included by `user_management_content_fragment.html.j2` | | `workers_content_fragment.html.j2` | htmx content fragment | Swaps `#workers-content`; includes hidden-input OOB sync | | `workers_rows_fragment.html.j2` | shared row partial | Included by `workers_content_fragment.html.j2` | Column notes: - **htmx content fragment**: returned as the main swap payload for a target. - **OOB / poll fragment**: returned for out-of-band updates, often on timers. - **shared partial**: included by another template rather than rendered as the top-level response body. ## Context contracts Each template has an explicit context contract documenting the required keys. Templates do not fetch data; views provide fully shaped context. ### `base.html.j2` Uses shared base context only. All other templates extend this. ### `actions.html.j2` | Key | Type | Description | | --- | --- | --- | | `actions` | list of dicts | Action rows (see below) | | `visible_actions` | int | Action rows rendered on the current page | | `num_actions` | int | Total matching action count | | `page_size` | int | Page size used for the current result set | | `current_page` | int | 1-based page index rendered in the summary | | `run_id_filter` | string | Active run filter, if the page is scoped to one run | | `max_count` | int or None | Effective server-side action cap carried through GET forms | | `sort` | string | Active sort field (`time`, `event`, `source`, `target`, `comment`) | | `order` | string | Active sort direction (`asc` or `desc`) | | `sort_summary` | string | Optional summary line describing capped full-result sorting scope | | `filters` | dict | `{action, username, text, run_id}` | | `pages` | list | Pagination items | Each action row: | Key | Type | | --- | --- | | `time_label` | string (preformatted) | | `time_url` | string | | `event` | string | | `agent_name` | string | | `agent_url` | string or None | | `target_name` | string | | `target_url` | string or None | | `message` | string | Full-page `/actions` responses may override the shared `open_graph` metadata with a summary of the first visible action row. htmx fragment responses do not render page-head tags. ### `contributors.html.j2` | Key | Type | Description | | --- | --- | --- | | `is_monthly` | bool | Monthly vs all-time view | | `is_approver` | bool | Current user is approver | | `summary` | dict | `{testers, developers, active_testers, cpu_hours, games, tests}`; the template derives the CPU years | | `users` | list of dicts | Contributor rows (current page) | | `pages` | list | Pagination items | | `search` | string | Active search query | | `sort` | string | Active server sort field | | `order` | string | Active sort direction | | `view` | string | `paged` or `all` | | `highlight` | string | Highlighted username, usually set by `findme` redirects | | `is_truncated` | bool | Whether `view=all` was capped | | `num_users` | int | Total filtered row count before paging/cap | | `max_all` | int | Hard cap used for `view=all` | Each contributor row: `username`, `user_url`, `rank`, `last_updated_label`, `last_updated_sort`, `games_per_hour`, `cpu_hours`, `games`, `tests`, `tests_repo_url`, `tests_user_url`. ### `elo_results.html.j2` Included as a partial within run display templates. | Key | Type | Description | | --- | --- | --- | | `run` | dict | The run whose results are shown | | `show_gauge` | bool, optional | Render the live ELO gauge; default `false` | | `results_info` | dict, optional | Formatted results; default `format_results(run)` | ### `login.html.j2` | Key | Type | Description | | --- | --- | --- | | `remember_me_checked` | bool | Initial checked state for the Remember me checkbox | | `remember_me_cookie_name` | string | UI-state cookie name mirrored by shared application JS | Behavior notes: - The form submits `stay_logged_in=0` through a hidden input and `stay_logged_in=1` through the checkbox so the server can distinguish an explicit opt-out from the checked/default case. - When no `login_remember_me` UI cookie exists, the checkbox renders checked. An explicit opt-out stored in that cookie renders the checkbox unchecked on later visits. - `login.html.j2` defaults `remember_me_cookie_name` to `login_remember_me` because the same template is also used for generic UI 403 rendering. - `application.js` mirrors checkbox changes into the same UI-state cookie via `writeUiCookie()`, and `POST /login` refreshes it server-side for progressive enhancement. ### `machines_fragment.html.j2` | Key | Type | Description | | --- | --- | --- | | `machines` | list of dicts | Machine rows | Behavior notes: - The fragment refreshes the `#workers-count` label out of band with the same short format used by the homepage shell: `Workers - <total>` or `Workers - <total> (<filtered>)`. - Homepage polling keeps including the current filter form state, so fragment refreshes continue while the `q` search filter is active. - The hidden homepage Workers header is refreshed from the current machine snapshot during `/tests` and page-1 same-route live run-table fragment rendering, so a collapsed panel still shows a live filtered count. Each machine row: `username`, `country_code`, `concurrency`, `worker_url`, `worker_short`, `nps_m` (preformatted string), `max_memory`, `system`, `worker_arch`, `compiler_label`, `python_label`, `version_label`, `run_url`, `run_label`, `last_active_label`, `last_active_sort`. ### `nn_upload.html.j2` | Key | Type | | --- | --- | | `upload_url` | string | | `testing_guidelines_url` | string | | `cc0_url` | string | | `nn_stats_url` | string | ### `nns.html.j2` | Key | Type | Description | | --- | --- | --- | | `filters` | dict | `{network_name, user, master_only}` | | `pages` | list | Pagination items | | `nns` | list of dicts | Neural network rows | Each nn row: `time_label`, `name`, `name_url`, `user`, `first_test_label`, `first_test_url`, `last_test_label`, `last_test_url`, `downloads`, `is_master`. Behavior notes: - Search is URL-driven and rendered by the same `/nns` endpoint. - htmx search updates only `#nns-content`; full-page rendering still works. - Typing in `network_name` / `user` and toggling `master_only` triggers htmx requests, while submit remains available as a non-JS fallback. - `network_name` and `user` are literal case-insensitive substring filters; regex metacharacters are escaped before reaching Mongo. - `nns_content_fragment.html.j2` pairs a hidden `master_only=0` field with the checkbox `value="1"` and `data-ui-cookie-*` attributes, so unchecked htmx requests and cookie persistence stay synchronized without inline JS. - The page shell owns the heading; the summary cards, explanatory copy, filter form (`#search_nn`), view toggle, pagination, and table live in the content fragment. ### `notfound.html.j2` Shared base context only. ### `pagination.html.j2` Reusable partial included by other templates. | Key | Type | Description | | --- | --- | --- | | `pages` | list of dicts | Each: `{idx, url, state}` | `state` values: `"active"`, `"disabled"`, or empty string. ### `rate_limits.html.j2` | Key | Type | Description | | --- | --- | --- | | `server_rate_limit` | int | The server's remaining GitHub API calls, first paint | | `server_reset` | string | When the GitHub rate limit resets, first paint | ### `run_table.html.j2` | Key | Type | | --- | --- | | `header` | string or None | | `count` | int or None | | `count_text` | string or None | | `runs` | list of run row dicts | | `pages` | list of pagination items | | `toggle` | string or None | | `toggle_state` | `"Hide"` or `"Show"` | | `show_delete` | bool | | `active_run_filters` | dict or None | ### `run_tables.html.j2` | Key | Type | | --- | --- | | `page_idx` | int | | `prefix` | string | | `pending_approval_runs` | list of run rows | | `paused_runs` | list of run rows | | `failed_runs` | list of run rows | | `active_runs` | list of run rows | | `active_count_text` | string | | `active_run_filters` | dict or None | | `finished_runs` | list of run rows | | `num_finished_runs` | int | | `finished_runs_pages` | list | ### `signup.html.j2` | Key | Type | | --- | --- | | `recaptcha_site_key` | string | ### `sprt_calc.html.j2` Shared base context only. ### `tasks_content_fragment.html.j2` | Key | Type | | --- | --- | | `tasks` | list of task row dicts | | `show_pentanomial` | bool | | `show_residual` | bool | | `run_id` | string | | `show_task` | int | | `sort` | string (default `"idx"`) | | `order` | string (`"asc"` or `"desc"`, default `"desc"`) | | `q` | string (combined worker/info filter) | | `view` | string (`"paged"` or `"all"`) | | `pages` | list of pagination dicts | | `num_tasks` | int | | `max_all` | int | | `is_truncated` | bool | Primary swap target: `#tasks-content`. The fragment swaps the scrolling task table body into `#tasks-content` and refreshes the fixed controls/pagination wrappers out of band. OOB updates target `#tasks-view-controls`, `#tasks-pagination`, and the hidden form inputs `#tasks_sort`, `#tasks_order`, and `#tasks_view`. Each task row: `task_id`, `row_class`, `worker_label`, `worker_url`, `info_label`, `last_updated_label`, `played_label`, `results_cells`, `crashes`, `time_losses`, `residual_label`, `residual_bg`. ### `tasks_controls_fragment.html.j2` Included by `tests_view.html.j2` for the page-owned tasks table shell and returned OOB by `tasks_content_fragment.html.j2` after sort, filter, or view changes. | Key | Type | | --- | --- | | `run_id` | string | | `show_task` | int | | `sort` | string | | `order` | string | | `q` | string | | `view` | string | | `num_tasks` | int | | `max_all` | int | | `is_truncated` | bool | ### `tasks_rows_fragment.html.j2` Included by `tasks_content_fragment.html.j2`. Renders `<tr>` rows from the `tasks` list. No standalone context requirements beyond `tasks`, `show_pentanomial`, and `show_residual`. ### `tests.html.j2` | Key | Type | | --- | --- | | `page_idx` | int | | `cores` | int | | `nps_m` | string | | `games_per_minute` | int | | `pending_hours` | string | | `machines_shown` | bool | | `machines_count` | int | | `run_tables_ctx` | dict (for `run_tables.html.j2`) | Behavior notes: - `tests.html.j2` forwards the homepage Active-panel first-paint filter state through `run_tables_ctx`, including restored checkbox selections, filtered count text, and initial hide selectors. - `run_tables_ctx` is intentionally lightweight. Unfinished-run rows omit `tasks`, `bad_tasks`, and `args.spsa.param_history`; task detail stays on the detail and tasks routes. - Notification button state is not part of `run_tables_ctx` because it is derived from browser-local follow state at page load time. ### `tests_finished.html.j2` | Key | Type | | --- | --- | | `filters` | dict (`ltc_only`, `success_only`, `yellow_only`, `username_query`, `text`, `max_count`, `mode`, the `*_query_string` keys, `filtered_query_suffix`) | | `title` | string (the title suffix, e.g. `- Greens`) | | `title_text` | string | | `search_mode` | bool | | `page_idx` | int | | `finished_page_size` | int | | `show_gauge` | bool | | `finished_runs` | list of run rows | | `visible_finished_runs` | int | | `num_finished_runs` | int | | `finished_runs_pages` | list | ### `tests_live_elo.html.j2` | Key | Type | | --- | --- | | `run` | dict | | `page_title` | string | | `run_status_label` | string | | `sprt_state` | string | | `elo_raw`, `ci_lower_raw`, `ci_upper_raw` | float | | `LLR_raw`, `LOS_raw`, `a_raw`, `b_raw` | float | | `elo_value`, `ci_lower`, `ci_upper`, `LLR`, `LOS` | number | | `W`, `L`, `D`, `games` | int | | `w_pct`, `l_pct`, `d_pct` | float | | `pentanomial` | list | | `elo_model`, `elo0`, `elo1`, `alpha`, `beta` | mixed | The page script renders LOS, LLR, and Elo gauges from `gauge-data` attributes. The Elo gauge supports a fixed default range (`[-4, +4]`) and a dynamic range. The gauge reports the uncapped server Elo value while the needle remains visually bounded by the active range. ### `tests_run.html.j2` | Key | Type | | --- | --- | | `args` | dict (run arguments, empty for new test) | | `is_rerun` | bool | | `rescheduled_from` | string or None | | `form_action` | string | | `tests_repo_value` | string | | `master_info` | dict or None | | `valid_books` | iterable | | `pt_info` | dict | | `setup` | dict | | `supported_arches` | list | | `supported_compilers` | list | Rendered structure notes: - the preset chooser caption for `Test type` is a neutral heading row, not a `label` wrapper; - the ellipsis control is a sibling button that toggles the extra preset blocks through Bootstrap collapse; - the collapsed preset blocks expose stable ids so the toggle button can name them through `aria-controls`. Tests repository contract: - `tests_repo_value` is rendered from the current GitHub repo value for the form - trailing-slash input is accepted on submit, but persisted run data is canonicalized and validated as the slash-free form ### `tests_stats.html.j2` Page shell for `/tests/stats/{id}`. Includes the shared stats content fragment and, for unfinished non-SPSA runs, a visibility-aware htmx poller targeting `#tests-stats-content` using the dedicated raw-statistics poll cadence `poll.tests_stats`. | Key | Type | | --- | --- | | `run` | dict | | `page_title` | string | | `stats` | dict | ### `tests_stats_content_fragment.html.j2` Shared stats-body fragment used by both the full-page shell and `HX-Request` responses for `/tests/stats/{id}`. | Key | Type | | --- | --- | | `run` | dict | | `page_title` | string | | `stats` | dict | Rendered structure: - `#tests-stats-content` root element - original heading-and-table statistics layout shared by full-page and htmx renders - SPRT bounds rendered as a table - SPSA message rendered in place of the statistics tables when applicable ### `tests_user.html.j2` | Key | Type | | --- | --- | | `username` | string | | `is_approver` | bool | | `run_tables_ctx` | dict | ### `tests_view.html.j2` | Key | Type | | --- | --- | | `run` | dict | | `run_args` | list of tuples `(name, value, url)` | | `page_title` | string | | `approver` | bool | | `chi2` | value | | `run_status_label` | string | | `tasks_totals` | string (active workers summary) | | `tasks_shown` | bool | | `show_task` | int | | `follow` | int | | `has_pgns` | bool (run has stored task PGNs) | | `can_modify_run` | bool | | `same_user` | bool | | `pt_info` | dict | | `document_size` | int | | `spsa_data` | dict or None | | `notes` | list of strings | | `warnings` | list of strings | | `use_3dot_diff` | bool | | `allow_github_api_calls` | bool | Detail-page merged live polling contract: - Unfinished runs render one visibility-aware htmx poller targeting `/tests/view/{id}/detail`. - The poller includes `#tests-view-detail-expected`, a hidden server-owned input carrying the current canonical `expected` status. - The poller uses `hx-swap="none"` and the dedicated cadence `poll.tests_view_detail`. - The submitted `expected` value must match the page's canonical `run_status_label`: `active`, `paused`, or `pending`. - The shared OOB targets are `#elo-<run_id>`, `#run-status-<run_id>`, `#tasks-totals`, `#tests-view-details`, `#tests-view-time`, and either `#tests-view-stats` or the embedded `#spsa-data-<run_id>` payload depending on the run type. - `tests_view_detail_fragment.html.j2` OOB-refreshes the hidden expected-state input alongside the visible status label so paused/pending transitions can settle back to `204` on the next poll. - SPSA runs keep the chart shell stable in `tests_view.html.j2`; live detail refreshes update only the embedded `application/json` payload contents so `static/js/spsa.js` can keep the payload node mounted, skip unchanged redraws, and redraw changed payloads without replacing the mounted chart shell. The full page renders the `% c` checkbox from a browser-readable cookie on first paint. Detail-page tasks loader contract: - When `tasks_shown` is true, `#tasks-content` starts an htmx load request from `tests_view.html.j2`. - The template registers its swap observer and its `htmx:response:error` and `htmx:error` listeners before `await DOMContentLoaded()` so the initial `load` request cannot outrun the promise-resolution path. - The swap observer matches on the **swap target**, through `onHtmxSwap((target) => target.id === "tasks-content", ...)`. htmx dispatches swap events on the element that issued the request, and `#tasks-content` is filled by two: its own `load`/poll triggers, and `#tasks-filters` when the reader types. An element-level `htmx:after:swap` listener on the panel sees only the first kind, so it misses every form-driven fill -- including the replacement for a load request the form aborted, which `hx-sync` makes a reachable case. `onHtmxSwap` also drops responses htmx did not swap, so an error is never recorded as a completed load. - The same script also resolves immediately if `#tasks-content` is already marked loaded or already contains rows. Run-table row contract: - Run tables use the normal `.table-striped` contract. - Active-run filtering emits a first-paint style block that hides excluded rows, and the Active filter script keeps the visible rows contiguous in tbody order so the normal `.table-striped` pattern stays correct while filters are active. The first-paint style block is hide-only and does not encode row parity. - The Active row markup carries filter dimensions plus a source-order index for restoring the current server order after checkbox changes and OOB swaps; it does not use a row-parity contract. ### `tests_view_detail_fragment.html.j2` Merged OOB poll fragment returned by `/tests/view/{id}/detail`. Composes the shared detail-page summary + detail sections with `hx-swap-oob` enabled. | Key | Type | | --- | --- | | `run` | dict | | `run_status_label` | string | | `tasks_totals` | string | | `run_args` | list of tuples `(name, value, url)` | | `approver` | bool | | `chi2` | dict | | `document_size` | int | | `spsa_data` | dict or None | Rendered behavior: - always includes `elo_results_fragment.html.j2` - always includes `tests_view_details_section.html.j2` - always includes `tests_view_time_section.html.j2` - includes `tests_view_stats_section.html.j2` for non-SPSA runs - emits an OOB `#spsa-data-<run_id>` `application/json` payload update for SPSA runs using `innerHTML` so the existing script node stays mounted ### `tests_view_details_section.html.j2` Shared detail-table section used by `tests_view.html.j2` and the live detail fragment. | Key | Type | | --- | --- | | `run` | dict | | `run_args` | list of tuples `(name, value, url)` | | `approver` | bool | | `document_size` | int | Rendered structure: - `#tests-view-details` root element - run argument rows, document size, actions link, raw statistics link when applicable, and approver link when present ### `tests_view_stats_section.html.j2` Shared compact chi-square block for the test detail page. | Key | Type | | --- | --- | | `chi2` | dict | Rendered structure: - `#tests-view-stats` root element - compact `chi^2`, `dof`, and `p-value` table ### `tests_view_time_section.html.j2` Shared time block for the test detail page. | Key | Type | | --- | --- | | `run` | dict | Rendered structure: - `#tests-view-time` root element - start time and last updated rows ### `tests_view_spsa_section.html.j2` Shared SPSA chart section for the test detail page. | Key | Type | | --- | --- | | `run` | dict | | `spsa_data` | dict or None | | `spsa_percentage_checked` | bool | Rendered structure: - `#tests-view-spsa` root element - DOM-embedded `application/json` payload for the current SPSA state, exposing `param_names` plus server-shaped `chart_rows`; those chart rows fold together the start row, compact sampled history rows, and the current live point, with `c_values` present when `% c` mode can be rendered - cookie-backed `% c` checkbox rendered from `spsa_percentage_checked` - `#spsa_history_scroll` retained scroll container - CSS-owned `#spsa_history_plot` shell for the fixed-size chart (Google Charts uses 1000x500; layout and scrolling handled by CSS and the scroll container) - chart toolbar and chart container used by `static/js/spsa.js` ### `user.html.j2` | Key | Type | | --- | --- | | `profile` | bool | | `user` | dict (`username`, `email`, `tests_repo`, etc.) | | `limit` | value | | `hours` | int | | `extract_repo_from_link` | string | | `form_action` | URL | | `registration_time_label` | string | | `blocked` | bool | Tests repository contract: - `user["tests_repo"]` is persisted as the canonical slash-free GitHub repo URL - profile form submissions may include a trailing slash, but stored user data is normalized and validated before save ### `user_management.html.j2` | Key | Type | | --- | --- | | `all_count` | int | | `pending_count` | int | | `blocked_count` | int | | `idle_count` | int | | `approvers_count` | int | | `group` | string | | `sort` | string | | `order` | string | | `q` | string | | `view` | string | | `pages` | list | | `selected_users` | list of user row dicts | | `num_selected_users` | int | | `max_all` | int | | `is_truncated` | bool | Each user row: `username`, `user_url`, `registration_label`, `groups`, `groups_label`, `email`. ### `workers.html.j2` | Key | Type | | --- | --- | | `show_admin` | bool | | `worker_name` | string | | `last_updated_label` | string | | `message` | string | | `blocked` | bool | | `show_email` | bool | | `filter_value` | string | | `sort` | string | | `order` | string | | `q` | string | | `view` | string | | `pages` | list | | `blocked_workers` | list of dicts | | `num_workers` | int | | `max_all` | int | | `is_truncated` | bool | Each blocked worker row: `worker_name`, `last_updated_label`, `actions_url`, `owner_email`, `mailto_url`. ## Fragment context contracts Fragment templates receive the shared base context (via `build_template_context()`) plus handler-specific keys. ### `actions_content_fragment.html.j2` Same context as `actions.html.j2` (`actions`, `visible_actions`, `num_actions`, `page_size`, `current_page`, `run_id_filter`, `max_count`, `sort`, `order`, `sort_summary`, `filters`, `pages`). `actions.html.j2` renders the page shell and filter form, then includes `actions_content_fragment.html.j2` inside `#actions-content`. ### `active_run_filters_fragment.html.j2` | Key | Type | | --- | --- | | `active_run_filters` | dict or `None` (parsed cookie state) | | `cookies.ui_state_max_age` | int (cookie max-age seconds) | Renders the faceted filter panel (SPRT/SPSA/NumGames, STC/LTC, ST/SMP) above the Active runs table, wherever `run_table.html.j2` includes it: the Active panel on page 1 of a run list without a username. Server-side rendering of initial checkbox state eliminates the flash where all rows are briefly visible before JS reapplies the persisted filter. ### `contributors_content_fragment.html.j2` Same context as the content area of `contributors.html.j2`: `users`, `pages`, `sort`, `order`, `view`, `num_users`, `max_all`, `is_truncated`, and, in the htmx response only, `is_hx`. Sortable headers are dual-mode links (`href` + `hx-get`) targeting `#contributors-content` with `hx-push-url="true"`. The outer contributors search form keeps `view`, `sort`, and `order` in hidden inputs. htmx fragment responses refresh those inputs out of band so later form submissions preserve the live table state. ### `contributors_rows_fragment.html.j2` | Key | Type | | --- | --- | | `users` | list of contributor row dicts | ### `tests_run_tables_fragment.html.j2` | Key | Type | Description | | --- | --- | --- | | `panels` | list of dicts | Each: `tbody_id`, `rows`, `show_delete`, `empty_text` | | `count_updates` | list of dicts | Each: `id`, `text` (OOB count spans) | | `machines_count` | int or absent | Worker count (OOB `#workers-count`) | | `workers_count_text` | string or absent | The workers-counter text for `#workers-count` | | `stats` | dict or absent | Homepage stats (OOB, omitted when filtered by user) | | `stop_polling` | bool or absent | Remove `#run-tables-poller` and stop the poll | Behavior notes: - The unfinished-run portion of this fragment uses the same lightweight row shape as `run_tables_ctx`. - When homepage workers filters are active, the fragment recomputes the `#workers-count` filtered value from the current machine snapshot instead of trusting the last cookie-backed filtered count. - `workers_count_text` remains the single shared workers-counter string used by the homepage shell and OOB fragment updates. ### `elo_results_fragment.html.j2` Shared OOB partial included by `tests_view_detail_fragment.html.j2`. | Key | Type | | --- | --- | | `run` | dict | | `run_status_label` | string, optional (OOB `#run-status-{id}`; computed from the run when absent) | | `tasks_totals` | string, optional (OOB `#tasks-totals`) | | `show_gauge`, `results_info` | optional, as for `elo_results.html.j2` | ### `homepage_stats_fragment.html.j2` | Key | Type | | --- | --- | | `cores` | int | | `nps_m` | string | | `games_per_minute` | int | | `pending_hours` | string | ### `live_elo_fragment.html.j2` | Key | Type | | --- | --- | | `run` | dict | | `run_status_label` | string | | `sprt_state` | string | | `elo_raw`, `ci_lower_raw`, `ci_upper_raw` | float | | `LLR_raw`, `LOS_raw`, `a_raw`, `b_raw` | float | | `elo_value`, `ci_lower`, `ci_upper`, `LLR`, `LOS` | number | | `W`, `L`, `D`, `games` | int | | `w_pct`, `l_pct`, `d_pct` | float | | `pentanomial` | list | | `elo_model`, `elo0`, `elo1`, `alpha`, `beta` | mixed | This fragment is returned by `/tests/live_elo_update/{id}` and swaps `#live-elo-data` out-of-band while preserving the current client-side gauge mode. ### `machines_fragment.html.j2` | Key | Type | | --- | --- | | `machines` | list of machine row dicts | | `sort` | string | | `order` | string | | `q` | string | | `current_page` | int | | `my_workers` | bool | | `pages` | list | | `machines_count` | int | | `workers_count_text` | string (OOB `#workers-count`) | This fragment also refreshes the hidden sort/page inputs and the `#workers-count` label out of band so homepage polling, sorting, paging, and filters stay in sync without replacing the filter controls themselves. The machine rows come from the current server machine snapshot. The same snapshot is reused by `/tests` and its page-1 same-route live run-table fragment when they need to render a live filtered workers count while the table itself is collapsed. ### `nns_content_fragment.html.j2` Same context as `nns.html.j2` (`filters`, `pages`, `nns`, `sort`, `order`, `view`, `num_nns`, `max_all`, `is_truncated`) plus `nns_summary` with `nets`, `master_nets`, `contributors`, and `downloads`. The fragment owns the NNS summary cards and the explanatory copy as well as the filter form, view toggle, pagination, and table so filtered htmx responses keep the full vertical page order synchronized with the current server state. The `network_name` and `user` filters remain literal case-insensitive substring searches. Regex syntax is not part of the public contract. Sortable headers are dual-mode links (`href` + `hx-get`) targeting `#nns-content` with `hx-push-url="true"`. The fragment-owned GET form keeps `view`, `sort`, and `order` in hidden inputs. Because the full filter form is inside the swapped fragment, htmx responses do not need out-of-band hidden-input refresh for this page. The `/rate_limits` page client row and the sidebar `GitHub Rate Limits` link both project their cadence from `poll.rate_limits_github`. The `/rate_limits` server row projects its separate cadence from `poll.rate_limits_server`. The sidebar link keeps a fixed label and uses the same red status styling as the pending-users sidebar item whenever the client GitHub budget is below the threshold. The sidebar link is rendered directly in `base.html.j2` with the same `data-poll-seconds` cadence that `application.js` uses for client-side GitHub budget checks. `application.js` owns the full browser-side lifecycle for that client poll: - it initializes on every page that renders `#rate-limits-nav-link`; - it pauses its timer while the document is hidden; - it refreshes immediately when the page becomes visible again and on window `focus`; - it refreshes again on persisted `pageshow` so bfcache restores do not leave stale sidebar or `/rate_limits` client-row state. The `/rate_limits/server` endpoint returns a tiny inline HTML fragment: the remaining server budget plus an out-of-band `#server_reset` update. This route does not need a dedicated Jinja template. The pending-users sidebar wrapper, the `/rate_limits/server` poller, and the client-side GitHub rate-limit refresh all use `visibilitychange` activation, so an active page refreshes after a hidden tab becomes visible again. The pending-users wrapper and the `/rate_limits/server` poller also fire on `load`, so each fetches once on page load beside its server-rendered value. The GitHub sidebar link also restores the last known client warning state from local storage before first paint so page navigation does not briefly flash the link back to its normal color. ### `run_table_row_fragment.html.j2` | Key | Type | | --- | --- | | `row` | run row dict | | `show_delete` | bool | | `show_gauge` | bool | The `row` payload is shaped by `build_run_table_rows()` in `server/fishtest/http/template_helpers.py`. Its `diff_url` field is derived from the canonical run diff URL builder. ### `tasks_content_fragment.html.j2` Content fragment for the tasks table. Swaps the scrolling table markup into `#tasks-content` and refreshes the fixed controls/pagination wrappers OOB. Includes `tasks_rows_fragment.html.j2` for the `<tr>` rows. Context keys: `tasks`, `show_pentanomial`, `show_residual`, `run_id`, `show_task`, `sort`, `order`, `q`, `view`, `pages`, `num_tasks`, `max_all`, `is_truncated`. ### `tasks_rows_fragment.html.j2` Row renderer included by `tasks_content_fragment.html.j2`. Context keys: `tasks`, `show_pentanomial`, `show_residual`. ### `tests_filter_tabs_fragment.html.j2` Reusable partial included by `tests_finished_content_fragment.html.j2`, `tests_finished_results_fragment.html.j2` and `tests_user_content_fragment.html.j2` for filter tab buttons (All / Green / Yellow / LTC). | Key | Type | Description | | --- | --- | --- | | `filters` | dict | `{success_only, yellow_only, ltc_only}` | | `hx_target` | string | Target element ID for `hx-target` | | `base_url` | string | Base URL for filter links (default `/tests/finished`) | When present, `filters.all_query_string`, `filters.green_query_string`, `filters.yellow_query_string`, `filters.ltc_query_string` and `filters.filtered_query_suffix` preserve additional GET state such as username search fields while the user switches between the tab filters. ### `tests_finished_content_fragment.html.j2` | Key | Type | | --- | --- | | `filters` | dict (`ltc_only`, `success_only`, `yellow_only`, `username_query`, `text`, `max_count`) | | `finished_runs` | list of run rows | | `num_finished_runs` | int | | `finished_page_size` | int | | `finished_runs_pages` | list | This full-page include owns the tab strip and the search-first `/tests/finished` GET form. Username substring uses the cached list of usernames in the users collection (`userdb.get_usernames()`, cached 30 s) and the exact-username finished-run path, while the `text` field searches the run info of finished rows (see the finished tests parameters in [UI routes](<http://official-stockfish.github.io/fishtest/ui-reference/index.md#finished-tests-testsfinished-query-parameters>)). The form preserves the effective `max_count` cap so tab switches and pagination stay on the same server-authoritative finished-tests query contract. ### `tests_finished_results_fragment.html.j2` | Key | Type | | --- | --- | | `filters` | dict | | `finished_runs` | list of run rows | | `num_finished_runs` | int | | `visible_finished_runs` | int | | `finished_page_size` | int | | `finished_runs_pages` | list | | `page_idx` | int | | `search_mode` | bool | | `is_hx` | bool | This is the htmx fragment returned by `/tests/finished` for fragment requests. It updates `#tests-finished-content` and, in navigation mode, piggy-backs an out-of-band replacement of the tab wrapper so the active tab stays aligned with the pushed URL after htmx tab clicks. ### `tests_user_content_fragment.html.j2` | Key | Type | | --- | --- | | `username` | string | | `is_approver` | bool | | `filters` | dict | | `run_tables_ctx` | dict | ### `user_management_content_fragment.html.j2` Same context as the content area of `user_management.html.j2`: `group`, `sort`, `order`, `q`, `view`, `pages`, `selected_users`, `num_selected_users`, `max_all`, `is_truncated`, and, in the htmx response only, `is_hx`. The outer GET form keeps `sort`, `order`, and `view` in hidden inputs. htmx fragment responses refresh those inputs out of band so later form-triggered requests preserve the current table state. ### `user_management_rows_fragment.html.j2` | Key | Type | Description | | --- | --- | --- | | `selected_users` | list of user row dicts | Filtered user rows | ### `workers_content_fragment.html.j2` Same context as the content area of `workers.html.j2`: `filter_value`, `sort`, `order`, `q`, `view`, `pages`, `blocked_workers`, `show_email`, `num_workers`, `max_all`, `is_truncated`, and, in the htmx response only, `is_hx`. Sortable headers are dual-mode links (`href` + `hx-get`) targeting `#workers-content` with `hx-push-url="true"`. The outer GET form keeps `sort`, `order`, and `view` in hidden inputs. htmx fragment responses refresh those inputs out of band so later form-triggered requests preserve the current table state. ## htmx shell-state rule When a GET form stays outside the swapped fragment but the fragment owns sort/view/pagination links, the fragment must refresh any stateful hidden form inputs out of band. This repo uses the same pattern as `/tests/machines`: - keep stable ids on the outer hidden inputs; - return matching hidden inputs from the fragment with `hx-swap-oob="true"`; - render those out-of-band inputs only in the htmx response, behind `{% if is_hx | default(false) %}`, with the view passing `is_hx` through `extra_context`. A content fragment that the full page includes would otherwise render every id twice. That keeps later form submissions aligned with the current server-authoritative table state without introducing page-specific synchronization JavaScript. ### `workers_rows_fragment.html.j2` | Key | Type | Description | | --- | --- | --- | | `blocked_workers` | list of dicts | Filtered worker rows | | `show_email` | bool | Show owner email column | ## Authoring rules 1. **Templates are declarative**: all data shaping stays in view handlers. Templates receive pre-computed values and render them. 2. **JavaScript data**: pass via the `|tojson` filter. Never interpolate Python values directly into `<script>` blocks. 3. **Display strings**: prefer preformatted values (e.g., `*_label` keys) over formatting in templates. 4. **URLs**: prefer explicit URL keys (e.g., `*_url`) over building URLs in templates. 5. **Macros**: use Jinja2 macros for repeated patterns (pagination, run tables). 6. **Request object**: templates read `request.url` and `request.url.path` for the current address (form actions, query links); nothing else on the request. 7. **Escaping boundary**: view handlers pass raw strings. Jinja2 autoescape handles HTML-escaping at render time. Do not pre-escape values into plain strings with `html.escape()` in Python -- that causes double-escaping. Escaping in Python is appropriate when constructing a `Markup` value (escape untrusted input first, then wrap). 8. **`|safe` filter**: use only on values already typed as `Markup`, or after an explicit `|e` escape followed by controlled transformations (e.g., `{{ value | e | replace("\n", "<br>") | safe }}`). 9. **External links**: every `target="_blank"` anchor must include `rel="noopener noreferrer"` to prevent reverse-tabnabbing. 10. **No inline event handlers**: use unobtrusive JavaScript (`addEventListener` or delegated listeners) instead of `onclick`, `onsubmit`, or similar HTML attributes. 11. **Fragment templates do not extend `base.html.j2`**: htmx fragment templates are standalone files. They receive the shared base context via `build_template_context()` but must not use `{% extends %}` or `{% block %}` directives. 12. **OOB swap elements carry their own `hx-swap-oob` attribute**: the view handler does not need to set response headers for OOB updates. Each OOB element in the fragment template declares its own ID and swap strategy (e.g., `<span id="count" hx-swap-oob="innerHTML">`). 13. **Row OOB requires a `<template>` wrapper, and the wrapper carries the attributes**: a `<tr>` cannot stand on its own in parsed HTML. Put `id` and `hx-swap-oob` on the `<template>` itself: ``` <template id="my-table" hx-swap-oob="innerHTML"> {% for row in rows %}...{% endfor %} </template> ``` htmx locates out-of-band elements with `querySelectorAll`, which does not descend into template content, so an `hx-swap-oob` nested inside the wrapper is silently ignored. htmx strips the wrapper before the swap. Targets that can stand alone, such as a `<div>`, need no wrapper. 14. **DOM API over `innerHTML` in error handlers**: JavaScript retry-button construction must use `createElement` / `textContent` / `setAttribute` instead of string concatenation with `innerHTML`. This prevents XSS from error messages and avoids escaping issues. 15. **Unicode over HTML entities**: use literal Unicode characters (e.g., `<=` or the actual symbol) instead of HTML entities (`≤`, `>`) in templates. This eliminates the need for `|safe` on values that contain the entity. 16. **Explicit CSRF hidden fields**: every server-rendered `<form>` that posts to a `require_csrf` route must include an explicit hidden input: ``` <input type="hidden" name="csrf_token" value="{{ csrf_token }}"> ``` The meta-tag CSRF token is a fallback for htmx headers; forms must not rely on it as the sole CSRF transport. 17. **Polling trigger policy**: every periodic htmx poller must include three trigger components: (a) a periodic trigger gated on `document.visibilityState === 'visible'`, written `every[<condition>] Ns`, the one spelling the templates use, (b) an immediate `visibilitychange[...] from:document` refresh, and (c) for section-scoped pollers, a gate on the section's expanded state. See [Architecture](<http://official-stockfish.github.io/fishtest/architecture/index.md>) for the full policy. ## Adding a new template ### Page template 1. Create `templates/mypage.html.j2` extending `base.html.j2`: ``` {% extends "base.html.j2" %} {% block body %} ... {% endblock %} ``` 2. Define the context contract (required keys and types) in this document. 3. Build the context in the view handler using the shared base context plus page-specific keys. 4. Return the context dict from the handler; `_dispatch_view` renders the template specified in the route config's `renderer` key. 5. Add a test that verifies the template renders without errors. ### Fragment template 1. Create `templates/mypage_fragment.html.j2` as a standalone file (no `{% extends %}`). 2. Define the context contract in this document. 3. In the view handler, use `_render_hx_fragment()` to return the fragment when `HX-Request` is present: ``` return ( _render_hx_fragment(request, "mypage_fragment.html.j2", context) or context ) ``` 4. For OOB elements, add `hx-swap-oob` attributes directly on elements inside the fragment template. Rows travel inside a `<template>` that carries the `id` and `hx-swap-oob` attributes. 5. Add a test that verifies both the full-page and fragment responses. # Developer references Curated web references and project-specific patterns for the four libraries that form the fishtest server stack. For server architecture and request flow, see [Architecture](<http://official-stockfish.github.io/fishtest/architecture/index.md>). For the threading model and async/sync boundaries, see [Threading model](<http://official-stockfish.github.io/fishtest/threading-model/index.md>). ## FastAPI ### Canonical references | Topic | URL | | --- | --- | | Bigger applications (APIRouter) | https://fastapi.tiangolo.com/tutorial/bigger-applications/ | | Dependencies overview | https://fastapi.tiangolo.com/tutorial/dependencies/ | | Dependencies in decorators | https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/ | | Handling errors | https://fastapi.tiangolo.com/tutorial/handling-errors/ | | Middleware | https://fastapi.tiangolo.com/tutorial/middleware/ | | Request forms | https://fastapi.tiangolo.com/tutorial/request-forms/ | | Request files / UploadFile | https://fastapi.tiangolo.com/tutorial/request-files/ | | Lifespan events | https://fastapi.tiangolo.com/advanced/events/ | | Behind a proxy / root\_path | https://fastapi.tiangolo.com/advanced/behind-a-proxy/ | | Templates | https://fastapi.tiangolo.com/advanced/templates/ | | Testing | https://fastapi.tiangolo.com/tutorial/testing/ | ### Project patterns **Router structure**: `api.py` and `views.py` each define an `APIRouter`. `app.py` assembles them with `app.include_router(...)`. ``` from fastapi import FastAPI from .api import router as api_router from .views import router as views_router # openapi_url is read from OPENAPI_URL env var; defaults to None (disabled # in production, enables full interactive docs when set in development). app = FastAPI(lifespan=lifespan, openapi_url=openapi_url) app.include_router(views_router) app.include_router(api_router) ``` **No dependency injection**: fishtest does not use FastAPI's `Depends()` / `Annotated` dependency system. Authentication, CSRF, and session access are enforced centrally -- in `_dispatch_view` for UI routes and per-handler in the API router -- not through injected dependencies. **Lifespan**: Manages MongoDB client, scheduler, and caches. One `@asynccontextmanager` in `app.py`. ``` from contextlib import asynccontextmanager @asynccontextmanager async def lifespan(app: FastAPI): # startup yield # shutdown ``` **Error shaping**: UI errors return HTML via exception handlers. Worker API errors return JSON with `{"error": "...", "duration": N}`. **Sync handlers**: Sync view/API functions are automatically run via `run_in_threadpool` by Starlette/FastAPI. Most fishtest handlers use `async def` with explicit `run_in_threadpool` calls for blocking DB work. **Testing**: HTTP tests build their application with `build_test_app()`, a `FastAPI()` wired like production without the lifespan, the `RejectNonPrimaryWorkerApiMiddleware` and the `/static` mount, around a `RunDb` on the test MongoDB database. `test_app.py` builds the production application with `create_app()` around a stub `RunDb`. Because the app uses no FastAPI dependencies, there are no `app.dependency_overrides`. ## Starlette ### Canonical references | Topic | URL | | --- | --- | | Middleware | https://www.starlette.dev/middleware/ | | Requests | https://www.starlette.dev/requests/ | | Responses | https://www.starlette.dev/responses/ | | Routing / url\_for | https://www.starlette.dev/routing/ | | StaticFiles | https://www.starlette.dev/staticfiles/ | | Exceptions | https://www.starlette.dev/exceptions/ | | Lifespan | https://www.starlette.dev/lifespan/ | | TestClient | https://www.starlette.dev/testclient/ | | Thread pool | https://www.starlette.dev/threadpool/ | ### Project patterns **Session middleware**: `FishtestSessionMiddleware` is a pure ASGI middleware class; it does not subclass Starlette's `SessionMiddleware`. It signs and verifies the `fishtest_session` cookie directly with `itsdangerous.TimestampSigner`. Per-request cookie lifetime, the `Secure` flag, and forced expiry are driven through `scope["session_max_age"]`, `scope["session_secure"]`, and `scope["session_force_clear"]`. It follows the pure ASGI middleware shape shown below. **Pure ASGI middleware** (preferred over `BaseHTTPMiddleware`): ``` class MyMiddleware: def __init__(self, app: ASGIApp) -> None: self.app = app async def __call__(self, scope, receive, send) -> None: if scope["type"] != "http": await self.app(scope, receive, send) return # pre-processing await self.app(scope, receive, send) ``` Current middleware stack (all are pure ASGI): - Installation order in `app.add_middleware(...)`: `HeadMethodMiddleware` -\> `ShutdownGuardMiddleware` -\> `AttachRequestStateMiddleware` -\> `RejectNonPrimaryWorkerApiMiddleware` -\> `RedirectBlockedUiUsersMiddleware` -\> `FishtestSessionMiddleware` - Runtime order (outermost -\> innermost): `FishtestSessionMiddleware` -\> `RedirectBlockedUiUsersMiddleware` -\> `RejectNonPrimaryWorkerApiMiddleware` -\> `AttachRequestStateMiddleware` -\> `ShutdownGuardMiddleware` -\> `HeadMethodMiddleware` **Request form limits** (DOS protection): ``` post = await request.form( max_files=FORM_MAX_FILES, # UI_FORM_MAX_FILES = 2 max_fields=FORM_MAX_FIELDS, # UI_FORM_MAX_FIELDS = 200 max_part_size=FORM_MAX_PART_SIZE, # UI_FORM_MAX_PART_SIZE_BYTES = 200 MB ) ``` **URL generation**: templates write route paths literally and build static asset URLs with `static_url`; no route carries a `name=`, and no code calls `url_for`. **Response classes**: - `HTMLResponse` for UI endpoints - `JSONResponse` for API endpoints - `RedirectResponse` for redirects - `StreamingResponse` for PGN downloads **Thread pool**: Sync functions and file I/O consume threadpool tokens. Keep blocking DB and filesystem work off the event loop via `run_in_threadpool`. ## Jinja2 ### Canonical references | Topic | URL | | --- | --- | | Template designer docs | https://jinja.palletsprojects.com/en/latest/templates/ | | API (Environment, autoescape) | https://jinja.palletsprojects.com/en/latest/api/ | | Starlette templates integration | https://www.starlette.dev/templates/ | | FastAPI templates integration | https://fastapi.tiangolo.com/advanced/templates/ | ### Project patterns **Environment setup**: one `jinja2.Environment`, built on the first render (`_jinja_templates()` in `template_renderer.py` is cached), with `select_autoescape(["html", "xml", "j2"])`, `StrictUndefined` and the `jinja2.ext.do` extension. The globals and filters are registered as the environment is built. **Template rendering**: synchronous, always off the event loop. A view in the `_VIEW_ROUTES` table is registered with `add_api_route`, and its handler returns the context; `_dispatch_view` then renders the template in the threadpool: ``` response = await run_in_threadpool( render_template_to_response, request=request, template_name=renderer, context=context, ) ``` **Key rules**: - `render_template_response()` raises `ValueError` when the context has no `request`, so every render passes it explicitly. - `Jinja2Templates` accepts `directory=` or `env=`, not both. - `TemplateResponse` exposes `.template` and `.context` for test assertions. - JS data is passed via `{{ value|tojson }}`. **Registered globals** (repository-specific): | Global | Source | | --- | --- | | `url_for` | Injected by Starlette; unused | | `static_url` | `server/fishtest/http/jinja.py` | | `poll`, `finished`, `cookies` | UI settings, `server/fishtest/http/jinja.py` | | `htmx.input_changed_delay_ms` | `server/fishtest/http/jinja.py` | | Formatting helpers | `server/fishtest/http/template_helpers.py` | | `get_tc_ratio` | `server/fishtest/util.py` | | `gh`, `fishtest` | registered in `server/fishtest/http/jinja.py` | | `copy`, `datetime`, `math`, `float`, `urllib` | Python modules and builtins | Filters beside Jinja2's own: `urlencode`, `split` and `string`. **Autoescaping**: Enabled for `.html`, `.xml`, `.j2` extensions. Raw HTML must use `{{ value|safe }}` or `{% autoescape false %}`. ## htmx ### Canonical references | Topic | URL | | --- | --- | | Documentation | https://four.htmx.org/docs | | Reference index | https://four.htmx.org/reference | | Swap | https://four.htmx.org/reference/attributes/hx-swap | | OOB swaps | https://four.htmx.org/reference/attributes/hx-swap-oob | | Status-scoped behavior | https://four.htmx.org/reference/attributes/hx-status | | Push URL | https://four.htmx.org/reference/attributes/hx-push-url | | Indicator | https://four.htmx.org/reference/attributes/hx-indicator | | Sync / request coordination | https://four.htmx.org/reference/attributes/hx-sync | | Triggers | https://four.htmx.org/reference/attributes/hx-trigger | | Swap event | https://four.htmx.org/reference/events/htmx-after-swap | | Empty swap after OOB | https://four.htmx.org/reference/config/htmx-config-allowEmptySwapAfterOOB | | What's new in htmx 4 | https://four.htmx.org/docs/whats-new-in-htmx-4 | | Template fragments essay | https://htmx.org/essays/template-fragments/ | | Hypermedia Systems (book) | https://hypermedia.systems/ | | Web security with htmx | https://htmx.org/essays/web-security-basics-with-htmx/ | | `Vary` (MDN) | https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Vary | | Search inputs (MDN) | https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/input/search | | Search clear pseudo-element (MDN) | https://developer.mozilla.org/en-US/docs/Web/CSS/::-webkit-search-cancel-button | | Search event (MDN) | https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/search\_event | | `aria-sort` (MDN) | https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Reference/Attributes/aria-sort | | `visibilitychange` (MDN) | https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilitychange\_event | ### Project patterns **CDN loading**: htmx 4.0.1 is loaded from `cdn.jsdelivr.net` in `base.html.j2` with an SRI integrity hash. No npm build step, and no htmx extensions. ``` <script src="https://cdn.jsdelivr.net/npm/htmx.org@4.0.1/dist/htmx.min.js" integrity="sha256-oKuwTy9FofidHUhEAjJFU35eYBTIexRFU+Bge0zDITA=" crossorigin="anonymous" referrerpolicy="no-referrer"></script> ``` **Response swapping**: htmx swaps every response whose status is not listed in `htmx.config.noSwap`, which holds `204` and `304`. This server answers errors with whole pages rather than partials sized for a swap target, so the `<body>` element in `base.html.j2` states the policy for the whole document: ``` <body hx-status:4xx:inherited="swap:none push:false" hx-status:5xx:inherited="swap:none push:false" > ``` `:inherited` carries the attribute to every descendant, so an element-level request and an `htmx.ajax()` call from `<body>` are both covered. Declare the policy in one of the two places, never both: htmx consults `hx-status` only for a code that `noSwap` does not already claim, and a `noSwap` hit returns before the attribute is read. A suppressed status still runs the swap pipeline with swap `none`, so `htmx:after:swap` fires for `4xx` and `5xx`. Handlers that record load state must check the response status. `swap:none push:false` reaches the main swap and the history entry. The title is adopted after the swap and out-of-band elements in the response body are applied regardless, neither of them gated on the status, so a whole error page would still rename the tab and overwrite any element whose id it collides with. `application.js` closes both with a document-level `htmx:before:swap` guard that clears `detail.ctx.title` and empties `detail.tasks`, the array htmx iterates to perform every swap in the response, main and out-of-band alike. **Settle phase**: `htmx.config.defaultSettleDelay` is `0`, which skips settling altogether. The phase exists to animate a swap through the `htmx-settling` and `htmx-added` classes, and it reaches that by copying the attributes of each replaced element onto its replacement and restoring the response's own attributes one tick later. The restore writes the `value` property of an input only when that input does not hold focus, and htmx restores focus before it settles, so a field being typed in while its own subtree is swapped keeps the `value` attribute copied off the element it replaced. No stylesheet here targets either class. **Swap events**: htmx fires one `htmx:before:swap` / `htmx:after:swap` pair per response, both on the element that issued the request. Only `htmx:before:swap` carries the swapped elements, in `detail.tasks`. `application.js` provides `onHtmxSwap(matches, callback)` and `htmxSwapSucceeded(event)` for this; listeners that skip the target filter fire on every request the page makes, including the sidebar poll present on every page. `swap()` awaits the swap tasks between the two events, so two responses in flight interleave and the pair cannot be joined by arrival order. `onHtmxSwap` keys pending targets on `detail.ctx`, the request context both events carry. `detail.tasks` names the element a swap targeted, which for `outerHTML` and `delete` is detached by the time the pair closes. `onHtmxSwap` resolves each target to what the swap left in the document -- the replacement carries the same `id` -- and drops the ones that left nothing. Callers therefore never need a document-wide fallback, which matters because `hx-swap-oob="true"` means `outerHTML` and the hidden sort/order/page inputs carry it on nearly every poll response the app sends. **Source versus target**: htmx dispatches `htmx:before:swap` and `htmx:after:swap` on the element that *issued* the request, not on the element that was swapped. An element-level listener on a swap target therefore only sees requests that element issued itself. Where a region is filled from more than one place -- its own poll trigger and a filter form, say -- match on the target with `onHtmxSwap` instead. **Aborted requests**: htmx reports an aborted fetch through `htmx:error`, the same event a network failure uses, and logs it at error level. Aborts are routine here: `hx-sync` names a queue on the filter form, the form itself carries no `hx-sync`, so a keystroke in the filter aborts an in-flight poll on that queue, and htmx applies a 60s default timeout. `application.js` provides `htmxRequestAborted(event)`; handlers that reset load state must call it, or a cancelled tick is shown to the reader as a failure while its replacement is already in flight. **History restores**: a back or forward navigation to a pushed URL swaps a refetched `<body>` into the document. htmx runs every `<script>` in it again, and every element a listener was bound to at load time is replaced by a new one. A second run of an inline script that declares a top-level `const` or `let` throws, and a listener bound directly to a shell control is lost. The controls on the page shell -- the theme toggle, the Logout link, and the close buttons of the notification and error banners -- are therefore delegated `document` listeners in `application.js`, and a page reachable through a pushed URL carries no inline `<script>` in `<body>`. `test_page_shell_survives_a_history_restore` in `test_views_tests.py` guards both rules. **Detail-page diff renderer**: `/tests/view/{id}` loads jsdiff from `cdn.jsdelivr.net` in `tests_view.html.j2` for the inline Diff panel. The asset is pinned and protected with SRI. ``` <script src="https://cdn.jsdelivr.net/npm/diff@9.0.0/dist/diff.min.js" integrity="sha256-tRqdKIXywJDcl7mBAnOV9+fmVYpGx1rjdH2yZ5E6ias=" crossorigin="anonymous" referrerpolicy="no-referrer"></script> ``` **Fragment detection in Starlette/FastAPI**: htmx sends `HX-Request: true` on every request it makes, and `HX-Request-Type` stating the scope of the swap. `partial` targets a region of the current page; `full` replaces the document, which is what a boosted navigation asks for. A back navigation names itself with `HX-History-Restore-Request` and carries `HX-Request-Type: full`, but no `HX-Request`: the restore passes its own request object, which replaces the core headers, and only the request type is added back afterwards. The server rejects each of those cases by name instead of requiring `partial`, so a header rename degrades to treating every htmx request as a fragment request rather than swapping whole pages into fragment targets: ``` def _is_hx_request(request) -> bool: headers = getattr(request, "headers", None) if headers is None: return False if (headers.get("HX-Request") or "").lower() != "true": return False if (headers.get("HX-History-Restore-Request") or "").lower() == "true": return False if (headers.get("HX-Request-Type") or "").lower() == "full": return False return (headers.get("Sec-Fetch-Mode") or "").lower() != "navigate" ``` **Dual-mode rendering with Jinja2**: the view handler renders either a fragment template or the full-page template from the same URL. The `_render_hx_fragment()` helper encapsulates the check-and-render pattern: ``` def _render_hx_fragment(request, template_name, context): if not _is_hx_request(request): return None return render_template_to_response( request=request.raw_request, template_name=template_name, context=build_template_context( request.raw_request, request.session, context ), ) ``` Fragment templates are standalone `.html.j2` files that do not extend `base.html.j2`. This avoids partial-block rendering complexity and keeps fragments self-contained. **Content fragments for stateful tables**: stateful list pages do not return only row fragments. They return content fragments (for example `contributors_content_fragment`, `user_management_content_fragment`, `workers_content_fragment`, `actions_content_fragment`) so that view toggles, truncation banners, pagination, and sort state remain synchronized with the table body. **Vary header for HTTP caching**: when the same URL can return either a full page or a fragment, every header the choice reads must appear in `Vary` so that HTTP caches (nginx, CDNs) store separate representations: ``` for header in FRAGMENT_REQUEST_HEADERS: _append_vary_header(response, header) ``` Every token earns its place: `HX-Request-Type` separates a fragment request from a boosted navigation to the same URL, and `HX-History-Restore-Request` and `Sec-Fetch-Mode` each mark a request the same URL answers with a whole page. Use the same `Vary` value on the full-page response, the fragment response, and any `304 Not Modified` response for that URL. **OOB swaps with Jinja2**: out-of-band elements carry `hx-swap-oob` attributes directly in the template markup, and one response can update many elements. Rows need a `<template>` wrapper because a `<tr>` cannot stand on its own in parsed HTML. Put `id` and `hx-swap-oob` on the `<template>` element itself. htmx locates out-of-band elements with `querySelectorAll`, which does not descend into template content, so an `hx-swap-oob` on an element inside the wrapper is silently ignored and the swap never happens. htmx strips the wrapper before applying the swap. ``` {# OOB element that can stand alone -- no wrapper #} <span id="count" hx-swap-oob="innerHTML">{{ count }}</span> {# OOB rows -- wrapper carries the id and the swap #} <template id="my-table" hx-swap-oob="innerHTML"> {% for row in rows %} <tr>...</tr> {% endfor %} </template> ``` Only wrap what the parser requires. A `<div>` or `<span>` target needs no `<template>`. **Polling lifecycle**: htmx clears a poll interval only when the element carrying `hx-trigger="every Ns"` leaves the document. A poll ends from the response body, by removing that element: - **200** -- swap the response content, continue polling. - **204** -- no content change; htmx skips the swap, continues polling. - **200 with a driver-removing element** -- terminal state: ``` <div id="{{ poller_id }}" hx-swap-oob="delete"></div> ``` A status code cannot stop a poll. **Request coordination**: `hx-sync` is used where user actions and polling can target the same fragment. The main repo pattern is `hx-sync="#machines-filters:abort"`, which puts the poll driver and the sort/pagination links on the queue owned by the filter form. `abort` means *drop this request while one is in flight on that queue*, so it is the poll that yields: the filter form declares no `hx-sync` of its own, which leaves it on the default `queue first` strategy, and htmx aborts an in-flight `abort` request to run it. A sort or pagination click that lands inside a poll's request window is dropped rather than queued. **Attribute inheritance**: htmx applies an ancestor's attribute to a descendant only where the ancestor marks it `:inherited`, for example `hx-target:inherited="#output"`. Sort and pagination links inside a filter form therefore inherit nothing and send only their own query string. A `GET` collects the enclosing form only when the requesting element is the form itself. **Search portability**: `input changed delay:{{ htmx.input_changed_delay_ms }}ms` is the portable search trigger baseline. Native `search` events and `::-webkit-search-cancel-button` styling are browser-specific enhancements, not the correctness contract. Search inputs keep visible labels or another valid accessible name. **Conditional polling with visibility**: polls are gated on tab visibility to avoid unnecessary server load. The condition goes on the `every` token itself, with the interval after it: ``` <div hx-get="/endpoint" hx-trigger="every[document.visibilityState === 'visible'] 30s" hx-swap="none"> </div> ``` htmx splits a trigger into one leading token plus modifiers, and reads a `[condition]` filter off the leading token (`#parseTriggerSpecs` then `#extractFilter`). `every[<condition>] Ns` is that form; htmx also rewrites `every Ns [<condition>]` into it before parsing. The templates write the condition on the `every` token only. `test_poll_conditions_are_attached_to_the_every_token` in `test_http_boundary.py` guards the whole template tree against the other spellings. Treat the transition to `hidden` as the point to stop background UI updates. **Focus-return immediate refresh**: every visibility-gated poller also triggers on `visibilitychange` so that returning to the tab produces an immediate update instead of waiting for the next poll cycle. A named event carries its own filter directly, with no space before the bracket: ``` <div hx-get="/endpoint" hx-trigger="every[document.visibilityState === 'visible'] 30s, visibilitychange[document.visibilityState === 'visible'] from:document" hx-swap="none"> </div> ``` Section-scoped pollers (machines, tasks) combine both the tab visibility and section expanded state in a single filter expression: ``` <div hx-get="/endpoint" hx-trigger="every[document.visibilityState === 'visible' && document.getElementById('section').classList.contains('show')] 60s, visibilitychange[document.visibilityState === 'visible' && document.getElementById('section').classList.contains('show')] from:document" hx-swap="innerMorph"> </div> ``` A polled region a reader interacts with uses a morph swap: `innerHTML` gives the region new nodes on every tick, which drops keyboard focus out of it. **Error recovery in JavaScript**: retry buttons in htmx error handlers must be constructed with DOM API (`createElement`, `textContent`, `setAttribute`) rather than string concatenation with `innerHTML`, to prevent XSS from error messages and to keep htmx attributes functional (via `htmx.process()`). ## Python, MongoDB, and tooling ### Canonical references | Topic | URL | | --- | --- | | Python 3.15 docs | https://docs.python.org/3.15/ | | MongoDB manual | https://www.mongodb.com/docs/manual/ | | PyMongo | https://www.mongodb.com/docs/languages/python/pymongo-driver/current/ | | Uvicorn | https://uvicorn.dev/ | | vtjson | https://github.com/vdbergh/vtjson | | uv | https://docs.astral.sh/uv/ | | Ruff | https://docs.astral.sh/ruff/ | | ty | https://docs.astral.sh/ty/ | | pre-commit | https://pre-commit.com/ | | Prettier | https://prettier.io/docs/ | | zizmor | https://docs.zizmor.sh/ | | zensical | https://zensical.org/docs/ | | nginx | https://nginx.org/en/docs/ | Use [Development](<http://official-stockfish.github.io/fishtest/development/index.md>) for local lint and test workflows. ## Tooling references | Tool | Path | Purpose | | --- | --- | --- | | Repository dev tools | `pyproject.toml`, `uv.lock` | Shared repo tooling configuration and the docs site tools | | Server Python project | `server/pyproject.toml`, `server/uv.lock` | Server dependency and tool configuration | | Worker Python project | `worker/pyproject.toml`, `worker/uv.lock` | Worker dependency configuration | | Server test package | `server/tests/` | Unit and HTTP contract tests | | Pre-commit hooks | `.pre-commit-config.yaml` | Checks run on every commit | | CI workflows | `.github/workflows/*.yaml` | Lint, server and worker tests, docs site | | Docs site | `mkdocs.yml` | The zensical configuration of this site | ## Testing patterns ### Test structure Server tests live in `server/tests/`. All tests use `unittest.TestCase`. MongoDB is required for most tests (the CI workflow starts `mongod` before running the suite). User-facing HTTP route tests are split by route family or one focused UI motif instead of accumulating in one omnibus module. ### Fixtures Most test files import `test_support`, which provides: - `get_rundb()`: returns a `RunDb` connected to the test MongoDB instance. - `build_test_app(...)`: constructs a `FastAPI()` application with selectable API and views routers. - `make_test_client(...)`: wraps `build_test_app` in a Starlette `TestClient`. - `cleanup_test_rundb(...)`: drops test collections after a test class runs. - `find_run(...)`: retrieves a run from the database by field match. - `extract_csrf_token(html)`: parses a CSRF token from rendered HTML. - `extract_meta_content(html, ...)`: reads a `<meta>` tag's content from rendered HTML. - `require_fastapi()`: imports FastAPI and the test client, skipping the test when the server dependencies are missing. User-facing UI route modules also reuse `ui_user_test_case.py` for shared client setup, login helpers, run creation, and DB cleanup. Worker-related fixtures must match the `short_worker_name` pattern (`.*-[\d]+cores-[a-zA-Z0-9]{2,8}`) or `WorkerDb.update_worker()` schema validation fails. ### Key test modules | Module | Coverage | | --- | --- | | `test_app.py` | Application startup, middleware, lifespan | | `test_api.py` | Worker API protocol (request\_task, update\_task, beat) | | `test_users.py` | Login, signup, remember-me, userdb auth flags, basic UI smoke | | `test_views_admin.py` | Workers, user-management, rate-limits, and shared admin UI contracts | | `test_views_tests.py` | `/tests` and `/tests/user/{username}` filter state and live-table polling | | `test_views_actions.py` | Actions search, pagination, sorting | | `test_views_contributors.py` | Contributors search, rank jump, sorting, and HTMX state sync | | `test_views_detail.py` | `/tests/view/{id}` detail polling, `/tests/tasks/{id}`, and task UI assets | | `test_views_finished.py` | Finished-runs search and pagination | | `test_views_helpers.py` | Shared pagination, parameter, and merge helpers | | `test_views_machines.py` | Machines helper behavior plus `/tests/machines` HTTP contracts | | `test_views_run.py` | Run-form validation, SPSA parsing, permissions, and run action routes | | `test_spsa_workflow.py` | Shared classic SPSA form, worker update, and chart-payload helper contracts | | `test_http_boundary.py` | HTTP boundary invariants and template contracts | | `test_http_dependencies.py` | Request-state dependency wiring | | `test_http_errors.py` | API vs UI error shaping | | `test_http_helpers.py` | Jinja/static helpers and shared HTTP utilities | | `test_http_middleware.py` | Middleware behavior and blocked-user flow | | `test_http_settings.py` | Runtime settings and environment parsing | | `test_http_ui_session_semantics.py` | Session commit and UI CSRF semantics | | `test_nn.py` | Neural network upload and listing | | `test_rundb.py` | `RunDb` persistence and run lifecycle | | `test_kvstore.py` | Key-value store behavior | | `test_lru_cache.py` | LRU cache storage, eviction, and decorator behavior | | `test_github_api.py` | GitHub API helpers | | `test_delta_update_users.py` | Monthly contributor stats rebuild helpers | | `test_http_open_graph.py` | Open Graph metadata helpers | | `test_http_ui_cookies.py` | Browser-readable UI cookie helpers | | `test_views_routes.py` | UI route HTTP method contracts | | `test_views_stats.py` | `/tests/stats` page and fragment contracts |