From 9baa624f2df6cd641248a479144e8f2ae551d4e5 Mon Sep 17 00:00:00 2001 From: Yoshiofthewire Date: Wed, 25 Nov 2026 14:59:11 -0500 Subject: [PATCH 1/2] chore(deps): PostgreSQL 18 with an automatic, non-destructive upgrade from 17 Matrix's Postgres moves to 18.7 (pinned by digest). A 17 stack upgrades on its next `docker compose up -d`: the one-shot postgres-17-dump (17.12 image, no network, read-only root) dumps pgdata/ once into upgrade-from-17/, and the postgres service restores it into 18/docker on the same volume before the stock entrypoint runs. Both run scripts/postgres-17-to-18.sh, the suite's kit v2, byte for byte; it refuses to dump while postmaster.pid exists, and both services stop with a 2-minute grace so a clean stop removes it. The 17 data is never deleted or written; rolling back is the previous release's Compose files. - Dockerfile: postgresql18-client, so the app's pg_dump/pg_restore match. - Health pins regenerated (postgres 18.7); CI's Postgres suite runs on 18. - check-compose-matrix holds the layout, the one-shot, the kit's checksum and mode; the Podman overlay maps and labels the new bind. - scripts/test-postgres-17-to-18.sh (CI job postgres-upgrade) seeds 17 with the last 17 Compose files and proves the move with 17 running, a refused dump beside a live 17, passwords over the network, matrix-init re-runs and rotation, rerun, rollback, a bad dump, clean-up, a fresh install and a 17 backup restored on 18. - Operator note in docs/CHAT-SETUP.md "PostgreSQL 18". Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 18 ++- .github/workflows/release-image.yml | 1 + AGENTS.md | 12 +- CHANGELOG.md | 6 + Dockerfile | 4 +- docker-compose.matrix-podman.yml | 9 +- docker-compose.matrix.yml | 44 ++++++-- docs/ASSURANCE-CASE.md | 2 +- docs/CHAT-SETUP.md | 29 +++++ docs/DEVELOPMENT.md | 2 +- docs/RESTORE.md | 3 +- internal/health/genpins/main_test.go | 2 +- internal/health/pins.go | 2 +- scripts/agent-probe/probe.sh | 4 +- scripts/check-compose-matrix.sh | 34 ++++-- scripts/check-compose-podman.sh | 5 + scripts/matrix-acceptance.sh | 2 +- scripts/postgres-17-to-18.sh | 89 +++++++++++++++ scripts/test-postgres-17-to-18.sh | 157 +++++++++++++++++++++++++++ 19 files changed, 396 insertions(+), 29 deletions(-) create mode 100755 scripts/postgres-17-to-18.sh create mode 100755 scripts/test-postgres-17-to-18.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 838b668d..8d272912 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -130,7 +130,7 @@ jobs: timeout-minutes: 20 services: postgres: - image: postgres:17.6-alpine@sha256:ef257d85f76e48da1c64832459b59fcaba1a4dac97bf5d7450c77753542eee94 + image: postgres:18.7-alpine3.24@sha256:0115267ab5a509022df9319c77be365cef335adb71556c75f60f5360ee247e71 env: POSTGRES_USER: ci POSTGRES_PASSWORD: ci @@ -154,6 +154,22 @@ jobs: KY_TEST_POSTGRES_DSN: postgres://ci:ci@127.0.0.1:5432/ci_test?sslmode=disable run: go test -race -count=1 ./... + # The Matrix overlay's automatic PostgreSQL 17 -> 18 move, on real 17 data seeded with the last + # 17 Compose files (the commit the script names). + postgres-upgrade: + name: PostgreSQL 17 to 18 upgrade (Matrix Compose) + if: github.event.pull_request.draft != true + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 + with: + go-version-file: go.mod + cache: true + - run: git fetch --no-tags --depth=1 origin "$(sed -nE 's/^PG17_REF=\$\{PG17_REF:-([0-9a-f]{40})\}.*/\1/p' scripts/test-postgres-17-to-18.sh)" + - run: scripts/test-postgres-17-to-18.sh + web: name: Frontend typecheck & build if: github.event.pull_request.draft != true diff --git a/.github/workflows/release-image.yml b/.github/workflows/release-image.yml index f87d4bce..7b7d3c1d 100644 --- a/.github/workflows/release-image.yml +++ b/.github/workflows/release-image.yml @@ -122,6 +122,7 @@ jobs: REQUIRED: | Go build, vet & tests (SQLite) Go tests (PostgreSQL) + PostgreSQL 17 to 18 upgrade (Matrix Compose) Frontend typecheck & build Browser regressions (production server) Matrix acceptance (encrypted storage, closed server) diff --git a/AGENTS.md b/AGENTS.md index 6ca0a17b..12b327be 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -163,7 +163,7 @@ When the user requests a durable behavior change, record it here or in the relev `postgres_password`, never created by Docker (a `/dev/null` mask inside a read-only bind breaks `docker cp`). The role does not bound the app: the configs it backs up hold the owner passwords and shared secrets; - the image's `postgresql17-client` major must equal the Postgres tag, which the check enforces), and + the image's `postgresql18-client` major must equal the Postgres tag, which the check enforces), and it hands the app the `KY_MATRIX_*` locations and MAS admin settings: the internal `matrix-admin` network (only app and mas; alias `mas-admin`) and the admin secret as a Compose secret. It requires `KY_KYIDENTITY_HMAC_SECRET`, as config does with Matrix set. `scripts/check-compose-matrix.sh` checks it @@ -183,6 +183,14 @@ When the user requests a durable behavior change, record it here or in the relev stock (owner decision 2026-10-02): exactly that file at `/app/config.json:ro`, which its image copies at start, so a rename shows after `docker compose restart element`; the check refuses any `/dev/null`, `/tmp/element-web-config` or `/docker-entrypoint` mount on Element. + Postgres is 18 on the whole `matrix-postgres` volume at `/var/lib/postgresql` (the image's + `18/docker`, no `PGDATA`), beside the 17 data in `pgdata/`, which nothing deletes or writes + (owner decision 2026-11-25). A 17 stack moves on its next `up`: the one-shot `postgres-17-dump` + (17 image, no network, read-only root) dumps `pgdata/` once, and postgres's entrypoint + restores it before the stock one; both run `scripts/postgres-17-to-18.sh`, Ky's shared kit, + byte for byte (the check holds its checksum; fix it upstream in the kit, never only here). + `scripts/test-postgres-17-to-18.sh` (CI job `postgres-upgrade`) proves the move on 17 data + seeded with the last 17 Compose files; operator steps in `docs/CHAT-SETUP.md` "PostgreSQL 18". `restore-matrix` (profile `restore`, `docker compose run --rm restore-matrix`) runs the app image as `KY_MATRIX_UID:KY_MATRIX_GID` with no capability on `matrix-db` only; it is the only read-write media mount besides Synapse, and its `./data`, `./backups` and `./matrix` are @@ -246,7 +254,7 @@ When the user requests a durable behavior change, record it here or in the relev CI (`.github/workflows/ci.yml`) runs on every push and every non-draft pull request (drafts skip until marked ready): - `make lint` equivalent: gofmt, `go vet`, `go mod tidy`/`verify`, `scripts/check-compose-proxy.sh`, `scripts/check-compose-matrix.sh` and `scripts/check-compose-podman.sh` - `release binary is repeatable` (Go job): builds `./cmd/server` the way the Dockerfile does (`-trimpath`, from `git archive` copies, committed `web/dist`) in two directories and requires identical bytes. Keep the Dockerfile's `go build` and that step in step; `docs/VERIFYING-RELEASES.md` gives users the same command for both release images -- `go test -race` with coverage on SQLite, and the same suite against PostgreSQL 17 +- `go test -race` with coverage on SQLite, and the same suite against PostgreSQL 18 - The same SQLite suite under `GODEBUG=fips140=on`, then `docs/check-strong-crypto-compose.py` (nine Compose chains; `docker-compose.strong-crypto.yml` may add only the app's `GODEBUG`). `docs/STRONG-CRYPTO.md` is the key-size table: update it with any key, secret or TLS client change diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c67078f..28ac745d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -89,6 +89,12 @@ are gone. ### Changed +- Matrix's database moves to PostgreSQL 18.7. An existing PostgreSQL 17 stack upgrades by + itself on the next `docker compose up -d`: a one-shot dumps the 17 data once and Postgres + restores it into a new `18/docker` directory on the same volume. The 17 data is kept for a + rollback until you remove it. It needs about twice the database's size free + ([Chat setup](docs/CHAT-SETUP.md#postgresql-18)). The app image's `pg_dump`/`pg_restore` are + now PostgreSQL 18, and capsules taken on 17 still restore. - A SCIM account with the admin role signs in to the console through KyIdentity only when `KY_SCIM_ALLOW_ADMIN=true`, and SCIM turning an inactive admin back on needs it too. An empty `roles` from SCIM now removes the admin role. diff --git a/Dockerfile b/Dockerfile index cdd699aa..a723a42f 100644 --- a/Dockerfile +++ b/Dockerfile @@ -25,9 +25,9 @@ RUN CGO_ENABLED=0 GOOS=linux go build -trimpath \ # Stage 3: Minimal Production Container FROM alpine:3.24@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf -# postgresql17-client: pg_dump/pg_restore for Matrix backups; its major must equal the +# postgresql18-client: pg_dump/pg_restore for Matrix backups; its major must equal the # postgres service's (scripts/check-compose-matrix.sh). -RUN apk --no-cache add ca-certificates tzdata postgresql17-client +RUN apk --no-cache add ca-certificates tzdata postgresql18-client WORKDIR /app COPY --from=backend-builder /app/kymessages /app/kymessages # /app/backups is the optional mount for sealed local capsules; KY_BACKUP_DIR is set by the diff --git a/docker-compose.matrix-podman.yml b/docker-compose.matrix-podman.yml index ac4d78b8..74e50cbf 100644 --- a/docker-compose.matrix-podman.yml +++ b/docker-compose.matrix-podman.yml @@ -2,9 +2,14 @@ # KY_MATRIX_UID to the same host user, so these services read the 0600 files matrix-init wrote # and the volume owner set by synapse-media-owner is the user Synapse runs as. matrix-init's # Podman command (docs/CHAT-SETUP.md) gives ./matrix the shared container SELinux label; -# restore-matrix relabels the restored ./data, ./backups and ./matrix it reads. +# restore-matrix relabels the restored ./data, ./backups and ./matrix it reads. Both Postgres +# services label the PostgreSQL 17 -> 18 script they run, which lives outside ./matrix. services: - postgres: {userns_mode: keep-id} + postgres-17-dump: + userns_mode: keep-id + volumes: + - &pg-upgrade {type: bind, source: ./scripts/postgres-17-to-18.sh, target: /ky/postgres-17-to-18.sh, read_only: true, bind: {create_host_path: false, selinux: z}} + postgres: {userns_mode: keep-id, volumes: [*pg-upgrade]} synapse-media-owner: {userns_mode: keep-id} synapse: {userns_mode: keep-id} mas: {userns_mode: keep-id} diff --git a/docker-compose.matrix.yml b/docker-compose.matrix.yml index 51f972d8..2d4b24cc 100644 --- a/docker-compose.matrix.yml +++ b/docker-compose.matrix.yml @@ -100,27 +100,57 @@ services: - {<<: *matrix-ro, source: ./matrix/secrets/kyidentity_client_secret, target: /matrix/secrets/kyidentity_client_secret} - matrix-media:/matrix-media:ro + # PostgreSQL 18 keeps its data in 18/docker of the same volume, beside the 17 data in pgdata/, + # which stays untouched (docs/CHAT-SETUP.md "PostgreSQL 18"). A 17 stack moves on its first + # start: this one-shot dumps pgdata/ once into upgrade-from-17/, then the postgres service + # restores that dump before it starts. Without 17 data it does nothing. + postgres-17-dump: + image: postgres:17.12-alpine3.24@sha256:f9cf3e1f0066f0eb0c48707d864f0ac5941e9ff454a072077d97a4d278d07d73 + user: "${KY_MATRIX_UID:?}:${KY_MATRIX_GID:?}" + entrypoint: ["bash", "/ky/postgres-17-to-18.sh", "dump"] + environment: + OLD: /v/pgdata + NEW: /v + network_mode: none + restart: "no" + # A clean stop removes postmaster.pid, without which the next dump refuses. + stop_grace_period: 2m + read_only: true + tmpfs: [/tmp] + security_opt: ["no-new-privileges:true"] + cap_drop: [ALL] + volumes: + - matrix-postgres:/v + - &pg-upgrade {type: bind, source: ./scripts/postgres-17-to-18.sh, target: /ky/postgres-17-to-18.sh, read_only: true, bind: {create_host_path: false}} + postgres: <<: *hardening - image: postgres:17.6-alpine@sha256:ef257d85f76e48da1c64832459b59fcaba1a4dac97bf5d7450c77753542eee94 + image: postgres:18.7-alpine3.24@sha256:0115267ab5a509022df9319c77be365cef335adb71556c75f60f5360ee247e71 user: "${KY_MATRIX_UID:?Set KY_MATRIX_UID (printed by matrix-init)}:${KY_MATRIX_GID:?Set KY_MATRIX_GID (printed by matrix-init)}" + # Restores postgres-17-dump's dump once, then runs the image's own entrypoint. + entrypoint: ["bash", "/ky/postgres-17-to-18.sh", "restore"] + command: [postgres] environment: POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password - # A subdirectory: the volume root belongs to the image's postgres user, and initdb must - # own its directory. - PGDATA: /var/lib/postgresql/data/pgdata secrets: [postgres_password] networks: [matrix-db] volumes: - - matrix-postgres:/var/lib/postgresql/data + - matrix-postgres:/var/lib/postgresql - ./matrix/postgres:/docker-entrypoint-initdb.d:ro - # TCP, not the socket: during first-run init the entrypoint's temporary server listens on - # the socket only, so this passes once init.sql has run and the real server is up. + - *pg-upgrade + depends_on: + postgres-17-dump: {condition: service_completed_successfully} + # Time for a clean shutdown, so a rollback to 17 or a restore never meets a crashed cluster. + stop_grace_period: 2m + # TCP, not the socket: during first-run init or the restore the temporary server listens on + # the socket only, so this passes once the real server is up. The restore takes about as + # long as a pg_dumpall restore of the data, hence the long start period. healthcheck: test: ["CMD", "pg_isready", "-h", "127.0.0.1", "-U", "postgres", "-d", "postgres"] interval: 5s timeout: 5s retries: 30 + start_period: 1h # The media volume starts root-owned (the image's /media); hand it to the Synapse user once # per start. Only CAP_CHOWN, no network. diff --git a/docs/ASSURANCE-CASE.md b/docs/ASSURANCE-CASE.md index 2afd52f1..9342b11b 100644 --- a/docs/ASSURANCE-CASE.md +++ b/docs/ASSURANCE-CASE.md @@ -154,7 +154,7 @@ encrypt. ## Evidence - **Tests:** the security tests named above and the whole suite under the race detector, on SQLite - and on PostgreSQL 17; Vitest; Chromium and Firefox regressions against the built server; the + and on PostgreSQL 18; Vitest; Chromium and Firefox regressions against the built server; the Matrix acceptance job (encrypted storage, closed server); backup acceptance and the smoke test, on every push and pull request. - **Static analysis:** `go vet`, `govulncheck`, strict TypeScript (`tsc`), `shellcheck` on the diff --git a/docs/CHAT-SETUP.md b/docs/CHAT-SETUP.md index c86f4e10..58bf3868 100644 --- a/docs/CHAT-SETUP.md +++ b/docs/CHAT-SETUP.md @@ -186,6 +186,35 @@ Upgrading a stack from before Matrix backups: `KY_BACKUP_MEDIA_FULL_KEEP`. 4. `docker compose up -d`. The first scheduled run then backs up Matrix. +## PostgreSQL 18 + +Matrix's database runs PostgreSQL 18. A stack set up on PostgreSQL 17 moves on the first +`docker compose up -d` after you update the checkout, with nothing to run by hand: + +- `postgres-17-dump`, a one-shot on the 17 image with no network, dumps the 17 data in the + `matrix-postgres` volume (`pgdata/`) once into `upgrade-from-17/` on the same volume. Postgres + then restores that dump into `18/docker` and starts 18. The roles and their passwords come + from the dump, so Synapse, MAS and backups connect as before. The 17 data is only read; it is + never deleted or rewritten. On later starts both steps see the move is done and do nothing. + A fresh install has nothing to move and initialises 18 directly. +- **Space:** about twice the database's size free on the volume's disk (the dump plus the new + cluster). With less, `postgres-17-dump` refuses and writes nothing: free space, then + `docker compose up -d` again. `docker compose logs postgres-17-dump` says which. It also + refuses while `pgdata/postmaster.pid` exists, that is, while 17 still runs on the data or + if 17 did not stop cleanly. Stop it, or start the previous release once and stop it, then + `docker compose up -d` again. +- **Time:** about as long as a dump and restore of the database. Postgres is unhealthy until + the restore finishes, so Synapse and MAS wait; its health check allows an hour. Watch with + `docker compose logs -f postgres`. A restore interrupted half-way starts again from scratch + on the next start. A dump that fails to restore never leaves an empty database: Postgres + stops with the error instead. +- **Roll back** by checking out the previous release (Compose files and app image together) + and `docker compose up -d`: 17 starts on its untouched data. Anything written while on 18 + is not in it. Going forward again reuses the 18 cluster. +- **Clean up**, once you are satisfied and no longer want to roll back, if you choose to: + `docker compose exec postgres rm -r /var/lib/postgresql/pgdata /var/lib/postgresql/upgrade-from-17`. + That frees the space and makes a rollback to 17 impossible. + Element's Home view (no room open) shows "Welcome to KyMessages" and links to the other suite apps KyIdentity lists, served by the console at `/element-home.html` (Element's `embedded_pages.home_url`). Each app still asks KyIdentity whether the person may open it. diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index 6046f1b3..3240056a 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -59,7 +59,7 @@ and `KY_TRUSTED_PROXIES`; publishes no port; names the network `kymessages-net`) ## Verification `make ci` runs formatting, module checks, race tests, frontend tests and the running -server smoke checks. `make test-postgres` needs a disposable PostgreSQL 17 instance. +server smoke checks. `make test-postgres` needs a disposable PostgreSQL 18 instance. See [web/AGENTS.md](../web/AGENTS.md) for production-CSP, keyboard and responsive browser checks. The smoke CI job also runs `python3 scripts/backup-acceptance.py`, a three-minute diff --git a/docs/RESTORE.md b/docs/RESTORE.md index a7042322..55bb87c5 100644 --- a/docs/RESTORE.md +++ b/docs/RESTORE.md @@ -119,7 +119,8 @@ restoring her keys from key backup; the server name and signing key were unchang image (`docker compose pull app`; `restore-matrix` runs the same image and never pulls) or build it (build overlay). 4. Only if this stack is meant to be replaced: `docker compose down -v`, which deletes its - Matrix database and media. Then `docker compose up -d postgres`, nothing else. + Matrix database and media. Then `docker compose up -d postgres`, nothing else. A capsule + taken while Matrix ran PostgreSQL 17 restores into the PostgreSQL 18 stack. 5. `docker compose run --rm restore-matrix`. Add `-skip-media` only if no media backup survived; uploads from before the backup are then missing. It runs as `KY_MATRIX_UID` with no capabilities and restores as the database owners, with no superuser. diff --git a/internal/health/genpins/main_test.go b/internal/health/genpins/main_test.go index 4cdc30c4..c6e07202 100644 --- a/internal/health/genpins/main_test.go +++ b/internal/health/genpins/main_test.go @@ -27,7 +27,7 @@ func TestPinsMatchCompose(t *testing.T) { func TestTagVersion(t *testing.T) { for image, want := range map[string]string{ - "postgres:17.6-alpine@sha256:ef25": "17.6", + "postgres:18.7-alpine3.24@sha256:0115": "18.7", "ghcr.io/element-hq/synapse:v1.162.0@sha256:6b84": "1.162.0", "ghcr.io/element-hq/matrix-authentication-service:1.26.0": "1.26.0", "registry.local:5000/element-web:v1.12.30": "1.12.30", diff --git a/internal/health/pins.go b/internal/health/pins.go index c0c17132..fd889f53 100644 --- a/internal/health/pins.go +++ b/internal/health/pins.go @@ -7,6 +7,6 @@ var Pins = map[string]string{ "element": "1.12.30", "livekit": "1.13.7", "mas": "1.26.0", - "postgres": "17.6", + "postgres": "18.7", "synapse": "1.162.0", } diff --git a/scripts/agent-probe/probe.sh b/scripts/agent-probe/probe.sh index beb4a6ad..fce82380 100755 --- a/scripts/agent-probe/probe.sh +++ b/scripts/agent-probe/probe.sh @@ -14,7 +14,7 @@ for tool in docker curl jq openssl python3; do command -v "$tool" >/dev/null || { echo "probe: $tool is required" >&2; exit 2; } done img() { grep -m1 -o "image: $1[^ ]*" "$pins" | cut -d' ' -f2; } -pg_image=$(img postgres:) +pg_image=$(img postgres:18) syn_image=$(img ghcr.io/element-hq/synapse:) mas_image=$(img ghcr.io/element-hq/matrix-authentication-service:) @@ -165,7 +165,7 @@ services: postgres: image: $pg_image environment: {POSTGRES_PASSWORD: "$(openssl rand -hex 16)"} - volumes: [pgdata:/var/lib/postgresql/data, ./pg-init:/docker-entrypoint-initdb.d:ro] + volumes: [pgdata:/var/lib/postgresql, ./pg-init:/docker-entrypoint-initdb.d:ro] healthcheck: {test: [CMD, pg_isready, -h, 127.0.0.1, -U, postgres], interval: 2s, retries: 60} mas: image: $mas_image diff --git a/scripts/check-compose-matrix.sh b/scripts/check-compose-matrix.sh index ddabf070..98620c44 100755 --- a/scripts/check-compose-matrix.sh +++ b/scripts/check-compose-matrix.sh @@ -22,17 +22,20 @@ out=$(render "${stack[@]}") || exit 1 declare -A image=( [livekit]=livekit/livekit-server:v1.13.7@sha256:6fd3b7088874c4d119160dd688798dfec852bc014786d392caad15f6f63912a3 - [postgres]=postgres:17.6-alpine@sha256:ef257d85f76e48da1c64832459b59fcaba1a4dac97bf5d7450c77753542eee94 + [postgres]=postgres:18.7-alpine3.24@sha256:0115267ab5a509022df9319c77be365cef335adb71556c75f60f5360ee247e71 + [postgres-17-dump]=postgres:17.12-alpine3.24@sha256:f9cf3e1f0066f0eb0c48707d864f0ac5941e9ff454a072077d97a4d278d07d73 [synapse]=ghcr.io/element-hq/synapse:v1.162.0@sha256:6b84a7bbac36f080b2d2e51e0289cf1b08b349598ea44a558df38d558f2c2311 [mas]=ghcr.io/element-hq/matrix-authentication-service:1.26.0@sha256:e089f1048a1d4a9a492ed17b9fe759100f1bd619407b001f5927928d88b780c4 [element]=ghcr.io/element-hq/element-web:v1.12.30@sha256:3e7dbd4424de9e11c812bc740acf2725b2abe66ea0d0802023b56fd85d3fa09a [synapse-media-owner]=ghcr.io/element-hq/synapse:v1.162.0@sha256:6b84a7bbac36f080b2d2e51e0289cf1b08b349598ea44a558df38d558f2c2311 ) # The named volume each service may use; every bind mount must be its own ./matrix/ path. -declare -A named=([livekit]="" [postgres]=matrix-postgres [synapse]=matrix-media [mas]="" [element]="" [synapse-media-owner]=matrix-media) -declare -A own=([livekit]=livekit [postgres]=postgres [synapse]=synapse [mas]=mas [element]=element [synapse-media-owner]=none) +declare -A named=([livekit]="" [postgres]=matrix-postgres [postgres-17-dump]=matrix-postgres [synapse]=matrix-media [mas]="" [element]="" [synapse-media-owner]=matrix-media) +declare -A own=([livekit]=livekit [postgres]=postgres [postgres-17-dump]=none [synapse]=synapse [mas]=mas [element]=element [synapse-media-owner]=none) +# The vendored PostgreSQL 17 -> 18 kit, byte for byte (Ky's postgres-17-to-18.sh). +pgkit=$root/scripts/postgres-17-to-18.sh pgkit_sha256=2992644109716cd34297fbcb76eba8907f4a5e3031a12c05aade010e5ea2b571 -[ "$(jq -c '[.services | keys[] | select(. != "app")] | sort' <<<"$out")" = '["element","livekit","mas","postgres","synapse","synapse-media-owner"]' ] \ +[ "$(jq -c '[.services | keys[] | select(. != "app")] | sort' <<<"$out")" = '["element","livekit","mas","postgres","postgres-17-dump","synapse","synapse-media-owner"]' ] \ || bad "unexpected Matrix services: $(jq -c '.services | keys' <<<"$out")" [ "$(jq '[.services | to_entries[] | select(.key != "livekit") | .value.ports // [] | length] | add' <<<"$out")" = 0 ] || bad "a service publishes a port" [ "$(jq -r '.networks.default.name' <<<"$out")" = kymessages-net ] || bad "network not named kymessages-net" @@ -49,7 +52,7 @@ for s in "${!image[@]}"; do case $type in volume) [ "$src" = "${named[$s]}" ] || bad "$s mounts volume $src" ;; bind) - case $s:$src in "$s:$root/matrix/${own[$s]}" | "$s:$root/matrix/${own[$s]}/"* | "synapse:$root/matrix/federation/federation.yaml") ;; *) bad "$s binds $src outside ./matrix/${own[$s]}" ;; esac + case $s:$src in "$s:$root/matrix/${own[$s]}" | "$s:$root/matrix/${own[$s]}/"* | "synapse:$root/matrix/federation/federation.yaml" | postgres:"$pgkit" | postgres-17-dump:"$pgkit") ;; *) bad "$s binds $src outside ./matrix/${own[$s]}" ;; esac [ "$ro" = true ] || bad "$s bind $src -> $target is writable" ;; *) bad "$s has a $type mount" ;; esac @@ -95,7 +98,7 @@ jq -e '[.services.element.volumes[] | select(.source == "/dev/null" or (.target for s in postgres synapse mas element livekit; do [ "$(jq -r --arg s "$s" '.services[$s].restart' <<<"$out")" = unless-stopped ] || bad "$s restart is not unless-stopped" done -for s in postgres synapse mas livekit; do +for s in postgres postgres-17-dump synapse mas livekit; do [ "$(jq -r --arg s "$s" '.services[$s].user' <<<"$out")" = 1234:5678 ] || bad "$s does not run as KY_MATRIX_UID:KY_MATRIX_GID" done for s in postgres synapse element; do @@ -127,6 +130,23 @@ bindjson() { printf 'services: {p: {image: x, volumes: [{type: bind, source: /x, | docker compose --env-file /dev/null -f - config --format json | jq -c '.services.p.volumes[0].bind'; } nocreate=$(bindjson false) if [ -z "$nocreate" ] || [ "$nocreate" = "$(bindjson true)" ]; then bad "this docker compose cannot express create_host_path false"; fi +# PostgreSQL 18 runs from 18/docker on the whole volume, so the 17 data in pgdata/ stays beside +# it; a 17 stack moves on its next start: the 17 one-shot dumps it once (no network, read-only +# root), then postgres restores the dump before its own entrypoint. Both run the vendored kit. +[ "$(sha256sum "$pgkit" | cut -d' ' -f1)" = "$pgkit_sha256" ] || bad "scripts/postgres-17-to-18.sh differs from the kit" +[ "$(stat -c %a "$pgkit")" = 755 ] || bad "scripts/postgres-17-to-18.sh is not mode 755" +pg=$(jq -c '.services.postgres' <<<"$out") dump=$(jq -c '.services["postgres-17-dump"]' <<<"$out") +[ "$(jq -c '[.entrypoint, .command, .environment.PGDATA, .depends_on["postgres-17-dump"].condition, .healthcheck.start_period, .stop_grace_period]' <<<"$pg")" \ + = '[["bash","/ky/postgres-17-to-18.sh","restore"],["postgres"],null,"service_completed_successfully","1h0m0s","2m0s"]' ] \ + || bad "postgres does not restore through the kit after postgres-17-dump, on the image's PGDATA: $pg" +[ "$(jq -c '[.entrypoint, .environment, .network_mode, .restart, .read_only, .tmpfs, .secrets, .depends_on, .stop_grace_period]' <<<"$dump")" \ + = '[["bash","/ky/postgres-17-to-18.sh","dump"],{"NEW":"/v","OLD":"/v/pgdata"},"none","no",true,["/tmp"],null,null,"2m0s"]' ] \ + || bad "postgres-17-dump is not the locked-down kit dump of pgdata/: $dump" +kitmount() { jq -c --arg k "$pgkit" --argjson nc "$nocreate" '[.volumes[] | if .type == "bind" then [.source == $k, .target, .read_only, .bind == $nc] else [.source, .target] end]' <<<"$1"; } +[ "$(kitmount "$pg")" = '[["matrix-postgres","/var/lib/postgresql"],[false,"/docker-entrypoint-initdb.d",true,false],[true,"/ky/postgres-17-to-18.sh",true,true]]' ] \ + || bad "postgres mounts are not matrix-postgres at /var/lib/postgresql, ./matrix/postgres and the kit (create_host_path false): $(kitmount "$pg")" +[ "$(kitmount "$dump")" = '[["matrix-postgres","/v"],[true,"/ky/postgres-17-to-18.sh",true,true]]' ] \ + || bad "postgres-17-dump mounts are not matrix-postgres at /v and the kit (create_host_path false): $(kitmount "$dump")" jq -e --arg f "$root/matrix/federation/federation.yaml" --argjson nc "$nocreate" \ '[.services.synapse.volumes[] | select(.source == $f)] | length == 1 and .[0].target == "/federation.yaml" and .[0].read_only == true and .[0].bind == $nc' <<<"$out" >/dev/null \ || bad "synapse does not bind ./matrix/federation/federation.yaml read-only at /federation.yaml, create_host_path false" @@ -247,7 +267,7 @@ chatonly() (unset KY_MATRIX_RTC_HOST KY_MATRIX_MEDIA_BIND_IP; KY_MATRIX_CALLS=of for extra in "" "$root/docker-compose.static-ip.yml"; do args=(); [ -z "$extra" ] || args=(-f "$extra") co=$(chatonly "${args[@]}") || { bad "chat-only does not compose ${extra:+with $extra}"; continue; } - [ "$(jq -c '.services | keys' <<<"$co")" = '["app","element","livekit","mas","postgres","synapse","synapse-media-owner"]' ] || bad "chat-only services: $(jq -c '.services | keys' <<<"$co")" + [ "$(jq -c '.services | keys' <<<"$co")" = '["app","element","livekit","mas","postgres","postgres-17-dump","synapse","synapse-media-owner"]' ] || bad "chat-only services: $(jq -c '.services | keys' <<<"$co")" [ "$(jq -c '.services.livekit | [.scale, .profiles]' <<<"$co")" = '[0,null]' ] || bad "chat-only LiveKit is not at scale 0 outside any profile: $(jq -c '.services.livekit | [.scale, .profiles]' <<<"$co")" [ "$(jq '[.services[] | .ports // [] | length] | add' <<<"$co")" = 0 ] || bad "chat-only publishes a port" [ "$(jq -r '.services.app.environment.KY_MATRIX_CALLS' <<<"$co")" = off ] || bad "chat-only app does not have KY_MATRIX_CALLS=off" diff --git a/scripts/check-compose-podman.sh b/scripts/check-compose-podman.sh index 8ca87dac..07f58b45 100755 --- a/scripts/check-compose-podman.sh +++ b/scripts/check-compose-podman.sh @@ -52,6 +52,11 @@ for c in "${chains[@]}"; do jq -e --arg r "$root" '[.services[] | (.volumes // [])[] | select(.type == "bind" and (.source == $r + "/data" or .source == $r + "/backups"))] | length > 0 and all(.bind.selinux == "z")' <<<"$p" >/dev/null \ || bad "$name: ./data or ./backups is mounted without the shared SELinux label" done +# Both Postgres services run the PostgreSQL 17 -> 18 script from ./scripts, outside the ./matrix +# that matrix-init labels. +# shellcheck disable=SC2086 +k=$(render $base $matrix $mpod | jq -c --arg k "$root/scripts/postgres-17-to-18.sh" '[.services | to_entries[] | .key as $s | .value.volumes // [] | .[] | select(.source == $k) | [$s, .read_only, .bind.selinux]] | sort') +[ "$k" = '[["postgres",true,"z"],["postgres-17-dump",true,"z"]]' ] || bad "the PostgreSQL 17 -> 18 script binds: $k" # restore-matrix reads a restored ./matrix the host wrote, so it relabels it too, read-only. # shellcheck disable=SC2086 r=$(render $base $matrix $mpod --profile restore | jq -c --arg r "$root" '[.services["restore-matrix"].volumes[] | select(.type == "bind") | [(.source | ltrimstr($r)), .read_only, .bind.selinux]] | sort') diff --git a/scripts/matrix-acceptance.sh b/scripts/matrix-acceptance.sh index d492d0f9..252831b9 100755 --- a/scripts/matrix-acceptance.sh +++ b/scripts/matrix-acceptance.sh @@ -1367,7 +1367,7 @@ caps=("$state"/backups/*.kycap) # Unmatched, the glob stays literal and still counts one. [[ -f ${caps[0]} ]] || { echo " FAILED: no sealed capsule in the backup copy" >&2; false; } expect "${#caps[@]}" 1 "one sealed capsule" -dc rm -sfv app element synapse mas postgres livekit synapse-media-owner >/dev/null +dc rm -sfv app element synapse mas postgres postgres-17-dump livekit synapse-media-owner >/dev/null for v in matrix-postgres matrix-media; do docker volume rm "${project}_$v" >/dev/null; done expect "$(docker volume ls -q --filter "label=com.docker.compose.project=$project" | grep -cE '_(matrix-postgres|matrix-media)$' || true)" 0 "Matrix volumes gone" rm -r "$scratch/data" "$scratch/backups" diff --git a/scripts/postgres-17-to-18.sh b/scripts/postgres-17-to-18.sh new file mode 100755 index 00000000..85b7729b --- /dev/null +++ b/scripts/postgres-17-to-18.sh @@ -0,0 +1,89 @@ +#!/bin/bash +# Moves a PostgreSQL 17 data directory to 18 by dump and restore. The 17 data is only read +# (starting 17 may replay its WAL); it is never deleted or reinitialised. +# dump in the postgres:17 image. OLD = the 17 data directory, NEW = the directory that the +# 18 container mounts at /var/lib/postgresql. Dumps OLD once into NEW/upgrade-from-17. +# restore in the postgres:18 image, as its entrypoint: restores that dump once into +# $PGDATA.part, renames it to $PGDATA, then runs the image's entrypoint with the args. +# Runs as root (compose) or as the postgres user (Kubernetes runAsUser 70). +set -Eeuo pipefail +mode=${1:-}; shift || true +new=${NEW:-/var/lib/postgresql} +dump_dir=$new/upgrade-from-17 +as_pg() { if [ "$(id -u)" = 0 ]; then gosu postgres "$@"; else "$@"; fi; } +sock=$(mktemp -d) +[ "$(id -u)" != 0 ] || chown postgres "$sock" + +case $mode in +dump) + old=${OLD:?set OLD to the PostgreSQL 17 data directory} + if [ -s "$new/18/docker/PG_VERSION" ] || [ -s "$dump_dir/dump.sql" ]; then + echo "postgres-17-to-18: already done"; exit 0 + fi + if [ ! -s "$old/PG_VERSION" ]; then + echo "postgres-17-to-18: no PostgreSQL 17 data in $old, nothing to move"; exit 0 + fi + if [ "$(cat "$old/PG_VERSION")" != 17 ]; then + echo "postgres-17-to-18: $old holds PostgreSQL $(cat "$old/PG_VERSION"), expected 17" >&2; exit 1 + fi + # PostgreSQL's own lock check cannot see a server in another container (its PID 1 looks + # like our grandparent), so a 17 still running on OLD would get a second postmaster. + if [ -e "$old/postmaster.pid" ]; then + echo "postgres-17-to-18: $old/postmaster.pid exists: PostgreSQL 17 is running on it, or did not stop cleanly; stop it (start it once with the previous setup and stop it, if it crashed), then start again" >&2 + exit 1 + fi + # The dump and the restored cluster each take at most about the size of the 17 data. + need=$(( $(du -sk "$old" | cut -f1) * 2 )) + free=$(df -Pk "$new" | awk 'NR == 2 { print $4 }') + if [ "$free" -lt "$need" ]; then + echo "postgres-17-to-18: $new has $((free / 1024)) MiB free, the move needs $((need / 1024)) MiB; free space or grow the volume, then start again" >&2 + exit 1 + fi + mkdir -p "$dump_dir" + [ "$(id -u)" != 0 ] || chown postgres "$new" "$dump_dir" + # No network, and a private socket that only trusts local connections. + printf 'local all all trust\n' > "$sock/hba" + [ "$(id -u)" != 0 ] || chown postgres "$sock/hba" + as_pg pg_ctl -D "$old" -w -t 3600 -l "$sock/log" \ + -o "-c listen_addresses= -c unix_socket_directories=$sock -c hba_file=$sock/hba" start || + { cat "$sock/log" >&2; exit 1; } + trap 'as_pg pg_ctl -D "$old" -m fast -w stop' EXIT + su=$(as_pg psql -h "$sock" -U "${POSTGRES_USER:-postgres}" -d template1 -XAtc "select rolname from pg_roles where oid = 10") + printf '%s\n' "$su" > "$dump_dir/superuser" + as_pg pg_dumpall -h "$sock" -U "$su" -f "$dump_dir/dump.sql.part" + as_pg sync "$dump_dir/dump.sql.part" + mv "$dump_dir/dump.sql.part" "$dump_dir/dump.sql" + sync "$dump_dir" + echo "postgres-17-to-18: dumped $old into $dump_dir/dump.sql; the 17 data is kept" + ;; +restore) + final=${PGDATA:?} + if [ ! -s "$final/PG_VERSION" ] && [ -s "$dump_dir/dump.sql" ]; then + # shellcheck source=/dev/null # the image's entrypoint, only inside the postgres image + source /usr/local/bin/docker-entrypoint.sh + # initdb's superuser is the 17 cluster's bootstrap role, so the dump's roles map one to one. + POSTGRES_USER=$(cat "$dump_dir/superuser") + export POSTGRES_USER PGDATA=$final.part + rm -rf "$PGDATA" # a restore an earlier start did not finish; never the 17 data + docker_setup_env + docker_create_db_directories + as_pg bash -c 'source /usr/local/bin/docker-entrypoint.sh; docker_setup_env; docker_init_database_dir; pg_setup_hba_conf' + as_pg pg_ctl -D "$PGDATA" -w -o "-c listen_addresses= -c unix_socket_directories=$sock" start + # pg_dumpall writes CREATE ROLE for the role it ran as, which initdb already made: drop that + # one line, only in the roles section above the first \connect (row data comes later). + q=$(as_pg psql -h "$sock" -U "$POSTGRES_USER" -d postgres -XAtc "select quote_ident(current_user)") + awk -v skip="CREATE ROLE $q;" 'seen || $0 != skip { print } /^\\connect / { seen = 1 }' "$dump_dir/dump.sql" | + as_pg psql -h "$sock" -U "$POSTGRES_USER" -d postgres -X -q -v ON_ERROR_STOP=1 + as_pg vacuumdb -h "$sock" -U "$POSTGRES_USER" --all --analyze-only -q + as_pg pg_ctl -D "$PGDATA" -m fast -w stop + sync "$PGDATA" + mv "$PGDATA" "$final" + sync "$(dirname "$final")" + export PGDATA=$final + echo "postgres-17-to-18: restored $dump_dir/dump.sql into $final" + fi + rm -rf "$sock" + exec docker-entrypoint.sh "$@" + ;; +*) echo "usage: postgres-17-to-18.sh dump | restore postgres [args...]" >&2; exit 2 ;; +esac diff --git a/scripts/test-postgres-17-to-18.sh b/scripts/test-postgres-17-to-18.sh new file mode 100755 index 00000000..3112167e --- /dev/null +++ b/scripts/test-postgres-17-to-18.sh @@ -0,0 +1,157 @@ +#!/usr/bin/env bash +# PostgreSQL 17 -> 18 on the Matrix overlay as shipped (docs/CHAT-SETUP.md "PostgreSQL 18"). +# Seeds real 17 data with the last 17 Compose files ($PG17_REF), real matrix-init SQL and a +# 17-era backup, then switches to this checkout's Compose files with 17 still running and +# proves: rows, roles and passwords survive; the 17 data is untouched and 17 still starts on it +# (rollback); a rerun is a no-op; matrix-init's kybackup-role.sql and rotation work after the +# move; a dump that fails to restore never yields a cluster; a fresh install initialises; and +# that 17 backup restores on 18 with the app's pg_restore flags. +# usage: scripts/test-postgres-17-to-18.sh [kymessages binary] (needs docker, jq, git; go +# when no binary is given). Postgres runs as the caller (KY_MATRIX_UID); contacts nothing. +set -Eeuo pipefail +repo=$(git -C "$(dirname "$0")" rev-parse --show-toplevel) +PG17_REF=${PG17_REF:-d83af54f578a94aa79b8cd3d5ae5398e2ca97457} # master before the move to 18 +P18=postgres:18.7-alpine3.24@sha256:0115267ab5a509022df9319c77be365cef335adb71556c75f60f5360ee247e71 +s=$(mktemp -d) +proj=kypg1718-$$ fresh=kypg18-$$ +fail() { echo "FAIL: $*" >&2; dc logs --no-color --tail 30 postgres postgres-17-dump >&2 2>/dev/null || true; exit 1; } +dcp() { local p=$1; shift; docker compose --env-file /dev/null --project-directory "$s" -p "$p" -f "$s/docker-compose.yml" -f "$s/docker-compose.matrix.yml" "$@"; } +dc() { dcp "$proj" "$@"; } +cleanup() { + dcp "$proj" down -v --remove-orphans >/dev/null 2>&1 || true + dcp "$fresh" down -v --remove-orphans >/dev/null 2>&1 || true + rm -rf "$s" +} +trap cleanup EXIT +uid=$(id -u) gid=$(id -g) +export KY_ADMIN_PASSWORD=test-only KY_APP_URL=https://chat.example.com KY_SESSION_SECRET=test-only \ + KY_TRUSTED_PROXIES=10.91.0.10 KY_UID=$uid KY_GID=$gid KY_MATRIX_UID=$uid KY_MATRIX_GID=$gid \ + KY_MATRIX_SERVER_NAME=example.com KY_MATRIX_HOST=https://matrix.example.com KY_MATRIX_CHAT_HOST=https://chat.example.com \ + KY_MATRIX_AUTH_HOST=https://auth.example.com KY_ADMIN_HOST=https://admin.example.com KY_KYIDENTITY_ISSUER=https://id.example.com \ + KY_MATRIX_MAS_CLIENT_ID=mas-client KY_MATRIX_ADMIN_CLIENT_ID=01J0000000000000000000ADMN KY_KYIDENTITY_HMAC_SECRET=test-only \ + KY_MATRIX_CALLS=off +unset KY_NETWORK_SUBNET KY_NETWORK KY_MATRIX_RTC_HOST KY_MATRIX_MEDIA_BIND_IP + +bin=${1:-} +if [ -z "$bin" ]; then bin=$s/kymessages; go build -C "$repo" -o "$bin" ./cmd/server; fi +init() { "$bin" matrix-init -dir "$s/matrix" >"$s/init.out"; } +old() { git -C "$repo" archive "$PG17_REF" docker-compose.yml docker-compose.matrix.yml compose | tar -x -C "$s"; } +new() { (cd "$repo" && cp -r docker-compose.yml docker-compose.matrix.yml compose "$s/" && mkdir -p "$s/scripts" && cp scripts/postgres-17-to-18.sh "$s/scripts/"); } +secret() { cat "$s/matrix/secrets/$1"; } +# pq PROJECT ROLE DB SQL: from another container on matrix-db with the role's password, as +# Synapse, MAS and the app connect (inside the postgres container the image trusts 127.0.0.1). +pq() { + local pw; pw=$(secret "$2_db_password" 2>/dev/null || secret postgres_password) + PGPASSWORD=${PW:-$pw} docker run --rm -i -e PGPASSWORD --network "$1_matrix-db" --entrypoint psql "$P18" -h postgres -U "$2" -d "$3" -XAtc "$4" +} +q() { pq "$proj" "$@"; } +in_vol() { docker run --rm --user "$KY_MATRIX_UID:$KY_MATRIX_GID" -v "${1}_matrix-postgres:/v" --entrypoint sh "$P18" -c "$2"; } +logs() { dc logs --no-color "$1" 2>&1; } +up() { dc up -d --wait --wait-timeout 300 postgres >/dev/null 2>&1; } +rows() { q synapse synapse "select count(*) || ',' || sum((j->>'g')::int) from t"; } +seeded=50000,1250025000 + +# 1. A 17 stack as shipped, with matrix-init's init.sql and kybackup-role.sql, and real data. +init; [ -s "$s/matrix/postgres/init.sql" ] || fail "matrix-init wrote no init.sql" +old; grep -q 'postgres:17' "$s/docker-compose.matrix.yml" || fail "$PG17_REF is not a 17 stack" +up || fail "17 did not start" +q synapse synapse "create table t(id bigserial primary key, s text unique, j jsonb); + insert into t(s, j) select 'row' || g, jsonb_build_object('g', g) from generate_series(1, 50000) g" >/dev/null +q mas mas "create extension pg_trgm; create table u(name text); create index on u using gin (name gin_trgm_ops); + insert into u values ('alice'), ('bob')" >/dev/null +[ "$(rows)" = $seeded ] || fail "seed" +# A backup as the 17 app takes it (internal/backup dumpParts: custom format, as kybackup). +for db in synapse mas; do + dc exec -T -e PGPASSWORD="$(secret kybackup_db_password)" postgres pg_dump --format=custom --host=127.0.0.1 \ + --username=kybackup --dbname=$db --no-password >"$s/$db.dump" || fail "17 backup of $db" +done + +# 2. The move: this checkout's Compose files, applied while 17 runs, as an operator would. +new +# The dump run by hand beside the live 17 is refused and writes nothing (two servers, one data). +dc run --rm postgres-17-dump >"$s/run.out" 2>&1 && fail "the dump ran beside a live 17" +grep -q 'postmaster.pid exists' "$s/run.out" || fail "no live-server refusal: $(cat "$s/run.out")" +in_vol "$proj" 'test ! -e /v/upgrade-from-17/dump.sql' || fail "the refused dump wrote a dump" +since=$(date +%s) +up || fail "18 did not start after the move" +logs postgres-17-dump | grep -q 'dumped /v/pgdata' || fail "no dump" +logs postgres | grep -q 'restored' || fail "no restore" +# Compose stops 17 before the dump starts it again on the same data. +ev=$(docker events --since "$since" --until "$(date +%s)" --filter "label=com.docker.compose.project=$proj" --format '{{.TimeNano}} {{.Actor.Attributes.name}} {{.Action}}' | sort -n) +stop17=$(awk '/postgres-1 die/ { print NR; exit }' <<<"$ev") dump=$(awk '/postgres-17-dump-1 start/ { print NR; exit }' <<<"$ev") +[ -n "$stop17" ] && [ -n "$dump" ] && [ "$stop17" -lt "$dump" ] || fail "the dump started before 17 stopped: $ev" +[ "$(q postgres postgres 'show server_version_num' | cut -c1-2)" = 18 ] || fail "not 18" +[ "$(q postgres postgres 'show data_directory')" = /var/lib/postgresql/18/docker ] || fail "data directory" +[ "$(q postgres postgres 'show data_checksums')" = on ] || fail "checksums" +[ "$(rows)" = $seeded ] || fail "synapse rows or password" +[ "$(q synapse postgres "select datcollate from pg_database where datname = 'synapse'")" = C ] || fail "synapse collation" +[ "$(q mas mas "select string_agg(name, ',') from u where name % 'alic'")" = alice ] || fail "mas pg_trgm or password" +[ "$(q kybackup synapse 'select count(*) from t')" = 50000 ] || fail "kybackup password or read grant" +PW=wrong q synapse synapse 'select 1' >/dev/null 2>&1 && fail "a wrong password is accepted" +q kybackup synapse 'delete from t' >/dev/null 2>&1 && fail "kybackup can write" +[ "$(in_vol "$proj" 'cat /v/pgdata/PG_VERSION')" = 17 ] || fail "17 data changed" + +# 3. matrix-init after the move: kybackup-role.sql re-applies, and a rotated password applies. +init +dc exec -T postgres psql -U postgres -v ON_ERROR_STOP=1 -f /docker-entrypoint-initdb.d/kybackup-role.sql >/dev/null || fail "kybackup-role.sql" +rm "$s/matrix/secrets/synapse_db_password"; init +grep -qF -- '-f /docker-entrypoint-initdb.d/role-passwords.sql' "$s/init.out" || fail "matrix-init did not print the rotation step" +rows >/dev/null 2>&1 && fail "the new synapse password worked before role-passwords.sql" +dc exec -T postgres psql -U postgres -v ON_ERROR_STOP=1 -f /docker-entrypoint-initdb.d/role-passwords.sql >/dev/null || fail "role-passwords.sql" +[ "$(rows)" = $seeded ] || fail "rotated synapse password" +q synapse synapse "insert into t(s, j) values ('on18', '{\"g\": 0}')" >/dev/null + +# 4. A rerun is a no-op. +dc up -d --wait --wait-timeout 300 --force-recreate postgres-17-dump postgres >/dev/null 2>&1 || fail "rerun" +logs postgres-17-dump | grep -q 'already done' || fail "rerun dumped again" +logs postgres | grep -q 'restored' && fail "rerun restored again" +[ "$(q synapse synapse 'select count(*) from t')" = 50001 ] || fail "rows after rerun" + +# 5. Rollback: the previous Compose files start 17 on the untouched 17 data; then forward again. +dc down --remove-orphans >/dev/null 2>&1; rm -r "$s/scripts"; old +up || fail "17 no longer starts on its data" +[ "$(q postgres postgres 'show server_version_num' | cut -c1-2)" = 17 ] || fail "rollback is not 17" +[ "$(q kybackup synapse 'select count(*) from t')" = 50000 ] || fail "17 data changed" +dc down --remove-orphans >/dev/null 2>&1; new +up || fail "18 did not start after the rollback" +[ "$(q synapse synapse 'select count(*) from t')" = 50001 ] || fail "18 data lost after the rollback" +logs postgres | grep -q 'restored' && fail "restored again after the rollback" + +# 6. A dump that fails to restore never yields a cluster, however often postgres restarts. +dc stop postgres >/dev/null 2>&1 +in_vol "$proj" 'mv /v/18/docker /v/18/docker.saved && cp /v/upgrade-from-17/dump.sql /v/dump.good && echo "THIS IS NOT SQL;" >> /v/upgrade-from-17/dump.sql' +dc up -d --wait --wait-timeout 60 postgres >/dev/null 2>&1 && fail "postgres came up on a bad dump" +dc stop postgres >/dev/null 2>&1 +[ "$(docker inspect -f '{{.RestartCount}}' "$(dc ps -aq postgres)")" -ge 1 ] || fail "postgres did not retry the bad dump" +in_vol "$proj" 'test ! -e /v/18/docker' || fail "a bad dump produced a cluster" +in_vol "$proj" 'rm -rf /v/18/docker.part && mv /v/18/docker.saved /v/18/docker && mv /v/dump.good /v/upgrade-from-17/dump.sql' +up || fail "18 did not come back" +[ "$(q synapse synapse 'select count(*) from t')" = 50001 ] || fail "rows after the bad dump" + +# 6b. The documented clean-up removes the 17 data and the dump; 18 keeps running on later starts. +dc exec -T postgres rm -r /var/lib/postgresql/pgdata /var/lib/postgresql/upgrade-from-17 || fail "clean-up" +dc up -d --wait --wait-timeout 300 --force-recreate postgres-17-dump postgres >/dev/null 2>&1 || fail "18 after the clean-up" +logs postgres-17-dump | grep -q 'already done' || fail "dump after the clean-up" +[ "$(q synapse synapse 'select count(*) from t')" = 50001 ] || fail "rows after the clean-up" + +# 7. A fresh install: nothing to move, a plain initdb with matrix-init's SQL. +dcp "$fresh" up -d --wait --wait-timeout 300 postgres >/dev/null 2>&1 || fail "fresh 18 did not start" +dcp "$fresh" logs --no-color postgres-17-dump | grep -q 'nothing to move' || fail "fresh install did not skip the dump" +dcp "$fresh" logs --no-color postgres | grep -q 'restored' && fail "fresh install restored something" +fq() { pq "$fresh" "$@"; } +[ "$(fq postgres postgres 'show data_directory')" = /var/lib/postgresql/18/docker ] || fail "fresh data directory" +fq synapse synapse 'select 1' >/dev/null || fail "fresh synapse login" +fq kybackup mas 'select 1' >/dev/null || fail "fresh kybackup login" + +# 8. The 17 backup restores on 18 as restore-matrix does it (internal/backup pgRestore), after +# the drill's checks (pg_restore --list and a full read). +for db in synapse mas; do + dcp "$fresh" exec -T postgres pg_restore --list <"$s/$db.dump" >/dev/null || fail "18 cannot list the 17 $db backup" + dcp "$fresh" exec -T postgres pg_restore --file=/dev/null <"$s/$db.dump" || fail "18 cannot read the 17 $db backup" + PGPASSWORD=$(secret ${db}_db_password) docker run --rm -i -e PGPASSWORD --network "${fresh}_matrix-db" --entrypoint pg_restore "$P18" \ + --host=postgres --port=5432 --username=$db --dbname=$db --no-password --no-owner --no-privileges --single-transaction --exit-on-error <"$s/$db.dump" || + fail "the 17 $db backup does not restore on 18" +done +[ "$(fq synapse synapse "select count(*) || ',' || sum((j->>'g')::int) from t")" = $seeded ] || fail "restored synapse rows" +[ "$(fq mas mas "select string_agg(name, ',') from u where name % 'alic'")" = alice ] || fail "restored mas pg_trgm" +echo "PASS: 17 -> 18 on the shipped Compose files: move with 17 running, rows and passwords, matrix-init re-run and rotation, rerun, rollback to 17, bad dump, fresh install, 17 backup restored on 18" From b220882fb373718cddda1c18ed384ff500f54075 Mon Sep 17 00:00:00 2001 From: Yoshiofthewire Date: Wed, 25 Nov 2026 16:23:12 -0500 Subject: [PATCH 2/2] fix(ci): matrix-acceptance carries the PostgreSQL 17 -> 18 kit The harness runs Compose with its scratch dir as the project directory and copied only compose/ and overrides/, so the kit bind (./scripts/postgres-17-to-18.sh) had no source and every leg failed at the stack step. Copy the script there too. Co-Authored-By: Claude Opus 5.5 --- scripts/matrix-acceptance.sh | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/scripts/matrix-acceptance.sh b/scripts/matrix-acceptance.sh index 252831b9..65004bce 100755 --- a/scripts/matrix-acceptance.sh +++ b/scripts/matrix-acceptance.sh @@ -94,7 +94,9 @@ fi cp -r "$here/overrides" "$scratch/overrides" # docker-compose.matrix.yml includes compose/calls-*.yml, resolved in the project directory. cp -r "$repo/compose" "$scratch/compose" -chmod -R a+rX "$scratch/overrides" "$scratch/nginx-extra" +# Postgres and its 17 -> 18 dump one-shot bind-mount ./scripts/postgres-17-to-18.sh. +mkdir -p "$scratch/scripts" && cp "$repo/scripts/postgres-17-to-18.sh" "$scratch/scripts/" +chmod -R a+rX "$scratch/overrides" "$scratch/nginx-extra" "$scratch/scripts" # Compose interpolation. The network name is project-scoped, never kymessages-net. export KY_NETWORK=$project-net