diff --git a/astro.config.mjs b/astro.config.mjs index 2b3d646..570a305 100644 --- a/astro.config.mjs +++ b/astro.config.mjs @@ -121,6 +121,7 @@ export default defineConfig({ { label: "Overview", slug: "backend/overview" }, { label: "API Reference", slug: "backend/api-reference" }, { label: "Database", slug: "backend/database" }, + { label: "Result Storage", slug: "backend/result-storage" }, { label: "Simulation Lifecycle", slug: "backend/simulation-lifecycle", diff --git a/public/openapi.yaml b/public/openapi.yaml index cfa88c6..7195662 100644 --- a/public/openapi.yaml +++ b/public/openapi.yaml @@ -894,6 +894,7 @@ paths: the response will include results only for the specified estimator. If no `estimator_name` is provided, the response will include results for all estimators associated with the job. Additionally, you can specify pages using the `page_number` or `page_numbers` parameter to limit the response to specific pages. + Pages come as signed links to the results bucket, which the client fetches through nginx (/yaptide-results/). parameters: - in: query name: job_id @@ -1377,9 +1378,33 @@ components: task_state: type: string enum: [PENDING, RUNNING, COMPLETED, FAILED] - Page: + Page: type: object - description: Page object + description: A result page in the results bucket, as signed links to its objects (a Zarr v3 array). A page + stored before the bucket and not moved there yet comes as the page itself, with its values in data.values. + properties: + page_number: + type: integer + name: + type: string + dimensions: + type: integer + format: + type: string + enum: [zarr-v3] + description: How the page is stored + url: + type: string + description: Signed link of the page's zarr.json, valid 15 minutes + files: + type: object + description: Signed link of each of the page's objects, valid 15 minutes; c/0 answers 404 for a page without + values + properties: + zarr.json: + type: string + c/0: + type: string Estimator: type: object description: Estimator object includes estimator's name, associated metadata, and list of pages. diff --git a/src/content/docs/api-reference/results.md b/src/content/docs/api-reference/results.md index 30c4bdf..9c8903c 100644 --- a/src/content/docs/api-reference/results.md +++ b/src/content/docs/api-reference/results.md @@ -5,7 +5,9 @@ description: Simulation results, estimators, inputs, and log file retrieval. ## Get Results -Retrieve simulation results with optional filtering by estimator and page. +Retrieve simulation results with optional filtering by estimator and page. Each page comes as **signed links** to +its objects in the results bucket, not as its values: the browser fetches them through nginx +(`/yaptide-results/...`), see [Result Storage](/for_developers/backend/result-storage/). ```http GET /results?job_id=abc123-def456 @@ -39,10 +41,12 @@ GET /results?job_id=abc123-def456 { "page_number": 1, "name": "Z (Dose)", - "data": { - "values": [0.0, 0.001, 0.015, ...], - "dimensions": [[0.0, 0.5, 1.0, ...]], - "unit": "Gy" + "dimensions": 1, + "format": "zarr-v3", + "url": "https:///yaptide-results/simulations/17/z_profile_/1/3f2a9c0d1e4b5a67/zarr.json?X-Amz-...", + "files": { + "zarr.json": "https:///yaptide-results/simulations/17/z_profile_/1/3f2a9c0d1e4b5a67/zarr.json?X-Amz-...", + "c/0": "https:///yaptide-results/simulations/17/z_profile_/1/3f2a9c0d1e4b5a67/c/0?X-Amz-..." } } ] @@ -67,7 +71,18 @@ GET /results?job_id=abc123-def456&page_numbers=1-3,5 Returns only the specified pages across all estimators. -> **Note:** Result data is stored compressed (zlib) in the database. The API decompresses transparently. +**A stored page:** + +| Field | Description | +|---|---| +| `page_number`, `name`, `dimensions` | The page, as kept in the database | +| `format` | `zarr-v3`: a Zarr v3 array of float32 values in one shard | +| `files` | Signed link for each object: `zarr.json` (metadata; its `attributes.yaptide_page` is the page as the JSON pages had it, without the values) and `c/0` (the shard) | +| `url` | The link of `zarr.json` | + +The links last 15 minutes; ask `/results` again for new ones. A page without values has no shard, and its `c/0` link +answers 404, which a Zarr reader takes as the fill value. A page stored before the results bucket and not yet moved +there (`db_manage copy-pages-to-storage`) still comes as the page itself, with `data.values`. --- @@ -180,7 +195,10 @@ Log files are useful for debugging failed simulations — they contain the simul ## Internal: Upload Results -**Worker-facing only.** Simulation workers call this to save results to the database. +**Worker-facing only.** The merge of a direct simulation and the collect job of a batch simulation call this with +the merged results. Each page comes with its values; the backend writes it to the results bucket as a Zarr array and +keeps where it is in the database. Pages stored before for the same estimator and page are replaced, and their objects +removed. Answers `202` when stored, `500` when the bucket did not take the pages (nothing is kept then). ```http POST /results diff --git a/src/content/docs/architecture/data-flow.md b/src/content/docs/architecture/data-flow.md index b3f74b4..dbb4c6f 100644 --- a/src/content/docs/architecture/data-flow.md +++ b/src/content/docs/architecture/data-flow.md @@ -76,7 +76,8 @@ POST /jobs/direct - POSTs status updates to `POST /tasks` (primaries completed, estimated time) 4. When all N tasks complete, a **merge task** (`get_job_results`) runs: - Averages estimator results across all tasks - - Compresses and stores results in the database (`EstimatorModel` → `PageModel`) + - POSTs them to `POST /results`, which writes each page to the results bucket as a Zarr array and records it in + the database (`EstimatorModel` → `PageModel` → `PageObjectModel`) 5. Job state transitions: `PENDING → RUNNING → MERGING_QUEUED → MERGING_RUNNING → COMPLETED` **Polling**: The UI polls `GET /jobs/direct?job_id=` at intervals to check status and fetch partial progress. @@ -97,7 +98,8 @@ POST /jobs/batch - Uploads watcher and data-sender scripts - Submits a **Slurm array job** (`sbatch`) + a collect job 3. The cluster's **watcher script** monitors each array task and POSTs progress back to the YAPTIDE backend. -4. When all array tasks finish, the **collect job** gathers results and POSTs them to `POST /results`. +4. When all array tasks finish, the **collect job** gathers results and POSTs them to `POST /results`, which stores + them as for direct execution. **Polling**: The UI polls `GET /jobs/batch?job_id=`. The backend also checks cluster status via `sacct` over SSH. @@ -122,10 +124,14 @@ Regardless of the execution path, results follow the same structure: - **Estimators** — named result containers (e.g., `detector_dose`, `mesh_fluence`) - **Pages** — individual scoring dimensions within an estimator (e.g., energy bins, spatial slices) -Each page contains: -- `page_name` — descriptive name -- `page_dimension` — number of dimensions -- `compressed_data` — gzip-compressed JSON with axes, values, and metadata +Each page is a Zarr v3 array in the results bucket: its values (float32) in one shard, and its axes, unit and +metadata as attributes of its `zarr.json`. The database keeps the page's `page_name`, `page_dimension` and where it is +stored (`PageObjectModel`). + +`GET /results` answers with **signed links** to each page's objects, never with the values. The browser fetches them +from nginx (`/yaptide-results/`), which passes them to the bucket; result data does not go through Flask. See +[Result Storage](/for_developers/backend/result-storage/) and +[Results Loading](/for_developers/frontend/results-loading/). The UI renders results using **JSRoot** (CERN ROOT's JavaScript library): - 1D histograms (e.g., Bragg peak depth-dose curves) @@ -135,13 +141,14 @@ The UI renders results using **JSRoot** (CERN ROOT's JavaScript library): ## Data Persistence -All simulation data is stored in PostgreSQL with gzip compression. +Simulation data is stored in PostgreSQL with gzip compression, except the result pages, which are kept in the S3 +bucket. | Data | Storage | |---|---| | Input files (JSON or raw) | `InputModel.compressed_data` | | Estimator metadata | `EstimatorModel` (name, filename) | -| Result pages | `PageModel.compressed_data` | +| Result pages | Zarr arrays in the results bucket; `PageModel` + `PageObjectModel` (key, size, format) | | Simulation logs | `LogfilesModel.compressed_data` | | Job state and metadata | `SimulationModel` + `TaskModel` | diff --git a/src/content/docs/architecture/overview.md b/src/content/docs/architecture/overview.md index 2bbc166..5faefd2 100644 --- a/src/content/docs/architecture/overview.md +++ b/src/content/docs/architecture/overview.md @@ -24,15 +24,16 @@ YAPTIDE is composed of **three repositories** that work together to provide a co │ │ └─────────────────────────┘ │ │ │ └──────────────────────┬───────────────────────────┘ │ └─────────────────────────┼───────────────────────────────┘ - │ HTTPS (REST API) + │ HTTPS (REST API, result pages) ┌─────────────────────────┼───────────────────────────────┐ │ Nginx │ :8443 │ -│ ┌───────┴───────┐ │ -│ │ Flask API │ :6000 │ -│ └───┬───────┬──┘ │ -│ │ │ │ -│ ┌──────────┤ ├──────────┐ │ -│ ▼ ▼ ▼ ▼ │ +│ ├──── /yaptide-results/ ───┐ │ +│ ┌───────┴───────┐ ▼ │ +│ │ Flask API │ :6000 ┌──────────┐│ +│ └───┬───────┬──┘ ──────▶│ Garage ││ +│ │ │ │ (S3, the ││ +│ ┌──────────┤ ├──────────┐ │ pages) ││ +│ ▼ ▼ ▼ ▼ └──────────┘│ │ ┌──────────┐ ┌───────┐ ┌─────────────────────┐ │ │ │ Redis │ │ PgSQL │ │ Celery Workers │ │ │ │ (broker) │ │ (DB) │ │ │ │ @@ -62,12 +63,15 @@ YAPTIDE is composed of **three repositories** that work together to provide a co ### Backend (`yaptide` repository) -The backend is a **Flask** API server with **Celery** for async task execution and **PostgreSQL** for persistence. +The backend is a **Flask** API server with **Celery** for async task execution, **PostgreSQL** for persistence and +an S3 bucket (**Garage**) for result pages. - **REST API** — Handles authentication, job submission, status polling, and result retrieval. - **Simulation Worker** — Celery worker that runs simulator binaries (SHIELD-HIT12A, FLUKA) in temporary directories, monitors progress, and posts updates back to Flask. - **Helper Worker** — Celery worker for HPC batch job submission via SSH (PLGrid/Slurm) and cleanup tasks. -- **Nginx** — Reverse proxy with TLS termination. +- **Garage** — S3-compatible object storage holding the result pages as Zarr arrays; Flask writes them, the browser + reads them with signed links. See [Result Storage](/for_developers/backend/result-storage/). +- **Nginx** — Reverse proxy with TLS termination; passes `/yaptide-results/` to Garage. ### UI (`ui` repository) diff --git a/src/content/docs/backend/database.md b/src/content/docs/backend/database.md index e069ef9..89386f3 100644 --- a/src/content/docs/backend/database.md +++ b/src/content/docs/backend/database.md @@ -25,7 +25,7 @@ SimulationModel ──< TaskModel (polymorphic) └── BatchTaskModel SimulationModel ──< InputModel -SimulationModel ──< EstimatorModel ──< PageModel +SimulationModel ──< EstimatorModel ──< PageModel ──o PageObjectModel SimulationModel ──< LogfilesModel ClusterModel ──< BatchSimulationModel @@ -147,7 +147,20 @@ ClusterModel ──< BatchSimulationModel | `page_number` | Integer | 0-based page index | | `page_name` | String | Descriptive name | | `page_dimension` | Integer | Number of dimensions | -| `compressed_data` | LargeBinary | gzip-compressed result data (axes, values) | +| `compressed_data` | LargeBinary | Empty for pages in the results bucket. Pages stored before the bucket keep their gzip-compressed JSON (axes, values) here until `db_manage copy-pages-to-storage` and `clear-pages-in-postgres` move them | + +**`PageObject`** — where a page is in the results bucket (one row per page at most). + +| Column | Type | Description | +|---|---|---| +| `page_id` | Integer (PK, FK → Page, cascade) | | +| `key` | String | Prefix of the page's objects, `simulations/////` | +| `size` | Integer | Size of the page's objects in bytes | +| `format` | String | `zarr-v3` | + +The page's values are only in the bucket, so the `PageObject` migration (`9e2b41c7d5a3`) refuses to downgrade while +the table has rows: `db_manage move-pages-to-postgres` brings the pages back first. See +[Result Storage](/for_developers/backend/result-storage/). **`Logfiles`** — simulation log output. @@ -168,7 +181,8 @@ ClusterModel ──< BatchSimulationModel ## Data Compression -All large binary fields use gzip compression: +Result pages are not in the database: they are Zarr arrays in the results bucket, each chunk compressed with zstd +([Result Storage](/for_developers/backend/result-storage/)). The other large binary fields use gzip compression: ```python from yaptide.persistence.models import compress, decompress @@ -180,7 +194,7 @@ model.compressed_data = compress(json.dumps(data).encode()) data = json.loads(decompress(model.compressed_data).decode()) ``` -This reduces storage for large simulation results (estimator pages can be several MB uncompressed). +This reduces storage for inputs, estimator metadata and logs. ## Migration Workflow diff --git a/src/content/docs/backend/docker-deployment.md b/src/content/docs/backend/docker-deployment.md index 5c1139a..2a2ba07 100644 --- a/src/content/docs/backend/docker-deployment.md +++ b/src/content/docs/backend/docker-deployment.md @@ -3,13 +3,14 @@ title: Docker Deployment description: Running the YAPTIDE backend with Docker Compose. --- -The backend deployment uses **Docker Compose** with 6 services. This is the recommended way to run the full stack. +The backend deployment uses **Docker Compose** with 7 services. This is the recommended way to run the full stack. ## Services ```yaml # Simplified view of docker-compose.yml services: + garage: # S3 bucket for the result pages redis: # Celery broker + result backend postgresql: # Primary database yaptide_flask: # Flask API server (gunicorn) @@ -22,6 +23,7 @@ services: | Service | Image | Port | Role | |---|---|---|---| +| `garage` | `dxflrs/garage:v2.6.0` | 3900 (internal) | S3 object storage for result pages, bucket `yaptide-results`, persisted via named volumes | | `redis` | `redis:8-alpine` | 6379 (internal) | Celery message broker and result backend | | `postgresql` | `postgres:16-alpine` | 5432 (internal) | Primary database, persisted via named volume | | `yaptide_flask` | `Dockerfile-flask` | 6000 (internal) | Flask API server under gunicorn, migrates the database on start | @@ -50,6 +52,23 @@ progress finish during a redeploy. Nginx resolves `yaptide_flask` through Docker's DNS on each request (cached for 10 s), so a restarted Flask container is reached at its new address without reloading nginx. +### Result Storage + +Result pages live in the `yaptide-results` bucket of the `garage` service (single node, configured by `garage.toml`), +see [Result Storage](/for_developers/backend/result-storage/). Garage creates the bucket and its key on the first +start from three values that must be in `.env` (compose refuses to start without them): + +```bash +echo "RESULTS_S3_ACCESS_KEY=GK$(openssl rand -hex 12)" >> .env +echo "RESULTS_S3_SECRET_KEY=$(openssl rand -hex 32)" >> .env +echo "GARAGE_RPC_SECRET=$(openssl rand -hex 32)" >> .env +``` + +Keep them: the key pair is fixed after the first start, and a new secret for the same key id stops Garage from +starting. Garage publishes no port. Flask reaches it inside the compose network (`http://garage:3900`), and the +browser reaches it through nginx at `/yaptide-results/` (GET only) with links that Flask signs for +`BACKEND_EXTERNAL_URL`. That variable must therefore be the address the browser reaches nginx at. + ### Exposed Ports | Port | Protocol | Service | @@ -57,10 +76,16 @@ container is reached at its new address without reloading nginx. | `5000` | HTTP | Nginx → Flask API | | `8443` | HTTPS | Nginx → Flask API (TLS) | +Both ports also serve `/yaptide-results/`, the result pages in Garage. + ## Quick Start ```bash cd yaptide +# once: the keys of the results bucket, see Result Storage above +echo "RESULTS_S3_ACCESS_KEY=GK$(openssl rand -hex 12)" >> .env +echo "RESULTS_S3_SECRET_KEY=$(openssl rand -hex 32)" >> .env +echo "GARAGE_RPC_SECRET=$(openssl rand -hex 32)" >> .env docker compose up --build -d ``` @@ -133,7 +158,7 @@ Set these in a `.env` file in the `yaptide/` root or pass them via Docker: | `CELERY_BROKER_URL` | `redis://redis:6379/0` | Redis broker URL | | `CELERY_RESULT_BACKEND` | `redis://redis:6379/0` | Redis result backend | | `BACKEND_INTERNAL_URL` | `http://yaptide_flask:6000` | Internal URL for worker → Flask | -| `BACKEND_EXTERNAL_URL` | `https://localhost:8443` | Public-facing URL | +| `BACKEND_EXTERNAL_URL` | `https://localhost:8443` | Public-facing URL; signed links to result pages point here | | `MAX_CORES` | (all) | CPU limit for simulation worker | | `LOG_LEVEL_ROOT` | `INFO` | Logging verbosity | | `YAPTIDE_TOKEN_SECRET` | (generated at start) | Secret for access tokens and simulation update keys, shared by all gunicorn workers | @@ -141,6 +166,20 @@ Set these in a `.env` file in the `yaptide/` root or pass them via Docker: | `GUNICORN_WORKERS` | (sized to the container) | Number of gunicorn workers; above 32, raise PostgreSQL's `max_connections` to match | | `GUNICORN_TIMEOUT` | `300` | Seconds a worker may spend on one request (large `/results` uploads) | +### Results Bucket + +| Variable | Default | Description | +|---|---|---| +| `RESULTS_S3_ACCESS_KEY` | (required) | Key id of the bucket, `GK` + 24 hex characters; Garage creates it on the first start | +| `RESULTS_S3_SECRET_KEY` | (required) | Its secret, 64 hex characters | +| `GARAGE_RPC_SECRET` | (required) | Garage's internal secret, 64 hex characters | +| `RESULTS_S3_BUCKET` | `yaptide-results` | Set by `docker-compose.yml` | +| `RESULTS_S3_ENDPOINT` | `http://garage:3900` | Set by `docker-compose.yml`; where Flask writes the pages | +| `RESULTS_S3_PUBLIC_ENDPOINT` | `BACKEND_EXTERNAL_URL` | Optional: another address for the browser's signed links | +| `RESULTS_S3_REGION` | `garage` | Optional: the region of another S3 server | + +Flask does not start without the bucket settings. + ### Authentication | Variable | Description | @@ -180,9 +219,13 @@ For production, replace the self-signed certificates with real ones: ## Volume Persistence -The PostgreSQL data is stored in a **named Docker volume** (`postgres_data`). This survives `docker compose down` but is removed with `docker compose down -v`. +The PostgreSQL data is stored in a **named Docker volume** (`postgres_data`), and the result pages in two +(`garage_meta`, `garage_data`). They survive `docker compose down` but are removed with `docker compose down -v`. + +> To completely reset the database and the results: `docker compose down -v && docker compose up --build -d` -> To completely reset the database: `docker compose down -v && docker compose up --build -d` +`scripts/backup.sh` ([Backups](/for_developers/backend/result-storage/#backups)) sends a `pg_dump` and a mirror of the bucket to a second S3 +server, and restores them. ## Container Images on GHCR diff --git a/src/content/docs/backend/result-storage.md b/src/content/docs/backend/result-storage.md new file mode 100644 index 0000000..cb2782c --- /dev/null +++ b/src/content/docs/backend/result-storage.md @@ -0,0 +1,157 @@ +--- +title: Result Storage +description: How result pages are kept in an S3 bucket as Zarr arrays, and read by the browser with signed links. +--- + +Result pages are not kept in PostgreSQL. Each page is a **Zarr v3 array** in an S3 bucket, the `garage` service of +`docker-compose.yml` on a deployment. The database keeps only the page's name, dimension and where it is stored. The +browser fetches the pages straight from the bucket with **signed links**, so result data passes neither through +PostgreSQL nor through Flask. + +| Code | Role | +|---|---| +| `yaptide/persistence/result_storage.py` | S3 client, keys, put, read, delete, signed links | +| `yaptide/batch/result_format.py` | Zarr v3 writer and reader for one page (standard library only, numpy and zstandard when present) | +| `PageObjectModel` in `yaptide/persistence/models.py` | Where a page is: key, size, format | +| `page_content`, `store_results` in `yaptide/routes/common_sim_routes.py` | `GET /results` and `POST /results` | +| `nginx.conf`, `/yaptide-results/` | The browser's way to the bucket | +| `yaptide/admin/db_manage.py` | Moving pages stored before the bucket, and back | + +## Configuration + +A bucket is required: Flask does not start without these settings (`docker-compose.yml` sets them from `.env`). + +| Variable | Description | +|---|---| +| `RESULTS_S3_BUCKET` | Bucket name, `yaptide-results` in compose | +| `RESULTS_S3_ENDPOINT` | Where Flask reaches the bucket, `http://garage:3900` in compose | +| `RESULTS_S3_ACCESS_KEY`, `RESULTS_S3_SECRET_KEY` | Keys of the bucket | +| `RESULTS_S3_PUBLIC_ENDPOINT` | Optional: address the browser's links are signed for; default `BACKEND_EXTERNAL_URL` | +| `RESULTS_S3_REGION` | Optional: region the requests are signed for; default `garage` | + +On a deployment, Garage creates the bucket and the key on its first start from `RESULTS_S3_ACCESS_KEY`, +`RESULTS_S3_SECRET_KEY` and `GARAGE_RPC_SECRET`, see [Docker Deployment](/for_developers/backend/docker-deployment/#result-storage). + +## Storage Layout + +``` +simulations/////zarr.json +simulations/////c/0 +``` + +- `zarr.json` — the array's metadata. Its `attributes.yaptide_page` holds the page as the JSON pages had it (name, + unit, axes, metadata), without the values. +- `c/0` — one shard holding every chunk of the values, as float32 in the order pymchelper keeps them (flat). A + page of dimension 0 has one value; a page without values has no shard. + +Chunks hold 65 536 values (256 KiB) and are compressed with zstd (level 1). Where zstandard is missing the writer +falls back to gzip (level 1), which any Zarr reader also opens. Chunks of zeros only are left out of the shard (its +index marks them empty), so sparse results take little space. Any Zarr v3 reader opens a page; the UI reads them as +described in [Results Loading](/for_developers/frontend/results-loading/). + +### Revisions + +Every time a page is stored, it gets a new **revision**, a random 16-hex-digit name, so its objects go under a new +prefix. The database points the page at the new prefix only once all its objects are in the bucket, in the same +commit as the estimators. A reader therefore always gets either the old page or the new one, never a page half +written, and the old prefix is removed only after the commit. + +## Writing Results + +The merge of a direct simulation and the collect job of a batch simulation send the merged results, values +included, to `POST /results`. For each page, `store_results`: + +1. waits for other results of the same simulation being stored (a PostgreSQL advisory lock), so two requests do not + both create the estimators; +2. converts the page to Zarr (`result_format.page_files`) and puts its objects under a new revision; each upload + carries its `Content-MD5`, so the bucket refuses a body that arrived changed; +3. points the page's `PageObject` row at the new prefix and empties `Page.compressed_data`; +4. commits the estimators and pages together, then removes the prefixes of the pages they replaced. + +If the bucket fails on any page, nothing of these results is kept: the transaction is rolled back, the objects +already put are removed, and the request answers `500`. The simulation stays in its state. + +## Reading Results + +`GET /results` answers each stored page with its `page_number`, `name`, `dimensions`, `format` (`zarr-v3`), and +a signed link for each object in `files` (`url` is the link of `zarr.json`). See the +[Results API](/for_developers/api-reference/results/). + +- **Links last 15 minutes** (`URL_SECONDS`). The UI fetches a page right after asking for it; a link that leaks stops + working soon after, and a client that needs a page later asks `/results` again. +- **Links are signed for `BACKEND_EXTERNAL_URL`** (or `RESULTS_S3_PUBLIC_ENDPOINT`), at the path + `//`. Nginx passes `/yaptide-results/` to Garage with the `Host` header and the path unchanged, since + the signature covers both. That route allows only `GET` (and `HEAD`), answers a browser's preflight (`OPTIONS`) itself, and adds the CORS + headers. +- **The bucket allows no anonymous access.** Garage publishes no port; only Flask, inside the compose network, + holds the keys. A request through nginx without a valid signature, or with another method, is refused (`403`). + +A page stored before the bucket and not moved there yet still has its data in `Page.compressed_data` and goes to the +UI as the page itself, as before. + +## Deleting + +Deleting a simulation (`DELETE /user/simulations`) removes it from the database first, then every object under +`simulations//` in the request, listed and deleted 500 keys per request with a patient client (2 minutes per +request, 5 attempts). A failure is logged and leaves objects no page points at; the simulation is gone either way. +`db_manage remove-simulation` removes the objects too. + +## Pages Stored Before the Bucket + +Pages stored before this storage keep their gzip-compressed JSON in `Page.compressed_data`. Three `db_manage` +commands, run in the `yaptide_flask` container, move them; all take `--dry-run` and `--batch-size`: + +```bash +docker exec yaptide_flask python -m yaptide.admin.db_manage copy-pages-to-storage +docker exec yaptide_flask python -m yaptide.admin.db_manage clear-pages-in-postgres --dry-run +docker exec yaptide_flask python -m yaptide.admin.db_manage clear-pages-in-postgres +``` + +1. **Back up first**: `scripts/backup.sh`, or at least a `pg_dump --format=custom`. +2. **`copy-pages-to-storage`** converts each page of a finished simulation (completed, failed or canceled) to Zarr, + as new pages are stored, uploads it and checks every object in the bucket (size and MD5). It only reads the + database: the pages are still served from it. The revision of a copy is taken from the page's id and its Zarr + objects, so a repeated run finds the copies already made and uploads only what is missing, also after + `move-pages-to-postgres`; it can be stopped and repeated at any time. Pages of running simulations are left to the backend, which may replace them; run again after they end. +3. **`clear-pages-in-postgres --dry-run`** lists any page without a matching copy. +4. **`clear-pages-in-postgres`** makes the copies the only ones: for each batch whose every page is verified in the + bucket, in one transaction, it empties `compressed_data` and adds the `PageObject` row. A page the backend + stored again meanwhile is left alone. From then on the pages are read from the bucket. + +**Back:** `move-pages-to-postgres` reads every page kept in the bucket, converts it back to JSON (the values keep +float32 precision) and writes it into `Page.compressed_data`, removing its `PageObject` row; the objects stay in the +bucket. Run it before downgrading below migration `9e2b41c7d5a3`, which refuses while `PageObject` has rows, since +they are the only record of those pages. + +## Backups + +`scripts/backup.sh`, run on the host from the backend's repository directory, sends a `pg_dump` (custom format) and a +mirror of the result pages to a second S3 server. It reads `.env`: + +| Variable | | +|---|---| +| `BACKUP_S3_ENDPOINT` | address of the backup S3 server, e.g. `https://s3.example.org` | +| `BACKUP_S3_BUCKET` | bucket for the backups, created beforehand | +| `BACKUP_S3_ACCESS_KEY`, `BACKUP_S3_SECRET_KEY` | keys allowed to list, read, write and delete in it | +| `BACKUP_S3_REGION` | only if the server wants one | + +In the backup bucket: `postgres/daily/DATE.dump` (kept 14 days), `postgres/weekly/DATE.dump` (Sundays, kept 8 weeks), +`results/` (the pages, mirrored at every run) and `replaced/DATE/` (pages removed or replaced in Garage since the run +before, kept 14 days). It needs only Docker (rclone runs from the pinned `rclone/rclone` image). `.env` itself is not +backed up: keep a copy elsewhere, a restored Garage needs the same keys. Nightly, e.g.: + +``` +30 2 * * * cd /path/to/yaptide && scripts/backup.sh >> /var/log/yaptide-backup.log 2>&1 +``` + +Restore (also on a new server, after `docker compose up -d postgresql garage`): + +``` +docker compose stop nginx yaptide_flask yaptide_simulation_worker yaptide_helper_worker +scripts/backup.sh restore 2026-10-17 # pg_restore of that dump, then the missing pages copied back into Garage +docker compose up -d +``` + +The restore asks for the database name, and first saves the database it replaces to `postgres/before-restore/` +(kept), to undo it with `pg_restore --clean`. The nightly run stops, before removing any backup, when the dump fails +or when the bucket has less than half of the pages mirrored (a lost Garage). diff --git a/src/content/docs/backend/testing.md b/src/content/docs/backend/testing.md index 6ef8f8d..7f2c823 100644 --- a/src/content/docs/backend/testing.md +++ b/src/content/docs/backend/testing.md @@ -45,11 +45,19 @@ Key differences from production: - **Database**: in-memory SQLite (no PostgreSQL required) - **Celery broker**: `memory://` (no Redis required) - **Celery backend**: `cache+memory://` (no Redis required) +- **Results bucket**: an in-process S3 mock (moto) started for the test session, bucket `yaptide-results-test`; or a + real S3 server, see [Results Bucket](#results-bucket) ## Fixtures Fixtures are defined in `tests/conftest.py` and provide the test infrastructure. +### `results_bucket` + +Session-wide and automatic: the backend needs a results bucket to start. Without `RESULTS_S3_ENDPOINT` set, it starts +moto's S3 server on a free local port and points `RESULTS_S3_*` at it; with it set, it uses that server. It creates +the bucket when missing, and every test starts with no result pages in it (`results_bucket_emptied`). + ### `app` Creates a Flask application configured for testing: @@ -101,6 +109,9 @@ These fixtures load JSON from `tests/res/` resource files. | `test_download_topas.py` | TOPAS binary download from S3 | | `test_migrations.py` | Every migration up and down on PostgreSQL, data migrations, `prepare_database` | | `test_estimator_matching.py` | Estimators bound to the editor outputs by their result file (`POST /results`, `GET /results`) | +| `test_result_storage.py` | Result pages written to the bucket as Zarr, signed links in `GET /results`, replaced pages and deleted simulations removed | +| `test_result_format.py` | The Zarr page writer and reader without zstandard (gzip) and uncompressed | +| `test_result_pages_admin.py` | `db_manage` copy, clear and move of pages stored before the bucket (SQLite, or PostgreSQL with `TEST_DATABASE_URI`) | ### Integration Tests @@ -128,6 +139,20 @@ TEST_DATABASE_URI=postgresql+psycopg://postgres:pw@localhost:55432/migrations po docker stop yaptide-test-pg ``` +### Results Bucket + +The storage tests run against moto by default. To run them, or the whole suite, against a real Garage, as deployed: + +```bash +cd yaptide +AK=GK$(openssl rand -hex 12); SK=$(openssl rand -hex 32) +docker run -d --rm --name yaptide-test-garage -p 3900:3900 -v "$PWD/garage.toml:/etc/garage.toml:ro" \ + -e GARAGE_RPC_SECRET=$(openssl rand -hex 32) -e GARAGE_DEFAULT_ACCESS_KEY=$AK -e GARAGE_DEFAULT_SECRET_KEY=$SK \ + -e GARAGE_DEFAULT_BUCKET=yaptide-results-test dxflrs/garage:v2.6.0 /garage server --single-node --default-bucket +RESULTS_S3_ENDPOINT=http://127.0.0.1:3900 RESULTS_S3_ACCESS_KEY=$AK RESULTS_S3_SECRET_KEY=$SK poetry run pytest +docker stop yaptide-test-garage +``` + ## Writing New Tests ### Basic Pattern diff --git a/src/content/docs/contributing/glossary.md b/src/content/docs/contributing/glossary.md index 439ed10..199053a 100644 --- a/src/content/docs/contributing/glossary.md +++ b/src/content/docs/contributing/glossary.md @@ -58,6 +58,14 @@ Quick reference for domain-specific terms that appear across the codebase and do **Poetry** : Python dependency manager used by the backend and converter. Replaces pip + requirements.txt with `pyproject.toml` + `poetry.lock`. +**Garage** +: The S3-compatible object storage (`garage` service in `docker-compose.yml`) holding the result pages, in the + bucket `yaptide-results`. + +**Zarr** +: A format for chunked, compressed n-dimensional arrays, stored as plain objects (`zarr.json` and chunk files). Each + result page is one Zarr v3 array. + **Keycloak** : An open-source identity provider. YAPTIDE uses it for SSO authentication, especially for PLGrid HPC access. @@ -94,7 +102,8 @@ Quick reference for domain-specific terms that appear across the codebase and do : The process of recording (tallying) physical quantities during particle transport. A scoring definition ties a quantity to a detector. **Page / Output** -: A single scored quantity on a single detector. One simulation can produce multiple pages of results. +: A single scored quantity on a single detector. One simulation can produce multiple pages of results. The backend + stores each page as a Zarr v3 array in the results bucket, and `GET /results` hands out signed links to it. **LET (Linear Energy Transfer)** : Energy deposited by a charged particle per unit path length. Typically measured in keV/µm. diff --git a/src/content/docs/docker-setup/docker-celery.mdx b/src/content/docs/docker-setup/docker-celery.mdx index ce83f9f..d6b6694 100644 --- a/src/content/docs/docker-setup/docker-celery.mdx +++ b/src/content/docs/docker-setup/docker-celery.mdx @@ -74,6 +74,11 @@ scripts/start_with_docker_develop.ps1 +On the first start the scripts also write the keys of the results bucket (Garage, which holds the result pages) +into `.env`: `RESULTS_S3_ACCESS_KEY`, `RESULTS_S3_SECRET_KEY` and `GARAGE_RPC_SECRET`. Keep them; Garage does not +start with other keys once it has started with these. Running `docker compose up` yourself needs them in `.env` +first, see [Docker Deployment → Result Storage](/for_developers/backend/docker-deployment/#result-storage). + There's two startup modes. The fast mode has custom healthcheck frequency, but requires Docker Engine v25. The slow mode is compatible with older Docker versions. @@ -132,7 +137,7 @@ Open **http://localhost** and log in using credentials you created (username: `a docker compose down ``` -To also delete all data (PostgreSQL volume, simulator cache): +To also delete all data (PostgreSQL volume, result pages in Garage, simulator cache): ```bash docker compose down -v ``` @@ -159,7 +164,8 @@ Or use a GUI tool like DataGrip or pgAdmin. | Container | Port | Purpose | | --------------------------- | ------------------------- | ---------------- | -| `yaptide_nginx` | 5000 (HTTP), 8443 (HTTPS) | Reverse proxy | +| `yaptide_nginx` | 5000 (HTTP), 8443 (HTTPS) | Reverse proxy, also for the result pages (`/yaptide-results/`) | +| `yaptide_garage` | 3900 (internal) | Results bucket (S3) | | `yaptide_flask` | 6000 (internal) | Flask API | | `yaptide_postgresql` | 5432 | Database | | `yaptide_redis` | 6379 (internal) | Celery broker | diff --git a/src/content/docs/docker-setup/docker-slurm.mdx b/src/content/docs/docker-setup/docker-slurm.mdx index f1f40bf..66bace8 100644 --- a/src/content/docs/docker-setup/docker-slurm.mdx +++ b/src/content/docs/docker-setup/docker-slurm.mdx @@ -23,3 +23,7 @@ gives you hot-reload — no container rebuilds on every change. :::caution[Work in Progress] This page is not yet complete — we are still working on the SLURM integration and will update this guide once it's ready. In the meantime, see the [Docker — Celery](/for_developers/docker-setup/docker-celery/) guide for the Celery setup. ::: + +The Docker stack is the same as in the [Docker — Celery](/for_developers/docker-setup/docker-celery/) guide, +including the `garage` service holding the result pages; its keys must be in `.env` before the first start, see +[Docker Deployment → Result Storage](/for_developers/backend/docker-deployment/#result-storage). diff --git a/src/content/docs/local-setup/local-celery.mdx b/src/content/docs/local-setup/local-celery.mdx index 57c4e85..a48bc68 100644 --- a/src/content/docs/local-setup/local-celery.mdx +++ b/src/content/docs/local-setup/local-celery.mdx @@ -111,7 +111,7 @@ Then run the download with S3 and decryption enabled: The free demo binary is sufficient for development and testing. The full licensed version of SHIELD-HIT12A (and FLUKA) requires S3 access and an encryption key — contact your institution or the SHIELD-HIT12A team for access. ::: -### 3. Start Redis +### 3. Start Redis and the results bucket Redis is the message broker between Flask and the Celery workers. The simplest approach is a Docker container: @@ -120,6 +120,33 @@ The simplest approach is a Docker container: docker run --detach --publish 6379:6379 --name yaptide_redis_local redis:7-alpine ``` +Result pages are kept in an S3 bucket. Start Garage, the S3 server the Docker deployment uses, from the `yaptide/` +directory (the keys below are fixed for local development only): + + + + +```bash +docker run --detach --publish 3900:3900 --name yaptide_garage_local -v "$PWD/garage.toml:/etc/garage.toml:ro" -e GARAGE_RPC_SECRET=fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210 -e GARAGE_DEFAULT_ACCESS_KEY=GK0123456789abcdef01234567 -e GARAGE_DEFAULT_SECRET_KEY=0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef -e GARAGE_DEFAULT_BUCKET=yaptide-results dxflrs/garage:v2.4.1 /garage server --single-node --default-bucket +``` + + + + +```powershell +docker run --detach --publish 3900:3900 --name yaptide_garage_local -v "${PWD}/garage.toml:/etc/garage.toml:ro" -e GARAGE_RPC_SECRET=fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210 -e GARAGE_DEFAULT_ACCESS_KEY=GK0123456789abcdef01234567 -e GARAGE_DEFAULT_SECRET_KEY=0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef -e GARAGE_DEFAULT_BUCKET=yaptide-results dxflrs/garage:v2.4.1 /garage server --single-node --default-bucket +``` + + + + +Without nginx in front, the browser fetches the pages from Garage itself, so the bucket has to allow the frontend's +origin (once, after the first start): + +```bash +poetry run python -c "import boto3; boto3.client('s3', endpoint_url='http://127.0.0.1:3900', region_name='garage', aws_access_key_id='GK0123456789abcdef01234567', aws_secret_access_key='0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef').put_bucket_cors(Bucket='yaptide-results', CORSConfiguration={'CORSRules': [{'AllowedOrigins': ['http://localhost:3000', 'http://127.0.0.1:3000'], 'AllowedMethods': ['GET'], 'AllowedHeaders': ['*'], 'ExposeHeaders': ['Content-Length', 'Content-Encoding']}]})" +``` + ### 4. Start the Celery simulation worker This worker picks up simulation jobs from the queue and runs the simulator. It needs access to the simulator binaries (the `bin` directory from step 2). @@ -176,19 +203,23 @@ Open a third backend terminal and go to the `yaptide/` directory. Run: ```bash -FLASK_SQLALCHEMY_ECHO=True FLASK_USE_CORS=True FLASK_SQLALCHEMY_DATABASE_URI="sqlite:///db.sqlite" CELERY_BROKER_URL=redis://127.0.0.1:6379/0 CELERY_RESULT_BACKEND=redis://127.0.0.1:6379/0 poetry run flask --debug --app yaptide.application run +RESULTS_S3_BUCKET=yaptide-results RESULTS_S3_ENDPOINT=http://127.0.0.1:3900 RESULTS_S3_PUBLIC_ENDPOINT=http://127.0.0.1:3900 RESULTS_S3_ACCESS_KEY=GK0123456789abcdef01234567 RESULTS_S3_SECRET_KEY=0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef FLASK_SQLALCHEMY_ECHO=True FLASK_USE_CORS=True FLASK_SQLALCHEMY_DATABASE_URI="sqlite:///db.sqlite" CELERY_BROKER_URL=redis://127.0.0.1:6379/0 CELERY_RESULT_BACKEND=redis://127.0.0.1:6379/0 poetry run flask --debug --app yaptide.application run ``` ```powershell -$env:FLASK_SQLALCHEMY_ECHO="True"; $env:FLASK_USE_CORS="True"; $env:FLASK_SQLALCHEMY_DATABASE_URI="sqlite:///db.sqlite"; $env:CELERY_BROKER_URL="redis://127.0.0.1:6379/0"; $env:CELERY_RESULT_BACKEND="redis://127.0.0.1:6379/0"; poetry run flask --debug --app yaptide.application run +$env:RESULTS_S3_BUCKET="yaptide-results"; $env:RESULTS_S3_ENDPOINT="http://127.0.0.1:3900"; $env:RESULTS_S3_PUBLIC_ENDPOINT="http://127.0.0.1:3900"; $env:RESULTS_S3_ACCESS_KEY="GK0123456789abcdef01234567"; $env:RESULTS_S3_SECRET_KEY="0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; $env:FLASK_SQLALCHEMY_ECHO="True"; $env:FLASK_USE_CORS="True"; $env:FLASK_SQLALCHEMY_DATABASE_URI="sqlite:///db.sqlite"; $env:CELERY_BROKER_URL="redis://127.0.0.1:6379/0"; $env:CELERY_RESULT_BACKEND="redis://127.0.0.1:6379/0"; poetry run flask --debug --app yaptide.application run ``` +**Why the `RESULTS_S3_*` variables?** Flask writes the result pages to the bucket at `RESULTS_S3_ENDPOINT` and hands +the browser links signed for `RESULTS_S3_PUBLIC_ENDPOINT`; it does not start without them. See +[Result Storage](/for_developers/backend/result-storage/). + **Why `FLASK_USE_CORS=True`?** During development, the frontend runs on `localhost:3000` and the backend on `localhost:5000`. Without CORS enabled, the browser blocks cross-origin requests. This creates `db.sqlite` inside `./instance/` (default [Flask instance folder](https://flask.palletsprojects.com/en/3.0.x/config/#instance-folders)). diff --git a/src/content/docs/local-setup/local-slurm.mdx b/src/content/docs/local-setup/local-slurm.mdx index 7556a80..38bb975 100644 --- a/src/content/docs/local-setup/local-slurm.mdx +++ b/src/content/docs/local-setup/local-slurm.mdx @@ -108,7 +108,7 @@ Then run the download with S3 and decryption enabled: The free demo binary is sufficient for development and testing. The full licensed version of SHIELD-HIT12A (and FLUKA) requires S3 access and an encryption key — contact your institution or the SHIELD-HIT12A team for access. ::: -### 3. Start Redis +### 3. Start Redis and the results bucket Redis is the message broker between Flask and the Celery workers. The simplest approach is a Docker container: @@ -117,6 +117,33 @@ The simplest approach is a Docker container: docker run --detach --publish 6379:6379 --name yaptide_redis_local redis:7-alpine ``` +Result pages are kept in an S3 bucket. Start Garage, the S3 server the Docker deployment uses, from the `yaptide/` +directory (the keys below are fixed for local development only): + + + + +```bash +docker run --detach --publish 3900:3900 --name yaptide_garage_local -v "$PWD/garage.toml:/etc/garage.toml:ro" -e GARAGE_RPC_SECRET=fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210 -e GARAGE_DEFAULT_ACCESS_KEY=GK0123456789abcdef01234567 -e GARAGE_DEFAULT_SECRET_KEY=0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef -e GARAGE_DEFAULT_BUCKET=yaptide-results dxflrs/garage:v2.4.1 /garage server --single-node --default-bucket +``` + + + + +```powershell +docker run --detach --publish 3900:3900 --name yaptide_garage_local -v "${PWD}/garage.toml:/etc/garage.toml:ro" -e GARAGE_RPC_SECRET=fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210 -e GARAGE_DEFAULT_ACCESS_KEY=GK0123456789abcdef01234567 -e GARAGE_DEFAULT_SECRET_KEY=0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef -e GARAGE_DEFAULT_BUCKET=yaptide-results dxflrs/garage:v2.4.1 /garage server --single-node --default-bucket +``` + + + + +Without nginx in front, the browser fetches the pages from Garage itself, so the bucket has to allow the frontend's +origin (once, after the first start): + +```bash +poetry run python -c "import boto3; boto3.client('s3', endpoint_url='http://127.0.0.1:3900', region_name='garage', aws_access_key_id='GK0123456789abcdef01234567', aws_secret_access_key='0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef').put_bucket_cors(Bucket='yaptide-results', CORSConfiguration={'CORSRules': [{'AllowedOrigins': ['http://localhost:3000', 'http://127.0.0.1:3000'], 'AllowedMethods': ['GET'], 'AllowedHeaders': ['*'], 'ExposeHeaders': ['Content-Length', 'Content-Encoding']}]})" +``` + ### 4. Setup .env Add these variables to the `.env` file in the project root: @@ -193,19 +220,23 @@ Open a third backend terminal and go to the `yaptide/` directory. Run: ```bash -FLASK_USE_CORS=True FLASK_SQLALCHEMY_DATABASE_URI="sqlite:///db.sqlite" CELERY_BROKER_URL=redis://127.0.0.1:6379/0 CELERY_RESULT_BACKEND=redis://127.0.0.1:6379/0 poetry run flask --app yaptide.application run --host 0.0.0.0 +RESULTS_S3_BUCKET=yaptide-results RESULTS_S3_ENDPOINT=http://127.0.0.1:3900 RESULTS_S3_PUBLIC_ENDPOINT=http://127.0.0.1:3900 RESULTS_S3_ACCESS_KEY=GK0123456789abcdef01234567 RESULTS_S3_SECRET_KEY=0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef FLASK_USE_CORS=True FLASK_SQLALCHEMY_DATABASE_URI="sqlite:///db.sqlite" CELERY_BROKER_URL=redis://127.0.0.1:6379/0 CELERY_RESULT_BACKEND=redis://127.0.0.1:6379/0 poetry run flask --app yaptide.application run --host 0.0.0.0 ``` ```powershell -$env:FLASK_USE_CORS="True"; $env:FLASK_SQLALCHEMY_DATABASE_URI="sqlite:///db.sqlite"; $env:CELERY_BROKER_URL="redis://127.0.0.1:6379/0"; $env:CELERY_RESULT_BACKEND="redis://127.0.0.1:6379/0"; poetry run flask --app yaptide.application run --host 0.0.0.0 +$env:RESULTS_S3_BUCKET="yaptide-results"; $env:RESULTS_S3_ENDPOINT="http://127.0.0.1:3900"; $env:RESULTS_S3_PUBLIC_ENDPOINT="http://127.0.0.1:3900"; $env:RESULTS_S3_ACCESS_KEY="GK0123456789abcdef01234567"; $env:RESULTS_S3_SECRET_KEY="0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; $env:FLASK_USE_CORS="True"; $env:FLASK_SQLALCHEMY_DATABASE_URI="sqlite:///db.sqlite"; $env:CELERY_BROKER_URL="redis://127.0.0.1:6379/0"; $env:CELERY_RESULT_BACKEND="redis://127.0.0.1:6379/0"; poetry run flask --app yaptide.application run --host 0.0.0.0 ``` +**Why the `RESULTS_S3_*` variables?** Flask writes the result pages to the bucket at `RESULTS_S3_ENDPOINT` and hands +the browser links signed for `RESULTS_S3_PUBLIC_ENDPOINT`; it does not start without them. See +[Result Storage](/for_developers/backend/result-storage/). + **Why `FLASK_USE_CORS=True`?** During development, the frontend runs on `localhost:3000` and the backend on `localhost:5000`. Without CORS enabled, the browser blocks cross-origin requests. This creates `db.sqlite` inside `./instance/` (default [Flask instance folder](https://flask.palletsprojects.com/en/3.0.x/config/#instance-folders)).