Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 39 additions & 17 deletions src/content/docs/backend/database.md
Original file line number Diff line number Diff line change
Expand Up @@ -184,47 +184,69 @@ This reduces storage for large simulation results (estimator pages can be severa

## Migration Workflow

The project uses **Flask-Migrate** (Alembic) for schema changes.
The project uses **Flask-Migrate** (Alembic) for schema changes. Migrations live in `migrations/versions/`.

### Creating a New Migration
### Migrations on Start

```bash
# After modifying models.py
poetry run flask --app yaptide.application db migrate -m "Add new column"
The database is brought to the current models when the Flask container starts, before gunicorn starts its workers
(`run_flask.sh` calls `prepare_database` from `yaptide/persistence/models.py`):

- A database with an `alembic_version` table is upgraded to the latest revision (`flask db upgrade`).
- A database without it (a new one, or one whose tables were only ever created from the models) gets the missing
tables from the models and is stamped with the latest revision, so later migrations apply to it.

# Review the generated migration in migrations/versions/
# Then apply:
poetry run flask --app yaptide.application db upgrade
The application never creates tables on import. The same step can be run by hand, e.g. for local development:

```bash
poetry run flask --app yaptide.application prepare-db
```

### Development Workflow
### Writing Migrations

Every migration must be **reversible** and **independent of the current models**:

- `downgrade()` undoes `upgrade()`, so a deployment can go back to the previous revision.
- A migration never imports `yaptide.persistence.models`. The models follow the latest revision, and a migration runs
against a database at its own revision. A data migration describes the tables it reads and writes as they are at
its revision, with `sa.table(...)` / `sa.column(...)`, and works through `op.get_bind()` (see
`migrations/versions/41149fa64bd2_.py` and `5003b9acb1f4_.py`).
- Use `op.batch_alter_table` for column changes, so they also run on SQLite. `migrations/env.py` turns SQLite's
foreign keys off during migrations, as batch operations recreate tables there.

### Creating a New Migration

1. Modify `persistence/models.py`
2. Generate migration: `flask db migrate -m "description"`
3. Review the auto-generated migration script
4. Test locally: `flask db upgrade`
2. Generate the migration against a database at the latest revision:
`poetry run flask --app yaptide.application db migrate -m "description"`
3. Review the generated script in `migrations/versions/`, write its `downgrade()` and any data migration
4. Run `tests/test_migrations.py` against PostgreSQL (see [Testing → Migration Tests](/for_developers/backend/testing/#migration-tests))
5. Commit the migration file alongside the model changes

### Production Migration

> Always back up the database before running migrations in production.
> Always back up the database before deploying a version with new migrations.

```bash
# Backup
docker compose exec postgresql pg_dump -U yaptide yaptide > backup.sql
```

The new migrations are applied when the new `yaptide_flask` container starts. To go back one revision before
deploying the previous version:

# Apply migration
docker compose exec yaptide_flask flask --app yaptide.application db upgrade
```bash
docker compose exec yaptide_flask flask --app yaptide.application db downgrade
```

### Testing Migrations

To test a migration against a copy of the production database:
`tests/test_migrations.py` runs every migration up and down on an empty PostgreSQL database and checks that the data
migrations carry existing rows over. To test a migration against a copy of the production database:

1. Dump production: `pg_dump -U yaptide yaptide > prod_backup.sql`
2. Load into a test database: `psql -U yaptide test_db < prod_backup.sql`
3. Point `FLASK_SQLALCHEMY_DATABASE_URI` at the test DB
4. Run `flask db upgrade`
4. Run `flask --app yaptide.application db upgrade`, then `db downgrade` back to the previous revision
5. Verify the application works correctly

## Database Access from Outside Docker
Expand Down
31 changes: 28 additions & 3 deletions src/content/docs/backend/docker-deployment.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ The backend deployment uses **Docker Compose** with 6 services. This is the reco
services:
redis: # Celery broker + result backend
postgresql: # Primary database
yaptide_flask: # Flask API server
yaptide_flask: # Flask API server (gunicorn)
yaptide_simulation_worker: # Celery simulation worker
yaptide_helper_worker: # Celery helper worker
nginx: # Reverse proxy with TLS
Expand All @@ -24,11 +24,32 @@ services:
|---|---|---|---|
| `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 |
| `yaptide_flask` | `Dockerfile-flask` | 6000 (internal) | Flask API server under gunicorn, migrates the database on start |
| `yaptide_simulation_worker` | `Dockerfile-simulation-worker` | — | Runs simulator binaries via Celery |
| `yaptide_helper_worker` | `Dockerfile-helper-worker` | — | Batch job submission and cleanup via Celery |
| `nginx` | `Dockerfile-nginx` | 5000, 8443 | Reverse proxy with TLS termination |

### Flask Server

The `yaptide_flask` container starts `run_flask.sh`, which:

1. Prepares the database once, before any worker starts (`prepare_database` in `yaptide/persistence/models.py`):
a database under migrations is upgraded to the latest revision; a new database is created from the models and
stamped with the latest revision. See [Database → Migration Workflow](/for_developers/backend/database/#migration-workflow).
2. Starts **gunicorn** with the settings in `gunicorn.conf.py`: sync workers, `2 × CPUs + 1` by default, limited by
the container's memory (about 300 MB per worker) and capped at 32, each holding one PostgreSQL connection.

All gunicorn workers sign and verify tokens with the same secrets, `YAPTIDE_TOKEN_SECRET` and
`YAPTIDE_REFRESH_TOKEN_SECRET`. When they are not set, `run_flask.sh` generates them at start and logs a warning:
every restart then invalidates logged-in sessions and the update keys of running HPC jobs, so set both in
production.

The service has a `stop_grace_period` of 40 s, longer than gunicorn's 30 s graceful shutdown, so requests in
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.

### Exposed Ports

| Port | Protocol | Service |
Expand All @@ -43,7 +64,7 @@ cd yaptide
docker compose up --build -d
```

Wait for all services to be healthy:
The database is created or migrated when `yaptide_flask` starts. Wait for all services to be healthy:

```bash
docker compose ps
Expand Down Expand Up @@ -115,6 +136,10 @@ Set these in a `.env` file in the `yaptide/` root or pass them via Docker:
| `BACKEND_EXTERNAL_URL` | `https://localhost:8443` | Public-facing URL |
| `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 |
| `YAPTIDE_REFRESH_TOKEN_SECRET` | (generated at start) | Secret for refresh tokens, shared by all gunicorn workers |
| `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) |

### Authentication

Expand Down
17 changes: 16 additions & 1 deletion src/content/docs/backend/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ title: Backend Testing
description: Test structure, fixtures, and how to write tests for the YAPTIDE backend.
---

The backend uses **pytest** with an in-memory SQLite database and an in-memory Celery broker. No external services are required to run tests.
The backend uses **pytest** with an in-memory SQLite database and an in-memory Celery broker. No external services are required to run tests, except the migration tests, which need PostgreSQL.

## Running Tests

Expand Down Expand Up @@ -99,6 +99,8 @@ These fixtures load JSON from `tests/res/` resource files.
| `test_download_shieldhit.py` | SHIELD-HIT12A binary download from S3 |
| `test_download_fluka.py` | FLUKA binary download from S3 |
| `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`) |

### Integration Tests

Expand All @@ -113,6 +115,19 @@ Located in `tests/integration/`:
| `test_simulation_deletion.py` | Simulation and result cleanup |
| `test_environment.py` | Environment variable handling |

### Migration Tests

`tests/test_migrations.py` needs an **empty PostgreSQL database** given in `TEST_DATABASE_URI`; without it the tests
are skipped (SQLite cannot run all migrations). The tests run every migration from an empty database to the latest
revision, back down and up again, check that the data migrations carry existing rows over, and that
`prepare_database` creates a new database or upgrades a migrated one. Each test leaves the database empty.

```bash
docker run -d --rm --name yaptide-test-pg -e POSTGRES_PASSWORD=pw -e POSTGRES_DB=migrations -p 55432:5432 postgres:16-alpine
TEST_DATABASE_URI=postgresql+psycopg://postgres:pw@localhost:55432/migrations poetry run pytest tests/test_migrations.py
docker stop yaptide-test-pg
```

## Writing New Tests

### Basic Pattern
Expand Down
Loading