From 051ed7e8ec98f69a23e13371af8b4da65335f67e Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Thu, 30 Apr 2026 09:30:55 -0700 Subject: [PATCH 01/36] Fix ClickHouse bind mount provisioning --- deploy/server.tf | 4 +-- docs/production-incident-baseline.md | 49 ++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 2 deletions(-) diff --git a/deploy/server.tf b/deploy/server.tf index 19ae756c51..4f4bb12d57 100644 --- a/deploy/server.tf +++ b/deploy/server.tf @@ -128,7 +128,7 @@ resource "terraform_data" "data_volume_mount_alias" { count = var.data_volume_size_gb > 0 ? 1 : 0 triggers_replace = [ - "volume-mount-alias-v4", + "volume-mount-alias-v5", hcloud_volume.dofek_data[0].id, ] @@ -156,7 +156,7 @@ resource "terraform_data" "staging_data_volume_mount_alias" { count = var.staging_data_volume_size_gb > 0 ? 1 : 0 triggers_replace = [ - "volume-mount-alias-v2", + "volume-mount-alias-v3", hcloud_volume.dofek_staging_data[0].id, ] diff --git a/docs/production-incident-baseline.md b/docs/production-incident-baseline.md index a873ed1837..86e3fca09c 100644 --- a/docs/production-incident-baseline.md +++ b/docs/production-incident-baseline.md @@ -1502,3 +1502,52 @@ Validated with: If a future Cypress job hangs after specs appear to finish, inspect host-side plugin imports for long-lived clients or timers before changing timeouts or adding explicit process exits. + +## 2026-04-30: Web deploy failed on missing ClickHouse bind-mount path + +### Impact + +The `Deploy Web` workflow for commit `7af8b2f972c09cc998efe62eaced0e8817f85dd7` +failed for both production and staging before stack deployment. The app rollout +did not proceed. + +### Evidence That Mattered + +Terraform ran first and reported no infrastructure changes: + +```text +No changes. Your infrastructure matches the configuration. +Apply complete! Resources: 0 added, 0 changed, 0 destroyed. +``` + +Both deploy-stack jobs then failed in `Validate host bind mount paths`: + +```text +Required host bind mount path is missing: /mnt/dofek-data/clickhouse +Process completed with exit code 1. +``` + +The ClickHouse rollout commit added `/mnt/dofek-data/clickhouse` to the +Terraform `mkdir -p` command, but did not bump the +`terraform_data.*data_volume_mount_alias` replacement triggers in the same +commit. + +### Root Cause + +The ClickHouse host bind-mount directory was added to the Terraform +remote-exec provisioner without replacing the existing `terraform_data` +resources. Terraform provisioners only rerun on resource creation/replacement, +so Terraform considered the resources current and did not create the new +directory on either host. + +### Fix or Mitigation + +Bumped the production and staging data-volume mount-alias trigger strings so +the next Terraform apply replaces those `terraform_data` resources and reruns +the existing provisioners that create `/mnt/dofek-data/clickhouse`. + +### Remaining Risk + +This fixes the missed ClickHouse provisioning run. Future changes to the +`/mnt/dofek-data` directory list still require a corresponding trigger bump in +the same commit. From 1a5005efcc66f48361506e96a7ae52de1823d857 Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Thu, 30 Apr 2026 09:39:02 -0700 Subject: [PATCH 02/36] Document ClickHouse deploy prerequisites --- deploy/README.md | 1 + docs/production-incident-baseline.md | 13 ++++++++++--- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/deploy/README.md b/deploy/README.md index f8c1c1dd17..c3d62e5171 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -125,6 +125,7 @@ CI (main) -> build dofek + dofek-ml (same tag) 1. Install the Infisical CLI, login with OIDC machine identity (`identity-id=46b66f72-0c77-4cfe-be1b-a43395e77be7`), and render `${{ github.workspace }}/.env.` from `.github/templates/infisical-dotenv.tmpl`. The template escapes embedded newlines only when `secret.IsMultilineEncodingEnabled` is true. - Must include `CREDENTIAL_ENCRYPTION_KEY_BASE64` (base64-encoded 32-byte key). + - Must include `CLICKHOUSE_PASSWORD` for the ClickHouse service and app `CLICKHOUSE_URL` interpolation. - Optional: `CREDENTIAL_ENCRYPTION_KEY_NAMESPACE` (default `dofek`) and `CREDENTIAL_ENCRYPTION_KEY_NAME` (default `provider-credentials`). 2. Point Docker CLI at the remote daemon with `DOCKER_HOST=ssh://root@`. 3. Login to GHCR on the CI runner. diff --git a/docs/production-incident-baseline.md b/docs/production-incident-baseline.md index 86e3fca09c..f624c15edd 100644 --- a/docs/production-incident-baseline.md +++ b/docs/production-incident-baseline.md @@ -1546,8 +1546,15 @@ Bumped the production and staging data-volume mount-alias trigger strings so the next Terraform apply replaces those `terraform_data` resources and reruns the existing provisioners that create `/mnt/dofek-data/clickhouse`. +The rerun then exposed a second missing prerequisite: `CLICKHOUSE_PASSWORD` was +absent from both Infisical environments, so `docker stack config` failed while +interpolating ClickHouse environment variables. Added `CLICKHOUSE_PASSWORD` to +both `prod` and `staging` in Infisical. + ### Remaining Risk -This fixes the missed ClickHouse provisioning run. Future changes to the -`/mnt/dofek-data` directory list still require a corresponding trigger bump in -the same commit. +This fixes the missed ClickHouse provisioning run and the missing ClickHouse +secret. Future changes to the `/mnt/dofek-data` directory list still require a +corresponding trigger bump in the same commit. Future stack-level environment +variables must be added to Infisical before the workflow that references them is +merged or deployed. From 465149f9f3127ad929bc71501dfdfcf847c3970f Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Thu, 30 Apr 2026 09:46:58 -0700 Subject: [PATCH 03/36] Read ClickHouse password from deploy dotenv --- .github/workflows/deploy-web-stack.yml | 2 +- docs/production-incident-baseline.md | 17 ++++++++++++----- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/.github/workflows/deploy-web-stack.yml b/.github/workflows/deploy-web-stack.yml index c76d908525..d95835ff09 100644 --- a/.github/workflows/deploy-web-stack.yml +++ b/.github/workflows/deploy-web-stack.yml @@ -329,7 +329,7 @@ jobs: run: | migration_output_file="$RUNNER_TEMP/migrate.log" encoded_clickhouse_password="$( - node -e 'const password = process.env.CLICKHOUSE_PASSWORD; if (!password) { throw new Error("CLICKHOUSE_PASSWORD is required"); } process.stdout.write(encodeURIComponent(password));' + node "$RUNNER_TEMP/run-with-dotenv-env.mjs" node -e 'const password = process.env.CLICKHOUSE_PASSWORD; if (!password) { throw new Error("CLICKHOUSE_PASSWORD is required"); } process.stdout.write(encodeURIComponent(password));' )" for attempt in $(seq 1 12); do echo "Starting migration attempt ${attempt}/12..." diff --git a/docs/production-incident-baseline.md b/docs/production-incident-baseline.md index f624c15edd..47c491a060 100644 --- a/docs/production-incident-baseline.md +++ b/docs/production-incident-baseline.md @@ -1551,10 +1551,17 @@ absent from both Infisical environments, so `docker stack config` failed while interpolating ClickHouse environment variables. Added `CLICKHOUSE_PASSWORD` to both `prod` and `staging` in Infisical. +The next rerun reached the migration step and showed that the workflow encoded +`CLICKHOUSE_PASSWORD` from the runner process environment instead of the +rendered Infisical dotenv file. Updated the migration step to run that encoding +through the existing dotenv command runner. + ### Remaining Risk -This fixes the missed ClickHouse provisioning run and the missing ClickHouse -secret. Future changes to the `/mnt/dofek-data` directory list still require a -corresponding trigger bump in the same commit. Future stack-level environment -variables must be added to Infisical before the workflow that references them is -merged or deployed. +This fixes the missed ClickHouse provisioning run, the missing ClickHouse +secret, and the migration-step dotenv mismatch. Future changes to the +`/mnt/dofek-data` directory list still require a corresponding trigger bump in +the same commit. Future stack-level environment variables must be added to +Infisical before the workflow that references them is merged or deployed, and +workflow steps must read Infisical-only secrets from the rendered dotenv file +rather than from the runner environment. From 5337d4df48768bead6704b03da058d87f0997146 Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Thu, 30 Apr 2026 10:12:39 -0700 Subject: [PATCH 04/36] Run deploy migrations as named containers --- .github/workflows/deploy-web-stack.yml | 39 ++++++++++++++------------ docs/production-incident-baseline.md | 38 +++++++++++++++++++++---- 2 files changed, 53 insertions(+), 24 deletions(-) diff --git a/.github/workflows/deploy-web-stack.yml b/.github/workflows/deploy-web-stack.yml index d95835ff09..e0ba241fa7 100644 --- a/.github/workflows/deploy-web-stack.yml +++ b/.github/workflows/deploy-web-stack.yml @@ -331,27 +331,30 @@ jobs: encoded_clickhouse_password="$( node "$RUNNER_TEMP/run-with-dotenv-env.mjs" node -e 'const password = process.env.CLICKHOUSE_PASSWORD; if (!password) { throw new Error("CLICKHOUSE_PASSWORD is required"); } process.stdout.write(encodeURIComponent(password));' )" - for attempt in $(seq 1 12); do - echo "Starting migration attempt ${attempt}/12..." - if timeout 90s docker run --rm --network "${STACK_NAME}_default" \ - --env-file "$INFISICAL_ENV_FILE" \ - --entrypoint sh \ - "ghcr.io/asherlc/dofek:${IMAGE_TAG}" \ - -euc "export DATABASE_URL=\"postgres://health:\${POSTGRES_PASSWORD}@db:5432/health\"; export CLICKHOUSE_URL=\"http://default:${encoded_clickhouse_password}@clickhouse:8123\"; exec ./entrypoint.sh migrate" >"$migration_output_file" 2>&1; then - echo "Migration attempt ${attempt}/12 succeeded." - break - fi + migration_container="${STACK_NAME}_migrate_${GITHUB_RUN_ID}_${GITHUB_RUN_ATTEMPT}" + cleanup_migration_container() { + docker rm -f "$migration_container" >/dev/null 2>&1 || true + } + trap cleanup_migration_container EXIT + + echo "Starting migration container ${migration_container}..." + if timeout 50m docker run --name "$migration_container" --rm --network "${STACK_NAME}_default" \ + --env-file "$INFISICAL_ENV_FILE" \ + --entrypoint sh \ + "ghcr.io/asherlc/dofek:${IMAGE_TAG}" \ + -euc "export DATABASE_URL=\"postgres://health:\${POSTGRES_PASSWORD}@db:5432/health\"; export CLICKHOUSE_URL=\"http://default:${encoded_clickhouse_password}@clickhouse:8123\"; exec ./entrypoint.sh migrate" >"$migration_output_file" 2>&1; then + echo "Migration succeeded." + trap - EXIT + cleanup_migration_container + else migration_exit_code=$? - echo "Migration attempt ${attempt}/12 failed (exit code ${migration_exit_code})." + echo "Migration failed (exit code ${migration_exit_code})." echo "Migration output (last 60 lines):" tail -n 60 "$migration_output_file" || true - if [ "$attempt" -eq 12 ]; then - echo "::error::Migration failed after 12 attempts" - exit 1 - fi - echo "Migration attempt $attempt failed; retrying in 5s..." - sleep 5 - done + cleanup_migration_container + echo "::error::Migration failed" + exit 1 + fi - name: Deploy stack env: diff --git a/docs/production-incident-baseline.md b/docs/production-incident-baseline.md index 47c491a060..bc12e11919 100644 --- a/docs/production-incident-baseline.md +++ b/docs/production-incident-baseline.md @@ -1556,12 +1556,38 @@ The next rerun reached the migration step and showed that the workflow encoded rendered Infisical dotenv file. Updated the migration step to run that encoding through the existing dotenv command runner. +A later rerun reached the migration container and then appeared stuck. Production +Postgres showed one migration session holding advisory lock `728370291` while +running: + +```sql +UPDATE fitness.metric_stream +SET id = gen_random_uuid() +WHERE id IS NULL; +``` + +The table was a compressed Timescale hypertable with 195 chunks, 189 compressed +chunks, and about 37 GB of chunk data. Later workflow retries were not applying +migrations; they were blocked on the same advisory lock. Because the workflow +wrapped `docker run` with the runner-side `timeout` while using remote Docker +over SSH, each timeout killed the local Docker client but left the remote +migration container running. + +Updated the migration step to run one named migration container with a 50-minute +timeout and explicit cleanup of that remote container on failure or timeout. +The longer timeout is intentionally scoped to migrations because this release +contains a one-time 37 GB compressed-hypertable backfill; the named-container +cleanup prevents future runner-side timeouts from leaking remote migration +processes. + ### Remaining Risk This fixes the missed ClickHouse provisioning run, the missing ClickHouse -secret, and the migration-step dotenv mismatch. Future changes to the -`/mnt/dofek-data` directory list still require a corresponding trigger bump in -the same commit. Future stack-level environment variables must be added to -Infisical before the workflow that references them is merged or deployed, and -workflow steps must read Infisical-only secrets from the rendered dotenv file -rather than from the runner environment. +secret, the migration-step dotenv mismatch, and the remote migration-container +leak. Future changes to the `/mnt/dofek-data` directory list still require a +corresponding trigger bump in the same commit. Future stack-level environment +variables must be added to Infisical before the workflow that references them is +merged or deployed, and workflow steps must read Infisical-only secrets from the +rendered dotenv file rather than from the runner environment. Large compressed +hypertable backfills should be called out in deploy planning so the migration +timeout is intentional rather than discovered during release. From eb1889f9bc8821a4f6fca0507523cda3d60fa5bd Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Thu, 30 Apr 2026 11:11:30 -0700 Subject: [PATCH 05/36] Add server-side migration timeout --- .github/workflows/deploy-web-stack.yml | 5 +++-- docs/production-incident-baseline.md | 15 +++++++++------ 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/.github/workflows/deploy-web-stack.yml b/.github/workflows/deploy-web-stack.yml index e0ba241fa7..00709631ac 100644 --- a/.github/workflows/deploy-web-stack.yml +++ b/.github/workflows/deploy-web-stack.yml @@ -338,11 +338,12 @@ jobs: trap cleanup_migration_container EXIT echo "Starting migration container ${migration_container}..." - if timeout 50m docker run --name "$migration_container" --rm --network "${STACK_NAME}_default" \ + if timeout 55m docker run --name "$migration_container" --rm --network "${STACK_NAME}_default" \ --env-file "$INFISICAL_ENV_FILE" \ + --env "CLICKHOUSE_PASSWORD_ENCODED=$encoded_clickhouse_password" \ --entrypoint sh \ "ghcr.io/asherlc/dofek:${IMAGE_TAG}" \ - -euc "export DATABASE_URL=\"postgres://health:\${POSTGRES_PASSWORD}@db:5432/health\"; export CLICKHOUSE_URL=\"http://default:${encoded_clickhouse_password}@clickhouse:8123\"; exec ./entrypoint.sh migrate" >"$migration_output_file" 2>&1; then + -euc 'timeout -k 30 3000 sh -euc '"'"'export DATABASE_URL="postgres://health:${POSTGRES_PASSWORD}@db:5432/health"; export CLICKHOUSE_URL="http://default:${CLICKHOUSE_PASSWORD_ENCODED}@clickhouse:8123"; exec ./entrypoint.sh migrate'"'"'' >"$migration_output_file" 2>&1; then echo "Migration succeeded." trap - EXIT cleanup_migration_container diff --git a/docs/production-incident-baseline.md b/docs/production-incident-baseline.md index bc12e11919..3a5553976e 100644 --- a/docs/production-incident-baseline.md +++ b/docs/production-incident-baseline.md @@ -1573,12 +1573,15 @@ wrapped `docker run` with the runner-side `timeout` while using remote Docker over SSH, each timeout killed the local Docker client but left the remote migration container running. -Updated the migration step to run one named migration container with a 50-minute -timeout and explicit cleanup of that remote container on failure or timeout. -The longer timeout is intentionally scoped to migrations because this release -contains a one-time 37 GB compressed-hypertable backfill; the named-container -cleanup prevents future runner-side timeouts from leaking remote migration -processes. +Updated the migration step to run one named migration container with explicit +cleanup of that remote container on failure or timeout. The first cleanup fix +still depended on the runner-side `timeout docker run` regaining control over +SSH, which did not happen reliably. The workflow now also runs BusyBox +`timeout` inside the remote container, so the migration process exits from the +server side even if the runner-side Docker client hangs. The longer timeout is +intentionally scoped to migrations because this release contains a one-time +37 GB compressed-hypertable backfill; the named-container cleanup prevents +future runner-side timeouts from leaking remote migration processes. ### Remaining Risk From 3dfff4bc777f3b92c7a005a09ba4a1877ca15cf6 Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Thu, 30 Apr 2026 12:02:33 -0700 Subject: [PATCH 06/36] Run deploy migrations detached --- .github/workflows/deploy-web-stack.yml | 35 +++++++++++++++++++++++--- deploy/stack.yml | 2 +- docs/production-incident-baseline.md | 31 ++++++++++++++++++++--- 3 files changed, 61 insertions(+), 7 deletions(-) diff --git a/.github/workflows/deploy-web-stack.yml b/.github/workflows/deploy-web-stack.yml index 00709631ac..ed7e614308 100644 --- a/.github/workflows/deploy-web-stack.yml +++ b/.github/workflows/deploy-web-stack.yml @@ -338,17 +338,46 @@ jobs: trap cleanup_migration_container EXIT echo "Starting migration container ${migration_container}..." - if timeout 55m docker run --name "$migration_container" --rm --network "${STACK_NAME}_default" \ + cleanup_migration_container + docker run --detach --name "$migration_container" --network "${STACK_NAME}_default" \ --env-file "$INFISICAL_ENV_FILE" \ --env "CLICKHOUSE_PASSWORD_ENCODED=$encoded_clickhouse_password" \ --entrypoint sh \ "ghcr.io/asherlc/dofek:${IMAGE_TAG}" \ - -euc 'timeout -k 30 3000 sh -euc '"'"'export DATABASE_URL="postgres://health:${POSTGRES_PASSWORD}@db:5432/health"; export CLICKHOUSE_URL="http://default:${CLICKHOUSE_PASSWORD_ENCODED}@clickhouse:8123"; exec ./entrypoint.sh migrate'"'"'' >"$migration_output_file" 2>&1; then + -euc 'timeout -k 30 3000 sh -euc '"'"'export DATABASE_URL="postgres://health:${POSTGRES_PASSWORD}@db:5432/health"; export CLICKHOUSE_URL="http://default:${CLICKHOUSE_PASSWORD_ENCODED}@clickhouse:8123"; exec ./entrypoint.sh migrate'"'"'' + + migration_timeout_seconds=3300 + migration_start_seconds=$SECONDS + while true; do + container_state="$(docker inspect --format '{{.State.Running}} {{.State.ExitCode}}' "$migration_container" 2>/dev/null || true)" + if [ -z "$container_state" ]; then + echo "::error::Migration container ${migration_container} disappeared before completion" + exit 1 + fi + + migration_running="$(printf '%s\n' "$container_state" | awk '{print $1}')" + migration_exit_code="$(printf '%s\n' "$container_state" | awk '{print $2}')" + if [ "$migration_running" = "false" ]; then + break + fi + + elapsed_seconds=$((SECONDS - migration_start_seconds)) + if [ "$elapsed_seconds" -ge "$migration_timeout_seconds" ]; then + echo "::error::Migration exceeded ${migration_timeout_seconds}s" + cleanup_migration_container + exit 1 + fi + + echo "Migration still running after ${elapsed_seconds}s..." + sleep 15 + done + + docker logs "$migration_container" >"$migration_output_file" 2>&1 || true + if [ "$migration_exit_code" -eq 0 ]; then echo "Migration succeeded." trap - EXIT cleanup_migration_container else - migration_exit_code=$? echo "Migration failed (exit code ${migration_exit_code})." echo "Migration output (last 60 lines):" tail -n 60 "$migration_output_file" || true diff --git a/deploy/stack.yml b/deploy/stack.yml index c6eaac8aec..1d22a7032e 100644 --- a/deploy/stack.yml +++ b/deploy/stack.yml @@ -177,7 +177,7 @@ services: deploy: resources: limits: - memory: 1G + memory: 2G databasus: image: databasus/databasus:v3.32.1 diff --git a/docs/production-incident-baseline.md b/docs/production-incident-baseline.md index 3a5553976e..0764a05245 100644 --- a/docs/production-incident-baseline.md +++ b/docs/production-incident-baseline.md @@ -1583,12 +1583,37 @@ intentionally scoped to migrations because this release contains a one-time 37 GB compressed-hypertable backfill; the named-container cleanup prevents future runner-side timeouts from leaking remote migration processes. +The next retry showed that even with the server-side timeout, a long attached +`docker run` over SSH can fail with: + +```text +client_loop: send disconnect: Broken pipe +error waiting for container +``` + +Updated the migration step again to start the migration container detached, +then poll `docker inspect` with short SSH calls and collect `docker logs` after +the container exits. This keeps the release job from depending on one long-lived +SSH stream while the database is doing a multi-minute table rewrite. + +Staging also failed after Postgres migrations and materialized-view sync because +ClickHouse exceeded the service's 1 GB memory limit while applying the +ClickHouse migrations: + +```text +(total) memory limit exceeded ... current RSS: 966.99 MiB, maximum: 921.60 MiB +``` + +Raised the ClickHouse service memory limit to 2 GB so the ClickHouse migration +has enough memory to create the Postgres bridge and analytics read models. + ### Remaining Risk This fixes the missed ClickHouse provisioning run, the missing ClickHouse -secret, the migration-step dotenv mismatch, and the remote migration-container -leak. Future changes to the `/mnt/dofek-data` directory list still require a -corresponding trigger bump in the same commit. Future stack-level environment +secret, the migration-step dotenv mismatch, the remote migration-container leak, +the long-lived SSH session failure mode, and the ClickHouse memory ceiling seen +on staging. Future changes to the `/mnt/dofek-data` directory list still require +a corresponding trigger bump in the same commit. Future stack-level environment variables must be added to Infisical before the workflow that references them is merged or deployed, and workflow steps must read Infisical-only secrets from the rendered dotenv file rather than from the runner environment. Large compressed From c9e40cf1849d8411624dd30b9b9ad0b3f07ba3c9 Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Thu, 30 Apr 2026 12:04:27 -0700 Subject: [PATCH 07/36] Apply ClickHouse memory before migrations --- .github/workflows/deploy-web-stack.yml | 22 ++++++++++++++++++++++ docs/production-incident-baseline.md | 6 ++++++ 2 files changed, 28 insertions(+) diff --git a/.github/workflows/deploy-web-stack.yml b/.github/workflows/deploy-web-stack.yml index ed7e614308..9f74147f56 100644 --- a/.github/workflows/deploy-web-stack.yml +++ b/.github/workflows/deploy-web-stack.yml @@ -323,6 +323,28 @@ jobs: sleep 5 done + - name: Apply ClickHouse resource limits + run: | + docker service update --limit-memory 2G "${STACK_NAME}_clickhouse" + + - name: Wait for ClickHouse after resource update + run: | + for attempt in $(seq 1 36); do + clickhouse_output=$(timeout 15s docker run --rm --network "${STACK_NAME}_default" \ + postgres:18-alpine sh -euc \ + "wget -qO- http://clickhouse:8123/ping" 2>&1 || true) + if [ "$clickhouse_output" = "Ok." ]; then + echo "ClickHouse is reachable after resource update." + break + fi + if [ "$attempt" -eq 36 ]; then + echo "::error::ClickHouse did not become reachable within 180s after resource update" + exit 1 + fi + echo "ClickHouse post-update readiness attempt ${attempt}/36: retrying in 5s..." + sleep 5 + done + - name: Run migrations env: IMAGE_TAG: ${{ steps.resolve.outputs.tag }} diff --git a/docs/production-incident-baseline.md b/docs/production-incident-baseline.md index 0764a05245..bfc8fb5a98 100644 --- a/docs/production-incident-baseline.md +++ b/docs/production-incident-baseline.md @@ -1606,6 +1606,12 @@ ClickHouse migrations: Raised the ClickHouse service memory limit to 2 GB so the ClickHouse migration has enough memory to create the Postgres bridge and analytics read models. +Because migrations run before the normal `docker stack deploy`, the workflow +also applies that ClickHouse memory limit with `docker service update` before +running migrations, then waits for ClickHouse to become reachable again. The +stack file remains the desired-state source of truth; the pre-migration service +update makes the needed resource limit effective before the migration that +requires it. ### Remaining Risk From ae8f086b2b67357e0e7913e00ca0c091a0b68934 Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Thu, 30 Apr 2026 13:04:40 -0700 Subject: [PATCH 08/36] Run deploy migrations without telemetry --- .github/workflows/deploy-web-stack.yml | 2 +- docs/production-incident-baseline.md | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/.github/workflows/deploy-web-stack.yml b/.github/workflows/deploy-web-stack.yml index 9f74147f56..245ca97e13 100644 --- a/.github/workflows/deploy-web-stack.yml +++ b/.github/workflows/deploy-web-stack.yml @@ -366,7 +366,7 @@ jobs: --env "CLICKHOUSE_PASSWORD_ENCODED=$encoded_clickhouse_password" \ --entrypoint sh \ "ghcr.io/asherlc/dofek:${IMAGE_TAG}" \ - -euc 'timeout -k 30 3000 sh -euc '"'"'export DATABASE_URL="postgres://health:${POSTGRES_PASSWORD}@db:5432/health"; export CLICKHOUSE_URL="http://default:${CLICKHOUSE_PASSWORD_ENCODED}@clickhouse:8123"; exec ./entrypoint.sh migrate'"'"'' + -euc 'export DATABASE_URL="postgres://health:${POSTGRES_PASSWORD}@db:5432/health"; export CLICKHOUSE_URL="http://default:${CLICKHOUSE_PASSWORD_ENCODED}@clickhouse:8123"; exec node --experimental-transform-types --enable-source-maps --disable-warning=ExperimentalWarning src/db/run-migrate.ts' migration_timeout_seconds=3300 migration_start_seconds=$SECONDS diff --git a/docs/production-incident-baseline.md b/docs/production-incident-baseline.md index bfc8fb5a98..be51ccc67a 100644 --- a/docs/production-incident-baseline.md +++ b/docs/production-incident-baseline.md @@ -1613,6 +1613,15 @@ stack file remains the desired-state source of truth; the pre-migration service update makes the needed resource limit effective before the migration that requires it. +Production then showed the heavy Postgres statement disappear from +`pg_stat_activity` while the migration Node process stayed alive with no active +Postgres or ClickHouse query and an external HTTPS connection from the +instrumented entrypoint. Updated the deploy migration command to run +`src/db/run-migrate.ts` directly with Node's TypeScript support, without the +OpenTelemetry instrumentation imports used by the long-running app entrypoint. +The deploy step still captures container logs, but the one-shot migration no +longer depends on telemetry export shutdown behavior to finish the release. + ### Remaining Risk This fixes the missed ClickHouse provisioning run, the missing ClickHouse From aac47bfe03cbbf3341a76ffc0c048ef09fc0700e Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Thu, 30 Apr 2026 13:42:28 -0700 Subject: [PATCH 09/36] Document unresolved production migration --- docs/production-incident-baseline.md | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/docs/production-incident-baseline.md b/docs/production-incident-baseline.md index be51ccc67a..9a4ebc95f7 100644 --- a/docs/production-incident-baseline.md +++ b/docs/production-incident-baseline.md @@ -1622,15 +1622,26 @@ OpenTelemetry instrumentation imports used by the long-running app entrypoint. The deploy step still captures container logs, but the one-shot migration no longer depends on telemetry export shutdown behavior to finish the release. +That did not resolve the production migration. A direct non-instrumented Node +run still lost the active backend after the `UPDATE fitness.metric_stream ...` +statement, and a follow-up count showed `187,684,929` rows still had `id IS +NULL`. The workflow-only retry strategy is therefore blocked: production needs +an explicit decision on how to complete `0007_metric_stream_primary_key.sql` +without relying on the current Node migration runner to perform the 37 GB +compressed-hypertable rewrite in one statement. + ### Remaining Risk This fixes the missed ClickHouse provisioning run, the missing ClickHouse secret, the migration-step dotenv mismatch, the remote migration-container leak, the long-lived SSH session failure mode, and the ClickHouse memory ceiling seen -on staging. Future changes to the `/mnt/dofek-data` directory list still require -a corresponding trigger bump in the same commit. Future stack-level environment -variables must be added to Infisical before the workflow that references them is -merged or deployed, and workflow steps must read Infisical-only secrets from the -rendered dotenv file rather than from the runner environment. Large compressed -hypertable backfills should be called out in deploy planning so the migration -timeout is intentional rather than discovered during release. +on staging. Production deployment remains unresolved because +`0007_metric_stream_primary_key.sql` cannot currently complete the +`metric_stream` UUID backfill through the Node migration runner. Future changes +to the `/mnt/dofek-data` directory list still require a corresponding trigger +bump in the same commit. Future stack-level environment variables must be added +to Infisical before the workflow that references them is merged or deployed, and +workflow steps must read Infisical-only secrets from the rendered dotenv file +rather than from the runner environment. Large compressed hypertable backfills +should be called out in deploy planning so the migration timeout is intentional +rather than discovered during release. From d68d1a785136c38eff833a9edeade87ccbed14ab Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Thu, 30 Apr 2026 13:56:59 -0700 Subject: [PATCH 10/36] Backfill metric stream IDs in chunk batches --- docs/production-incident-baseline.md | 52 ++++++++ drizzle/0007_metric_stream_primary_key.sql | 4 +- ...ric-stream-primary-key.integration.test.ts | 57 +++++---- src/db/migrate.test.ts | 49 ++++++++ src/db/migrate.ts | 117 +++++++++++++++++- 5 files changed, 254 insertions(+), 25 deletions(-) diff --git a/docs/production-incident-baseline.md b/docs/production-incident-baseline.md index 9a4ebc95f7..adfa6251ba 100644 --- a/docs/production-incident-baseline.md +++ b/docs/production-incident-baseline.md @@ -1645,3 +1645,55 @@ workflow steps must read Infisical-only secrets from the rendered dotenv file rather than from the runner environment. Large compressed hypertable backfills should be called out in deploy planning so the migration timeout is intentional rather than discovered during release. + +## 2026-04-30: Metric Stream Primary Key Backfill Split Into Chunk Batches + +### Symptoms + +Production deploy remained blocked in the schema migration step after the +earlier ClickHouse bind-mount and migration-runner fixes. The pending migration +was still `0007_metric_stream_primary_key.sql`. + +### User Impact + +Production could not advance to the new stack image because migrations run +before `docker stack deploy`. Staging had already moved past this point, but +production remained on the previous release. + +### Evidence + +Production catalog checks showed `fitness.metric_stream` still had no primary +key, and `187,684,929` rows still had `id IS NULL`. The failed migration path +was the single full-history statement: + +```sql +UPDATE fitness.metric_stream +SET id = gen_random_uuid() +WHERE id IS NULL; +``` + +The table was a compressed Timescale hypertable, so this one statement attempted +to rewrite the historical compressed workload as one unbounded operation. + +### Root Cause + +`0007_metric_stream_primary_key.sql` used a single full-table UUID backfill for +a large compressed hypertable. The migration runner executed each migration +statement separately, but the backfill itself was still one unbounded statement, +so production could not complete the migration reliably. + +### Fix or Mitigation + +Replaced the full-table backfill statement in `0007_metric_stream_primary_key.sql` +with a migration-runner marker that performs the `metric_stream.id` backfill in +bounded batches of `100,000` rows per Timescale chunk time range. Each batch is +its own Postgres query, so progress commits incrementally before the migration +adds the composite primary key `(id, recorded_at)` and switches replica identity +to that key. + +### Remaining Risk + +The production rerun still has to build the primary-key index after the ID +backfill completes, and that operation may take time on the 187M-row hypertable. +If that becomes the next blocker, investigate it separately rather than adding +generic deploy retries. diff --git a/drizzle/0007_metric_stream_primary_key.sql b/drizzle/0007_metric_stream_primary_key.sql index ddbddd66c2..f0e9d7be54 100644 --- a/drizzle/0007_metric_stream_primary_key.sql +++ b/drizzle/0007_metric_stream_primary_key.sql @@ -7,9 +7,7 @@ ALTER COLUMN id SET DEFAULT gen_random_uuid(); ALTER TABLE fitness.metric_stream REPLICA IDENTITY FULL; --> statement-breakpoint -UPDATE fitness.metric_stream -SET id = gen_random_uuid() -WHERE id IS NULL; +-- dofek:backfill-metric-stream-id --> statement-breakpoint DO $$ BEGIN diff --git a/src/db/metric-stream-primary-key.integration.test.ts b/src/db/metric-stream-primary-key.integration.test.ts index d2241f7b4c..a3f83bc7c7 100644 --- a/src/db/metric-stream-primary-key.integration.test.ts +++ b/src/db/metric-stream-primary-key.integration.test.ts @@ -1,6 +1,10 @@ +import { mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { Client } from "pg"; import { GenericContainer } from "testcontainers"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { runMigrations } from "./migrate.ts"; describe("metric_stream primary key migration", () => { let connectionString: string; @@ -41,25 +45,30 @@ describe("metric_stream primary key migration", () => { } }); - it("adds a replica-safe primary key without validating a NOT NULL check", async () => { + it("adds a replica-safe primary key using the chunked ID backfill", async () => { const client = new Client({ connectionString }); await client.connect(); try { + await client.query("CREATE EXTENSION IF NOT EXISTS timescaledb"); await client.query("CREATE EXTENSION IF NOT EXISTS pgcrypto"); await client.query("CREATE SCHEMA IF NOT EXISTS fitness"); await client.query(` - CREATE TABLE fitness.metric_stream_ci_repro ( + CREATE TABLE fitness.metric_stream ( recorded_at timestamptz NOT NULL, user_id uuid NOT NULL, provider_id text NOT NULL, - channel text NOT NULL + source_type text NOT NULL, + channel text NOT NULL, + activity_id uuid, + scalar real, + vector real[] ) `); await client.query( - "SELECT create_hypertable('fitness.metric_stream_ci_repro', 'recorded_at', if_not_exists => TRUE)", + "SELECT create_hypertable('fitness.metric_stream', 'recorded_at', if_not_exists => TRUE)", ); await client.query(` - ALTER TABLE fitness.metric_stream_ci_repro + ALTER TABLE fitness.metric_stream SET ( timescaledb.compress = true, timescaledb.compress_segmentby = 'user_id,provider_id,channel', @@ -67,23 +76,24 @@ describe("metric_stream primary key migration", () => { ) `); await client.query(` - INSERT INTO fitness.metric_stream_ci_repro (recorded_at, user_id, provider_id, channel) - VALUES (now(), gen_random_uuid(), 'garmin', 'power') + INSERT INTO fitness.metric_stream ( + recorded_at, user_id, provider_id, source_type, channel, scalar + ) + VALUES + ('2026-01-01T00:00:00Z', gen_random_uuid(), 'garmin', 'api', 'power', 200), + ('2026-01-02T00:00:00Z', gen_random_uuid(), 'garmin', 'api', 'power', 210), + ('2026-01-03T00:00:00Z', gen_random_uuid(), 'garmin', 'api', 'power', 220) `); - await client.query("ALTER TABLE fitness.metric_stream_ci_repro ADD COLUMN id uuid"); - await client.query( - "ALTER TABLE fitness.metric_stream_ci_repro ALTER COLUMN id SET DEFAULT gen_random_uuid()", - ); - await client.query( - "UPDATE fitness.metric_stream_ci_repro SET id = gen_random_uuid() WHERE id IS NULL", - ); - await client.query( - "ALTER TABLE fitness.metric_stream_ci_repro ADD CONSTRAINT metric_stream_ci_repro_pkey PRIMARY KEY (id, recorded_at)", - ); - await client.query( - "ALTER TABLE fitness.metric_stream_ci_repro REPLICA IDENTITY USING INDEX metric_stream_ci_repro_pkey", + const tmpDir = mkdtempSync(join(tmpdir(), "metric-stream-primary-key-")); + const migrationContent = readFileSync( + join(import.meta.dirname, "../../drizzle/0007_metric_stream_primary_key.sql"), + "utf-8", ); + writeFileSync(join(tmpDir, "0007_metric_stream_primary_key.sql"), migrationContent); + + const migrationCount = await runMigrations(connectionString, tmpDir); + expect(migrationCount).toBe(1); const primaryKeyResult = await client.query<{ column_name: string; @@ -98,7 +108,7 @@ describe("metric_stream primary key migration", () => { ON attribute.attrelid = index.indrelid AND attribute.attnum = ANY(index.indkey) WHERE namespace.nspname = 'fitness' - AND class.relname = 'metric_stream_ci_repro' + AND class.relname = 'metric_stream' AND index.indisprimary ORDER BY array_position(index.indkey, attribute.attnum) `); @@ -111,10 +121,15 @@ describe("metric_stream primary key migration", () => { SELECT is_nullable FROM information_schema.columns WHERE table_schema = 'fitness' - AND table_name = 'metric_stream_ci_repro' + AND table_name = 'metric_stream' AND column_name = 'id' `); expect(nullableResult.rows).toEqual([{ is_nullable: "NO" }]); + + const nullIdResult = await client.query<{ missing_id_count: string }>( + "SELECT count(*) AS missing_id_count FROM fitness.metric_stream WHERE id IS NULL", + ); + expect(nullIdResult.rows).toEqual([{ missing_id_count: "0" }]); } finally { await client.end(); } diff --git a/src/db/migrate.test.ts b/src/db/migrate.test.ts index f325f859a5..377a112fe9 100644 --- a/src/db/migrate.test.ts +++ b/src/db/migrate.test.ts @@ -120,6 +120,55 @@ describe("runMigrations", () => { expect(executedQueries()).toContain("CREATE TABLE b (id INT)"); }); + it("backfills metric_stream IDs in bounded Timescale chunk batches", async () => { + const { runMigrations } = await import("./migrate.ts"); + + mockReaddirSync.mockReturnValue(["0007_metric_stream_primary_key.sql"]); + mockReadFileSync.mockReturnValue("-- dofek:backfill-metric-stream-id"); + const chunkRows = [ + { + chunk_schema: "_timescaledb_internal", + chunk_name: "_hyper_1_1_chunk", + range_start: "2026-01-01T00:00:00.000Z", + range_end: "2026-01-02T00:00:00.000Z", + }, + { + chunk_schema: "_timescaledb_internal", + chunk_name: "_hyper_1_2_chunk", + range_start: "2026-01-02T00:00:00.000Z", + range_end: "2026-01-03T00:00:00.000Z", + }, + ]; + const updateRowCounts = [100_000, 7, 0, 42, 0]; + mockClientQuery.mockImplementation((text: string) => { + if (text.includes("timescaledb_information.chunks")) { + return Promise.resolve({ rows: chunkRows }); + } + if (text.includes("UPDATE fitness.metric_stream AS metric_stream")) { + return Promise.resolve({ rows: [], rowCount: updateRowCounts.shift() ?? 0 }); + } + return Promise.resolve({ rows: [] }); + }); + + await runMigrations("postgres://localhost/test", "/tmp/migrations"); + + const backfillCalls = mockClientQuery.mock.calls.filter(([text]) => + String(text).includes("UPDATE fitness.metric_stream AS metric_stream"), + ); + expect(backfillCalls).toHaveLength(5); + expect(String(backfillCalls[0]?.[0])).toContain("LIMIT $3"); + expect(backfillCalls[0]?.[1]).toEqual([ + "2026-01-01T00:00:00.000Z", + "2026-01-02T00:00:00.000Z", + 100_000, + ]); + expect(backfillCalls[3]?.[1]).toEqual([ + "2026-01-02T00:00:00.000Z", + "2026-01-03T00:00:00.000Z", + 100_000, + ]); + }); + it("returns 0 when no pending migrations exist", async () => { const { runMigrations } = await import("./migrate.ts"); diff --git a/src/db/migrate.ts b/src/db/migrate.ts index 95178ae43a..79f5c99ef0 100644 --- a/src/db/migrate.ts +++ b/src/db/migrate.ts @@ -6,6 +6,15 @@ import { logger } from "../logger.ts"; /** Postgres advisory lock key — serializes concurrent migration runs across containers */ export const MIGRATION_LOCK_KEY = 728370291; +const METRIC_STREAM_ID_BACKFILL_MARKER = "-- dofek:backfill-metric-stream-id"; +const METRIC_STREAM_ID_BACKFILL_BATCH_SIZE = 100_000; + +interface MetricStreamChunkRow { + chunk_schema: string; + chunk_name: string; + range_start: Date | string | null; + range_end: Date | string | null; +} /** * Detect migration files that share the same numeric prefix (e.g., two 0049_* files). @@ -48,6 +57,108 @@ function parseStatements(content: string): Array { .filter(Boolean); } +async function backfillMetricStreamIdsForTimeRange( + client: Client, + rangeStart: Date | string, + rangeEnd: Date | string, +): Promise { + let updatedRows = 0; + let totalRows = 0; + + do { + const result = await client.query( + `WITH candidate_rows AS ( + SELECT ctid + FROM fitness.metric_stream + WHERE id IS NULL + AND recorded_at >= $1 + AND recorded_at < $2 + LIMIT $3 + ) + UPDATE fitness.metric_stream AS metric_stream + SET id = gen_random_uuid() + FROM candidate_rows + WHERE metric_stream.ctid = candidate_rows.ctid + AND metric_stream.id IS NULL + AND metric_stream.recorded_at >= $1 + AND metric_stream.recorded_at < $2`, + [rangeStart, rangeEnd, METRIC_STREAM_ID_BACKFILL_BATCH_SIZE], + ); + updatedRows = result.rowCount ?? 0; + totalRows += updatedRows; + } while (updatedRows > 0); + + return totalRows; +} + +async function backfillMetricStreamIdsWithoutChunkRanges(client: Client): Promise { + let updatedRows = 0; + let totalRows = 0; + + do { + const result = await client.query( + `WITH candidate_rows AS ( + SELECT ctid + FROM fitness.metric_stream + WHERE id IS NULL + LIMIT $1 + ) + UPDATE fitness.metric_stream AS metric_stream + SET id = gen_random_uuid() + FROM candidate_rows + WHERE metric_stream.ctid = candidate_rows.ctid + AND metric_stream.id IS NULL`, + [METRIC_STREAM_ID_BACKFILL_BATCH_SIZE], + ); + updatedRows = result.rowCount ?? 0; + totalRows += updatedRows; + } while (updatedRows > 0); + + return totalRows; +} + +async function backfillMetricStreamIds(client: Client): Promise { + logger.info( + `[migrate] Backfilling metric_stream.id in batches of ${METRIC_STREAM_ID_BACKFILL_BATCH_SIZE}`, + ); + + const chunksResult = await client.query(` + SELECT chunk_schema, chunk_name, range_start, range_end + FROM timescaledb_information.chunks + WHERE hypertable_schema = 'fitness' + AND hypertable_name = 'metric_stream' + ORDER BY range_start NULLS FIRST, chunk_schema, chunk_name + `); + + if (chunksResult.rows.length === 0) { + const totalRows = await backfillMetricStreamIdsWithoutChunkRanges(client); + logger.info(`[migrate] Backfilled ${totalRows} metric_stream.id row(s) without chunk ranges`); + return; + } + + let totalRows = 0; + for (const chunk of chunksResult.rows) { + if (!chunk.range_start || !chunk.range_end) { + logger.warn( + `[migrate] Skipping metric_stream chunk with missing time bounds: ${chunk.chunk_schema}.${chunk.chunk_name}`, + ); + continue; + } + + const chunkRows = await backfillMetricStreamIdsForTimeRange( + client, + chunk.range_start, + chunk.range_end, + ); + totalRows += chunkRows; + logger.info( + `[migrate] Backfilled ${chunkRows} metric_stream.id row(s) in ${chunk.chunk_schema}.${chunk.chunk_name}`, + ); + } + + logger.info(`[migrate] Backfilled ${totalRows} metric_stream.id row(s) across Timescale chunks`); +} + /** * Run pending migrations from the drizzle/ directory. * @@ -166,7 +277,11 @@ export async function runMigrations(databaseUrl: string, migrationsDir?: string) const contentHash = computeContentHash(content); const requiresRefresh = migrationRequiresMaterializedViewRefresh(content); for (const stmt of parseStatements(content)) { - await client.query(stmt); + if (stmt === METRIC_STREAM_ID_BACKFILL_MARKER) { + await backfillMetricStreamIds(client); + } else { + await client.query(stmt); + } } await client.query( `INSERT INTO drizzle.__drizzle_migrations ( From 029d40e757b836de85a9d1a109523ea43a2e9ab3 Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Thu, 30 Apr 2026 14:18:15 -0700 Subject: [PATCH 11/36] Backfill metric stream IDs by time window --- docs/production-incident-baseline.md | 31 +++++++ ...ric-stream-primary-key.integration.test.ts | 2 +- src/db/migrate.test.ts | 32 ++++--- src/db/migrate.ts | 93 ++++++++++--------- 4 files changed, 99 insertions(+), 59 deletions(-) diff --git a/docs/production-incident-baseline.md b/docs/production-incident-baseline.md index adfa6251ba..dba59ef21d 100644 --- a/docs/production-incident-baseline.md +++ b/docs/production-incident-baseline.md @@ -1697,3 +1697,34 @@ The production rerun still has to build the primary-key index after the ID backfill completes, and that operation may take time on the 187M-row hypertable. If that becomes the next blocker, investigate it separately rather than adding generic deploy retries. + +### Follow-up Evidence + +The first production rerun with the bounded backfill image built and pushed both +`sha-d68d1a7` images, passed Terraform and image pulls, then failed immediately +in the migration container with: + +```text +error: transparent decompression only supports tableoid system column +``` + +That error came from using `ctid` to identify a limited set of rows inside +compressed Timescale chunks. Timescale transparent decompression does not expose +`ctid`; only `tableoid` is available as a system column in that path. + +### Follow-up Fix + +Changed the metric_stream ID backfill again to avoid system columns entirely. +The runner now updates `metric_stream.id` by one-hour `recorded_at` windows +within each Timescale chunk time range: + +```sql +UPDATE fitness.metric_stream AS metric_stream +SET id = gen_random_uuid() +WHERE metric_stream.id IS NULL + AND metric_stream.recorded_at >= $1 + AND metric_stream.recorded_at < $2; +``` + +This preserves bounded progress without relying on unsupported compressed-chunk +system columns. diff --git a/src/db/metric-stream-primary-key.integration.test.ts b/src/db/metric-stream-primary-key.integration.test.ts index a3f83bc7c7..fbd38f35ab 100644 --- a/src/db/metric-stream-primary-key.integration.test.ts +++ b/src/db/metric-stream-primary-key.integration.test.ts @@ -45,7 +45,7 @@ describe("metric_stream primary key migration", () => { } }); - it("adds a replica-safe primary key using the chunked ID backfill", async () => { + it("adds a replica-safe primary key using the time-window ID backfill", async () => { const client = new Client({ connectionString }); await client.connect(); try { diff --git a/src/db/migrate.test.ts b/src/db/migrate.test.ts index 377a112fe9..de067f9bd7 100644 --- a/src/db/migrate.test.ts +++ b/src/db/migrate.test.ts @@ -120,7 +120,7 @@ describe("runMigrations", () => { expect(executedQueries()).toContain("CREATE TABLE b (id INT)"); }); - it("backfills metric_stream IDs in bounded Timescale chunk batches", async () => { + it("backfills metric_stream IDs in bounded Timescale time windows", async () => { const { runMigrations } = await import("./migrate.ts"); mockReaddirSync.mockReturnValue(["0007_metric_stream_primary_key.sql"]); @@ -130,22 +130,21 @@ describe("runMigrations", () => { chunk_schema: "_timescaledb_internal", chunk_name: "_hyper_1_1_chunk", range_start: "2026-01-01T00:00:00.000Z", - range_end: "2026-01-02T00:00:00.000Z", + range_end: "2026-01-01T02:00:00.000Z", }, { chunk_schema: "_timescaledb_internal", chunk_name: "_hyper_1_2_chunk", - range_start: "2026-01-02T00:00:00.000Z", - range_end: "2026-01-03T00:00:00.000Z", + range_start: "2026-01-02T00:30:00.000Z", + range_end: "2026-01-02T01:00:00.000Z", }, ]; - const updateRowCounts = [100_000, 7, 0, 42, 0]; mockClientQuery.mockImplementation((text: string) => { if (text.includes("timescaledb_information.chunks")) { return Promise.resolve({ rows: chunkRows }); } if (text.includes("UPDATE fitness.metric_stream AS metric_stream")) { - return Promise.resolve({ rows: [], rowCount: updateRowCounts.shift() ?? 0 }); + return Promise.resolve({ rows: [], rowCount: 7 }); } return Promise.resolve({ rows: [] }); }); @@ -155,17 +154,20 @@ describe("runMigrations", () => { const backfillCalls = mockClientQuery.mock.calls.filter(([text]) => String(text).includes("UPDATE fitness.metric_stream AS metric_stream"), ); - expect(backfillCalls).toHaveLength(5); - expect(String(backfillCalls[0]?.[0])).toContain("LIMIT $3"); + expect(backfillCalls).toHaveLength(3); + expect(String(backfillCalls[0]?.[0])).not.toContain("ctid"); + expect(String(backfillCalls[0]?.[0])).not.toContain("LIMIT"); expect(backfillCalls[0]?.[1]).toEqual([ - "2026-01-01T00:00:00.000Z", - "2026-01-02T00:00:00.000Z", - 100_000, + new Date("2026-01-01T00:00:00.000Z"), + new Date("2026-01-01T01:00:00.000Z"), ]); - expect(backfillCalls[3]?.[1]).toEqual([ - "2026-01-02T00:00:00.000Z", - "2026-01-03T00:00:00.000Z", - 100_000, + expect(backfillCalls[1]?.[1]).toEqual([ + new Date("2026-01-01T01:00:00.000Z"), + new Date("2026-01-01T02:00:00.000Z"), + ]); + expect(backfillCalls[2]?.[1]).toEqual([ + new Date("2026-01-02T00:30:00.000Z"), + new Date("2026-01-02T01:00:00.000Z"), ]); }); diff --git a/src/db/migrate.ts b/src/db/migrate.ts index 79f5c99ef0..91b2e903f1 100644 --- a/src/db/migrate.ts +++ b/src/db/migrate.ts @@ -7,7 +7,7 @@ import { logger } from "../logger.ts"; /** Postgres advisory lock key — serializes concurrent migration runs across containers */ export const MIGRATION_LOCK_KEY = 728370291; const METRIC_STREAM_ID_BACKFILL_MARKER = "-- dofek:backfill-metric-stream-id"; -const METRIC_STREAM_ID_BACKFILL_BATCH_SIZE = 100_000; +const METRIC_STREAM_ID_BACKFILL_WINDOW_MILLISECONDS = 60 * 60 * 1000; interface MetricStreamChunkRow { chunk_schema: string; @@ -16,6 +16,11 @@ interface MetricStreamChunkRow { range_end: Date | string | null; } +interface MetricStreamNullIdBoundsRow { + range_start: Date | string | null; + range_end: Date | string | null; +} + /** * Detect migration files that share the same numeric prefix (e.g., two 0049_* files). * This indicates concurrent PRs created conflicting migrations that must be reconciled. @@ -62,65 +67,67 @@ async function backfillMetricStreamIdsForTimeRange( rangeStart: Date | string, rangeEnd: Date | string, ): Promise { - let updatedRows = 0; let totalRows = 0; + let windowStart = parseMigrationDate(rangeStart); + const finalRangeEnd = parseMigrationDate(rangeEnd); + + while (windowStart < finalRangeEnd) { + const nextWindowEnd = new Date( + Math.min( + windowStart.getTime() + METRIC_STREAM_ID_BACKFILL_WINDOW_MILLISECONDS, + finalRangeEnd.getTime(), + ), + ); + if (nextWindowEnd <= windowStart) { + throw new Error("metric_stream ID backfill time window did not advance"); + } - do { const result = await client.query( - `WITH candidate_rows AS ( - SELECT ctid - FROM fitness.metric_stream - WHERE id IS NULL - AND recorded_at >= $1 - AND recorded_at < $2 - LIMIT $3 - ) - UPDATE fitness.metric_stream AS metric_stream + `UPDATE fitness.metric_stream AS metric_stream SET id = gen_random_uuid() - FROM candidate_rows - WHERE metric_stream.ctid = candidate_rows.ctid - AND metric_stream.id IS NULL + WHERE metric_stream.id IS NULL AND metric_stream.recorded_at >= $1 AND metric_stream.recorded_at < $2`, - [rangeStart, rangeEnd, METRIC_STREAM_ID_BACKFILL_BATCH_SIZE], + [windowStart, nextWindowEnd], ); - updatedRows = result.rowCount ?? 0; - totalRows += updatedRows; - } while (updatedRows > 0); + totalRows += result.rowCount ?? 0; + windowStart = nextWindowEnd; + } return totalRows; } async function backfillMetricStreamIdsWithoutChunkRanges(client: Client): Promise { - let updatedRows = 0; - let totalRows = 0; + const boundsResult = await client.query(` + SELECT + min(recorded_at) AS range_start, + max(recorded_at) + INTERVAL '1 millisecond' AS range_end + FROM fitness.metric_stream + WHERE id IS NULL + `); - do { - const result = await client.query( - `WITH candidate_rows AS ( - SELECT ctid - FROM fitness.metric_stream - WHERE id IS NULL - LIMIT $1 - ) - UPDATE fitness.metric_stream AS metric_stream - SET id = gen_random_uuid() - FROM candidate_rows - WHERE metric_stream.ctid = candidate_rows.ctid - AND metric_stream.id IS NULL`, - [METRIC_STREAM_ID_BACKFILL_BATCH_SIZE], - ); - updatedRows = result.rowCount ?? 0; - totalRows += updatedRows; - } while (updatedRows > 0); + const bounds = boundsResult.rows[0]; + if (!bounds?.range_start || !bounds.range_end) { + return 0; + } - return totalRows; + return backfillMetricStreamIdsForTimeRange(client, bounds.range_start, bounds.range_end); +} + +function parseMigrationDate(value: Date | string): Date { + if (value instanceof Date) { + return value; + } + + const parsedDate = new Date(value); + if (Number.isNaN(parsedDate.getTime())) { + throw new Error(`Invalid migration timestamp: ${value}`); + } + return parsedDate; } async function backfillMetricStreamIds(client: Client): Promise { - logger.info( - `[migrate] Backfilling metric_stream.id in batches of ${METRIC_STREAM_ID_BACKFILL_BATCH_SIZE}`, - ); + logger.info("[migrate] Backfilling metric_stream.id in one-hour time windows"); const chunksResult = await client.query(` SELECT chunk_schema, chunk_name, range_start, range_end From fd78d35e253c9cefe0cde0e842de3a6019575cb4 Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Thu, 30 Apr 2026 14:44:20 -0700 Subject: [PATCH 12/36] Backfill metric stream IDs by chunk range --- docs/production-incident-baseline.md | 17 ++++++++ ...ric-stream-primary-key.integration.test.ts | 2 +- src/db/migrate.test.ts | 10 ++--- src/db/migrate.ts | 42 +++++++------------ 4 files changed, 35 insertions(+), 36 deletions(-) diff --git a/docs/production-incident-baseline.md b/docs/production-incident-baseline.md index dba59ef21d..23079e49ee 100644 --- a/docs/production-incident-baseline.md +++ b/docs/production-incident-baseline.md @@ -1728,3 +1728,20 @@ WHERE metric_stream.id IS NULL This preserves bounded progress without relying on unsupported compressed-chunk system columns. + +### Second Follow-up Evidence + +The production rerun with one-hour windows was correct but still too +under-batched for the deploy window. Production had `195` Timescale chunks for +`fitness.metric_stream`, which meant up to `32,760` hourly update statements +before the migration could add the primary key. After roughly twenty minutes the +container had only completed a small subset of chunks, so the run was cancelled +before the workflow timeout killed it. + +### Second Follow-up Fix + +Changed the marker handler to issue one bounded update per Timescale chunk range +instead of one update per hour inside each chunk. The statement still filters by +`id IS NULL` and `recorded_at >= $1 AND recorded_at < $2`, so already completed +chunks from prior attempts remain committed and the migration is still +resumable. diff --git a/src/db/metric-stream-primary-key.integration.test.ts b/src/db/metric-stream-primary-key.integration.test.ts index fbd38f35ab..5aa48d55aa 100644 --- a/src/db/metric-stream-primary-key.integration.test.ts +++ b/src/db/metric-stream-primary-key.integration.test.ts @@ -45,7 +45,7 @@ describe("metric_stream primary key migration", () => { } }); - it("adds a replica-safe primary key using the time-window ID backfill", async () => { + it("adds a replica-safe primary key using the chunk-range ID backfill", async () => { const client = new Client({ connectionString }); await client.connect(); try { diff --git a/src/db/migrate.test.ts b/src/db/migrate.test.ts index de067f9bd7..588c1caebd 100644 --- a/src/db/migrate.test.ts +++ b/src/db/migrate.test.ts @@ -120,7 +120,7 @@ describe("runMigrations", () => { expect(executedQueries()).toContain("CREATE TABLE b (id INT)"); }); - it("backfills metric_stream IDs in bounded Timescale time windows", async () => { + it("backfills metric_stream IDs in bounded Timescale chunk ranges", async () => { const { runMigrations } = await import("./migrate.ts"); mockReaddirSync.mockReturnValue(["0007_metric_stream_primary_key.sql"]); @@ -154,18 +154,14 @@ describe("runMigrations", () => { const backfillCalls = mockClientQuery.mock.calls.filter(([text]) => String(text).includes("UPDATE fitness.metric_stream AS metric_stream"), ); - expect(backfillCalls).toHaveLength(3); + expect(backfillCalls).toHaveLength(2); expect(String(backfillCalls[0]?.[0])).not.toContain("ctid"); expect(String(backfillCalls[0]?.[0])).not.toContain("LIMIT"); expect(backfillCalls[0]?.[1]).toEqual([ new Date("2026-01-01T00:00:00.000Z"), - new Date("2026-01-01T01:00:00.000Z"), - ]); - expect(backfillCalls[1]?.[1]).toEqual([ - new Date("2026-01-01T01:00:00.000Z"), new Date("2026-01-01T02:00:00.000Z"), ]); - expect(backfillCalls[2]?.[1]).toEqual([ + expect(backfillCalls[1]?.[1]).toEqual([ new Date("2026-01-02T00:30:00.000Z"), new Date("2026-01-02T01:00:00.000Z"), ]); diff --git a/src/db/migrate.ts b/src/db/migrate.ts index 91b2e903f1..2ea3cc6ef0 100644 --- a/src/db/migrate.ts +++ b/src/db/migrate.ts @@ -7,7 +7,6 @@ import { logger } from "../logger.ts"; /** Postgres advisory lock key — serializes concurrent migration runs across containers */ export const MIGRATION_LOCK_KEY = 728370291; const METRIC_STREAM_ID_BACKFILL_MARKER = "-- dofek:backfill-metric-stream-id"; -const METRIC_STREAM_ID_BACKFILL_WINDOW_MILLISECONDS = 60 * 60 * 1000; interface MetricStreamChunkRow { chunk_schema: string; @@ -62,39 +61,26 @@ function parseStatements(content: string): Array { .filter(Boolean); } -async function backfillMetricStreamIdsForTimeRange( +async function backfillMetricStreamIdsForChunkRange( client: Client, rangeStart: Date | string, rangeEnd: Date | string, ): Promise { - let totalRows = 0; - let windowStart = parseMigrationDate(rangeStart); - const finalRangeEnd = parseMigrationDate(rangeEnd); - - while (windowStart < finalRangeEnd) { - const nextWindowEnd = new Date( - Math.min( - windowStart.getTime() + METRIC_STREAM_ID_BACKFILL_WINDOW_MILLISECONDS, - finalRangeEnd.getTime(), - ), - ); - if (nextWindowEnd <= windowStart) { - throw new Error("metric_stream ID backfill time window did not advance"); - } + const chunkRangeStart = parseMigrationDate(rangeStart); + const chunkRangeEnd = parseMigrationDate(rangeEnd); + if (chunkRangeEnd <= chunkRangeStart) { + throw new Error("metric_stream ID backfill chunk range did not advance"); + } - const result = await client.query( - `UPDATE fitness.metric_stream AS metric_stream + const result = await client.query( + `UPDATE fitness.metric_stream AS metric_stream SET id = gen_random_uuid() WHERE metric_stream.id IS NULL AND metric_stream.recorded_at >= $1 AND metric_stream.recorded_at < $2`, - [windowStart, nextWindowEnd], - ); - totalRows += result.rowCount ?? 0; - windowStart = nextWindowEnd; - } - - return totalRows; + [chunkRangeStart, chunkRangeEnd], + ); + return result.rowCount ?? 0; } async function backfillMetricStreamIdsWithoutChunkRanges(client: Client): Promise { @@ -111,7 +97,7 @@ async function backfillMetricStreamIdsWithoutChunkRanges(client: Client): Promis return 0; } - return backfillMetricStreamIdsForTimeRange(client, bounds.range_start, bounds.range_end); + return backfillMetricStreamIdsForChunkRange(client, bounds.range_start, bounds.range_end); } function parseMigrationDate(value: Date | string): Date { @@ -127,7 +113,7 @@ function parseMigrationDate(value: Date | string): Date { } async function backfillMetricStreamIds(client: Client): Promise { - logger.info("[migrate] Backfilling metric_stream.id in one-hour time windows"); + logger.info("[migrate] Backfilling metric_stream.id in Timescale chunk ranges"); const chunksResult = await client.query(` SELECT chunk_schema, chunk_name, range_start, range_end @@ -152,7 +138,7 @@ async function backfillMetricStreamIds(client: Client): Promise { continue; } - const chunkRows = await backfillMetricStreamIdsForTimeRange( + const chunkRows = await backfillMetricStreamIdsForChunkRange( client, chunk.range_start, chunk.range_end, From b6ef9d925bbdf0eb4ac2d19fc38af42a7097b5e9 Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Thu, 30 Apr 2026 14:59:21 -0700 Subject: [PATCH 13/36] Fallback metric stream backfill on decompression limit --- docs/production-incident-baseline.md | 21 +++++++++ src/db/migrate.test.ts | 51 ++++++++++++++++++++++ src/db/migrate.ts | 65 +++++++++++++++++++++++++--- 3 files changed, 132 insertions(+), 5 deletions(-) diff --git a/docs/production-incident-baseline.md b/docs/production-incident-baseline.md index 23079e49ee..eaeec4a8be 100644 --- a/docs/production-incident-baseline.md +++ b/docs/production-incident-baseline.md @@ -1745,3 +1745,24 @@ instead of one update per hour inside each chunk. The statement still filters by `id IS NULL` and `recorded_at >= $1 AND recorded_at < $2`, so already completed chunks from prior attempts remain committed and the migration is still resumable. + +### Third Follow-up Evidence + +The first chunk-range production rerun got past the already-backfilled chunks +quickly, then failed on the next compressed chunk with: + +```text +error: tuple decompression limit exceeded by operation +``` + +That showed a full chunk-range update can exceed TimescaleDB's per-DML +decompression limit on chunks that still contain too many `id IS NULL` rows. + +### Third Follow-up Fix + +Kept the chunk-range update as the fast path for already-complete and smaller +chunks, but added a targeted fallback: when a chunk-range update hits the +Timescale tuple decompression limit, the migration retries that same chunk in +one-hour `recorded_at` windows. This keeps the deployment from spending hourly +queries on every already-finished chunk while keeping each DML statement below +the decompression cap for large remaining chunks. diff --git a/src/db/migrate.test.ts b/src/db/migrate.test.ts index 588c1caebd..a201a408fc 100644 --- a/src/db/migrate.test.ts +++ b/src/db/migrate.test.ts @@ -167,6 +167,57 @@ describe("runMigrations", () => { ]); }); + it("falls back to hourly metric_stream ID backfill when a chunk exceeds Timescale decompression limits", async () => { + const { runMigrations } = await import("./migrate.ts"); + + mockReaddirSync.mockReturnValue(["0007_metric_stream_primary_key.sql"]); + mockReadFileSync.mockReturnValue("-- dofek:backfill-metric-stream-id"); + const chunkRows = [ + { + chunk_schema: "_timescaledb_internal", + chunk_name: "_hyper_1_1_chunk", + range_start: "2026-01-01T00:00:00.000Z", + range_end: "2026-01-01T02:00:00.000Z", + }, + ]; + let updateAttempts = 0; + mockClientQuery.mockImplementation((text: string) => { + if (text.includes("timescaledb_information.chunks")) { + return Promise.resolve({ rows: chunkRows }); + } + if (text.includes("UPDATE fitness.metric_stream AS metric_stream")) { + updateAttempts++; + if (updateAttempts === 1) { + return Promise.reject(new Error("tuple decompression limit exceeded by operation")); + } + return Promise.resolve({ rows: [], rowCount: 5 }); + } + return Promise.resolve({ rows: [] }); + }); + + await runMigrations("postgres://localhost/test", "/tmp/migrations"); + + const backfillCalls = mockClientQuery.mock.calls.filter(([text]) => + String(text).includes("UPDATE fitness.metric_stream AS metric_stream"), + ); + expect(backfillCalls).toHaveLength(3); + expect(backfillCalls[0]?.[1]).toEqual([ + new Date("2026-01-01T00:00:00.000Z"), + new Date("2026-01-01T02:00:00.000Z"), + ]); + expect(backfillCalls[1]?.[1]).toEqual([ + new Date("2026-01-01T00:00:00.000Z"), + new Date("2026-01-01T01:00:00.000Z"), + ]); + expect(backfillCalls[2]?.[1]).toEqual([ + new Date("2026-01-01T01:00:00.000Z"), + new Date("2026-01-01T02:00:00.000Z"), + ]); + expect(mockLoggerWarn).toHaveBeenCalledWith( + expect.stringContaining("Falling back to one-hour metric_stream ID backfill"), + ); + }); + it("returns 0 when no pending migrations exist", async () => { const { runMigrations } = await import("./migrate.ts"); diff --git a/src/db/migrate.ts b/src/db/migrate.ts index 2ea3cc6ef0..7506356127 100644 --- a/src/db/migrate.ts +++ b/src/db/migrate.ts @@ -7,6 +7,7 @@ import { logger } from "../logger.ts"; /** Postgres advisory lock key — serializes concurrent migration runs across containers */ export const MIGRATION_LOCK_KEY = 728370291; const METRIC_STREAM_ID_BACKFILL_MARKER = "-- dofek:backfill-metric-stream-id"; +const METRIC_STREAM_ID_BACKFILL_WINDOW_MILLISECONDS = 60 * 60 * 1000; interface MetricStreamChunkRow { chunk_schema: string; @@ -83,6 +84,45 @@ async function backfillMetricStreamIdsForChunkRange( return result.rowCount ?? 0; } +async function backfillMetricStreamIdsForHourlyWindows( + client: Client, + rangeStart: Date | string, + rangeEnd: Date | string, +): Promise { + let totalRows = 0; + let windowStart = parseMigrationDate(rangeStart); + const finalRangeEnd = parseMigrationDate(rangeEnd); + + while (windowStart < finalRangeEnd) { + const nextWindowEnd = new Date( + Math.min( + windowStart.getTime() + METRIC_STREAM_ID_BACKFILL_WINDOW_MILLISECONDS, + finalRangeEnd.getTime(), + ), + ); + if (nextWindowEnd <= windowStart) { + throw new Error("metric_stream ID backfill time window did not advance"); + } + + const result = await client.query( + `UPDATE fitness.metric_stream AS metric_stream + SET id = gen_random_uuid() + WHERE metric_stream.id IS NULL + AND metric_stream.recorded_at >= $1 + AND metric_stream.recorded_at < $2`, + [windowStart, nextWindowEnd], + ); + totalRows += result.rowCount ?? 0; + windowStart = nextWindowEnd; + } + + return totalRows; +} + +function isTimescaleTupleDecompressionLimitError(error: unknown): boolean { + return error instanceof Error && error.message.includes("tuple decompression limit exceeded"); +} + async function backfillMetricStreamIdsWithoutChunkRanges(client: Client): Promise { const boundsResult = await client.query(` SELECT @@ -138,11 +178,26 @@ async function backfillMetricStreamIds(client: Client): Promise { continue; } - const chunkRows = await backfillMetricStreamIdsForChunkRange( - client, - chunk.range_start, - chunk.range_end, - ); + let chunkRows: number; + try { + chunkRows = await backfillMetricStreamIdsForChunkRange( + client, + chunk.range_start, + chunk.range_end, + ); + } catch (error: unknown) { + if (!isTimescaleTupleDecompressionLimitError(error)) { + throw error; + } + logger.warn( + `[migrate] Falling back to one-hour metric_stream ID backfill for ${chunk.chunk_schema}.${chunk.chunk_name}`, + ); + chunkRows = await backfillMetricStreamIdsForHourlyWindows( + client, + chunk.range_start, + chunk.range_end, + ); + } totalRows += chunkRows; logger.info( `[migrate] Backfilled ${chunkRows} metric_stream.id row(s) in ${chunk.chunk_schema}.${chunk.chunk_name}`, From 1ff480be8927c81f28c8232abe9d5dbeaa85e653 Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Thu, 30 Apr 2026 15:20:04 -0700 Subject: [PATCH 14/36] Allow chunk backfill decompression in migration session --- docs/production-incident-baseline.md | 16 ++++++++++++++++ src/db/migrate.test.ts | 3 +++ src/db/migrate.ts | 1 + 3 files changed, 20 insertions(+) diff --git a/docs/production-incident-baseline.md b/docs/production-incident-baseline.md index eaeec4a8be..9849aa0312 100644 --- a/docs/production-incident-baseline.md +++ b/docs/production-incident-baseline.md @@ -1766,3 +1766,19 @@ Timescale tuple decompression limit, the migration retries that same chunk in one-hour `recorded_at` windows. This keeps the deployment from spending hourly queries on every already-finished chunk while keeping each DML statement below the decompression cap for large remaining chunks. + +### Fourth Follow-up Evidence + +The hybrid fallback worked, but production progress was still too slow for a +deploy migration. The first large remaining chunk completed through hourly +fallback with `187,218` rows, while the original production null-ID count was +about `187.7M` rows. That made the backfill operationally too large for +per-hour DML in the deploy timeout window. + +### Fourth Follow-up Fix + +Kept the backfill chunk-bounded and resumable, but set +`timescaledb.max_tuples_decompressed_per_dml_transaction = 0` for the migration +session before the chunk updates. This removes the Timescale per-DML +decompression cap for this controlled migration session without changing the +database-wide setting. diff --git a/src/db/migrate.test.ts b/src/db/migrate.test.ts index a201a408fc..00f167a843 100644 --- a/src/db/migrate.test.ts +++ b/src/db/migrate.test.ts @@ -155,6 +155,9 @@ describe("runMigrations", () => { String(text).includes("UPDATE fitness.metric_stream AS metric_stream"), ); expect(backfillCalls).toHaveLength(2); + expect(executedQueries()).toContain( + "SET timescaledb.max_tuples_decompressed_per_dml_transaction = 0", + ); expect(String(backfillCalls[0]?.[0])).not.toContain("ctid"); expect(String(backfillCalls[0]?.[0])).not.toContain("LIMIT"); expect(backfillCalls[0]?.[1]).toEqual([ diff --git a/src/db/migrate.ts b/src/db/migrate.ts index 7506356127..07b0e801d9 100644 --- a/src/db/migrate.ts +++ b/src/db/migrate.ts @@ -154,6 +154,7 @@ function parseMigrationDate(value: Date | string): Date { async function backfillMetricStreamIds(client: Client): Promise { logger.info("[migrate] Backfilling metric_stream.id in Timescale chunk ranges"); + await client.query("SET timescaledb.max_tuples_decompressed_per_dml_transaction = 0"); const chunksResult = await client.query(` SELECT chunk_schema, chunk_name, range_start, range_end From d36e735a1cfe4234be8d800e2421788f9b5beb31 Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Thu, 30 Apr 2026 16:03:02 -0700 Subject: [PATCH 15/36] Defer metric stream primary key backfill --- README.md | 2 +- deploy/README.md | 4 +- docs/README.md | 2 +- docs/clickhouse-metric-stream.md | 29 +-- docs/production-incident-baseline.md | 28 +++ drizzle/0007_metric_stream_primary_key.sql | 18 -- src/db/clickhouse-migrations.test.ts | 19 +- src/db/clickhouse-migrations.ts | 11 ++ src/db/clickhouse.test.ts | 13 +- src/db/clickhouse.ts | 16 +- ...ream-replica-identity.integration.test.ts} | 49 +++--- src/db/migrate.integration.test.ts | 32 ++-- src/db/migrate.test.ts | 103 ++--------- src/db/migrate.ts | 166 +----------------- 14 files changed, 150 insertions(+), 342 deletions(-) rename src/db/{metric-stream-primary-key.integration.test.ts => metric-stream-replica-identity.integration.test.ts} (73%) diff --git a/README.md b/README.md index 858ad47a70..d707538a8e 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,7 @@ If you are starting cold and do not want to hunt through agent notes, begin here └─────────────┘ └───────────┘ ``` -Each data source is a **provider plugin** that implements a simple interface. The sync runner orchestrates all enabled providers. Raw data lands in a `fitness` Postgres schema. ClickHouse maintains a stored deduped sensor read model for heavy activity stream reads via native Postgres replication; derived rows are not written back to Postgres. The web dashboard provides sync controls, provider health monitoring, insights, and data exploration. A companion iOS app (Expo + React Native) provides native HealthKit integration and on-the-go access. Nutrition logging on web and iOS supports natural-language AI meal input that can split one message into multiple food items. Long-running sync jobs are processed by BullMQ workers backed by Redis. In production, the `worker` container registers repeatable scheduled sync jobs in BullMQ; the `sync` mode remains available for manual one-shot runs. +Each data source is a **provider plugin** that implements a simple interface. The sync runner orchestrates all enabled providers. Raw data lands in a `fitness` Postgres schema. ClickHouse maintains stored analytics read models for heavy activity stream reads; raw `metric_stream` replication is temporarily disabled behind an empty placeholder until the historic Timescale table has a stable primary key. Derived rows are not written back to Postgres. The web dashboard provides sync controls, provider health monitoring, insights, and data exploration. A companion iOS app (Expo + React Native) provides native HealthKit integration and on-the-go access. Nutrition logging on web and iOS supports natural-language AI meal input that can split one message into multiple food items. Long-running sync jobs are processed by BullMQ workers backed by Redis. In production, the `worker` container registers repeatable scheduled sync jobs in BullMQ; the `sync` mode remains available for manual one-shot runs. ## Quick Start diff --git a/deploy/README.md b/deploy/README.md index c3d62e5171..c292ef524e 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -9,7 +9,7 @@ Dofek is deployed as a **single-node Docker Swarm** stack on **Hetzner Cloud** ( - **Compute**: Hetzner Cloud `cax11` ARM64 servers running Ubuntu 24.04. Production uses `dofek`; staging uses `dofek-staging`. Each server runs `dockerd` initialized as a single-node swarm manager and has no deploy scripts or secrets on disk. - **Storage**: - **PostgreSQL**: Managed via TimescaleDB (running in the swarm). - - **ClickHouse**: Runs in the swarm as the stored deduped sensor read model for heavy activity stream reads, backed by native Postgres replication. See [docs/clickhouse-metric-stream.md](../docs/clickhouse-metric-stream.md). + - **ClickHouse**: Runs in the swarm as the stored analytics read-model service for heavy activity stream reads. Raw `metric_stream` replication is temporarily disabled behind a local placeholder until the historic Timescale table has a stable primary key. See [docs/clickhouse-metric-stream.md](../docs/clickhouse-metric-stream.md). - **Volume**: Terraform provisions a Hetzner Block Storage volume (`data_volume_size_gb`, default `100GB`) attached with `automount=true`. - **Stable mount alias**: Terraform maintains `/mnt/dofek-data` as a symlink to the attached Hetzner volume mount path (`/mnt/HC_Volume_`). - **DB data path**: The `db` service bind-mounts Postgres data to `/mnt/dofek-data/postgres`. @@ -47,7 +47,7 @@ Dofek is deployed as a **single-node Docker Swarm** stack on **Hetzner Cloud** ( - Zero-downtime updates for `web` and `worker` are configured via `deploy.update_config` (`order: start-first`, `failure_action: rollback`, healthcheck-gated `monitor` window). - The `default` overlay network is declared `attachable: true` so CI can run one-shot migration containers on it from a remote Docker context. - The `db` service has a 2 GiB container memory limit to prevent one PostgreSQL workload from exhausting the single-node host. If it hits that limit, treat it as a query/workload incident rather than increasing the cap by default. -- PostgreSQL is configured with `max_connections=40`, `work_mem=4MB`, `maintenance_work_mem=64MB`, and logical replication settings for ClickHouse CDC. +- PostgreSQL is configured with `max_connections=40`, `work_mem=4MB`, `maintenance_work_mem=64MB`, and logical replication settings needed when ClickHouse CDC is re-enabled. - `metric_stream` storage controls (Timescale hypertable + compression) are managed via `docs/metric-stream-timescaledb-runbook.md` and `drizzle/0006_metric_stream_timescale_policies.sql`. - Slack is forced to HTTP mode in production via `SLACK_MODE=http` on the `web` service. This avoids Socket Mode multi-consumer overlap during rolling deploys when `web` has multiple replicas. diff --git a/docs/README.md b/docs/README.md index 0b315b4a83..195e829bfa 100644 --- a/docs/README.md +++ b/docs/README.md @@ -8,7 +8,7 @@ Human-facing architecture notes, provider research, and operational runbooks for - [../README.md](../README.md): repository overview, local development, and the high-level architecture. - [../deploy/README.md](../deploy/README.md): production architecture, deploy flow, secrets, and debugging access. -- [clickhouse-metric-stream.md](clickhouse-metric-stream.md): ClickHouse deduped sensor read model backed by native Postgres replication. +- [clickhouse-metric-stream.md](clickhouse-metric-stream.md): ClickHouse deduped sensor read model and current metric stream placeholder. - [schema.md](schema.md): canonical database model and storage philosophy. - [adding-a-provider.md](adding-a-provider.md): how to build or extend a provider. - [testing.md](testing.md): testing patterns that come up repeatedly in this codebase. diff --git a/docs/clickhouse-metric-stream.md b/docs/clickhouse-metric-stream.md index 4d20046211..26172b720d 100644 --- a/docs/clickhouse-metric-stream.md +++ b/docs/clickhouse-metric-stream.md @@ -1,16 +1,19 @@ # ClickHouse Metric Stream Projection -`fitness.metric_stream` remains canonical in Postgres/Timescale. ClickHouse uses -native Postgres replication to keep a local copy of the raw stream and then -maintains stored `analytics.deduped_sensor` and `analytics.activity_summary` -refreshable materialized views for activity stream, zone, and summary reads. +`fitness.metric_stream` remains canonical in Postgres/Timescale. ClickHouse +currently uses an empty local `postgres_fitness.metric_stream` placeholder while +the historic Postgres table is missing a primary key. The stored +`analytics.deduped_sensor` and `analytics.activity_summary` refreshable +materialized views remain in place so the schema is stable, but raw metric rows +are not replicated into ClickHouse until a separate offline backfill adds stable +row IDs and a primary key. ```text Postgres/Timescale fitness.metric_stream | - | ClickHouse MaterializedPostgreSQL + | offline ID backfill + PK still required v -ClickHouse postgres_fitness.metric_stream +ClickHouse postgres_fitness.metric_stream placeholder | | refreshable materialized view v @@ -25,7 +28,7 @@ Activity stream, zone, and summary reads ``` Runtime API queries must read `analytics.deduped_sensor` or -`analytics.activity_summary`, not the raw metric stream. The raw replicated table +`analytics.activity_summary`, not the raw metric stream. The raw ClickHouse table exists only as the source for ClickHouse refresh jobs. Derived rows are never synced back to Postgres. @@ -57,10 +60,11 @@ ClickHouse migrations run from the normal one-shot `migrate` container when ClickHouse read models or old custom sync tables, belongs there so API startup does not repeatedly delete analytical state. -ClickHouse migrations create and update the bridge databases and read models: +ClickHouse migrations create and update the databases and read models: -- `postgres_fitness`: a `MaterializedPostgreSQL` database that replicates - `fitness.metric_stream`. +- `postgres_fitness.metric_stream`: an empty local MergeTree placeholder for the + raw metric stream. This intentionally does not use `MaterializedPostgreSQL` + until the Postgres hypertable has a stable primary key. - `postgres_fitness_live`: a PostgreSQL database bridge for scalar-only views in the Postgres `clickhouse` schema: `clickhouse.v_activity` and `clickhouse.v_activity_members`. @@ -69,8 +73,9 @@ ClickHouse migrations create and update the bridge databases and read models: - `analytics.activity_summary`: a refreshable materialized view refreshed from `analytics.deduped_sensor`. -Postgres must run with `wal_level=logical`, `max_replication_slots`, and -`max_wal_senders` enabled so ClickHouse can subscribe to changes. +Postgres still runs with `wal_level=logical`, `max_replication_slots`, and +`max_wal_senders` enabled so ClickHouse can subscribe to changes once the raw +metric stream replication path is re-enabled. API startup only verifies that the migrated ClickHouse tables exist. It must not create or rewrite analytical schema, because production runs multiple web diff --git a/docs/production-incident-baseline.md b/docs/production-incident-baseline.md index 9849aa0312..42212c038c 100644 --- a/docs/production-incident-baseline.md +++ b/docs/production-incident-baseline.md @@ -1782,3 +1782,31 @@ Kept the backfill chunk-bounded and resumable, but set session before the chunk updates. This removes the Timescale per-DML decompression cap for this controlled migration session without changing the database-wide setting. + +### Final Follow-up Evidence + +The controlled chunk update avoided the decompression limit but was still not a +deploy-time migration. A remaining chunk with `163,506` null-ID rows took about +fourteen minutes, while the historic table still had about `187M` rows requiring +IDs. Production also had exact duplicate metric rows, so there was no safe +natural-key primary key shortcut for `fitness.metric_stream`. + +### Final Fix + +Stopped trying to backfill historic `metric_stream.id` values and add the +primary key during deploy. Migration `0007_metric_stream_primary_key.sql` now +only adds the nullable `id` column, gives future rows a `gen_random_uuid()` +default, and leaves the table on `REPLICA IDENTITY FULL`. ClickHouse migration +`0003_disable_materialized_metric_stream` drops any previous +`postgres_fitness` MaterializedPostgreSQL database and recreates +`postgres_fitness.metric_stream` as an empty local MergeTree placeholder so +analytics schema creation can complete while raw metric replication remains +disabled. + +### Remaining Risk + +ClickHouse activity stream and summary read models remain schema-present but do +not receive raw historic metric samples through `postgres_fitness.metric_stream`. +The real fix still requires an offline maintenance job to backfill stable row +IDs, add the Timescale-compatible primary key, and then re-enable raw +ClickHouse replication. diff --git a/drizzle/0007_metric_stream_primary_key.sql b/drizzle/0007_metric_stream_primary_key.sql index f0e9d7be54..4865af5f36 100644 --- a/drizzle/0007_metric_stream_primary_key.sql +++ b/drizzle/0007_metric_stream_primary_key.sql @@ -6,21 +6,3 @@ ALTER COLUMN id SET DEFAULT gen_random_uuid(); --> statement-breakpoint ALTER TABLE fitness.metric_stream REPLICA IDENTITY FULL; ---> statement-breakpoint --- dofek:backfill-metric-stream-id ---> statement-breakpoint -DO $$ -BEGIN - IF NOT EXISTS ( - SELECT 1 - FROM pg_constraint - WHERE conrelid = 'fitness.metric_stream'::regclass - AND conname = 'metric_stream_pkey' - ) THEN - ALTER TABLE fitness.metric_stream - ADD CONSTRAINT metric_stream_pkey PRIMARY KEY (id, recorded_at); - END IF; -END $$; ---> statement-breakpoint -ALTER TABLE fitness.metric_stream -REPLICA IDENTITY USING INDEX metric_stream_pkey; diff --git a/src/db/clickhouse-migrations.test.ts b/src/db/clickhouse-migrations.test.ts index 167d17991c..4f024eca69 100644 --- a/src/db/clickhouse-migrations.test.ts +++ b/src/db/clickhouse-migrations.test.ts @@ -13,9 +13,10 @@ describe("buildClickHouseMigrationStatements", () => { expect(sql).toContain("DROP TABLE IF EXISTS fitness.metric_stream"); expect(sql).toContain("DROP TABLE IF EXISTS fitness.deduped_sensor"); expect(sql).toContain("DROP TABLE IF EXISTS analytics.deduped_sensor"); - expect(sql).toContain( - "ENGINE = MaterializedPostgreSQL('db:5432', 'health', 'health', 'secret')", - ); + expect(sql).toContain("DROP DATABASE IF EXISTS postgres_fitness SYNC"); + expect(sql).toContain("CREATE TABLE IF NOT EXISTS postgres_fitness.metric_stream"); + expect(sql).toContain("ENGINE = MergeTree"); + expect(sql).not.toContain("MaterializedPostgreSQL"); expect(sql).toContain( "ENGINE = PostgreSQL('db:5432', 'health', 'health', 'secret', 'clickhouse')", ); @@ -38,7 +39,7 @@ describe("runClickHouseMigrations", () => { const count = await runClickHouseMigrations(client, "postgres://health:secret@db:5432/health"); - expect(count).toBe(2); + expect(count).toBe(3); expect(command).toHaveBeenCalledWith({ query: "CREATE DATABASE IF NOT EXISTS fitness" }); expect(command).toHaveBeenCalledWith({ query: "CREATE DATABASE IF NOT EXISTS analytics" }); expect(command).toHaveBeenCalledWith( @@ -51,6 +52,16 @@ describe("runClickHouseMigrations", () => { query: expect.stringContaining("DROP TABLE IF EXISTS fitness.metric_stream"), }), ); + expect(command).toHaveBeenCalledWith( + expect.objectContaining({ + query: "DROP DATABASE IF EXISTS postgres_fitness SYNC", + }), + ); + expect(command).toHaveBeenCalledWith( + expect.objectContaining({ + query: expect.stringContaining("CREATE TABLE IF NOT EXISTS postgres_fitness.metric_stream"), + }), + ); expect(command).toHaveBeenCalledWith( expect.objectContaining({ query: expect.stringContaining( diff --git a/src/db/clickhouse-migrations.ts b/src/db/clickhouse-migrations.ts index 62b271231e..1fcd536abd 100644 --- a/src/db/clickhouse-migrations.ts +++ b/src/db/clickhouse-migrations.ts @@ -34,6 +34,17 @@ function clickHouseMigrations(postgresConnectionString: string) { id: "0002_clickhouse_postgres_bridge_and_activity_read_models", statements: buildClickHouseBootstrapStatements(postgresConnectionString), }, + { + id: "0003_disable_materialized_metric_stream", + statements: [ + "DROP VIEW IF EXISTS analytics.activity_summary", + "DROP TABLE IF EXISTS analytics.activity_summary", + "DROP VIEW IF EXISTS analytics.deduped_sensor", + "DROP TABLE IF EXISTS analytics.deduped_sensor", + "DROP DATABASE IF EXISTS postgres_fitness SYNC", + ...buildClickHouseBootstrapStatements(postgresConnectionString), + ], + }, ]; } diff --git a/src/db/clickhouse.test.ts b/src/db/clickhouse.test.ts index 2409c396d5..6dd9985ecb 100644 --- a/src/db/clickhouse.test.ts +++ b/src/db/clickhouse.test.ts @@ -20,17 +20,20 @@ describe("parsePostgresConnectionForClickHouse", () => { }); describe("buildClickHouseBootstrapStatements", () => { - it("creates native Postgres bridges and a ClickHouse deduped sensor view", () => { + it("creates a local metric stream placeholder and ClickHouse read models", () => { const sql = buildClickHouseBootstrapStatements("postgres://health:secret@db:5432/health").join( "\n", ); expect(sql).toContain("CREATE DATABASE IF NOT EXISTS analytics"); expect(sql).not.toContain("CREATE DATABASE IF NOT EXISTS fitness"); - expect(sql).toContain( - "ENGINE = MaterializedPostgreSQL('db:5432', 'health', 'health', 'secret')", - ); - expect(sql).toContain("materialized_postgresql_tables_list = 'metric_stream'"); + expect(sql).toContain("CREATE DATABASE IF NOT EXISTS postgres_fitness"); + expect(sql).toContain("CREATE TABLE IF NOT EXISTS postgres_fitness.metric_stream"); + expect(sql).toContain("activity_id Nullable(UUID)"); + expect(sql).toContain("recorded_at DateTime64(6, 'UTC')"); + expect(sql).toContain("ENGINE = MergeTree"); + expect(sql).not.toContain("MaterializedPostgreSQL"); + expect(sql).not.toContain("materialized_postgresql_tables_list"); expect(sql).toContain( "ENGINE = PostgreSQL('db:5432', 'health', 'health', 'secret', 'clickhouse')", ); diff --git a/src/db/clickhouse.ts b/src/db/clickhouse.ts index a10f9c7e22..499124e612 100644 --- a/src/db/clickhouse.ts +++ b/src/db/clickhouse.ts @@ -74,10 +74,18 @@ export function buildClickHouseBootstrapStatements(postgresConnectionString: str return [ "CREATE DATABASE IF NOT EXISTS analytics", - `CREATE DATABASE IF NOT EXISTS postgres_fitness -ENGINE = MaterializedPostgreSQL(${hostAndPort}, ${database}, ${user}, ${password}) -SETTINGS materialized_postgresql_schema = 'fitness', - materialized_postgresql_tables_list = 'metric_stream'`, + "CREATE DATABASE IF NOT EXISTS postgres_fitness", + `CREATE TABLE IF NOT EXISTS postgres_fitness.metric_stream ( + activity_id Nullable(UUID), + user_id UUID, + recorded_at DateTime64(6, 'UTC'), + channel String, + provider_id String, + scalar Nullable(Float32) +) +ENGINE = MergeTree +ORDER BY (user_id, activity_id, channel, recorded_at) +SETTINGS allow_nullable_key = 1`, `CREATE DATABASE IF NOT EXISTS postgres_fitness_live ENGINE = PostgreSQL(${hostAndPort}, ${database}, ${user}, ${password}, 'clickhouse')`, `CREATE MATERIALIZED VIEW IF NOT EXISTS analytics.deduped_sensor diff --git a/src/db/metric-stream-primary-key.integration.test.ts b/src/db/metric-stream-replica-identity.integration.test.ts similarity index 73% rename from src/db/metric-stream-primary-key.integration.test.ts rename to src/db/metric-stream-replica-identity.integration.test.ts index 5aa48d55aa..dbcd740b1e 100644 --- a/src/db/metric-stream-primary-key.integration.test.ts +++ b/src/db/metric-stream-replica-identity.integration.test.ts @@ -6,7 +6,7 @@ import { GenericContainer } from "testcontainers"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { runMigrations } from "./migrate.ts"; -describe("metric_stream primary key migration", () => { +describe("metric_stream replica identity migration", () => { let connectionString: string; let container: Awaited> | undefined; @@ -45,7 +45,7 @@ describe("metric_stream primary key migration", () => { } }); - it("adds a replica-safe primary key using the chunk-range ID backfill", async () => { + it("adds an ID default and full replica identity without backfilling historic rows", async () => { const client = new Client({ connectionString }); await client.connect(); try { @@ -85,7 +85,7 @@ describe("metric_stream primary key migration", () => { ('2026-01-03T00:00:00Z', gen_random_uuid(), 'garmin', 'api', 'power', 220) `); - const tmpDir = mkdtempSync(join(tmpdir(), "metric-stream-primary-key-")); + const tmpDir = mkdtempSync(join(tmpdir(), "metric-stream-replica-identity-")); const migrationContent = readFileSync( join(import.meta.dirname, "../../drizzle/0007_metric_stream_primary_key.sql"), "utf-8", @@ -95,27 +95,25 @@ describe("metric_stream primary key migration", () => { const migrationCount = await runMigrations(connectionString, tmpDir); expect(migrationCount).toBe(1); - const primaryKeyResult = await client.query<{ - column_name: string; + const replicaIdentityResult = await client.query<{ replica_identity: string; }>(` - -- cspell:ignore attname relreplident indrelid relnamespace attrelid attnum indkey nspname relname indisprimary pgcrypto segmentby pkey - SELECT attribute.attname AS column_name, class.relreplident AS replica_identity - FROM pg_index index - JOIN pg_class class ON class.oid = index.indrelid + -- cspell:ignore relreplident nspname relname + SELECT class.relreplident AS replica_identity + FROM pg_class class JOIN pg_namespace namespace ON namespace.oid = class.relnamespace - JOIN pg_attribute attribute - ON attribute.attrelid = index.indrelid - AND attribute.attnum = ANY(index.indkey) WHERE namespace.nspname = 'fitness' AND class.relname = 'metric_stream' - AND index.indisprimary - ORDER BY array_position(index.indkey, attribute.attnum) `); - expect(primaryKeyResult.rows).toEqual([ - { column_name: "id", replica_identity: "i" }, - { column_name: "recorded_at", replica_identity: "i" }, - ]); + expect(replicaIdentityResult.rows).toEqual([{ replica_identity: "f" }]); + + const primaryKeyResult = await client.query<{ primary_key_count: string }>(` + SELECT count(*) AS primary_key_count + FROM pg_constraint + WHERE conrelid = 'fitness.metric_stream'::regclass + AND contype = 'p' + `); + expect(primaryKeyResult.rows).toEqual([{ primary_key_count: "0" }]); const nullableResult = await client.query<{ is_nullable: "YES" | "NO" }>(` SELECT is_nullable @@ -124,12 +122,23 @@ describe("metric_stream primary key migration", () => { AND table_name = 'metric_stream' AND column_name = 'id' `); - expect(nullableResult.rows).toEqual([{ is_nullable: "NO" }]); + expect(nullableResult.rows).toEqual([{ is_nullable: "YES" }]); const nullIdResult = await client.query<{ missing_id_count: string }>( "SELECT count(*) AS missing_id_count FROM fitness.metric_stream WHERE id IS NULL", ); - expect(nullIdResult.rows).toEqual([{ missing_id_count: "0" }]); + expect(nullIdResult.rows).toEqual([{ missing_id_count: "3" }]); + + const insertedResult = await client.query<{ generated_id: string | null }>(` + INSERT INTO fitness.metric_stream ( + recorded_at, user_id, provider_id, source_type, channel, scalar + ) + VALUES ('2026-01-04T00:00:00Z', gen_random_uuid(), 'garmin', 'api', 'power', 230) + RETURNING id AS generated_id + `); + expect(insertedResult.rows[0]?.generated_id).toMatch( + /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/, + ); } finally { await client.end(); } diff --git a/src/db/migrate.integration.test.ts b/src/db/migrate.integration.test.ts index be044ec6b7..285f3e6197 100644 --- a/src/db/migrate.integration.test.ts +++ b/src/db/migrate.integration.test.ts @@ -94,32 +94,28 @@ describe("runMigrations", () => { expect(count).toBe(1); }); - it("gives metric_stream a replica-safe primary key", async () => { + it("gives metric_stream full replica identity without a deploy-time primary key backfill", async () => { const client = new Client({ connectionString: ctx.connectionString }); await client.connect(); try { - // cspell:ignore attname relreplident indrelid relnamespace attrelid attnum indkey nspname relname indisprimary - const result = await client.query<{ - column_name: string; + const replicaIdentityResult = await client.query<{ replica_identity: string; }>( - `SELECT attribute.attname AS column_name, class.relreplident AS replica_identity - FROM pg_index index - JOIN pg_class class ON class.oid = index.indrelid + `SELECT class.relreplident AS replica_identity + FROM pg_class class JOIN pg_namespace namespace ON namespace.oid = class.relnamespace - JOIN pg_attribute attribute - ON attribute.attrelid = index.indrelid - AND attribute.attnum = ANY(index.indkey) WHERE namespace.nspname = 'fitness' - AND class.relname = 'metric_stream' - AND index.indisprimary - ORDER BY array_position(index.indkey, attribute.attnum)`, + AND class.relname = 'metric_stream'`, ); - - expect(result.rows).toEqual([ - { column_name: "id", replica_identity: "i" }, - { column_name: "recorded_at", replica_identity: "i" }, - ]); + expect(replicaIdentityResult.rows).toEqual([{ replica_identity: "f" }]); + + const primaryKeyResult = await client.query<{ primary_key_count: string }>(` + SELECT count(*) AS primary_key_count + FROM pg_constraint + WHERE conrelid = 'fitness.metric_stream'::regclass + AND contype = 'p' + `); + expect(primaryKeyResult.rows).toEqual([{ primary_key_count: "0" }]); } finally { await client.end(); } diff --git a/src/db/migrate.test.ts b/src/db/migrate.test.ts index 00f167a843..8851f1d5e2 100644 --- a/src/db/migrate.test.ts +++ b/src/db/migrate.test.ts @@ -120,105 +120,24 @@ describe("runMigrations", () => { expect(executedQueries()).toContain("CREATE TABLE b (id INT)"); }); - it("backfills metric_stream IDs in bounded Timescale chunk ranges", async () => { + it("executes migration statements without custom marker hooks", async () => { const { runMigrations } = await import("./migrate.ts"); - mockReaddirSync.mockReturnValue(["0007_metric_stream_primary_key.sql"]); - mockReadFileSync.mockReturnValue("-- dofek:backfill-metric-stream-id"); - const chunkRows = [ - { - chunk_schema: "_timescaledb_internal", - chunk_name: "_hyper_1_1_chunk", - range_start: "2026-01-01T00:00:00.000Z", - range_end: "2026-01-01T02:00:00.000Z", - }, - { - chunk_schema: "_timescaledb_internal", - chunk_name: "_hyper_1_2_chunk", - range_start: "2026-01-02T00:30:00.000Z", - range_end: "2026-01-02T01:00:00.000Z", - }, - ]; - mockClientQuery.mockImplementation((text: string) => { - if (text.includes("timescaledb_information.chunks")) { - return Promise.resolve({ rows: chunkRows }); - } - if (text.includes("UPDATE fitness.metric_stream AS metric_stream")) { - return Promise.resolve({ rows: [], rowCount: 7 }); - } - return Promise.resolve({ rows: [] }); - }); - - await runMigrations("postgres://localhost/test", "/tmp/migrations"); - - const backfillCalls = mockClientQuery.mock.calls.filter(([text]) => - String(text).includes("UPDATE fitness.metric_stream AS metric_stream"), - ); - expect(backfillCalls).toHaveLength(2); - expect(executedQueries()).toContain( - "SET timescaledb.max_tuples_decompressed_per_dml_transaction = 0", + mockReaddirSync.mockReturnValue(["0007_metric_stream_replica_identity.sql"]); + mockReadFileSync.mockReturnValue( + "SELECT 1--> statement-breakpoint\n-- dofek:backfill-metric-stream-id", ); - expect(String(backfillCalls[0]?.[0])).not.toContain("ctid"); - expect(String(backfillCalls[0]?.[0])).not.toContain("LIMIT"); - expect(backfillCalls[0]?.[1]).toEqual([ - new Date("2026-01-01T00:00:00.000Z"), - new Date("2026-01-01T02:00:00.000Z"), - ]); - expect(backfillCalls[1]?.[1]).toEqual([ - new Date("2026-01-02T00:30:00.000Z"), - new Date("2026-01-02T01:00:00.000Z"), - ]); - }); - - it("falls back to hourly metric_stream ID backfill when a chunk exceeds Timescale decompression limits", async () => { - const { runMigrations } = await import("./migrate.ts"); - - mockReaddirSync.mockReturnValue(["0007_metric_stream_primary_key.sql"]); - mockReadFileSync.mockReturnValue("-- dofek:backfill-metric-stream-id"); - const chunkRows = [ - { - chunk_schema: "_timescaledb_internal", - chunk_name: "_hyper_1_1_chunk", - range_start: "2026-01-01T00:00:00.000Z", - range_end: "2026-01-01T02:00:00.000Z", - }, - ]; - let updateAttempts = 0; - mockClientQuery.mockImplementation((text: string) => { - if (text.includes("timescaledb_information.chunks")) { - return Promise.resolve({ rows: chunkRows }); - } - if (text.includes("UPDATE fitness.metric_stream AS metric_stream")) { - updateAttempts++; - if (updateAttempts === 1) { - return Promise.reject(new Error("tuple decompression limit exceeded by operation")); - } - return Promise.resolve({ rows: [], rowCount: 5 }); - } - return Promise.resolve({ rows: [] }); - }); await runMigrations("postgres://localhost/test", "/tmp/migrations"); - const backfillCalls = mockClientQuery.mock.calls.filter(([text]) => - String(text).includes("UPDATE fitness.metric_stream AS metric_stream"), - ); - expect(backfillCalls).toHaveLength(3); - expect(backfillCalls[0]?.[1]).toEqual([ - new Date("2026-01-01T00:00:00.000Z"), - new Date("2026-01-01T02:00:00.000Z"), - ]); - expect(backfillCalls[1]?.[1]).toEqual([ - new Date("2026-01-01T00:00:00.000Z"), - new Date("2026-01-01T01:00:00.000Z"), - ]); - expect(backfillCalls[2]?.[1]).toEqual([ - new Date("2026-01-01T01:00:00.000Z"), - new Date("2026-01-01T02:00:00.000Z"), - ]); - expect(mockLoggerWarn).toHaveBeenCalledWith( - expect.stringContaining("Falling back to one-hour metric_stream ID backfill"), + expect(executedQueries()).toContain("SELECT 1"); + expect(executedQueries()).toContain("-- dofek:backfill-metric-stream-id"); + expect(executedQueries().some((query) => query.includes("UPDATE fitness.metric_stream"))).toBe( + false, ); + expect( + executedQueries().some((query) => query.includes("timescaledb_information.chunks")), + ).toBe(false); }); it("returns 0 when no pending migrations exist", async () => { diff --git a/src/db/migrate.ts b/src/db/migrate.ts index 07b0e801d9..95178ae43a 100644 --- a/src/db/migrate.ts +++ b/src/db/migrate.ts @@ -6,20 +6,6 @@ import { logger } from "../logger.ts"; /** Postgres advisory lock key — serializes concurrent migration runs across containers */ export const MIGRATION_LOCK_KEY = 728370291; -const METRIC_STREAM_ID_BACKFILL_MARKER = "-- dofek:backfill-metric-stream-id"; -const METRIC_STREAM_ID_BACKFILL_WINDOW_MILLISECONDS = 60 * 60 * 1000; - -interface MetricStreamChunkRow { - chunk_schema: string; - chunk_name: string; - range_start: Date | string | null; - range_end: Date | string | null; -} - -interface MetricStreamNullIdBoundsRow { - range_start: Date | string | null; - range_end: Date | string | null; -} /** * Detect migration files that share the same numeric prefix (e.g., two 0049_* files). @@ -62,152 +48,6 @@ function parseStatements(content: string): Array { .filter(Boolean); } -async function backfillMetricStreamIdsForChunkRange( - client: Client, - rangeStart: Date | string, - rangeEnd: Date | string, -): Promise { - const chunkRangeStart = parseMigrationDate(rangeStart); - const chunkRangeEnd = parseMigrationDate(rangeEnd); - if (chunkRangeEnd <= chunkRangeStart) { - throw new Error("metric_stream ID backfill chunk range did not advance"); - } - - const result = await client.query( - `UPDATE fitness.metric_stream AS metric_stream - SET id = gen_random_uuid() - WHERE metric_stream.id IS NULL - AND metric_stream.recorded_at >= $1 - AND metric_stream.recorded_at < $2`, - [chunkRangeStart, chunkRangeEnd], - ); - return result.rowCount ?? 0; -} - -async function backfillMetricStreamIdsForHourlyWindows( - client: Client, - rangeStart: Date | string, - rangeEnd: Date | string, -): Promise { - let totalRows = 0; - let windowStart = parseMigrationDate(rangeStart); - const finalRangeEnd = parseMigrationDate(rangeEnd); - - while (windowStart < finalRangeEnd) { - const nextWindowEnd = new Date( - Math.min( - windowStart.getTime() + METRIC_STREAM_ID_BACKFILL_WINDOW_MILLISECONDS, - finalRangeEnd.getTime(), - ), - ); - if (nextWindowEnd <= windowStart) { - throw new Error("metric_stream ID backfill time window did not advance"); - } - - const result = await client.query( - `UPDATE fitness.metric_stream AS metric_stream - SET id = gen_random_uuid() - WHERE metric_stream.id IS NULL - AND metric_stream.recorded_at >= $1 - AND metric_stream.recorded_at < $2`, - [windowStart, nextWindowEnd], - ); - totalRows += result.rowCount ?? 0; - windowStart = nextWindowEnd; - } - - return totalRows; -} - -function isTimescaleTupleDecompressionLimitError(error: unknown): boolean { - return error instanceof Error && error.message.includes("tuple decompression limit exceeded"); -} - -async function backfillMetricStreamIdsWithoutChunkRanges(client: Client): Promise { - const boundsResult = await client.query(` - SELECT - min(recorded_at) AS range_start, - max(recorded_at) + INTERVAL '1 millisecond' AS range_end - FROM fitness.metric_stream - WHERE id IS NULL - `); - - const bounds = boundsResult.rows[0]; - if (!bounds?.range_start || !bounds.range_end) { - return 0; - } - - return backfillMetricStreamIdsForChunkRange(client, bounds.range_start, bounds.range_end); -} - -function parseMigrationDate(value: Date | string): Date { - if (value instanceof Date) { - return value; - } - - const parsedDate = new Date(value); - if (Number.isNaN(parsedDate.getTime())) { - throw new Error(`Invalid migration timestamp: ${value}`); - } - return parsedDate; -} - -async function backfillMetricStreamIds(client: Client): Promise { - logger.info("[migrate] Backfilling metric_stream.id in Timescale chunk ranges"); - await client.query("SET timescaledb.max_tuples_decompressed_per_dml_transaction = 0"); - - const chunksResult = await client.query(` - SELECT chunk_schema, chunk_name, range_start, range_end - FROM timescaledb_information.chunks - WHERE hypertable_schema = 'fitness' - AND hypertable_name = 'metric_stream' - ORDER BY range_start NULLS FIRST, chunk_schema, chunk_name - `); - - if (chunksResult.rows.length === 0) { - const totalRows = await backfillMetricStreamIdsWithoutChunkRanges(client); - logger.info(`[migrate] Backfilled ${totalRows} metric_stream.id row(s) without chunk ranges`); - return; - } - - let totalRows = 0; - for (const chunk of chunksResult.rows) { - if (!chunk.range_start || !chunk.range_end) { - logger.warn( - `[migrate] Skipping metric_stream chunk with missing time bounds: ${chunk.chunk_schema}.${chunk.chunk_name}`, - ); - continue; - } - - let chunkRows: number; - try { - chunkRows = await backfillMetricStreamIdsForChunkRange( - client, - chunk.range_start, - chunk.range_end, - ); - } catch (error: unknown) { - if (!isTimescaleTupleDecompressionLimitError(error)) { - throw error; - } - logger.warn( - `[migrate] Falling back to one-hour metric_stream ID backfill for ${chunk.chunk_schema}.${chunk.chunk_name}`, - ); - chunkRows = await backfillMetricStreamIdsForHourlyWindows( - client, - chunk.range_start, - chunk.range_end, - ); - } - totalRows += chunkRows; - logger.info( - `[migrate] Backfilled ${chunkRows} metric_stream.id row(s) in ${chunk.chunk_schema}.${chunk.chunk_name}`, - ); - } - - logger.info(`[migrate] Backfilled ${totalRows} metric_stream.id row(s) across Timescale chunks`); -} - /** * Run pending migrations from the drizzle/ directory. * @@ -326,11 +166,7 @@ export async function runMigrations(databaseUrl: string, migrationsDir?: string) const contentHash = computeContentHash(content); const requiresRefresh = migrationRequiresMaterializedViewRefresh(content); for (const stmt of parseStatements(content)) { - if (stmt === METRIC_STREAM_ID_BACKFILL_MARKER) { - await backfillMetricStreamIds(client); - } else { - await client.query(stmt); - } + await client.query(stmt); } await client.query( `INSERT INTO drizzle.__drizzle_migrations ( From 0d4aa69fbf3a5ef38aa67221ed1e895d94f6631c Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Thu, 30 Apr 2026 16:21:22 -0700 Subject: [PATCH 16/36] Encode ClickHouse password for stack deploy --- .github/workflows/deploy-web-stack.yml | 12 ++++++++---- deploy/README.md | 2 +- deploy/stack.yml | 4 ++-- docs/production-incident-baseline.md | 27 ++++++++++++++++++++++++++ 4 files changed, 38 insertions(+), 7 deletions(-) diff --git a/.github/workflows/deploy-web-stack.yml b/.github/workflows/deploy-web-stack.yml index 245ca97e13..455c138135 100644 --- a/.github/workflows/deploy-web-stack.yml +++ b/.github/workflows/deploy-web-stack.yml @@ -232,6 +232,13 @@ jobs: process.exit(result.status ?? 1); NODE + - name: Export encoded ClickHouse password + run: | + encoded_clickhouse_password="$( + node "$RUNNER_TEMP/run-with-dotenv-env.mjs" node -e 'const password = process.env.CLICKHOUSE_PASSWORD; if (!password) { throw new Error("CLICKHOUSE_PASSWORD is required"); } process.stdout.write(encodeURIComponent(password));' + )" + echo "CLICKHOUSE_PASSWORD_ENCODED=$encoded_clickhouse_password" >> "$GITHUB_ENV" + - name: Login to GHCR uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3 with: @@ -350,9 +357,6 @@ jobs: IMAGE_TAG: ${{ steps.resolve.outputs.tag }} run: | migration_output_file="$RUNNER_TEMP/migrate.log" - encoded_clickhouse_password="$( - node "$RUNNER_TEMP/run-with-dotenv-env.mjs" node -e 'const password = process.env.CLICKHOUSE_PASSWORD; if (!password) { throw new Error("CLICKHOUSE_PASSWORD is required"); } process.stdout.write(encodeURIComponent(password));' - )" migration_container="${STACK_NAME}_migrate_${GITHUB_RUN_ID}_${GITHUB_RUN_ATTEMPT}" cleanup_migration_container() { docker rm -f "$migration_container" >/dev/null 2>&1 || true @@ -363,7 +367,7 @@ jobs: cleanup_migration_container docker run --detach --name "$migration_container" --network "${STACK_NAME}_default" \ --env-file "$INFISICAL_ENV_FILE" \ - --env "CLICKHOUSE_PASSWORD_ENCODED=$encoded_clickhouse_password" \ + --env "CLICKHOUSE_PASSWORD_ENCODED=$CLICKHOUSE_PASSWORD_ENCODED" \ --entrypoint sh \ "ghcr.io/asherlc/dofek:${IMAGE_TAG}" \ -euc 'export DATABASE_URL="postgres://health:${POSTGRES_PASSWORD}@db:5432/health"; export CLICKHOUSE_URL="http://default:${CLICKHOUSE_PASSWORD_ENCODED}@clickhouse:8123"; exec node --experimental-transform-types --enable-source-maps --disable-warning=ExperimentalWarning src/db/run-migrate.ts' diff --git a/deploy/README.md b/deploy/README.md index c292ef524e..ff7704f087 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -125,7 +125,7 @@ CI (main) -> build dofek + dofek-ml (same tag) 1. Install the Infisical CLI, login with OIDC machine identity (`identity-id=46b66f72-0c77-4cfe-be1b-a43395e77be7`), and render `${{ github.workspace }}/.env.` from `.github/templates/infisical-dotenv.tmpl`. The template escapes embedded newlines only when `secret.IsMultilineEncodingEnabled` is true. - Must include `CREDENTIAL_ENCRYPTION_KEY_BASE64` (base64-encoded 32-byte key). - - Must include `CLICKHOUSE_PASSWORD` for the ClickHouse service and app `CLICKHOUSE_URL` interpolation. + - Must include `CLICKHOUSE_PASSWORD` for the ClickHouse service. The deploy workflow URL-encodes it into `CLICKHOUSE_PASSWORD_ENCODED` for app `CLICKHOUSE_URL` interpolation. - Optional: `CREDENTIAL_ENCRYPTION_KEY_NAMESPACE` (default `dofek`) and `CREDENTIAL_ENCRYPTION_KEY_NAME` (default `provider-credentials`). 2. Point Docker CLI at the remote daemon with `DOCKER_HOST=ssh://root@`. 3. Login to GHCR on the CI runner. diff --git a/deploy/stack.yml b/deploy/stack.yml index 1d22a7032e..6980fe694f 100644 --- a/deploy/stack.yml +++ b/deploy/stack.yml @@ -53,7 +53,7 @@ services: JOB_FILES_DIR: /app/job-files PUBLIC_URL: ${PUBLIC_URL:-https://dofek.asherlc.com} DATABASE_URL: postgres://health:${POSTGRES_PASSWORD}@db:5432/health - CLICKHOUSE_URL: http://default:${CLICKHOUSE_PASSWORD:?CLICKHOUSE_PASSWORD is required}@clickhouse:8123 + CLICKHOUSE_URL: http://default:${CLICKHOUSE_PASSWORD_ENCODED:?CLICKHOUSE_PASSWORD_ENCODED is required}@clickhouse:8123 REDIS_URL: redis://redis:6379 OTEL_SERVICE_NAME: dofek-web OTEL_RESOURCE_ATTRIBUTES: deployment.environment=${DEPLOY_ENVIRONMENT:-production} @@ -96,7 +96,7 @@ services: NODE_ENV: production JOB_FILES_DIR: /app/job-files DATABASE_URL: postgres://health:${POSTGRES_PASSWORD}@db:5432/health - CLICKHOUSE_URL: http://default:${CLICKHOUSE_PASSWORD:?CLICKHOUSE_PASSWORD is required}@clickhouse:8123 + CLICKHOUSE_URL: http://default:${CLICKHOUSE_PASSWORD_ENCODED:?CLICKHOUSE_PASSWORD_ENCODED is required}@clickhouse:8123 REDIS_URL: redis://redis:6379 OTEL_SERVICE_NAME: dofek-worker OTEL_RESOURCE_ATTRIBUTES: deployment.environment=${DEPLOY_ENVIRONMENT:-production} diff --git a/docs/production-incident-baseline.md b/docs/production-incident-baseline.md index 42212c038c..35d3953749 100644 --- a/docs/production-incident-baseline.md +++ b/docs/production-incident-baseline.md @@ -1810,3 +1810,30 @@ not receive raw historic metric samples through `postgres_fitness.metric_stream` The real fix still requires an offline maintenance job to backfill stable row IDs, add the Timescale-compatible primary key, and then re-enable raw ClickHouse replication. + +### Stack Deploy Follow-up Evidence + +After the migration cleanup deployed, the `Run migrations` step succeeded, but +`docker stack deploy` rolled back `dofek_worker`: + +```text +service rollback paused: update paused due to failure or early termination of task +``` + +Worker logs showed the first fatal app line: + +```text +[migrate] Error: ClickHouse URL is malformed. Expected format: http[s]://[username:password@]hostname:port[/database][?param1=value1¶m2=value2] +``` + +The migration container already URL-encoded `CLICKHOUSE_PASSWORD` before +constructing `CLICKHOUSE_URL`; the normal app services interpolated the raw +password into `deploy/stack.yml`, so reserved URL characters in the password +made the app `CLICKHOUSE_URL` invalid. + +### Stack Deploy Follow-up Fix + +The deploy workflow now exports `CLICKHOUSE_PASSWORD_ENCODED` once after the +Infisical dotenv file is available. `deploy/stack.yml` uses that encoded value +for `web` and `worker` `CLICKHOUSE_URL` interpolation, while the ClickHouse +service still receives the raw `CLICKHOUSE_PASSWORD`. From d0623505140e72173c925e94525127a16be67e31 Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Thu, 30 Apr 2026 16:42:33 -0700 Subject: [PATCH 17/36] Bound stack deploy wait during rollout --- .github/workflows/deploy-web-stack.yml | 11 ++++++++++- deploy/README.md | 2 +- docs/production-incident-baseline.md | 20 ++++++++++++++++++++ 3 files changed, 31 insertions(+), 2 deletions(-) diff --git a/.github/workflows/deploy-web-stack.yml b/.github/workflows/deploy-web-stack.yml index 455c138135..29463bff2e 100644 --- a/.github/workflows/deploy-web-stack.yml +++ b/.github/workflows/deploy-web-stack.yml @@ -416,7 +416,16 @@ jobs: env: IMAGE_TAG: ${{ steps.resolve.outputs.tag }} run: | - node "$RUNNER_TEMP/run-with-dotenv-env.mjs" docker stack deploy -c deploy/stack.yml --with-registry-auth --prune --detach=false "$STACK_NAME" + set +e + timeout 20m node "$RUNNER_TEMP/run-with-dotenv-env.mjs" docker stack deploy -c deploy/stack.yml --with-registry-auth --prune --detach=false "$STACK_NAME" + status=$? + set -e + if [ "$status" -eq 124 ]; then + echo "::error::docker stack deploy exceeded 20m" + fi + if [ "$status" -ne 0 ]; then + exit "$status" + fi - name: Plan materialized view sync id: view_sync_plan diff --git a/deploy/README.md b/deploy/README.md index ff7704f087..fece1fd5be 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -138,7 +138,7 @@ CI (main) -> build dofek + dofek-ml (same tag) When `CLICKHOUSE_URL` is present, this also runs tracked ClickHouse analytics migrations before the stack update. 8. Validate required host bind-mount directories before deploying the stack. This must fail before `docker stack deploy` if paths such as `/mnt/dofek-data/redis` are missing, because Swarm rejects tasks with missing bind sources. - 9. `docker stack deploy -c deploy/stack.yml --with-registry-auth --prune --detach=false dofek` — swarm performs a single stack-wide update, including `training-export-worker`, and CI waits for the rollout to converge before continuing. + 9. `docker stack deploy -c deploy/stack.yml --with-registry-auth --prune --detach=false dofek` — swarm performs a single stack-wide update, including `training-export-worker`, and CI waits for the rollout to converge before continuing. The deploy workflow bounds this wait at 20 minutes so a wedged Swarm rollback fails CI instead of running indefinitely. The workflow parses the Infisical dotenv file inside a child process for stack interpolation. Do not append the full dotenv file to `GITHUB_ENV`; GitHub Actions prints step environments and can expose Infisical-only secrets that GitHub does not automatically mask. 10. Run the materialized-view sync planner. It triggers the refresh webhook only when one of these is true: - a canonical `drizzle/_views/*.sql` hash changed diff --git a/docs/production-incident-baseline.md b/docs/production-incident-baseline.md index 35d3953749..a648c13710 100644 --- a/docs/production-incident-baseline.md +++ b/docs/production-incident-baseline.md @@ -1837,3 +1837,23 @@ The deploy workflow now exports `CLICKHOUSE_PASSWORD_ENCODED` once after the Infisical dotenv file is available. `deploy/stack.yml` uses that encoded value for `web` and `worker` `CLICKHOUSE_URL` interpolation, while the ClickHouse service still receives the raw `CLICKHOUSE_PASSWORD`. + +### Stack Rollout Recovery Evidence + +After the encoded password fix, production migrations succeeded and `dofek_web` +updated to `sha-0d4aa69`, but the GitHub Actions `docker stack deploy +--detach=false` process remained stuck. Live Swarm state showed `dofek_worker` +had rolled back to the older `sha-7af8b2f` service spec, where +`CLICKHOUSE_URL` still contained the raw password. That rollback target +crash-looped with the same malformed ClickHouse URL error, leaving the worker at +`0/1` while the deploy step waited indefinitely. + +### Stack Rollout Recovery Fix + +Recovered `dofek_worker` to the committed `sha-0d4aa69` image with the same +URL-encoded `CLICKHOUSE_URL` already present on the healthy `dofek_web` service. +After recovery, Swarm reported `dofek_web` `2/2`, `dofek_worker` `1/1`, and +`dofek_training-export-worker` `1/1`; `/healthz` returned `{"status":"ok"}`. +The deploy workflow now wraps `docker stack deploy --detach=false` in a +20-minute timeout so a future wedged rollout hard-fails with an explicit error +instead of leaving the job running indefinitely. From 3c0bfb94982dea03eb8acacfa57eb15d0c8dee55 Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Thu, 30 Apr 2026 19:32:29 -0700 Subject: [PATCH 18/36] Guard web deploy rollbacks --- .github/workflows/deploy-web-stack.yml | 33 ++++++++++++++++- docs/production-incident-baseline.md | 51 ++++++++++++++++++++++++++ 2 files changed, 82 insertions(+), 2 deletions(-) diff --git a/.github/workflows/deploy-web-stack.yml b/.github/workflows/deploy-web-stack.yml index 29463bff2e..9d6fc665eb 100644 --- a/.github/workflows/deploy-web-stack.yml +++ b/.github/workflows/deploy-web-stack.yml @@ -330,9 +330,18 @@ jobs: sleep 5 done - - name: Apply ClickHouse resource limits + - name: Ensure ClickHouse resource limits run: | - docker service update --limit-memory 2G "${STACK_NAME}_clickhouse" + desired_limit_bytes=2147483648 + current_limit_bytes="$( + docker service inspect "${STACK_NAME}_clickhouse" \ + --format '{{.Spec.TaskTemplate.Resources.Limits.MemoryBytes}}' + )" + if [ "$current_limit_bytes" = "$desired_limit_bytes" ]; then + echo "ClickHouse memory limit is already 2G." + else + docker service update --limit-memory 2G "${STACK_NAME}_clickhouse" + fi - name: Wait for ClickHouse after resource update run: | @@ -427,6 +436,26 @@ jobs: exit "$status" fi + for service in web worker training-export-worker; do + service_name="${STACK_NAME}_${service}" + update_state="$( + docker service inspect "$service_name" \ + --format '{{if .UpdateStatus}}{{.UpdateStatus.State}}{{end}}' + )" + image="$( + docker service inspect "$service_name" \ + --format '{{.Spec.TaskTemplate.ContainerSpec.Image}}' + )" + echo "${service_name} image=${image} update_state=${update_state:-none}" + case "$update_state" in + rollback_*|paused) + docker service ps "$service_name" --no-trunc + echo "::error::${service_name} did not finish deployment cleanly; update_state=${update_state}" + exit 1 + ;; + esac + done + - name: Plan materialized view sync id: view_sync_plan env: diff --git a/docs/production-incident-baseline.md b/docs/production-incident-baseline.md index a648c13710..eba223a0a9 100644 --- a/docs/production-incident-baseline.md +++ b/docs/production-incident-baseline.md @@ -1857,3 +1857,54 @@ After recovery, Swarm reported `dofek_web` `2/2`, `dofek_worker` `1/1`, and The deploy workflow now wraps `docker stack deploy --detach=false` in a 20-minute timeout so a future wedged rollout hard-fails with an explicit error instead of leaving the job running indefinitely. + +## 2026-05-01: Web Deploy Retry Reported Success After Worker Rollback + +### Symptoms + +A manual retry of the web deploy workflow completed with a successful GitHub +Actions conclusion, but live Swarm state showed `dofek_worker` had rolled back +while `dofek_web` updated to the newly built image digest for the same +`sha-d062350` tag. + +### User Impact + +The public web health check stayed healthy, and a worker task remained running +after rollback. The deploy result was still misleading because one required app +service did not finish the rollout cleanly. + +### Evidence + +`dofek_worker` update status was `rollback_completed`. Worker logs showed the +first fatal line during startup: + +```text +[migrate] Error: connect ECONNREFUSED 10.0.1.8:8123 +``` + +The same deploy run showed ClickHouse being restarted shortly before app +service rollout because the workflow unconditionally ran: + +```text +docker service update --limit-memory 2G dofek_clickhouse +``` + +### Root Cause + +The deploy workflow restarted ClickHouse on every run even when the desired 2G +memory limit was already set, creating an avoidable ClickHouse availability +blip before app service rollout. `docker stack deploy --detach=false` then +returned success even though `dofek_worker` rolled back. + +### Fix + +Changed the deploy workflow to inspect the current ClickHouse memory limit and +only run `docker service update --limit-memory 2G` when it differs. Added a +post-stack-deploy check that inspects required app services and hard-fails if +any required service reports a rollback or paused update state. + +### Remaining Risk + +The worker's startup path still depends on ClickHouse being reachable while it +runs migrations. Future deploys should now avoid the self-inflicted ClickHouse +restart and should fail loudly if a required service rolls back anyway. From 1b325f3a36f24c3920509b79030ae30822db9d52 Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Thu, 30 Apr 2026 19:58:20 -0700 Subject: [PATCH 19/36] Backfill metric stream primary key --- deploy/README.md | 2 +- docs/clickhouse-metric-stream.md | 13 +- ..._metric_stream_id_not_null_primary_key.sql | 127 ++++++++++++++++++ ...tream-replica-identity.integration.test.ts | 47 ++++++- src/db/migrate.integration.test.ts | 25 +++- 5 files changed, 200 insertions(+), 14 deletions(-) create mode 100644 drizzle/0009_metric_stream_id_not_null_primary_key.sql diff --git a/deploy/README.md b/deploy/README.md index fece1fd5be..3d7251de8d 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -9,7 +9,7 @@ Dofek is deployed as a **single-node Docker Swarm** stack on **Hetzner Cloud** ( - **Compute**: Hetzner Cloud `cax11` ARM64 servers running Ubuntu 24.04. Production uses `dofek`; staging uses `dofek-staging`. Each server runs `dockerd` initialized as a single-node swarm manager and has no deploy scripts or secrets on disk. - **Storage**: - **PostgreSQL**: Managed via TimescaleDB (running in the swarm). - - **ClickHouse**: Runs in the swarm as the stored analytics read-model service for heavy activity stream reads. Raw `metric_stream` replication is temporarily disabled behind a local placeholder until the historic Timescale table has a stable primary key. See [docs/clickhouse-metric-stream.md](../docs/clickhouse-metric-stream.md). + - **ClickHouse**: Runs in the swarm as the stored analytics read-model service for heavy activity stream reads. Raw `metric_stream` replication is temporarily disabled behind a local placeholder; re-enable it only through the tracked ClickHouse migration path after the Postgres primary key migration has landed. See [docs/clickhouse-metric-stream.md](../docs/clickhouse-metric-stream.md). - **Volume**: Terraform provisions a Hetzner Block Storage volume (`data_volume_size_gb`, default `100GB`) attached with `automount=true`. - **Stable mount alias**: Terraform maintains `/mnt/dofek-data` as a symlink to the attached Hetzner volume mount path (`/mnt/HC_Volume_`). - **DB data path**: The `db` service bind-mounts Postgres data to `/mnt/dofek-data/postgres`. diff --git a/docs/clickhouse-metric-stream.md b/docs/clickhouse-metric-stream.md index 26172b720d..59a6f885a5 100644 --- a/docs/clickhouse-metric-stream.md +++ b/docs/clickhouse-metric-stream.md @@ -2,16 +2,18 @@ `fitness.metric_stream` remains canonical in Postgres/Timescale. ClickHouse currently uses an empty local `postgres_fitness.metric_stream` placeholder while -the historic Postgres table is missing a primary key. The stored +the raw metric stream replication path is disabled. Migration +`drizzle/0009_metric_stream_id_not_null_primary_key.sql` backfills stable row +IDs and adds the Timescale-compatible `(id, recorded_at)` primary key. The stored `analytics.deduped_sensor` and `analytics.activity_summary` refreshable materialized views remain in place so the schema is stable, but raw metric rows -are not replicated into ClickHouse until a separate offline backfill adds stable -row IDs and a primary key. +are not replicated into ClickHouse until a separate change re-enables the +MaterializedPostgreSQL source. ```text Postgres/Timescale fitness.metric_stream | - | offline ID backfill + PK still required + | raw MaterializedPostgreSQL replication still disabled v ClickHouse postgres_fitness.metric_stream placeholder | @@ -64,7 +66,8 @@ ClickHouse migrations create and update the databases and read models: - `postgres_fitness.metric_stream`: an empty local MergeTree placeholder for the raw metric stream. This intentionally does not use `MaterializedPostgreSQL` - until the Postgres hypertable has a stable primary key. + until the replication path is explicitly re-enabled after the Postgres primary + key migration has landed. - `postgres_fitness_live`: a PostgreSQL database bridge for scalar-only views in the Postgres `clickhouse` schema: `clickhouse.v_activity` and `clickhouse.v_activity_members`. diff --git a/drizzle/0009_metric_stream_id_not_null_primary_key.sql b/drizzle/0009_metric_stream_id_not_null_primary_key.sql new file mode 100644 index 0000000000..c1d608ada1 --- /dev/null +++ b/drizzle/0009_metric_stream_id_not_null_primary_key.sql @@ -0,0 +1,127 @@ +CREATE EXTENSION IF NOT EXISTS pgcrypto WITH SCHEMA public; +--> statement-breakpoint +ALTER TABLE fitness.metric_stream +ADD COLUMN IF NOT EXISTS id uuid; +--> statement-breakpoint +ALTER TABLE fitness.metric_stream +ALTER COLUMN id SET DEFAULT gen_random_uuid(); +--> statement-breakpoint +CREATE OR REPLACE PROCEDURE fitness.backfill_metric_stream_ids(batch_size integer DEFAULT 50000) +LANGUAGE plpgsql +AS $$ +DECLARE + chunk_count integer; + current_chunk_index integer := 1; + chunk_start timestamptz; + chunk_end timestamptz; + updated_count integer; +BEGIN + IF batch_size < 1 THEN + RAISE EXCEPTION 'batch_size must be greater than zero'; + END IF; + + PERFORM set_config('lock_timeout', '5s', false); + PERFORM set_config('statement_timeout', '0', false); + + DROP TABLE IF EXISTS pg_temp.metric_stream_backfill_chunks; + CREATE TEMPORARY TABLE pg_temp.metric_stream_backfill_chunks ON COMMIT PRESERVE ROWS AS + SELECT + row_number() OVER (ORDER BY range_start NULLS FIRST, range_end NULLS LAST)::integer AS chunk_index, + range_start::timestamptz AS range_start, + range_end::timestamptz AS range_end + FROM timescaledb_information.chunks + WHERE hypertable_schema = 'fitness' + AND hypertable_name = 'metric_stream'; + + IF NOT EXISTS (SELECT 1 FROM pg_temp.metric_stream_backfill_chunks) THEN + INSERT INTO pg_temp.metric_stream_backfill_chunks (chunk_index, range_start, range_end) + VALUES (1, NULL, NULL); + END IF; + + SELECT count(*)::integer INTO chunk_count + FROM pg_temp.metric_stream_backfill_chunks; + + WHILE current_chunk_index <= chunk_count LOOP + SELECT range_start, range_end + INTO chunk_start, chunk_end + FROM pg_temp.metric_stream_backfill_chunks + WHERE metric_stream_backfill_chunks.chunk_index = current_chunk_index; + + LOOP + IF chunk_start IS NULL OR chunk_end IS NULL THEN + WITH target_rows AS ( + SELECT tableoid, ctid + FROM fitness.metric_stream + WHERE id IS NULL + LIMIT batch_size + ) + UPDATE fitness.metric_stream AS metric_stream + SET id = gen_random_uuid() + FROM target_rows + WHERE metric_stream.tableoid = target_rows.tableoid + AND metric_stream.ctid = target_rows.ctid; + ELSE + WITH target_rows AS ( + SELECT tableoid, ctid + FROM fitness.metric_stream + WHERE id IS NULL + AND recorded_at >= chunk_start + AND recorded_at < chunk_end + LIMIT batch_size + ) + UPDATE fitness.metric_stream AS metric_stream + SET id = gen_random_uuid() + FROM target_rows + WHERE metric_stream.tableoid = target_rows.tableoid + AND metric_stream.ctid = target_rows.ctid; + END IF; + + GET DIAGNOSTICS updated_count = ROW_COUNT; + RAISE NOTICE 'metric_stream id backfill chunk %/% updated % rows', current_chunk_index, chunk_count, updated_count; + COMMIT; + + EXIT WHEN updated_count = 0; + END LOOP; + + current_chunk_index := current_chunk_index + 1; + END LOOP; +END; +$$; +--> statement-breakpoint +CALL fitness.backfill_metric_stream_ids(50000); +--> statement-breakpoint +DROP PROCEDURE fitness.backfill_metric_stream_ids(integer); +--> statement-breakpoint +RESET lock_timeout; +--> statement-breakpoint +RESET statement_timeout; +--> statement-breakpoint +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 + FROM fitness.metric_stream + WHERE id IS NULL + LIMIT 1 + ) THEN + RAISE EXCEPTION 'fitness.metric_stream.id backfill incomplete: NULL ids remain'; + END IF; +END; +$$; +--> statement-breakpoint +ALTER TABLE fitness.metric_stream +ALTER COLUMN id SET NOT NULL; +--> statement-breakpoint +DO $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM pg_constraint + WHERE conrelid = 'fitness.metric_stream'::regclass + AND contype = 'p' + ) THEN + ALTER TABLE fitness.metric_stream + ADD CONSTRAINT metric_stream_pkey PRIMARY KEY (id, recorded_at); + END IF; +END; +$$; diff --git a/src/db/metric-stream-replica-identity.integration.test.ts b/src/db/metric-stream-replica-identity.integration.test.ts index dbcd740b1e..c884b745c3 100644 --- a/src/db/metric-stream-replica-identity.integration.test.ts +++ b/src/db/metric-stream-replica-identity.integration.test.ts @@ -45,10 +45,12 @@ describe("metric_stream replica identity migration", () => { } }); - it("adds an ID default and full replica identity without backfilling historic rows", async () => { + it("adds replica identity first, then backfills metric stream IDs and adds the primary key", async () => { const client = new Client({ connectionString }); await client.connect(); try { + await client.query("DROP SCHEMA IF EXISTS drizzle CASCADE"); + await client.query("DROP SCHEMA IF EXISTS fitness CASCADE"); await client.query("CREATE EXTENSION IF NOT EXISTS timescaledb"); await client.query("CREATE EXTENSION IF NOT EXISTS pgcrypto"); await client.query("CREATE SCHEMA IF NOT EXISTS fitness"); @@ -139,6 +141,49 @@ describe("metric_stream replica identity migration", () => { expect(insertedResult.rows[0]?.generated_id).toMatch( /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/, ); + + const primaryKeyMigrationContent = readFileSync( + join(import.meta.dirname, "../../drizzle/0009_metric_stream_id_not_null_primary_key.sql"), + "utf-8", + ); + writeFileSync( + join(tmpDir, "0009_metric_stream_id_not_null_primary_key.sql"), + primaryKeyMigrationContent, + ); + + const primaryKeyMigrationCount = await runMigrations(connectionString, tmpDir); + expect(primaryKeyMigrationCount).toBe(1); + + const backfilledResult = await client.query<{ missing_id_count: string }>( + "SELECT count(*) AS missing_id_count FROM fitness.metric_stream WHERE id IS NULL", + ); + expect(backfilledResult.rows).toEqual([{ missing_id_count: "0" }]); + + const nonNullableResult = await client.query<{ is_nullable: "YES" | "NO" }>(` + SELECT is_nullable + FROM information_schema.columns + WHERE table_schema = 'fitness' + AND table_name = 'metric_stream' + AND column_name = 'id' + `); + expect(nonNullableResult.rows).toEqual([{ is_nullable: "NO" }]); + + const finalPrimaryKeyResult = await client.query<{ + constraint_name: string; + columns: string; + }>(` + SELECT + constraint_name, + string_agg(column_name, ',' ORDER BY ordinal_position) AS columns + FROM information_schema.key_column_usage + WHERE table_schema = 'fitness' + AND table_name = 'metric_stream' + AND constraint_name = 'metric_stream_pkey' + GROUP BY constraint_name + `); + expect(finalPrimaryKeyResult.rows).toEqual([ + { constraint_name: "metric_stream_pkey", columns: "id,recorded_at" }, + ]); } finally { await client.end(); } diff --git a/src/db/migrate.integration.test.ts b/src/db/migrate.integration.test.ts index 285f3e6197..f38acb8d20 100644 --- a/src/db/migrate.integration.test.ts +++ b/src/db/migrate.integration.test.ts @@ -94,7 +94,7 @@ describe("runMigrations", () => { expect(count).toBe(1); }); - it("gives metric_stream full replica identity without a deploy-time primary key backfill", async () => { + it("gives metric_stream full replica identity and a Timescale-compatible primary key", async () => { const client = new Client({ connectionString: ctx.connectionString }); await client.connect(); try { @@ -109,13 +109,24 @@ describe("runMigrations", () => { ); expect(replicaIdentityResult.rows).toEqual([{ replica_identity: "f" }]); - const primaryKeyResult = await client.query<{ primary_key_count: string }>(` - SELECT count(*) AS primary_key_count - FROM pg_constraint - WHERE conrelid = 'fitness.metric_stream'::regclass - AND contype = 'p' + const nullableResult = await client.query<{ is_nullable: "YES" | "NO" }>(` + SELECT is_nullable + FROM information_schema.columns + WHERE table_schema = 'fitness' + AND table_name = 'metric_stream' + AND column_name = 'id' `); - expect(primaryKeyResult.rows).toEqual([{ primary_key_count: "0" }]); + expect(nullableResult.rows).toEqual([{ is_nullable: "NO" }]); + + const primaryKeyResult = await client.query<{ columns: string }>(` + SELECT string_agg(column_name, ',' ORDER BY ordinal_position) AS columns + FROM information_schema.key_column_usage + WHERE table_schema = 'fitness' + AND table_name = 'metric_stream' + AND constraint_name = 'metric_stream_pkey' + GROUP BY constraint_name + `); + expect(primaryKeyResult.rows).toEqual([{ columns: "id,recorded_at" }]); } finally { await client.end(); } From 25ceec55ff79575a2ee507905e82646ba5f3b8e4 Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Thu, 30 Apr 2026 20:18:36 -0700 Subject: [PATCH 20/36] Handle compressed metric stream backfill --- ..._metric_stream_id_not_null_primary_key.sql | 84 +++++++++++-------- ...tream-replica-identity.integration.test.ts | 16 ++++ 2 files changed, 65 insertions(+), 35 deletions(-) diff --git a/drizzle/0009_metric_stream_id_not_null_primary_key.sql b/drizzle/0009_metric_stream_id_not_null_primary_key.sql index c1d608ada1..a7eb72d017 100644 --- a/drizzle/0009_metric_stream_id_not_null_primary_key.sql +++ b/drizzle/0009_metric_stream_id_not_null_primary_key.sql @@ -14,6 +14,7 @@ DECLARE current_chunk_index integer := 1; chunk_start timestamptz; chunk_end timestamptz; + current_chunk_is_compressed boolean; updated_count integer; BEGIN IF batch_size < 1 THEN @@ -28,60 +29,73 @@ BEGIN SELECT row_number() OVER (ORDER BY range_start NULLS FIRST, range_end NULLS LAST)::integer AS chunk_index, range_start::timestamptz AS range_start, - range_end::timestamptz AS range_end + range_end::timestamptz AS range_end, + is_compressed FROM timescaledb_information.chunks WHERE hypertable_schema = 'fitness' AND hypertable_name = 'metric_stream'; IF NOT EXISTS (SELECT 1 FROM pg_temp.metric_stream_backfill_chunks) THEN - INSERT INTO pg_temp.metric_stream_backfill_chunks (chunk_index, range_start, range_end) - VALUES (1, NULL, NULL); + INSERT INTO pg_temp.metric_stream_backfill_chunks (chunk_index, range_start, range_end, is_compressed) + VALUES (1, NULL, NULL, false); END IF; SELECT count(*)::integer INTO chunk_count FROM pg_temp.metric_stream_backfill_chunks; WHILE current_chunk_index <= chunk_count LOOP - SELECT range_start, range_end - INTO chunk_start, chunk_end + SELECT range_start, range_end, is_compressed + INTO chunk_start, chunk_end, current_chunk_is_compressed FROM pg_temp.metric_stream_backfill_chunks WHERE metric_stream_backfill_chunks.chunk_index = current_chunk_index; - LOOP - IF chunk_start IS NULL OR chunk_end IS NULL THEN - WITH target_rows AS ( - SELECT tableoid, ctid - FROM fitness.metric_stream - WHERE id IS NULL - LIMIT batch_size - ) - UPDATE fitness.metric_stream AS metric_stream - SET id = gen_random_uuid() - FROM target_rows - WHERE metric_stream.tableoid = target_rows.tableoid - AND metric_stream.ctid = target_rows.ctid; - ELSE - WITH target_rows AS ( - SELECT tableoid, ctid - FROM fitness.metric_stream - WHERE id IS NULL - AND recorded_at >= chunk_start - AND recorded_at < chunk_end - LIMIT batch_size - ) - UPDATE fitness.metric_stream AS metric_stream - SET id = gen_random_uuid() - FROM target_rows - WHERE metric_stream.tableoid = target_rows.tableoid - AND metric_stream.ctid = target_rows.ctid; - END IF; + IF current_chunk_is_compressed THEN + UPDATE fitness.metric_stream + SET id = gen_random_uuid() + WHERE id IS NULL + AND recorded_at >= chunk_start + AND recorded_at < chunk_end; GET DIAGNOSTICS updated_count = ROW_COUNT; RAISE NOTICE 'metric_stream id backfill chunk %/% updated % rows', current_chunk_index, chunk_count, updated_count; COMMIT; + ELSE + LOOP + IF chunk_start IS NULL OR chunk_end IS NULL THEN + WITH target_rows AS ( + SELECT tableoid, ctid + FROM fitness.metric_stream + WHERE id IS NULL + LIMIT batch_size + ) + UPDATE fitness.metric_stream AS metric_stream + SET id = gen_random_uuid() + FROM target_rows + WHERE metric_stream.tableoid = target_rows.tableoid + AND metric_stream.ctid = target_rows.ctid; + ELSE + WITH target_rows AS ( + SELECT tableoid, ctid + FROM fitness.metric_stream + WHERE id IS NULL + AND recorded_at >= chunk_start + AND recorded_at < chunk_end + LIMIT batch_size + ) + UPDATE fitness.metric_stream AS metric_stream + SET id = gen_random_uuid() + FROM target_rows + WHERE metric_stream.tableoid = target_rows.tableoid + AND metric_stream.ctid = target_rows.ctid; + END IF; - EXIT WHEN updated_count = 0; - END LOOP; + GET DIAGNOSTICS updated_count = ROW_COUNT; + RAISE NOTICE 'metric_stream id backfill chunk %/% updated % rows', current_chunk_index, chunk_count, updated_count; + COMMIT; + + EXIT WHEN updated_count = 0; + END LOOP; + END IF; current_chunk_index := current_chunk_index + 1; END LOOP; diff --git a/src/db/metric-stream-replica-identity.integration.test.ts b/src/db/metric-stream-replica-identity.integration.test.ts index c884b745c3..94b1793cfe 100644 --- a/src/db/metric-stream-replica-identity.integration.test.ts +++ b/src/db/metric-stream-replica-identity.integration.test.ts @@ -142,6 +142,22 @@ describe("metric_stream replica identity migration", () => { /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/, ); + await client.query(` + SELECT compress_chunk(format('%I.%I', chunk_schema, chunk_name)::regclass, if_not_compressed => true) + FROM timescaledb_information.chunks + WHERE hypertable_schema = 'fitness' + AND hypertable_name = 'metric_stream' + `); + + const compressedChunkResult = await client.query<{ compressed_chunk_count: string }>(` + SELECT count(*) AS compressed_chunk_count + FROM timescaledb_information.chunks + WHERE hypertable_schema = 'fitness' + AND hypertable_name = 'metric_stream' + AND is_compressed + `); + expect(compressedChunkResult.rows).toEqual([{ compressed_chunk_count: "1" }]); + const primaryKeyMigrationContent = readFileSync( join(import.meta.dirname, "../../drizzle/0009_metric_stream_id_not_null_primary_key.sql"), "utf-8", From 1c906458979d2aaffc7d5d8998ac19f219499ad8 Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Thu, 30 Apr 2026 20:32:41 -0700 Subject: [PATCH 21/36] Allow compressed metric stream backfill --- drizzle/0009_metric_stream_id_not_null_primary_key.sql | 3 +++ 1 file changed, 3 insertions(+) diff --git a/drizzle/0009_metric_stream_id_not_null_primary_key.sql b/drizzle/0009_metric_stream_id_not_null_primary_key.sql index a7eb72d017..f3f69e037e 100644 --- a/drizzle/0009_metric_stream_id_not_null_primary_key.sql +++ b/drizzle/0009_metric_stream_id_not_null_primary_key.sql @@ -23,6 +23,7 @@ BEGIN PERFORM set_config('lock_timeout', '5s', false); PERFORM set_config('statement_timeout', '0', false); + PERFORM set_config('timescaledb.max_tuples_decompressed_per_dml_transaction', '0', false); DROP TABLE IF EXISTS pg_temp.metric_stream_backfill_chunks; CREATE TEMPORARY TABLE pg_temp.metric_stream_backfill_chunks ON COMMIT PRESERVE ROWS AS @@ -110,6 +111,8 @@ RESET lock_timeout; --> statement-breakpoint RESET statement_timeout; --> statement-breakpoint +RESET timescaledb.max_tuples_decompressed_per_dml_transaction; +--> statement-breakpoint DO $$ BEGIN IF EXISTS ( From 01a25fb350895839a83edd53156abb25ba7b2387 Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Thu, 30 Apr 2026 21:40:57 -0700 Subject: [PATCH 22/36] Backfill metric stream chunks resumably --- ..._metric_stream_id_not_null_primary_key.sql | 96 ++++++++++--------- 1 file changed, 50 insertions(+), 46 deletions(-) diff --git a/drizzle/0009_metric_stream_id_not_null_primary_key.sql b/drizzle/0009_metric_stream_id_not_null_primary_key.sql index f3f69e037e..dace642352 100644 --- a/drizzle/0009_metric_stream_id_not_null_primary_key.sql +++ b/drizzle/0009_metric_stream_id_not_null_primary_key.sql @@ -12,9 +12,10 @@ AS $$ DECLARE chunk_count integer; current_chunk_index integer := 1; + current_chunk_regclass regclass; chunk_start timestamptz; chunk_end timestamptz; - current_chunk_is_compressed boolean; + should_compress_after boolean; updated_count integer; BEGIN IF batch_size < 1 THEN @@ -29,73 +30,76 @@ BEGIN CREATE TEMPORARY TABLE pg_temp.metric_stream_backfill_chunks ON COMMIT PRESERVE ROWS AS SELECT row_number() OVER (ORDER BY range_start NULLS FIRST, range_end NULLS LAST)::integer AS chunk_index, + format('%I.%I', chunk_schema, chunk_name)::regclass AS chunk_regclass, range_start::timestamptz AS range_start, range_end::timestamptz AS range_end, - is_compressed + (range_end < now() - INTERVAL '7 days') AS should_compress_after FROM timescaledb_information.chunks WHERE hypertable_schema = 'fitness' AND hypertable_name = 'metric_stream'; IF NOT EXISTS (SELECT 1 FROM pg_temp.metric_stream_backfill_chunks) THEN - INSERT INTO pg_temp.metric_stream_backfill_chunks (chunk_index, range_start, range_end, is_compressed) - VALUES (1, NULL, NULL, false); + INSERT INTO pg_temp.metric_stream_backfill_chunks (chunk_index, chunk_regclass, range_start, range_end, should_compress_after) + VALUES (1, NULL, NULL, NULL, false); END IF; SELECT count(*)::integer INTO chunk_count FROM pg_temp.metric_stream_backfill_chunks; WHILE current_chunk_index <= chunk_count LOOP - SELECT range_start, range_end, is_compressed - INTO chunk_start, chunk_end, current_chunk_is_compressed + SELECT + metric_stream_backfill_chunks.chunk_regclass, + metric_stream_backfill_chunks.range_start, + metric_stream_backfill_chunks.range_end, + metric_stream_backfill_chunks.should_compress_after + INTO current_chunk_regclass, chunk_start, chunk_end, should_compress_after FROM pg_temp.metric_stream_backfill_chunks WHERE metric_stream_backfill_chunks.chunk_index = current_chunk_index; - IF current_chunk_is_compressed THEN - UPDATE fitness.metric_stream - SET id = gen_random_uuid() - WHERE id IS NULL - AND recorded_at >= chunk_start - AND recorded_at < chunk_end; + IF current_chunk_regclass IS NOT NULL THEN + PERFORM decompress_chunk(current_chunk_regclass, if_compressed => true); + COMMIT; + END IF; + + LOOP + IF chunk_start IS NULL OR chunk_end IS NULL THEN + WITH target_rows AS ( + SELECT tableoid, ctid + FROM fitness.metric_stream + WHERE id IS NULL + LIMIT batch_size + ) + UPDATE fitness.metric_stream AS metric_stream + SET id = gen_random_uuid() + FROM target_rows + WHERE metric_stream.tableoid = target_rows.tableoid + AND metric_stream.ctid = target_rows.ctid; + ELSE + WITH target_rows AS ( + SELECT tableoid, ctid + FROM fitness.metric_stream + WHERE id IS NULL + AND recorded_at >= chunk_start + AND recorded_at < chunk_end + LIMIT batch_size + ) + UPDATE fitness.metric_stream AS metric_stream + SET id = gen_random_uuid() + FROM target_rows + WHERE metric_stream.tableoid = target_rows.tableoid + AND metric_stream.ctid = target_rows.ctid; + END IF; GET DIAGNOSTICS updated_count = ROW_COUNT; RAISE NOTICE 'metric_stream id backfill chunk %/% updated % rows', current_chunk_index, chunk_count, updated_count; COMMIT; - ELSE - LOOP - IF chunk_start IS NULL OR chunk_end IS NULL THEN - WITH target_rows AS ( - SELECT tableoid, ctid - FROM fitness.metric_stream - WHERE id IS NULL - LIMIT batch_size - ) - UPDATE fitness.metric_stream AS metric_stream - SET id = gen_random_uuid() - FROM target_rows - WHERE metric_stream.tableoid = target_rows.tableoid - AND metric_stream.ctid = target_rows.ctid; - ELSE - WITH target_rows AS ( - SELECT tableoid, ctid - FROM fitness.metric_stream - WHERE id IS NULL - AND recorded_at >= chunk_start - AND recorded_at < chunk_end - LIMIT batch_size - ) - UPDATE fitness.metric_stream AS metric_stream - SET id = gen_random_uuid() - FROM target_rows - WHERE metric_stream.tableoid = target_rows.tableoid - AND metric_stream.ctid = target_rows.ctid; - END IF; - GET DIAGNOSTICS updated_count = ROW_COUNT; - RAISE NOTICE 'metric_stream id backfill chunk %/% updated % rows', current_chunk_index, chunk_count, updated_count; - COMMIT; + EXIT WHEN updated_count = 0; + END LOOP; - EXIT WHEN updated_count = 0; - END LOOP; + IF current_chunk_regclass IS NOT NULL AND should_compress_after THEN + PERFORM compress_chunk(current_chunk_regclass, if_not_compressed => true); + COMMIT; END IF; current_chunk_index := current_chunk_index + 1; From a035a1043e133abc147f2cd9cd02e8a5291db10c Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Thu, 30 Apr 2026 21:55:06 -0700 Subject: [PATCH 23/36] Document metric stream backfill blocker --- docs/production-incident-baseline.md | 48 ++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/docs/production-incident-baseline.md b/docs/production-incident-baseline.md index eba223a0a9..2e93adccc1 100644 --- a/docs/production-incident-baseline.md +++ b/docs/production-incident-baseline.md @@ -1908,3 +1908,51 @@ any required service reports a rollback or paused update state. The worker's startup path still depends on ClickHouse being reachable while it runs migrations. Future deploys should now avoid the self-inflicted ClickHouse restart and should fail loudly if a required service rolls back anyway. + +## 2026-05-01: Metric Stream Primary Key Backfill Remains Unfit for Deploy + +### Symptoms + +Attempts to complete `fitness.metric_stream` ID backfill, `SET NOT NULL`, and +primary-key migration in the production deploy path repeatedly failed or had to +be stopped before completion. + +### Evidence + +The deploy migration path hit three distinct blockers: + +- `transparent decompression only supports tableoid system column` +- `tuple decompression limit exceeded by operation` +- `Migration exceeded 3300s` + +A follow-up manual prod run installed the committed chunked backfill procedure +and started `CALL fitness.backfill_metric_stream_ids(50000);`. After about +eleven minutes it was still inside the first chunk update, producing repeated +WAL checkpoints every roughly 18-23 seconds. The active query was cancelled, +the only old decompressed chunk was recompressed, and production returned to +`190` compressed chunks / `5` uncompressed chunks with no active backfill or +materialized-view refresh sessions. + +### Root Cause + +The historic `metric_stream` table is too large for an in-deploy UUID rewrite, +even when the work is bounded by Timescale chunks. Updating existing rows +rewrites wide historical tuples and indexes, generates heavy WAL, and cannot +complete inside the GitHub Actions migration watchdog. Compressed chunks also +make row-by-row targeting and transparent decompression more constrained than a +regular Postgres table. + +### Fix or Mitigation + +The backfill was cancelled before another deploy timeout. The old decompressed +chunk from the cancelled attempt was recompressed. No primary key was added in +production. + +### Remaining Risk + +Do not deploy the current backfill-and-primary-key migration as-is. If +`metric_stream` is being retired, remove the remaining refresh/read paths and +drop or archive the table through an explicit cleanup migration instead. If the +table must remain, treat the ID rewrite as offline maintenance outside the +normal web deploy workflow and design it with separate WAL, timeout, and disk +headroom controls. From d9b722405a4b68e955248d79f6671fd821c886b5 Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Fri, 1 May 2026 08:49:38 -0700 Subject: [PATCH 24/36] Backfill metric stream ids by chunk table --- docs/production-incident-baseline.md | 12 ++-- ..._metric_stream_id_not_null_primary_key.sql | 63 +++++++++++-------- 2 files changed, 42 insertions(+), 33 deletions(-) diff --git a/docs/production-incident-baseline.md b/docs/production-incident-baseline.md index 2e93adccc1..3317f5a63a 100644 --- a/docs/production-incident-baseline.md +++ b/docs/production-incident-baseline.md @@ -1950,9 +1950,9 @@ production. ### Remaining Risk -Do not deploy the current backfill-and-primary-key migration as-is. If -`metric_stream` is being retired, remove the remaining refresh/read paths and -drop or archive the table through an explicit cleanup migration instead. If the -table must remain, treat the ID rewrite as offline maintenance outside the -normal web deploy workflow and design it with separate WAL, timeout, and disk -headroom controls. +Do not deploy the previous parent-hypertable backfill as-is. `metric_stream` +must stay because ClickHouse replication is blocked on a stable primary key or +replica identity index. Complete the ID rewrite with physical chunk-targeted +maintenance, keep materialized-view refreshes such as `fitness.deduped_sensor` +out of the maintenance window, and then add the Timescale-compatible +`(id, recorded_at)` identity. diff --git a/drizzle/0009_metric_stream_id_not_null_primary_key.sql b/drizzle/0009_metric_stream_id_not_null_primary_key.sql index dace642352..6dfcdec7b6 100644 --- a/drizzle/0009_metric_stream_id_not_null_primary_key.sql +++ b/drizzle/0009_metric_stream_id_not_null_primary_key.sql @@ -13,8 +13,6 @@ DECLARE chunk_count integer; current_chunk_index integer := 1; current_chunk_regclass regclass; - chunk_start timestamptz; - chunk_end timestamptz; should_compress_after boolean; updated_count integer; BEGIN @@ -49,38 +47,17 @@ BEGIN WHILE current_chunk_index <= chunk_count LOOP SELECT metric_stream_backfill_chunks.chunk_regclass, - metric_stream_backfill_chunks.range_start, - metric_stream_backfill_chunks.range_end, metric_stream_backfill_chunks.should_compress_after - INTO current_chunk_regclass, chunk_start, chunk_end, should_compress_after + INTO current_chunk_regclass, should_compress_after FROM pg_temp.metric_stream_backfill_chunks WHERE metric_stream_backfill_chunks.chunk_index = current_chunk_index; - IF current_chunk_regclass IS NOT NULL THEN - PERFORM decompress_chunk(current_chunk_regclass, if_compressed => true); - COMMIT; - END IF; - - LOOP - IF chunk_start IS NULL OR chunk_end IS NULL THEN - WITH target_rows AS ( - SELECT tableoid, ctid - FROM fitness.metric_stream - WHERE id IS NULL - LIMIT batch_size - ) - UPDATE fitness.metric_stream AS metric_stream - SET id = gen_random_uuid() - FROM target_rows - WHERE metric_stream.tableoid = target_rows.tableoid - AND metric_stream.ctid = target_rows.ctid; - ELSE + IF current_chunk_regclass IS NULL THEN + LOOP WITH target_rows AS ( SELECT tableoid, ctid FROM fitness.metric_stream WHERE id IS NULL - AND recorded_at >= chunk_start - AND recorded_at < chunk_end LIMIT batch_size ) UPDATE fitness.metric_stream AS metric_stream @@ -88,7 +65,39 @@ BEGIN FROM target_rows WHERE metric_stream.tableoid = target_rows.tableoid AND metric_stream.ctid = target_rows.ctid; - END IF; + + GET DIAGNOSTICS updated_count = ROW_COUNT; + RAISE NOTICE 'metric_stream id backfill table fallback chunk %/% updated % rows', current_chunk_index, chunk_count, updated_count; + COMMIT; + + EXIT WHEN updated_count = 0; + END LOOP; + + current_chunk_index := current_chunk_index + 1; + CONTINUE; + END IF; + + IF current_chunk_regclass IS NOT NULL THEN + PERFORM decompress_chunk(current_chunk_regclass, if_compressed => true); + COMMIT; + END IF; + + LOOP + EXECUTE format( + 'WITH target_rows AS ( + SELECT ctid + FROM %s + WHERE id IS NULL + LIMIT $1 + ) + UPDATE %s AS metric_stream + SET id = gen_random_uuid() + FROM target_rows + WHERE metric_stream.ctid = target_rows.ctid', + current_chunk_regclass, + current_chunk_regclass + ) + USING batch_size; GET DIAGNOSTICS updated_count = ROW_COUNT; RAISE NOTICE 'metric_stream id backfill chunk %/% updated % rows', current_chunk_index, chunk_count, updated_count; From 5ba814c1d53b60da40990f67619e40b4470224a7 Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Fri, 1 May 2026 09:03:29 -0700 Subject: [PATCH 25/36] Suppress metric stream backfill triggers --- docs/production-incident-baseline.md | 27 +++++++++++++------ ..._metric_stream_id_not_null_primary_key.sql | 7 +++++ 2 files changed, 26 insertions(+), 8 deletions(-) diff --git a/docs/production-incident-baseline.md b/docs/production-incident-baseline.md index 3317f5a63a..9445200f4f 100644 --- a/docs/production-incident-baseline.md +++ b/docs/production-incident-baseline.md @@ -1933,20 +1933,31 @@ the only old decompressed chunk was recompressed, and production returned to `190` compressed chunks / `5` uncompressed chunks with no active backfill or materialized-view refresh sessions. +Later testing against physical chunk +`_timescaledb_internal._hyper_1_118_chunk` showed that the row rewrite itself +was not the only bottleneck. With normal trigger execution, a 50k-row ID-only +update took about 63 seconds and cancellation showed time inside +`analytics.mark_activity_rollup_dirty_from_metric_stream_update()`. With +session-local trigger execution suppressed via `session_replication_role = +replica`, the same 50k-row update took about 2.2 seconds and the remaining +198,250 rows in that test chunk updated in about 6.1 seconds. + ### Root Cause -The historic `metric_stream` table is too large for an in-deploy UUID rewrite, -even when the work is bounded by Timescale chunks. Updating existing rows -rewrites wide historical tuples and indexes, generates heavy WAL, and cannot -complete inside the GitHub Actions migration watchdog. Compressed chunks also -make row-by-row targeting and transparent decompression more constrained than a -regular Postgres table. +The historic `metric_stream` table is too large for an in-deploy UUID rewrite +when the work fires metric-change triggers for every ID-only update. Updating +existing rows rewrites wide historical tuples and indexes, generates WAL, and +cannot complete inside the GitHub Actions migration watchdog when each row also +marks activity rollups dirty. Compressed chunks also make row-by-row targeting +and transparent decompression more constrained than a regular Postgres table. ### Fix or Mitigation The backfill was cancelled before another deploy timeout. The old decompressed -chunk from the cancelled attempt was recompressed. No primary key was added in -production. +chunk from the cancelled attempt was recompressed. The migration was updated to +run the ID-only rewrite with session-local trigger execution disabled, then +restore normal trigger behavior before `SET NOT NULL` and primary-key DDL. No +primary key was added in production yet. ### Remaining Risk diff --git a/drizzle/0009_metric_stream_id_not_null_primary_key.sql b/drizzle/0009_metric_stream_id_not_null_primary_key.sql index 6dfcdec7b6..ed9060c7e1 100644 --- a/drizzle/0009_metric_stream_id_not_null_primary_key.sql +++ b/drizzle/0009_metric_stream_id_not_null_primary_key.sql @@ -13,6 +13,7 @@ DECLARE chunk_count integer; current_chunk_index integer := 1; current_chunk_regclass regclass; + previous_replication_role text; should_compress_after boolean; updated_count integer; BEGIN @@ -23,6 +24,8 @@ BEGIN PERFORM set_config('lock_timeout', '5s', false); PERFORM set_config('statement_timeout', '0', false); PERFORM set_config('timescaledb.max_tuples_decompressed_per_dml_transaction', '0', false); + previous_replication_role := current_setting('session_replication_role'); + PERFORM set_config('session_replication_role', 'replica', false); DROP TABLE IF EXISTS pg_temp.metric_stream_backfill_chunks; CREATE TEMPORARY TABLE pg_temp.metric_stream_backfill_chunks ON COMMIT PRESERVE ROWS AS @@ -113,6 +116,8 @@ BEGIN current_chunk_index := current_chunk_index + 1; END LOOP; + + PERFORM set_config('session_replication_role', previous_replication_role, false); END; $$; --> statement-breakpoint @@ -126,6 +131,8 @@ RESET statement_timeout; --> statement-breakpoint RESET timescaledb.max_tuples_decompressed_per_dml_transaction; --> statement-breakpoint +RESET session_replication_role; +--> statement-breakpoint DO $$ BEGIN IF EXISTS ( From e1b2f55ce6b42a4c4b9ec33b8b8b3533aa5eedf2 Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Fri, 1 May 2026 09:04:26 -0700 Subject: [PATCH 26/36] Skip filled metric stream chunks --- ..._metric_stream_id_not_null_primary_key.sql | 30 ++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/drizzle/0009_metric_stream_id_not_null_primary_key.sql b/drizzle/0009_metric_stream_id_not_null_primary_key.sql index ed9060c7e1..db52263c4e 100644 --- a/drizzle/0009_metric_stream_id_not_null_primary_key.sql +++ b/drizzle/0009_metric_stream_id_not_null_primary_key.sql @@ -15,6 +15,7 @@ DECLARE current_chunk_regclass regclass; previous_replication_role text; should_compress_after boolean; + chunk_has_missing_ids boolean; updated_count integer; BEGIN IF batch_size < 1 THEN @@ -24,6 +25,17 @@ BEGIN PERFORM set_config('lock_timeout', '5s', false); PERFORM set_config('statement_timeout', '0', false); PERFORM set_config('timescaledb.max_tuples_decompressed_per_dml_transaction', '0', false); + + IF NOT EXISTS ( + SELECT 1 + FROM fitness.metric_stream + WHERE id IS NULL + LIMIT 1 + ) THEN + RAISE NOTICE 'metric_stream id backfill skipped: no NULL ids remain'; + RETURN; + END IF; + previous_replication_role := current_setting('session_replication_role'); PERFORM set_config('session_replication_role', 'replica', false); @@ -80,6 +92,22 @@ BEGIN CONTINUE; END IF; + EXECUTE format( + 'SELECT EXISTS ( + SELECT 1 + FROM %s + WHERE id IS NULL + )', + current_chunk_regclass + ) + INTO chunk_has_missing_ids; + + IF NOT chunk_has_missing_ids THEN + RAISE NOTICE 'metric_stream id backfill chunk %/% skipped: no NULL ids', current_chunk_index, chunk_count; + current_chunk_index := current_chunk_index + 1; + CONTINUE; + END IF; + IF current_chunk_regclass IS NOT NULL THEN PERFORM decompress_chunk(current_chunk_regclass, if_compressed => true); COMMIT; @@ -121,7 +149,7 @@ BEGIN END; $$; --> statement-breakpoint -CALL fitness.backfill_metric_stream_ids(50000); +CALL fitness.backfill_metric_stream_ids(500000); --> statement-breakpoint DROP PROCEDURE fitness.backfill_metric_stream_ids(integer); --> statement-breakpoint From 260fed38881ad1d7b0f1ef36c3edff48ac0088f0 Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Fri, 1 May 2026 12:22:14 -0700 Subject: [PATCH 27/36] Document metric stream primary key rollout --- docs/production-incident-baseline.md | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/docs/production-incident-baseline.md b/docs/production-incident-baseline.md index 9445200f4f..181a280a06 100644 --- a/docs/production-incident-baseline.md +++ b/docs/production-incident-baseline.md @@ -1956,14 +1956,20 @@ and transparent decompression more constrained than a regular Postgres table. The backfill was cancelled before another deploy timeout. The old decompressed chunk from the cancelled attempt was recompressed. The migration was updated to run the ID-only rewrite with session-local trigger execution disabled, then -restore normal trigger behavior before `SET NOT NULL` and primary-key DDL. No -primary key was added in production yet. +restore normal trigger behavior before `SET NOT NULL` and primary-key DDL. + +The final production run completed on 2026-05-01. The manual migration applied +`drizzle/0009_metric_stream_id_not_null_primary_key.sql`, backfilled all NULL +IDs, set `fitness.metric_stream.id` to `NOT NULL`, and added the +Timescale-compatible primary key on `(id, recorded_at)`. A normal web-stack +deploy then ran successfully from `Asherlc/metric-stream-id` at `sha-e1b2f55` +and recorded migration `0009_metric_stream_id_not_null_primary_key.sql` in +`drizzle.__drizzle_migrations`. ### Remaining Risk -Do not deploy the previous parent-hypertable backfill as-is. `metric_stream` -must stay because ClickHouse replication is blocked on a stable primary key or -replica identity index. Complete the ID rewrite with physical chunk-targeted -maintenance, keep materialized-view refreshes such as `fitness.deduped_sensor` -out of the maintenance window, and then add the Timescale-compatible -`(id, recorded_at)` identity. +`metric_stream` now has the required identity for ClickHouse work. The migration +left a small number of recently touched chunks uncompressed and increased disk +usage to roughly 57% on `/mnt/dofek-data`; routine compression, autovacuum, and +future maintenance should be monitored but no active backfill remained running. +Replica identity stayed `FULL`, matching the existing migration and tests. From fe8481a30f032fedf7a8a0a9c644d8dec65063ab Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Fri, 1 May 2026 12:30:00 -0700 Subject: [PATCH 28/36] Reenable metric stream ClickHouse replication --- README.md | 2 +- deploy/README.md | 4 +-- docs/clickhouse-metric-stream.md | 28 +++++++---------- drizzle/0010_oauth_token_primary_key.sql | 18 +++++++++++ src/db/clickhouse-migrations.test.ts | 10 ++++-- src/db/clickhouse-migrations.ts | 12 +++++++ src/db/clickhouse.test.ts | 11 +++---- src/db/clickhouse.ts | 40 +++++++++++++++++++++--- src/db/migrate.integration.test.ts | 27 ++++++++++++++++ 9 files changed, 118 insertions(+), 34 deletions(-) create mode 100644 drizzle/0010_oauth_token_primary_key.sql diff --git a/README.md b/README.md index d707538a8e..787ee852b0 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,7 @@ If you are starting cold and do not want to hunt through agent notes, begin here └─────────────┘ └───────────┘ ``` -Each data source is a **provider plugin** that implements a simple interface. The sync runner orchestrates all enabled providers. Raw data lands in a `fitness` Postgres schema. ClickHouse maintains stored analytics read models for heavy activity stream reads; raw `metric_stream` replication is temporarily disabled behind an empty placeholder until the historic Timescale table has a stable primary key. Derived rows are not written back to Postgres. The web dashboard provides sync controls, provider health monitoring, insights, and data exploration. A companion iOS app (Expo + React Native) provides native HealthKit integration and on-the-go access. Nutrition logging on web and iOS supports natural-language AI meal input that can split one message into multiple food items. Long-running sync jobs are processed by BullMQ workers backed by Redis. In production, the `worker` container registers repeatable scheduled sync jobs in BullMQ; the `sync` mode remains available for manual one-shot runs. +Each data source is a **provider plugin** that implements a simple interface. The sync runner orchestrates all enabled providers. Raw data lands in a `fitness` Postgres schema. ClickHouse maintains stored analytics read models for heavy activity stream reads, with raw `metric_stream` rows replicated from Postgres through the tracked ClickHouse migration path. Derived rows are not written back to Postgres. The web dashboard provides sync controls, provider health monitoring, insights, and data exploration. A companion iOS app (Expo + React Native) provides native HealthKit integration and on-the-go access. Nutrition logging on web and iOS supports natural-language AI meal input that can split one message into multiple food items. Long-running sync jobs are processed by BullMQ workers backed by Redis. In production, the `worker` container registers repeatable scheduled sync jobs in BullMQ; the `sync` mode remains available for manual one-shot runs. ## Quick Start diff --git a/deploy/README.md b/deploy/README.md index 3d7251de8d..64805849ad 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -9,7 +9,7 @@ Dofek is deployed as a **single-node Docker Swarm** stack on **Hetzner Cloud** ( - **Compute**: Hetzner Cloud `cax11` ARM64 servers running Ubuntu 24.04. Production uses `dofek`; staging uses `dofek-staging`. Each server runs `dockerd` initialized as a single-node swarm manager and has no deploy scripts or secrets on disk. - **Storage**: - **PostgreSQL**: Managed via TimescaleDB (running in the swarm). - - **ClickHouse**: Runs in the swarm as the stored analytics read-model service for heavy activity stream reads. Raw `metric_stream` replication is temporarily disabled behind a local placeholder; re-enable it only through the tracked ClickHouse migration path after the Postgres primary key migration has landed. See [docs/clickhouse-metric-stream.md](../docs/clickhouse-metric-stream.md). + - **ClickHouse**: Runs in the swarm as the stored analytics read-model service for heavy activity stream reads. Raw `metric_stream` replication is managed through tracked ClickHouse migrations after the Postgres primary key migration. See [docs/clickhouse-metric-stream.md](../docs/clickhouse-metric-stream.md). - **Volume**: Terraform provisions a Hetzner Block Storage volume (`data_volume_size_gb`, default `100GB`) attached with `automount=true`. - **Stable mount alias**: Terraform maintains `/mnt/dofek-data` as a symlink to the attached Hetzner volume mount path (`/mnt/HC_Volume_`). - **DB data path**: The `db` service bind-mounts Postgres data to `/mnt/dofek-data/postgres`. @@ -47,7 +47,7 @@ Dofek is deployed as a **single-node Docker Swarm** stack on **Hetzner Cloud** ( - Zero-downtime updates for `web` and `worker` are configured via `deploy.update_config` (`order: start-first`, `failure_action: rollback`, healthcheck-gated `monitor` window). - The `default` overlay network is declared `attachable: true` so CI can run one-shot migration containers on it from a remote Docker context. - The `db` service has a 2 GiB container memory limit to prevent one PostgreSQL workload from exhausting the single-node host. If it hits that limit, treat it as a query/workload incident rather than increasing the cap by default. -- PostgreSQL is configured with `max_connections=40`, `work_mem=4MB`, `maintenance_work_mem=64MB`, and logical replication settings needed when ClickHouse CDC is re-enabled. +- PostgreSQL is configured with `max_connections=40`, `work_mem=4MB`, `maintenance_work_mem=64MB`, and logical replication settings needed by ClickHouse change-data capture. - `metric_stream` storage controls (Timescale hypertable + compression) are managed via `docs/metric-stream-timescaledb-runbook.md` and `drizzle/0006_metric_stream_timescale_policies.sql`. - Slack is forced to HTTP mode in production via `SLACK_MODE=http` on the `web` service. This avoids Socket Mode multi-consumer overlap during rolling deploys when `web` has multiple replicas. diff --git a/docs/clickhouse-metric-stream.md b/docs/clickhouse-metric-stream.md index 59a6f885a5..1dca3096b5 100644 --- a/docs/clickhouse-metric-stream.md +++ b/docs/clickhouse-metric-stream.md @@ -1,21 +1,17 @@ # ClickHouse Metric Stream Projection -`fitness.metric_stream` remains canonical in Postgres/Timescale. ClickHouse -currently uses an empty local `postgres_fitness.metric_stream` placeholder while -the raw metric stream replication path is disabled. Migration -`drizzle/0009_metric_stream_id_not_null_primary_key.sql` backfills stable row -IDs and adds the Timescale-compatible `(id, recorded_at)` primary key. The stored -`analytics.deduped_sensor` and `analytics.activity_summary` refreshable -materialized views remain in place so the schema is stable, but raw metric rows -are not replicated into ClickHouse until a separate change re-enables the -MaterializedPostgreSQL source. +`fitness.metric_stream` remains canonical in Postgres/Timescale. After +`drizzle/0009_metric_stream_id_not_null_primary_key.sql` backfilled stable row +IDs and added the Timescale-compatible `(id, recorded_at)` primary key, +ClickHouse migration `0004_reenable_materialized_metric_stream` re-enabled raw +`metric_stream` replication through a `MaterializedPostgreSQL` source. ```text Postgres/Timescale fitness.metric_stream | - | raw MaterializedPostgreSQL replication still disabled + | raw MaterializedPostgreSQL replication v -ClickHouse postgres_fitness.metric_stream placeholder +ClickHouse postgres_fitness.metric_stream | | refreshable materialized view v @@ -64,10 +60,8 @@ does not repeatedly delete analytical state. ClickHouse migrations create and update the databases and read models: -- `postgres_fitness.metric_stream`: an empty local MergeTree placeholder for the - raw metric stream. This intentionally does not use `MaterializedPostgreSQL` - until the replication path is explicitly re-enabled after the Postgres primary - key migration has landed. +- `postgres_fitness.metric_stream`: a `MaterializedPostgreSQL` replica of the + raw metric stream. - `postgres_fitness_live`: a PostgreSQL database bridge for scalar-only views in the Postgres `clickhouse` schema: `clickhouse.v_activity` and `clickhouse.v_activity_members`. @@ -77,8 +71,8 @@ ClickHouse migrations create and update the databases and read models: `analytics.deduped_sensor`. Postgres still runs with `wal_level=logical`, `max_replication_slots`, and -`max_wal_senders` enabled so ClickHouse can subscribe to changes once the raw -metric stream replication path is re-enabled. +`max_wal_senders` enabled so ClickHouse can subscribe to raw metric stream +changes. API startup only verifies that the migrated ClickHouse tables exist. It must not create or rewrite analytical schema, because production runs multiple web diff --git a/drizzle/0010_oauth_token_primary_key.sql b/drizzle/0010_oauth_token_primary_key.sql new file mode 100644 index 0000000000..25435fe70f --- /dev/null +++ b/drizzle/0010_oauth_token_primary_key.sql @@ -0,0 +1,18 @@ +ALTER TABLE fitness.oauth_token + ALTER COLUMN user_id SET NOT NULL; + +--> statement-breakpoint + +DO $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM pg_constraint + WHERE conrelid = 'fitness.oauth_token'::regclass + AND contype = 'p' + ) THEN + ALTER TABLE fitness.oauth_token + ADD CONSTRAINT oauth_token_pkey PRIMARY KEY USING INDEX oauth_token_user_provider_uidx; + END IF; +END +$$; diff --git a/src/db/clickhouse-migrations.test.ts b/src/db/clickhouse-migrations.test.ts index 4f024eca69..b757b62739 100644 --- a/src/db/clickhouse-migrations.test.ts +++ b/src/db/clickhouse-migrations.test.ts @@ -16,7 +16,8 @@ describe("buildClickHouseMigrationStatements", () => { expect(sql).toContain("DROP DATABASE IF EXISTS postgres_fitness SYNC"); expect(sql).toContain("CREATE TABLE IF NOT EXISTS postgres_fitness.metric_stream"); expect(sql).toContain("ENGINE = MergeTree"); - expect(sql).not.toContain("MaterializedPostgreSQL"); + expect(sql).toContain("ENGINE = MaterializedPostgreSQL"); + expect(sql).toContain("materialized_postgresql_tables_list = 'metric_stream'"); expect(sql).toContain( "ENGINE = PostgreSQL('db:5432', 'health', 'health', 'secret', 'clickhouse')", ); @@ -39,7 +40,7 @@ describe("runClickHouseMigrations", () => { const count = await runClickHouseMigrations(client, "postgres://health:secret@db:5432/health"); - expect(count).toBe(3); + expect(count).toBe(4); expect(command).toHaveBeenCalledWith({ query: "CREATE DATABASE IF NOT EXISTS fitness" }); expect(command).toHaveBeenCalledWith({ query: "CREATE DATABASE IF NOT EXISTS analytics" }); expect(command).toHaveBeenCalledWith( @@ -62,6 +63,11 @@ describe("runClickHouseMigrations", () => { query: expect.stringContaining("CREATE TABLE IF NOT EXISTS postgres_fitness.metric_stream"), }), ); + expect(command).toHaveBeenCalledWith( + expect.objectContaining({ + query: expect.stringContaining("ENGINE = MaterializedPostgreSQL"), + }), + ); expect(command).toHaveBeenCalledWith( expect.objectContaining({ query: expect.stringContaining( diff --git a/src/db/clickhouse-migrations.ts b/src/db/clickhouse-migrations.ts index 1fcd536abd..aede28291b 100644 --- a/src/db/clickhouse-migrations.ts +++ b/src/db/clickhouse-migrations.ts @@ -1,5 +1,6 @@ import { buildClickHouseBootstrapStatements, + buildClickHousePlaceholderBootstrapStatements, type ClickHouseCommandClient, waitForClickHouseTable, } from "./clickhouse.ts"; @@ -36,6 +37,17 @@ function clickHouseMigrations(postgresConnectionString: string) { }, { id: "0003_disable_materialized_metric_stream", + statements: [ + "DROP VIEW IF EXISTS analytics.activity_summary", + "DROP TABLE IF EXISTS analytics.activity_summary", + "DROP VIEW IF EXISTS analytics.deduped_sensor", + "DROP TABLE IF EXISTS analytics.deduped_sensor", + "DROP DATABASE IF EXISTS postgres_fitness SYNC", + ...buildClickHousePlaceholderBootstrapStatements(postgresConnectionString), + ], + }, + { + id: "0004_reenable_materialized_metric_stream", statements: [ "DROP VIEW IF EXISTS analytics.activity_summary", "DROP TABLE IF EXISTS analytics.activity_summary", diff --git a/src/db/clickhouse.test.ts b/src/db/clickhouse.test.ts index 6dd9985ecb..2d98dd4ab6 100644 --- a/src/db/clickhouse.test.ts +++ b/src/db/clickhouse.test.ts @@ -20,7 +20,7 @@ describe("parsePostgresConnectionForClickHouse", () => { }); describe("buildClickHouseBootstrapStatements", () => { - it("creates a local metric stream placeholder and ClickHouse read models", () => { + it("creates replicated metric stream source and ClickHouse read models", () => { const sql = buildClickHouseBootstrapStatements("postgres://health:secret@db:5432/health").join( "\n", ); @@ -28,12 +28,9 @@ describe("buildClickHouseBootstrapStatements", () => { expect(sql).toContain("CREATE DATABASE IF NOT EXISTS analytics"); expect(sql).not.toContain("CREATE DATABASE IF NOT EXISTS fitness"); expect(sql).toContain("CREATE DATABASE IF NOT EXISTS postgres_fitness"); - expect(sql).toContain("CREATE TABLE IF NOT EXISTS postgres_fitness.metric_stream"); - expect(sql).toContain("activity_id Nullable(UUID)"); - expect(sql).toContain("recorded_at DateTime64(6, 'UTC')"); - expect(sql).toContain("ENGINE = MergeTree"); - expect(sql).not.toContain("MaterializedPostgreSQL"); - expect(sql).not.toContain("materialized_postgresql_tables_list"); + expect(sql).not.toContain("CREATE TABLE IF NOT EXISTS postgres_fitness.metric_stream"); + expect(sql).toContain("ENGINE = MaterializedPostgreSQL"); + expect(sql).toContain("materialized_postgresql_tables_list = 'metric_stream'"); expect(sql).toContain( "ENGINE = PostgreSQL('db:5432', 'health', 'health', 'secret', 'clickhouse')", ); diff --git a/src/db/clickhouse.ts b/src/db/clickhouse.ts index 499124e612..94ee80c850 100644 --- a/src/db/clickhouse.ts +++ b/src/db/clickhouse.ts @@ -66,16 +66,41 @@ export function parsePostgresConnectionForClickHouse( } export function buildClickHouseBootstrapStatements(postgresConnectionString: string): string[] { + return buildClickHouseBootstrapStatementsForMetricStreamSource( + postgresConnectionString, + "materialized-postgresql", + ); +} + +export function buildClickHousePlaceholderBootstrapStatements( + postgresConnectionString: string, +): string[] { + return buildClickHouseBootstrapStatementsForMetricStreamSource( + postgresConnectionString, + "placeholder", + ); +} + +function buildClickHouseBootstrapStatementsForMetricStreamSource( + postgresConnectionString: string, + metricStreamSource: "materialized-postgresql" | "placeholder", +): string[] { const postgres = parsePostgresConnectionForClickHouse(postgresConnectionString); const hostAndPort = clickHouseStringLiteral(postgres.hostAndPort); const database = clickHouseStringLiteral(postgres.database); const user = clickHouseStringLiteral(postgres.user); const password = clickHouseStringLiteral(postgres.password); - - return [ - "CREATE DATABASE IF NOT EXISTS analytics", - "CREATE DATABASE IF NOT EXISTS postgres_fitness", - `CREATE TABLE IF NOT EXISTS postgres_fitness.metric_stream ( + const metricStreamStatements = + metricStreamSource === "materialized-postgresql" + ? [ + `CREATE DATABASE IF NOT EXISTS postgres_fitness +ENGINE = MaterializedPostgreSQL(${hostAndPort}, ${database}, ${user}, ${password}) +SETTINGS materialized_postgresql_schema = 'fitness', + materialized_postgresql_tables_list = 'metric_stream'`, + ] + : [ + "CREATE DATABASE IF NOT EXISTS postgres_fitness", + `CREATE TABLE IF NOT EXISTS postgres_fitness.metric_stream ( activity_id Nullable(UUID), user_id UUID, recorded_at DateTime64(6, 'UTC'), @@ -86,6 +111,11 @@ export function buildClickHouseBootstrapStatements(postgresConnectionString: str ENGINE = MergeTree ORDER BY (user_id, activity_id, channel, recorded_at) SETTINGS allow_nullable_key = 1`, + ]; + + return [ + "CREATE DATABASE IF NOT EXISTS analytics", + ...metricStreamStatements, `CREATE DATABASE IF NOT EXISTS postgres_fitness_live ENGINE = PostgreSQL(${hostAndPort}, ${database}, ${user}, ${password}, 'clickhouse')`, `CREATE MATERIALIZED VIEW IF NOT EXISTS analytics.deduped_sensor diff --git a/src/db/migrate.integration.test.ts b/src/db/migrate.integration.test.ts index f38acb8d20..2e0e3a8cb7 100644 --- a/src/db/migrate.integration.test.ts +++ b/src/db/migrate.integration.test.ts @@ -131,4 +131,31 @@ describe("runMigrations", () => { await client.end(); } }); + + it("gives oauth_token its schema-declared composite primary key", async () => { + const client = new Client({ connectionString: ctx.connectionString }); + await client.connect(); + try { + const nullableResult = await client.query<{ is_nullable: "YES" | "NO" }>(` + SELECT is_nullable + FROM information_schema.columns + WHERE table_schema = 'fitness' + AND table_name = 'oauth_token' + AND column_name = 'user_id' + `); + expect(nullableResult.rows).toEqual([{ is_nullable: "NO" }]); + + const primaryKeyResult = await client.query<{ columns: string }>(` + SELECT string_agg(column_name, ',' ORDER BY ordinal_position) AS columns + FROM information_schema.key_column_usage + WHERE table_schema = 'fitness' + AND table_name = 'oauth_token' + AND constraint_name = 'oauth_token_pkey' + GROUP BY constraint_name + `); + expect(primaryKeyResult.rows).toEqual([{ columns: "user_id,provider_id" }]); + } finally { + await client.end(); + } + }); }); From 06e7a730fa1dd6967c1beebf7e3a2e5b693c9dd5 Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Fri, 1 May 2026 12:54:40 -0700 Subject: [PATCH 29/36] Wait longer for ClickHouse replicated tables --- src/db/clickhouse.test.ts | 23 +++++++++++++++++++++++ src/db/clickhouse.ts | 4 +++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/db/clickhouse.test.ts b/src/db/clickhouse.test.ts index 2d98dd4ab6..c35e42771d 100644 --- a/src/db/clickhouse.test.ts +++ b/src/db/clickhouse.test.ts @@ -115,4 +115,27 @@ describe("waitForClickHouseTable", () => { waitForClickHouseTable({ command: vi.fn().mockResolvedValue(undefined) }, "analytics", "foo"), ).rejects.toThrow("ClickHouse table verification requires a query-capable client"); }); + + it("waits for MaterializedPostgreSQL tables that appear after the initial snapshot starts", async () => { + vi.useFakeTimers(); + try { + let queryCount = 0; + const query = vi.fn().mockImplementation(() => ({ + json: vi.fn().mockResolvedValue([{ table_count: queryCount++ >= 45 ? 1 : 0 }]), + })); + + const result = waitForClickHouseTable( + { command: vi.fn().mockResolvedValue(undefined), query }, + "postgres_fitness", + "metric_stream", + ); + + await vi.advanceTimersByTimeAsync(60_000); + + await expect(result).resolves.toBeUndefined(); + expect(query).toHaveBeenCalledTimes(46); + } finally { + vi.useRealTimers(); + } + }); }); diff --git a/src/db/clickhouse.ts b/src/db/clickhouse.ts index 94ee80c850..8f96571d50 100644 --- a/src/db/clickhouse.ts +++ b/src/db/clickhouse.ts @@ -25,6 +25,8 @@ interface TableCountRow { table_count: number | string; } +const CLICKHOUSE_TABLE_WAIT_ATTEMPTS = 180; + interface ClickHousePostgresConnection { hostAndPort: string; database: string; @@ -515,7 +517,7 @@ export async function waitForClickHouseTable( throw new Error("ClickHouse table verification requires a query-capable client"); } - for (let attempt = 0; attempt < 30; attempt += 1) { + for (let attempt = 0; attempt < CLICKHOUSE_TABLE_WAIT_ATTEMPTS; attempt += 1) { const result = await client.query({ query: `SELECT count() AS table_count FROM system.tables WHERE database = ${clickHouseStringLiteral( database, From eef3cbccbc59619e45e99813405405df3ad9aaa7 Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Fri, 1 May 2026 13:22:48 -0700 Subject: [PATCH 30/36] Backfill ClickHouse metric stream --- src/db/clickhouse-migrations.test.ts | 81 +++++++++++- src/db/clickhouse-migrations.ts | 190 ++++++++++++++++++++++++++- 2 files changed, 264 insertions(+), 7 deletions(-) diff --git a/src/db/clickhouse-migrations.test.ts b/src/db/clickhouse-migrations.test.ts index b757b62739..51472511ec 100644 --- a/src/db/clickhouse-migrations.test.ts +++ b/src/db/clickhouse-migrations.test.ts @@ -1,4 +1,15 @@ -import { describe, expect, it, vi } from "vitest"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const pgClientMocks = vi.hoisted(() => ({ + connect: vi.fn(), + end: vi.fn(), + query: vi.fn(), +})); + +vi.mock("pg", () => ({ + Client: vi.fn(() => pgClientMocks), +})); + import { buildClickHouseMigrationStatements, runClickHouseMigrations, @@ -27,6 +38,14 @@ describe("buildClickHouseMigrationStatements", () => { }); describe("runClickHouseMigrations", () => { + beforeEach(() => { + pgClientMocks.connect.mockReset().mockResolvedValue(undefined); + pgClientMocks.end.mockReset().mockResolvedValue(undefined); + pgClientMocks.query.mockReset().mockResolvedValue({ + rows: [{ min_recorded_at: null, upper_bound: null }], + }); + }); + it("runs pending ClickHouse migrations once and records them", async () => { const command = vi.fn().mockResolvedValue(undefined); const query = vi.fn().mockImplementation(({ query: queryText }: { query: string }) => ({ @@ -40,7 +59,7 @@ describe("runClickHouseMigrations", () => { const count = await runClickHouseMigrations(client, "postgres://health:secret@db:5432/health"); - expect(count).toBe(4); + expect(count).toBe(5); expect(command).toHaveBeenCalledWith({ query: "CREATE DATABASE IF NOT EXISTS fitness" }); expect(command).toHaveBeenCalledWith({ query: "CREATE DATABASE IF NOT EXISTS analytics" }); expect(command).toHaveBeenCalledWith( @@ -82,6 +101,64 @@ describe("runClickHouseMigrations", () => { ); }); + it("backfills materialized metric stream in bounded recorded_at chunks", async () => { + pgClientMocks.query.mockResolvedValue({ + rows: [ + { + min_recorded_at: "2026-04-22 00:00:00+00", + upper_bound: "2026-04-22 12:00:00+00", + }, + ], + }); + const command = vi.fn().mockResolvedValue(undefined); + const query = vi.fn().mockImplementation(({ query: queryText }: { query: string }) => ({ + json: vi + .fn() + .mockResolvedValue( + queryText.includes("system.tables") + ? [{ table_count: 1 }] + : queryText.includes("0005_backfill_materialized_metric_stream") + ? [{ migration_count: 0 }] + : queryText.includes("metric_stream_backfill_chunks") + ? [{ chunk_count: 0 }] + : [{ migration_count: 1 }], + ), + })); + const client = { command, query }; + + const count = await runClickHouseMigrations(client, "postgres://health:secret@db:5432/health"); + + expect(count).toBe(1); + expect(command).toHaveBeenCalledWith( + expect.objectContaining({ + query: expect.stringContaining("INSERT INTO postgres_fitness.metric_stream"), + }), + ); + expect(command).toHaveBeenCalledWith( + expect.objectContaining({ + query: expect.stringContaining( + "CREATE TABLE IF NOT EXISTS analytics.metric_stream_backfill_chunks", + ), + }), + ); + const backfillStatements = command.mock.calls + .map(([options]) => String(options.query)) + .filter((queryText) => queryText.includes("INSERT INTO postgres_fitness.metric_stream")); + expect(backfillStatements).toHaveLength(2); + expect(backfillStatements[0]).toContain( + "metric_stream.recorded_at >= toDateTime64('2026-04-22 00:00:00.000', 6, 'UTC')", + ); + expect(backfillStatements[0]).toContain( + "metric_stream.recorded_at < toDateTime64('2026-04-22 06:00:00.000', 6, 'UTC')", + ); + expect(backfillStatements[1]).toContain( + "metric_stream.recorded_at >= toDateTime64('2026-04-22 06:00:00.000', 6, 'UTC')", + ); + expect(backfillStatements[1]).toContain( + "metric_stream.recorded_at < toDateTime64('2026-04-22 12:00:00.000', 6, 'UTC')", + ); + }); + it("skips already-applied ClickHouse migrations", async () => { const command = vi.fn().mockResolvedValue(undefined); const query = vi.fn().mockResolvedValue({ diff --git a/src/db/clickhouse-migrations.ts b/src/db/clickhouse-migrations.ts index aede28291b..49f05d7703 100644 --- a/src/db/clickhouse-migrations.ts +++ b/src/db/clickhouse-migrations.ts @@ -1,7 +1,9 @@ +import { Client } from "pg"; import { buildClickHouseBootstrapStatements, buildClickHousePlaceholderBootstrapStatements, type ClickHouseCommandClient, + parsePostgresConnectionForClickHouse, waitForClickHouseTable, } from "./clickhouse.ts"; @@ -9,11 +11,32 @@ interface MigrationCountRow { migration_count: number | string; } +interface MetricStreamBackfillBoundsRow { + min_recorded_at: string | null; + upper_bound: string | null; +} + +interface MetricStreamBackfillChunkCountRow { + chunk_count: number | string; +} + +const METRIC_STREAM_BACKFILL_CHUNK_MS = 6 * 60 * 60 * 1000; + function clickHouseStringLiteral(value: string): string { return `'${value.replaceAll("\\", "\\\\").replaceAll("'", "\\'")}'`; } -function clickHouseMigrations(postgresConnectionString: string) { +type ClickHouseMigration = + | { + id: string; + statements: string[]; + } + | { + id: string; + run: (client: ClickHouseCommandClient, postgresConnectionString: string) => Promise; + }; + +function clickHouseMigrations(postgresConnectionString: string): ClickHouseMigration[] { return [ { id: "0001_clickhouse_analytics_schema_cleanup", @@ -57,12 +80,16 @@ function clickHouseMigrations(postgresConnectionString: string) { ...buildClickHouseBootstrapStatements(postgresConnectionString), ], }, + { + id: "0005_backfill_materialized_metric_stream", + run: backfillMaterializedMetricStream, + }, ]; } export function buildClickHouseMigrationStatements(postgresConnectionString: string): string[] { - return clickHouseMigrations(postgresConnectionString).flatMap( - (migration) => migration.statements, + return clickHouseMigrations(postgresConnectionString).flatMap((migration) => + "statements" in migration ? migration.statements : [], ); } @@ -97,8 +124,12 @@ ORDER BY id`, continue; } - for (const statement of migration.statements) { - await runClickHouseMigrationStatement(client, statement); + if ("statements" in migration) { + for (const statement of migration.statements) { + await runClickHouseMigrationStatement(client, statement); + } + } else { + await migration.run(client, postgresConnectionString); } await client.command({ query: `INSERT INTO analytics.schema_migrations (id) VALUES (${migrationId})`, @@ -109,6 +140,155 @@ ORDER BY id`, return appliedCount; } +async function backfillMaterializedMetricStream( + client: ClickHouseCommandClient, + postgresConnectionString: string, +): Promise { + await waitForClickHouseTable(client, "postgres_fitness", "metric_stream"); + const bounds = await fetchMetricStreamBackfillBounds(postgresConnectionString); + if (!bounds.min_recorded_at || !bounds.upper_bound) { + return; + } + + const postgresMetricStreamSource = + buildPostgresMetricStreamTableFunction(postgresConnectionString); + const upperBound = parsePostgresTimestamp(bounds.upper_bound, "metric_stream upper bound"); + let chunkStart = parsePostgresTimestamp(bounds.min_recorded_at, "metric_stream lower bound"); + await client.command({ + query: `CREATE TABLE IF NOT EXISTS analytics.metric_stream_backfill_chunks ( + lower_bound DateTime64(6, 'UTC'), + upper_bound DateTime64(6, 'UTC'), + completed_at DateTime DEFAULT now() +) +ENGINE = MergeTree +ORDER BY (lower_bound, upper_bound)`, + }); + + while (chunkStart.getTime() < upperBound.getTime()) { + const chunkEnd = new Date( + Math.min(chunkStart.getTime() + METRIC_STREAM_BACKFILL_CHUNK_MS, upperBound.getTime()), + ); + if (await isMetricStreamBackfillChunkComplete(client, chunkStart, chunkEnd)) { + chunkStart = chunkEnd; + continue; + } + await client.command({ + query: buildMetricStreamBackfillStatement(postgresMetricStreamSource, chunkStart, chunkEnd), + clickhouse_settings: { + allow_experimental_database_materialized_postgresql: 1, + }, + }); + await client.command({ + query: `INSERT INTO analytics.metric_stream_backfill_chunks (lower_bound, upper_bound) +VALUES (${clickHouseDateTimeLiteral(chunkStart)}, ${clickHouseDateTimeLiteral(chunkEnd)})`, + }); + chunkStart = chunkEnd; + } +} + +async function isMetricStreamBackfillChunkComplete( + client: ClickHouseCommandClient, + chunkStart: Date, + chunkEnd: Date, +): Promise { + if (!client.query) { + throw new Error("ClickHouse metric stream backfill requires a query-capable client"); + } + const result = await client.query({ + query: `SELECT count() AS chunk_count +FROM analytics.metric_stream_backfill_chunks +WHERE lower_bound = ${clickHouseDateTimeLiteral(chunkStart)} + AND upper_bound = ${clickHouseDateTimeLiteral(chunkEnd)}`, + format: "JSONEachRow", + }); + const rows = await result.json(); + return Number(rows[0]?.chunk_count ?? 0) > 0; +} + +async function fetchMetricStreamBackfillBounds( + postgresConnectionString: string, +): Promise { + const postgresClient = new Client({ connectionString: postgresConnectionString }); + try { + await postgresClient.connect(); + const result = await postgresClient.query(` + SELECT + ( + SELECT recorded_at::text + FROM fitness.metric_stream + ORDER BY recorded_at ASC + LIMIT 1 + ) AS min_recorded_at, + ( + SELECT greatest(clock_timestamp(), recorded_at + interval '1 second')::text + FROM fitness.metric_stream + ORDER BY recorded_at DESC + LIMIT 1 + ) AS upper_bound + `); + return result.rows[0] ?? { min_recorded_at: null, upper_bound: null }; + } finally { + await postgresClient.end(); + } +} + +function buildPostgresMetricStreamTableFunction(postgresConnectionString: string): string { + const postgres = parsePostgresConnectionForClickHouse(postgresConnectionString); + return `postgresql(${clickHouseStringLiteral(postgres.hostAndPort)}, ${clickHouseStringLiteral( + postgres.database, + )}, 'metric_stream', ${clickHouseStringLiteral(postgres.user)}, ${clickHouseStringLiteral( + postgres.password, + )}, 'fitness')`; +} + +function parsePostgresTimestamp(value: string, label: string): Date { + const parsed = new Date(value); + if (Number.isNaN(parsed.getTime())) { + throw new Error(`Invalid ${label}: ${value}`); + } + return parsed; +} + +function buildMetricStreamBackfillStatement( + postgresMetricStreamSource: string, + chunkStart: Date, + chunkEnd: Date, +): string { + const lowerBound = clickHouseDateTimeLiteral(chunkStart); + const upperBound = clickHouseDateTimeLiteral(chunkEnd); + return `INSERT INTO postgres_fitness.metric_stream ( + recorded_at, + user_id, + provider_id, + device_id, + source_type, + channel, + activity_id, + scalar, + vector, + id +) +SELECT + metric_stream.recorded_at, + metric_stream.user_id, + metric_stream.provider_id, + metric_stream.device_id, + metric_stream.source_type, + metric_stream.channel, + metric_stream.activity_id, + metric_stream.scalar, + metric_stream.vector, + metric_stream.id +FROM ${postgresMetricStreamSource} AS metric_stream +WHERE metric_stream.recorded_at >= ${lowerBound} + AND metric_stream.recorded_at < ${upperBound}`; +} + +function clickHouseDateTimeLiteral(value: Date): string { + const clickHouseTimestamp = value.toISOString().replace("T", " ").replace("Z", ""); + return `toDateTime64(${clickHouseStringLiteral(clickHouseTimestamp)}, 6, 'UTC')`; +} + async function runClickHouseMigrationStatement( client: ClickHouseCommandClient, statement: string, From 4f932fce9fc1df245bf927a95371781ad3374dad Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Fri, 1 May 2026 13:37:03 -0700 Subject: [PATCH 31/36] Backfill metric stream by Timescale chunks --- src/db/clickhouse-migrations.test.ts | 10 ++++-- src/db/clickhouse-migrations.ts | 51 +++++++++++----------------- 2 files changed, 27 insertions(+), 34 deletions(-) diff --git a/src/db/clickhouse-migrations.test.ts b/src/db/clickhouse-migrations.test.ts index 51472511ec..a75e38ee05 100644 --- a/src/db/clickhouse-migrations.test.ts +++ b/src/db/clickhouse-migrations.test.ts @@ -42,7 +42,7 @@ describe("runClickHouseMigrations", () => { pgClientMocks.connect.mockReset().mockResolvedValue(undefined); pgClientMocks.end.mockReset().mockResolvedValue(undefined); pgClientMocks.query.mockReset().mockResolvedValue({ - rows: [{ min_recorded_at: null, upper_bound: null }], + rows: [], }); }); @@ -101,11 +101,15 @@ describe("runClickHouseMigrations", () => { ); }); - it("backfills materialized metric stream in bounded recorded_at chunks", async () => { + it("backfills materialized metric stream in Timescale chunk ranges", async () => { pgClientMocks.query.mockResolvedValue({ rows: [ { - min_recorded_at: "2026-04-22 00:00:00+00", + lower_bound: "2026-04-22 00:00:00+00", + upper_bound: "2026-04-22 06:00:00+00", + }, + { + lower_bound: "2026-04-22 06:00:00+00", upper_bound: "2026-04-22 12:00:00+00", }, ], diff --git a/src/db/clickhouse-migrations.ts b/src/db/clickhouse-migrations.ts index 49f05d7703..e5fd54c5a6 100644 --- a/src/db/clickhouse-migrations.ts +++ b/src/db/clickhouse-migrations.ts @@ -11,17 +11,15 @@ interface MigrationCountRow { migration_count: number | string; } -interface MetricStreamBackfillBoundsRow { - min_recorded_at: string | null; - upper_bound: string | null; +interface MetricStreamBackfillChunkRow { + lower_bound: string; + upper_bound: string; } interface MetricStreamBackfillChunkCountRow { chunk_count: number | string; } -const METRIC_STREAM_BACKFILL_CHUNK_MS = 6 * 60 * 60 * 1000; - function clickHouseStringLiteral(value: string): string { return `'${value.replaceAll("\\", "\\\\").replaceAll("'", "\\'")}'`; } @@ -145,15 +143,13 @@ async function backfillMaterializedMetricStream( postgresConnectionString: string, ): Promise { await waitForClickHouseTable(client, "postgres_fitness", "metric_stream"); - const bounds = await fetchMetricStreamBackfillBounds(postgresConnectionString); - if (!bounds.min_recorded_at || !bounds.upper_bound) { + const chunks = await fetchMetricStreamBackfillChunks(postgresConnectionString); + if (chunks.length === 0) { return; } const postgresMetricStreamSource = buildPostgresMetricStreamTableFunction(postgresConnectionString); - const upperBound = parsePostgresTimestamp(bounds.upper_bound, "metric_stream upper bound"); - let chunkStart = parsePostgresTimestamp(bounds.min_recorded_at, "metric_stream lower bound"); await client.command({ query: `CREATE TABLE IF NOT EXISTS analytics.metric_stream_backfill_chunks ( lower_bound DateTime64(6, 'UTC'), @@ -164,12 +160,10 @@ ENGINE = MergeTree ORDER BY (lower_bound, upper_bound)`, }); - while (chunkStart.getTime() < upperBound.getTime()) { - const chunkEnd = new Date( - Math.min(chunkStart.getTime() + METRIC_STREAM_BACKFILL_CHUNK_MS, upperBound.getTime()), - ); + for (const chunk of chunks) { + const chunkStart = parsePostgresTimestamp(chunk.lower_bound, "metric_stream chunk lower bound"); + const chunkEnd = parsePostgresTimestamp(chunk.upper_bound, "metric_stream chunk upper bound"); if (await isMetricStreamBackfillChunkComplete(client, chunkStart, chunkEnd)) { - chunkStart = chunkEnd; continue; } await client.command({ @@ -182,7 +176,6 @@ ORDER BY (lower_bound, upper_bound)`, query: `INSERT INTO analytics.metric_stream_backfill_chunks (lower_bound, upper_bound) VALUES (${clickHouseDateTimeLiteral(chunkStart)}, ${clickHouseDateTimeLiteral(chunkEnd)})`, }); - chunkStart = chunkEnd; } } @@ -205,28 +198,24 @@ WHERE lower_bound = ${clickHouseDateTimeLiteral(chunkStart)} return Number(rows[0]?.chunk_count ?? 0) > 0; } -async function fetchMetricStreamBackfillBounds( +async function fetchMetricStreamBackfillChunks( postgresConnectionString: string, -): Promise { +): Promise { const postgresClient = new Client({ connectionString: postgresConnectionString }); try { await postgresClient.connect(); - const result = await postgresClient.query(` + const result = await postgresClient.query(` SELECT - ( - SELECT recorded_at::text - FROM fitness.metric_stream - ORDER BY recorded_at ASC - LIMIT 1 - ) AS min_recorded_at, - ( - SELECT greatest(clock_timestamp(), recorded_at + interval '1 second')::text - FROM fitness.metric_stream - ORDER BY recorded_at DESC - LIMIT 1 - ) AS upper_bound + range_start::text AS lower_bound, + range_end::text AS upper_bound + FROM timescaledb_information.chunks + WHERE hypertable_schema = 'fitness' + AND hypertable_name = 'metric_stream' + AND range_start IS NOT NULL + AND range_end IS NOT NULL + ORDER BY range_start ASC `); - return result.rows[0] ?? { min_recorded_at: null, upper_bound: null }; + return result.rows; } finally { await postgresClient.end(); } From 0c6ec493bf2c994a0bba4b7e415c89963ef49f76 Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Fri, 1 May 2026 13:40:14 -0700 Subject: [PATCH 32/36] Document ClickHouse metric stream backfill incident --- docs/production-incident-baseline.md | 44 ++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/docs/production-incident-baseline.md b/docs/production-incident-baseline.md index 181a280a06..0fe22a0e8f 100644 --- a/docs/production-incident-baseline.md +++ b/docs/production-incident-baseline.md @@ -1973,3 +1973,47 @@ left a small number of recently touched chunks uncompressed and increased disk usage to roughly 57% on `/mnt/dofek-data`; routine compression, autovacuum, and future maintenance should be monitored but no active backfill remained running. Replica identity stayed `FULL`, matching the existing migration and tests. + +## 2026-05-01: ClickHouse Metric Stream Snapshot Missed Hypertable Rows + +### Symptoms + +ClickHouse replication setup for `postgres_fitness.metric_stream` deployed, but +the ClickHouse table stayed empty while production Postgres still had +`fitness.metric_stream` rows. The first backfill deploy attempt then had to be +cancelled during migration execution. + +### Evidence + +ClickHouse logs showed `MaterializedPostgreSQL` created `metric_stream` and +started replication. Direct ClickHouse reads through the `postgresql(...)` table +function returned source rows from Postgres, and a one-day source count returned +3,259,688 rows, but `postgres_fitness.metric_stream` had `0` rows. The first +backfill migration attempted to derive global `recorded_at` bounds from the +hypertable and remained active in Postgres during the deploy. Timescale metadata +showed the table has `195` physical chunks spanning `1989-12-28` through +`2104-02-14`, making a continuous 6-hour backfill range unfit for deploy. + +### Root Cause + +The ClickHouse `MaterializedPostgreSQL` initial snapshot did not materialize +existing Timescale hypertable chunk rows for `metric_stream`. The first manual +backfill design also treated the hypertable as one continuous time range instead +of iterating the actual Timescale chunks. + +### Fix or Mitigation + +Cancelled the bad deploy run and cancelled the active Postgres bounds query. +Changed `0005_backfill_materialized_metric_stream` to fetch chunk ranges from +`timescaledb_information.chunks`, backfill each real chunk into +`postgres_fitness.metric_stream`, and record completed ranges in +`analytics.metric_stream_backfill_chunks` so retries can resume. + +### Remaining Risk + +The chunked backfill still rewrites a large volume into ClickHouse and should be +monitored until `analytics.schema_migrations` includes +`0005_backfill_materialized_metric_stream` and `postgres_fitness.metric_stream` +has nonzero rows. Future read-model migrations should prefer ClickHouse-native +tables/materialized views for large time-series aggregates instead of Postgres +materialized views or unbounded hypertable scans. From 99e188dd95ea5fcb6a5aec4be7c95b5e984c1453 Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Fri, 1 May 2026 13:49:30 -0700 Subject: [PATCH 33/36] Document read-only ClickHouse backfill failure --- docs/production-incident-baseline.md | 45 ++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/docs/production-incident-baseline.md b/docs/production-incident-baseline.md index 0fe22a0e8f..ef27b41ee6 100644 --- a/docs/production-incident-baseline.md +++ b/docs/production-incident-baseline.md @@ -2017,3 +2017,48 @@ monitored until `analytics.schema_migrations` includes has nonzero rows. Future read-model migrations should prefer ClickHouse-native tables/materialized views for large time-series aggregates instead of Postgres materialized views or unbounded hypertable scans. + +## 2026-05-01: ClickHouse Metric Stream Backfill Target Was Read-Only + +### Symptoms + +The follow-up production deploy run for the chunk-based ClickHouse backfill +failed during the `Run migrations` step before `docker stack deploy`. + +### Evidence + +GitHub Actions run `25232097814` failed from commit +`4f932fce9fc1df245bf927a95371781ad3374dad`. The first fatal migration log line +was: + +```text +error: [migrate] Error: Method write is not supported by storage MaterializedPostgreSQL. +``` + +After the failure, ClickHouse still showed `0` rows in +`postgres_fitness.metric_stream`, no completed +`analytics.metric_stream_backfill_chunks`, and no +`0005_backfill_materialized_metric_stream` row in +`analytics.schema_migrations`. + +### Root Cause + +The backfill migration attempted to insert historical rows into +`postgres_fitness.metric_stream`, but that table is owned by the +`MaterializedPostgreSQL` database engine. The engine exposes a replicated +read-only table in ClickHouse, so it cannot be used as the destination for a +manual historical backfill. + +### Fix or Mitigation + +No code fix has been deployed yet. The next migration needs to keep the +`MaterializedPostgreSQL` table read-only and write historical rows into a +ClickHouse-native table, or replace the replication source strategy entirely. + +### Remaining Risk + +`analytics.deduped_sensor` remains empty because its raw ClickHouse metric +stream source is empty. Any strategy that keeps `MaterializedPostgreSQL` must +also prove that it receives new `metric_stream` inserts from the Timescale +hypertable; otherwise the canonical ClickHouse source needs to move to a +ClickHouse-native ingestion path. From a195da37876c07e7ba6afa7e8b9808d87d94313d Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Fri, 1 May 2026 14:02:13 -0700 Subject: [PATCH 34/36] Document Timescale chunk CDC gap --- docs/production-incident-baseline.md | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/docs/production-incident-baseline.md b/docs/production-incident-baseline.md index ef27b41ee6..21021e0e99 100644 --- a/docs/production-incident-baseline.md +++ b/docs/production-incident-baseline.md @@ -1993,13 +1993,23 @@ backfill migration attempted to derive global `recorded_at` bounds from the hypertable and remained active in Postgres during the deploy. Timescale metadata showed the table has `195` physical chunks spanning `1989-12-28` through `2104-02-14`, making a continuous 6-hour backfill range unfit for deploy. +Follow-up investigation showed `ONLY fitness.metric_stream` had no rows while +`fitness.metric_stream` had rows through the hypertable abstraction, and the +ClickHouse-created publication `health_ch_publication` contained only +`fitness.metric_stream`. None of the `195` +`_timescaledb_internal._hyper_*_chunk` child tables were in the publication. ### Root Cause -The ClickHouse `MaterializedPostgreSQL` initial snapshot did not materialize -existing Timescale hypertable chunk rows for `metric_stream`. The first manual -backfill design also treated the hypertable as one continuous time range instead -of iterating the actual Timescale chunks. +The ClickHouse `MaterializedPostgreSQL` initial snapshot and logical +replication target the published Postgres relation, `fitness.metric_stream`. +In TimescaleDB, the hypertable root relation is effectively an empty routing +table; the data live in `_timescaledb_internal` chunk tables. Because +`MaterializedPostgreSQL` created a publication for only the hypertable root, not +the chunks, the initial snapshot copied no historical rows and live chunk writes +were not discoverable by the CDC stream. The first manual backfill design also +treated the hypertable as one continuous time range instead of iterating the +actual Timescale chunks. ### Fix or Mitigation @@ -2059,6 +2069,6 @@ ClickHouse-native table, or replace the replication source strategy entirely. `analytics.deduped_sensor` remains empty because its raw ClickHouse metric stream source is empty. Any strategy that keeps `MaterializedPostgreSQL` must -also prove that it receives new `metric_stream` inserts from the Timescale -hypertable; otherwise the canonical ClickHouse source needs to move to a -ClickHouse-native ingestion path. +also handle Timescale chunk publications and prove that chunk inserts map back +into `postgres_fitness.metric_stream`; otherwise the canonical ClickHouse source +needs to move to a ClickHouse-native ingestion path. From fa2a07e9018b674feef9d58fdaaa5ef2857109c2 Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Fri, 1 May 2026 14:27:03 -0700 Subject: [PATCH 35/36] Use native ClickHouse metric stream backfill --- README.md | 2 +- deploy/README.md | 2 +- docs/clickhouse-metric-stream.md | 28 +++++++++++------- docs/production-incident-baseline.md | 21 ++++++++------ src/db/clickhouse-migrations.test.ts | 12 ++++---- src/db/clickhouse-migrations.ts | 43 ++++++++++++++++++++-------- src/db/clickhouse.test.ts | 11 +++---- src/db/clickhouse.ts | 32 ++++++--------------- 8 files changed, 84 insertions(+), 67 deletions(-) diff --git a/README.md b/README.md index 787ee852b0..5225714422 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,7 @@ If you are starting cold and do not want to hunt through agent notes, begin here └─────────────┘ └───────────┘ ``` -Each data source is a **provider plugin** that implements a simple interface. The sync runner orchestrates all enabled providers. Raw data lands in a `fitness` Postgres schema. ClickHouse maintains stored analytics read models for heavy activity stream reads, with raw `metric_stream` rows replicated from Postgres through the tracked ClickHouse migration path. Derived rows are not written back to Postgres. The web dashboard provides sync controls, provider health monitoring, insights, and data exploration. A companion iOS app (Expo + React Native) provides native HealthKit integration and on-the-go access. Nutrition logging on web and iOS supports natural-language AI meal input that can split one message into multiple food items. Long-running sync jobs are processed by BullMQ workers backed by Redis. In production, the `worker` container registers repeatable scheduled sync jobs in BullMQ; the `sync` mode remains available for manual one-shot runs. +Each data source is a **provider plugin** that implements a simple interface. The sync runner orchestrates all enabled providers. Raw data lands in a `fitness` Postgres schema. ClickHouse maintains stored analytics read models for heavy activity stream reads, with scalar `metric_stream` rows copied from Postgres through the tracked ClickHouse migration path. Derived rows are not written back to Postgres. The web dashboard provides sync controls, provider health monitoring, insights, and data exploration. A companion iOS app (Expo + React Native) provides native HealthKit integration and on-the-go access. Nutrition logging on web and iOS supports natural-language AI meal input that can split one message into multiple food items. Long-running sync jobs are processed by BullMQ workers backed by Redis. In production, the `worker` container registers repeatable scheduled sync jobs in BullMQ; the `sync` mode remains available for manual one-shot runs. ## Quick Start diff --git a/deploy/README.md b/deploy/README.md index 64805849ad..08bda8afc2 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -9,7 +9,7 @@ Dofek is deployed as a **single-node Docker Swarm** stack on **Hetzner Cloud** ( - **Compute**: Hetzner Cloud `cax11` ARM64 servers running Ubuntu 24.04. Production uses `dofek`; staging uses `dofek-staging`. Each server runs `dockerd` initialized as a single-node swarm manager and has no deploy scripts or secrets on disk. - **Storage**: - **PostgreSQL**: Managed via TimescaleDB (running in the swarm). - - **ClickHouse**: Runs in the swarm as the stored analytics read-model service for heavy activity stream reads. Raw `metric_stream` replication is managed through tracked ClickHouse migrations after the Postgres primary key migration. See [docs/clickhouse-metric-stream.md](../docs/clickhouse-metric-stream.md). + - **ClickHouse**: Runs in the swarm as the stored analytics read-model service for heavy activity stream reads. The raw scalar `metric_stream` copy is managed through tracked ClickHouse migrations and chunk-range backfill. See [docs/clickhouse-metric-stream.md](../docs/clickhouse-metric-stream.md). - **Volume**: Terraform provisions a Hetzner Block Storage volume (`data_volume_size_gb`, default `100GB`) attached with `automount=true`. - **Stable mount alias**: Terraform maintains `/mnt/dofek-data` as a symlink to the attached Hetzner volume mount path (`/mnt/HC_Volume_`). - **DB data path**: The `db` service bind-mounts Postgres data to `/mnt/dofek-data/postgres`. diff --git a/docs/clickhouse-metric-stream.md b/docs/clickhouse-metric-stream.md index 1dca3096b5..b54f539e6e 100644 --- a/docs/clickhouse-metric-stream.md +++ b/docs/clickhouse-metric-stream.md @@ -1,15 +1,15 @@ # ClickHouse Metric Stream Projection -`fitness.metric_stream` remains canonical in Postgres/Timescale. After -`drizzle/0009_metric_stream_id_not_null_primary_key.sql` backfilled stable row -IDs and added the Timescale-compatible `(id, recorded_at)` primary key, -ClickHouse migration `0004_reenable_materialized_metric_stream` re-enabled raw -`metric_stream` replication through a `MaterializedPostgreSQL` source. +`fitness.metric_stream` remains canonical in Postgres/Timescale. ClickHouse +keeps a native `MergeTree` scalar copy of the raw stream and backfills it from +Postgres by real Timescale chunk ranges. We do not use ClickHouse +`MaterializedPostgreSQL` for this hypertable because the hypertable root does +not contain the physical rows; the data live in Timescale chunk tables. ```text Postgres/Timescale fitness.metric_stream | - | raw MaterializedPostgreSQL replication + | chunk-range native backfill v ClickHouse postgres_fitness.metric_stream | @@ -60,19 +60,25 @@ does not repeatedly delete analytical state. ClickHouse migrations create and update the databases and read models: -- `postgres_fitness.metric_stream`: a `MaterializedPostgreSQL` replica of the - raw metric stream. +- `postgres_fitness.metric_stream`: a ClickHouse-native `MergeTree` scalar copy + of the raw metric stream. - `postgres_fitness_live`: a PostgreSQL database bridge for scalar-only views in the Postgres `clickhouse` schema: `clickhouse.v_activity` and `clickhouse.v_activity_members`. - `analytics.deduped_sensor`: a refreshable materialized view refreshed every - minute from the replicated raw rows and activity membership. + minute from the copied raw rows and activity membership. - `analytics.activity_summary`: a refreshable materialized view refreshed from `analytics.deduped_sensor`. +The native-table backfill is resumable within a successful migration attempt, +but migration `0006_backfill_native_metric_stream` intentionally drops the +backfill checkpoint table before rebuilding the raw table. If the migration +container fails before recording the migration, the next retry starts from a +clean raw table instead of trusting stale chunk checkpoints. + Postgres still runs with `wal_level=logical`, `max_replication_slots`, and -`max_wal_senders` enabled so ClickHouse can subscribe to raw metric stream -changes. +`max_wal_senders` enabled for future CDC tooling. ClickHouse's built-in +`MaterializedPostgreSQL` engine is not the CDC path for `metric_stream`. API startup only verifies that the migrated ClickHouse tables exist. It must not create or rewrite analytical schema, because production runs multiple web diff --git a/docs/production-incident-baseline.md b/docs/production-incident-baseline.md index 21021e0e99..a9b45b3b45 100644 --- a/docs/production-incident-baseline.md +++ b/docs/production-incident-baseline.md @@ -2061,14 +2061,19 @@ manual historical backfill. ### Fix or Mitigation -No code fix has been deployed yet. The next migration needs to keep the -`MaterializedPostgreSQL` table read-only and write historical rows into a -ClickHouse-native table, or replace the replication source strategy entirely. +The code fix replaces the `MaterializedPostgreSQL` target with a +ClickHouse-native `postgres_fitness.metric_stream` `MergeTree` table and adds +ClickHouse migration `0006_backfill_native_metric_stream`. That migration drops +the broken read-only database, recreates the raw scalar table and analytics +views, backfills by real Timescale chunk ranges through the `postgresql(...)` +table function, records completed ranges in +`analytics.metric_stream_backfill_chunks`, and refreshes the ClickHouse +read-model views after the backfill. ### Remaining Risk -`analytics.deduped_sensor` remains empty because its raw ClickHouse metric -stream source is empty. Any strategy that keeps `MaterializedPostgreSQL` must -also handle Timescale chunk publications and prove that chunk inserts map back -into `postgres_fitness.metric_stream`; otherwise the canonical ClickHouse source -needs to move to a ClickHouse-native ingestion path. +`analytics.deduped_sensor` remains empty until the native-table migration +deploys and finishes. This fixes the historical backfill/read-only problem, but +it is still a batch copy path rather than a long-running WAL CDC service; a +future PeerDB/ClickPipes-style CDC pipeline is still the better steady-state +answer for continuous Timescale chunk changes. diff --git a/src/db/clickhouse-migrations.test.ts b/src/db/clickhouse-migrations.test.ts index a75e38ee05..907fed030b 100644 --- a/src/db/clickhouse-migrations.test.ts +++ b/src/db/clickhouse-migrations.test.ts @@ -27,8 +27,8 @@ describe("buildClickHouseMigrationStatements", () => { expect(sql).toContain("DROP DATABASE IF EXISTS postgres_fitness SYNC"); expect(sql).toContain("CREATE TABLE IF NOT EXISTS postgres_fitness.metric_stream"); expect(sql).toContain("ENGINE = MergeTree"); - expect(sql).toContain("ENGINE = MaterializedPostgreSQL"); - expect(sql).toContain("materialized_postgresql_tables_list = 'metric_stream'"); + expect(sql).not.toContain("ENGINE = MaterializedPostgreSQL"); + expect(sql).not.toContain("materialized_postgresql_tables_list = 'metric_stream'"); expect(sql).toContain( "ENGINE = PostgreSQL('db:5432', 'health', 'health', 'secret', 'clickhouse')", ); @@ -59,7 +59,7 @@ describe("runClickHouseMigrations", () => { const count = await runClickHouseMigrations(client, "postgres://health:secret@db:5432/health"); - expect(count).toBe(5); + expect(count).toBe(6); expect(command).toHaveBeenCalledWith({ query: "CREATE DATABASE IF NOT EXISTS fitness" }); expect(command).toHaveBeenCalledWith({ query: "CREATE DATABASE IF NOT EXISTS analytics" }); expect(command).toHaveBeenCalledWith( @@ -82,7 +82,7 @@ describe("runClickHouseMigrations", () => { query: expect.stringContaining("CREATE TABLE IF NOT EXISTS postgres_fitness.metric_stream"), }), ); - expect(command).toHaveBeenCalledWith( + expect(command).not.toHaveBeenCalledWith( expect.objectContaining({ query: expect.stringContaining("ENGINE = MaterializedPostgreSQL"), }), @@ -101,7 +101,7 @@ describe("runClickHouseMigrations", () => { ); }); - it("backfills materialized metric stream in Timescale chunk ranges", async () => { + it("backfills native metric stream in Timescale chunk ranges", async () => { pgClientMocks.query.mockResolvedValue({ rows: [ { @@ -121,7 +121,7 @@ describe("runClickHouseMigrations", () => { .mockResolvedValue( queryText.includes("system.tables") ? [{ table_count: 1 }] - : queryText.includes("0005_backfill_materialized_metric_stream") + : queryText.includes("0006_backfill_native_metric_stream") ? [{ migration_count: 0 }] : queryText.includes("metric_stream_backfill_chunks") ? [{ chunk_count: 0 }] diff --git a/src/db/clickhouse-migrations.ts b/src/db/clickhouse-migrations.ts index e5fd54c5a6..4ac83b097a 100644 --- a/src/db/clickhouse-migrations.ts +++ b/src/db/clickhouse-migrations.ts @@ -80,7 +80,11 @@ function clickHouseMigrations(postgresConnectionString: string): ClickHouseMigra }, { id: "0005_backfill_materialized_metric_stream", - run: backfillMaterializedMetricStream, + statements: [], + }, + { + id: "0006_backfill_native_metric_stream", + run: replaceNativeMetricStreamAndBackfill, }, ]; } @@ -138,7 +142,32 @@ ORDER BY id`, return appliedCount; } -async function backfillMaterializedMetricStream( +async function replaceNativeMetricStreamAndBackfill( + client: ClickHouseCommandClient, + postgresConnectionString: string, +): Promise { + const resetStatements = [ + "DROP VIEW IF EXISTS analytics.activity_summary", + "DROP TABLE IF EXISTS analytics.activity_summary", + "DROP VIEW IF EXISTS analytics.deduped_sensor", + "DROP TABLE IF EXISTS analytics.deduped_sensor", + "DROP TABLE IF EXISTS analytics.metric_stream_backfill_chunks", + "DROP DATABASE IF EXISTS postgres_fitness SYNC", + ...buildClickHouseBootstrapStatements(postgresConnectionString), + ]; + + for (const statement of resetStatements) { + await runClickHouseMigrationStatement(client, statement); + } + + await backfillNativeMetricStream(client, postgresConnectionString); + await runClickHouseMigrationStatement(client, "SYSTEM REFRESH VIEW analytics.deduped_sensor"); + await runClickHouseMigrationStatement(client, "SYSTEM WAIT VIEW analytics.deduped_sensor"); + await runClickHouseMigrationStatement(client, "SYSTEM REFRESH VIEW analytics.activity_summary"); + await runClickHouseMigrationStatement(client, "SYSTEM WAIT VIEW analytics.activity_summary"); +} + +async function backfillNativeMetricStream( client: ClickHouseCommandClient, postgresConnectionString: string, ): Promise { @@ -168,9 +197,6 @@ ORDER BY (lower_bound, upper_bound)`, } await client.command({ query: buildMetricStreamBackfillStatement(postgresMetricStreamSource, chunkStart, chunkEnd), - clickhouse_settings: { - allow_experimental_database_materialized_postgresql: 1, - }, }); await client.command({ query: `INSERT INTO analytics.metric_stream_backfill_chunks (lower_bound, upper_bound) @@ -249,24 +275,18 @@ function buildMetricStreamBackfillStatement( recorded_at, user_id, provider_id, - device_id, - source_type, channel, activity_id, scalar, - vector, id ) SELECT metric_stream.recorded_at, metric_stream.user_id, metric_stream.provider_id, - metric_stream.device_id, - metric_stream.source_type, metric_stream.channel, metric_stream.activity_id, metric_stream.scalar, - metric_stream.vector, metric_stream.id FROM ${postgresMetricStreamSource} AS metric_stream WHERE metric_stream.recorded_at >= ${lowerBound} @@ -292,7 +312,6 @@ async function runClickHouseMigrationStatement( await client.command({ query: statement, clickhouse_settings: { - allow_experimental_database_materialized_postgresql: 1, allow_experimental_refreshable_materialized_view: 1, }, }); diff --git a/src/db/clickhouse.test.ts b/src/db/clickhouse.test.ts index c35e42771d..4f98afb916 100644 --- a/src/db/clickhouse.test.ts +++ b/src/db/clickhouse.test.ts @@ -20,7 +20,7 @@ describe("parsePostgresConnectionForClickHouse", () => { }); describe("buildClickHouseBootstrapStatements", () => { - it("creates replicated metric stream source and ClickHouse read models", () => { + it("creates native metric stream source and ClickHouse read models", () => { const sql = buildClickHouseBootstrapStatements("postgres://health:secret@db:5432/health").join( "\n", ); @@ -28,9 +28,10 @@ describe("buildClickHouseBootstrapStatements", () => { expect(sql).toContain("CREATE DATABASE IF NOT EXISTS analytics"); expect(sql).not.toContain("CREATE DATABASE IF NOT EXISTS fitness"); expect(sql).toContain("CREATE DATABASE IF NOT EXISTS postgres_fitness"); - expect(sql).not.toContain("CREATE TABLE IF NOT EXISTS postgres_fitness.metric_stream"); - expect(sql).toContain("ENGINE = MaterializedPostgreSQL"); - expect(sql).toContain("materialized_postgresql_tables_list = 'metric_stream'"); + expect(sql).toContain("CREATE TABLE IF NOT EXISTS postgres_fitness.metric_stream"); + expect(sql).toContain("ENGINE = MergeTree"); + expect(sql).not.toContain("ENGINE = MaterializedPostgreSQL"); + expect(sql).not.toContain("materialized_postgresql_tables_list = 'metric_stream'"); expect(sql).toContain( "ENGINE = PostgreSQL('db:5432', 'health', 'health', 'secret', 'clickhouse')", ); @@ -116,7 +117,7 @@ describe("waitForClickHouseTable", () => { ).rejects.toThrow("ClickHouse table verification requires a query-capable client"); }); - it("waits for MaterializedPostgreSQL tables that appear after the initial snapshot starts", async () => { + it("waits for ClickHouse tables that appear after startup", async () => { vi.useFakeTimers(); try { let queryCount = 0; diff --git a/src/db/clickhouse.ts b/src/db/clickhouse.ts index 8f96571d50..cbe6e90fa0 100644 --- a/src/db/clickhouse.ts +++ b/src/db/clickhouse.ts @@ -68,41 +68,27 @@ export function parsePostgresConnectionForClickHouse( } export function buildClickHouseBootstrapStatements(postgresConnectionString: string): string[] { - return buildClickHouseBootstrapStatementsForMetricStreamSource( - postgresConnectionString, - "materialized-postgresql", - ); + return buildClickHouseBootstrapStatementsForNativeMetricStream(postgresConnectionString); } export function buildClickHousePlaceholderBootstrapStatements( postgresConnectionString: string, ): string[] { - return buildClickHouseBootstrapStatementsForMetricStreamSource( - postgresConnectionString, - "placeholder", - ); + return buildClickHouseBootstrapStatementsForNativeMetricStream(postgresConnectionString); } -function buildClickHouseBootstrapStatementsForMetricStreamSource( +function buildClickHouseBootstrapStatementsForNativeMetricStream( postgresConnectionString: string, - metricStreamSource: "materialized-postgresql" | "placeholder", ): string[] { const postgres = parsePostgresConnectionForClickHouse(postgresConnectionString); const hostAndPort = clickHouseStringLiteral(postgres.hostAndPort); const database = clickHouseStringLiteral(postgres.database); const user = clickHouseStringLiteral(postgres.user); const password = clickHouseStringLiteral(postgres.password); - const metricStreamStatements = - metricStreamSource === "materialized-postgresql" - ? [ - `CREATE DATABASE IF NOT EXISTS postgres_fitness -ENGINE = MaterializedPostgreSQL(${hostAndPort}, ${database}, ${user}, ${password}) -SETTINGS materialized_postgresql_schema = 'fitness', - materialized_postgresql_tables_list = 'metric_stream'`, - ] - : [ - "CREATE DATABASE IF NOT EXISTS postgres_fitness", - `CREATE TABLE IF NOT EXISTS postgres_fitness.metric_stream ( + const metricStreamStatements = [ + "CREATE DATABASE IF NOT EXISTS postgres_fitness", + `CREATE TABLE IF NOT EXISTS postgres_fitness.metric_stream ( + id UUID, activity_id Nullable(UUID), user_id UUID, recorded_at DateTime64(6, 'UTC'), @@ -111,9 +97,9 @@ SETTINGS materialized_postgresql_schema = 'fitness', scalar Nullable(Float32) ) ENGINE = MergeTree -ORDER BY (user_id, activity_id, channel, recorded_at) +ORDER BY (user_id, activity_id, channel, recorded_at, id) SETTINGS allow_nullable_key = 1`, - ]; + ]; return [ "CREATE DATABASE IF NOT EXISTS analytics", From ecd51a765003d5ccc53ad500b8bd54fbc2f74548 Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Fri, 1 May 2026 15:23:32 -0700 Subject: [PATCH 36/36] Use PeerDB SQL template for metric stream CDC --- cspell.json | 1 + deploy/README.md | 2 +- docs/clickhouse-metric-stream.md | 9 +- docs/production-incident-baseline.md | 13 +- knip.json | 1 + src/db/clickhouse-cdc.test.ts | 321 +++++++++++++++++++++------ src/db/clickhouse-cdc.ts | 166 ++++++-------- src/db/clickhouse-migrations.test.ts | 177 ++++++++++++++- src/db/peerdb/metric-stream-cdc.sql | 36 +++ src/db/setup-clickhouse-cdc.test.ts | 32 +++ 10 files changed, 571 insertions(+), 187 deletions(-) create mode 100644 src/db/peerdb/metric-stream-cdc.sql create mode 100644 src/db/setup-clickhouse-cdc.test.ts diff --git a/cspell.json b/cspell.json index 8e92b41204..d7bfb92e80 100644 --- a/cspell.json +++ b/cspell.json @@ -27,6 +27,7 @@ "Wreturn", "timescale", "timescaledb", + "peerdb", "ClickHouse", "CLICKHOUSE", "clickhouse", diff --git a/deploy/README.md b/deploy/README.md index f5e39e7879..9e5bbc1f69 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -142,7 +142,7 @@ CI (main) -> build dofek + dofek-ml (same tag) 8. Validate required host bind-mount directories before deploying the stack. This must fail before `docker stack deploy` if paths such as `/mnt/dofek-data/redis` are missing, because Swarm rejects tasks with missing bind sources. 9. `docker stack deploy -c deploy/stack.yml --with-registry-auth --prune --detach=false dofek` — swarm performs a single stack-wide update, including `training-export-worker`, and CI waits for the rollout to converge before continuing. The deploy workflow bounds this wait at 20 minutes so a wedged Swarm rollback fails CI instead of running indefinitely. The workflow parses the Infisical dotenv file inside a child process for stack interpolation. Do not append the full dotenv file to `GITHUB_ENV`; GitHub Actions prints step environments and can expose Infisical-only secrets that GitHub does not automatically mask. - 10. Wait for PeerDB and run the one-shot ClickHouse CDC setup command. The command creates the Postgres peer, ClickHouse peer, and `dofek_metric_stream_cdc` mirror if they do not already exist. + 10. Wait for PeerDB and run the one-shot ClickHouse CDC setup command. The command loads `src/db/peerdb/metric-stream-cdc.sql`, substitutes deployment connection values, and creates the Postgres peer, ClickHouse peer, and `dofek_metric_stream_cdc` mirror if they do not already exist. 11. Run the materialized-view sync planner. It triggers the refresh webhook only when one of these is true: - a canonical `drizzle/_views/*.sql` hash changed - a stored dependency fingerprint for a materialized view changed diff --git a/docs/clickhouse-metric-stream.md b/docs/clickhouse-metric-stream.md index 6396136ab9..0b2437ea5f 100644 --- a/docs/clickhouse-metric-stream.md +++ b/docs/clickhouse-metric-stream.md @@ -87,10 +87,11 @@ clean raw table instead of trusting stale chunk checkpoints. Postgres runs with `wal_level=logical`, `max_replication_slots`, and `max_wal_senders` enabled for PeerDB. The deploy workflow runs `src/db/setup-clickhouse-cdc.ts` after `docker stack deploy`; that command -creates the PeerDB Postgres peer, ClickHouse peer, and -`dofek_metric_stream_cdc` mirror if they do not already exist. The mirror uses a -dedicated publication name, excludes `device_id`, `source_type`, and `vector`, -and enables soft deletes so delete events are represented in ClickHouse. +loads `src/db/peerdb/metric-stream-cdc.sql`, substitutes deployment +connection values, and applies the declarative PeerDB peer and mirror +definition. The mirror uses a dedicated publication name, excludes `device_id`, +`source_type`, and `vector`, and enables soft deletes so delete events are +represented in ClickHouse. ClickHouse's built-in `MaterializedPostgreSQL` engine is not the CDC path for `metric_stream`. diff --git a/docs/production-incident-baseline.md b/docs/production-incident-baseline.md index 56c29befce..84844ff6be 100644 --- a/docs/production-incident-baseline.md +++ b/docs/production-incident-baseline.md @@ -2101,12 +2101,13 @@ only covered historical batch copy. ### Fix or Mitigation -Added internal PeerDB services to the swarm and a one-shot TypeScript setup -command that creates the PeerDB Postgres peer, ClickHouse peer, and -`dofek_metric_stream_cdc` mirror. The mirror writes into -`peerdb.metric_stream`, excludes unused non-scalar columns, and uses soft -deletes. The production analytics read path intentionally stays on -`postgres_fitness.metric_stream` until the PeerDB initial snapshot is verified. +Added internal PeerDB services to the swarm and a one-shot setup command that +applies the declarative `src/db/peerdb/metric-stream-cdc.sql` definition for +the PeerDB Postgres peer, ClickHouse peer, and `dofek_metric_stream_cdc` +mirror. The mirror writes into `peerdb.metric_stream`, excludes unused +non-scalar columns, and uses soft deletes. The production analytics read path +intentionally stays on `postgres_fitness.metric_stream` until the PeerDB +initial snapshot is verified. ### Remaining Risk diff --git a/knip.json b/knip.json index 5367a26d44..d913447832 100644 --- a/knip.json +++ b/knip.json @@ -4,6 +4,7 @@ "entry": [ "src/index.ts", "src/server.ts", + "src/db/setup-clickhouse-cdc.ts", "src/jobs/worker.ts", "vitest.config.mutation.ts" ], diff --git a/src/db/clickhouse-cdc.test.ts b/src/db/clickhouse-cdc.test.ts index c7764242ce..394b915863 100644 --- a/src/db/clickhouse-cdc.test.ts +++ b/src/db/clickhouse-cdc.test.ts @@ -1,76 +1,259 @@ -import { describe, expect, it } from "vitest"; -import { - buildClickHousePeerStatement, - buildMetricStreamMirrorStatement, - buildPostgresPeerStatement, -} from "./clickhouse-cdc.ts"; - -describe("PeerDB ClickHouse CDC setup statements", () => { - it("creates a Postgres peer for the app database", () => { - expect( - buildPostgresPeerStatement({ - peerName: "dofek_postgres", - host: "db", - port: 5432, - user: "health", - password: "secret", - database: "health", - }), - ).toBe(`CREATE PEER IF NOT EXISTS dofek_postgres FROM POSTGRES WITH -( - host = 'db', - port = '5432', - user = 'health', - password = 'secret', - database = 'health' -)`); +import { readFile } from "node:fs/promises"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +const peerDbClientMocks = vi.hoisted(() => ({ + Client: vi.fn(), + connect: vi.fn(), + end: vi.fn(), + query: vi.fn(), +})); + +const clickHouseClientMocks = vi.hoisted(() => ({ + close: vi.fn(), + command: vi.fn(), + createClickHouseClientFromEnv: vi.fn(), +})); + +vi.mock("pg", () => ({ + Client: peerDbClientMocks.Client, +})); + +vi.mock("./clickhouse.ts", () => ({ + createClickHouseClientFromEnv: clickHouseClientMocks.createClickHouseClientFromEnv, +})); + +import { setupClickHouseCdc, setupClickHouseCdcFromEnv } from "./clickhouse-cdc.ts"; + +function credentialedUrl( + protocol: "http" | "postgres", + username: string, + credential: string, + hostAndPort: string, + path: string, +): string { + const url = new URL(`${protocol}://${hostAndPort}${path}`); + url.username = username; + url.password = credential; + return url.toString(); +} + +describe("PeerDB ClickHouse CDC setup", () => { + const originalDatabaseUrl = process.env.DATABASE_URL; + const originalClickHouseUrl = process.env.CLICKHOUSE_URL; + const originalPostgresPassword = process.env.POSTGRES_PASSWORD; + const originalTemplatePath = process.env.PEERDB_CDC_SQL_TEMPLATE_PATH; + + beforeEach(() => { + peerDbClientMocks.Client.mockReset().mockImplementation(() => peerDbClientMocks); + peerDbClientMocks.connect.mockReset().mockResolvedValue(undefined); + peerDbClientMocks.end.mockReset().mockResolvedValue(undefined); + peerDbClientMocks.query.mockReset().mockResolvedValue(undefined); + clickHouseClientMocks.command.mockReset().mockResolvedValue(undefined); + clickHouseClientMocks.close.mockReset().mockResolvedValue(undefined); + clickHouseClientMocks.createClickHouseClientFromEnv + .mockReset() + .mockReturnValue(clickHouseClientMocks); + delete process.env.PEERDB_CDC_SQL_TEMPLATE_PATH; }); - it("creates a ClickHouse peer using the native protocol port", () => { - expect( - buildClickHousePeerStatement({ - peerName: "dofek_clickhouse", - host: "clickhouse", - port: 9000, - user: "default", - password: "clickhouse-secret", - database: "peerdb", - }), - ).toBe(`CREATE PEER IF NOT EXISTS dofek_clickhouse FROM CLICKHOUSE WITH -( - host = 'clickhouse', - port = 9000, - user = 'default', - password = 'clickhouse-secret', - database = 'peerdb', - disable_tls = true -)`); + afterEach(() => { + if (originalDatabaseUrl === undefined) { + delete process.env.DATABASE_URL; + } else { + process.env.DATABASE_URL = originalDatabaseUrl; + } + if (originalClickHouseUrl === undefined) { + delete process.env.CLICKHOUSE_URL; + } else { + process.env.CLICKHOUSE_URL = originalClickHouseUrl; + } + if (originalPostgresPassword === undefined) { + delete process.env.POSTGRES_PASSWORD; + } else { + process.env.POSTGRES_PASSWORD = originalPostgresPassword; + } + if (originalTemplatePath === undefined) { + delete process.env.PEERDB_CDC_SQL_TEMPLATE_PATH; + } else { + process.env.PEERDB_CDC_SQL_TEMPLATE_PATH = originalTemplatePath; + } + }); + + it("executes a declarative PeerDB SQL template with escaped runtime values", async () => { + const peerDbQueries: string[] = []; + const clickHouseCommands: string[] = []; + + await setupClickHouseCdc({ + peerDbClient: { + async query(queryText) { + peerDbQueries.push(queryText); + }, + }, + clickHouseClient: { + async command(options) { + clickHouseCommands.push(options.query); + }, + }, + templateSql: "host = {{POSTGRES_HOST}}, password = {{POSTGRES_CREDENTIAL}}", + templateValues: { + clickHouseDatabase: "peerdb", + clickHouseHost: "clickhouse", + clickHouseCredential: "clickhouse-fixture", + clickHousePort: 9000, + clickHouseUser: "default", + postgresDatabase: "health", + postgresHost: "db", + postgresCredential: "pa'ss\\word", + postgresPort: 5432, + postgresUser: "health", + }, + }); + + expect(clickHouseCommands).toEqual(["CREATE DATABASE IF NOT EXISTS peerdb"]); + expect(peerDbQueries).toEqual(["host = 'db', password = 'pa\\'ss\\\\word'"]); }); - it("creates a metric stream mirror that excludes columns not used by analytics", () => { - expect( - buildMetricStreamMirrorStatement({ - mirrorName: "dofek_metric_stream_cdc", - sourcePeerName: "dofek_postgres", - destinationPeerName: "dofek_clickhouse", - publicationName: "peerdb_metric_stream_publication", + it("fails when the PeerDB SQL template references an unknown placeholder", async () => { + await expect( + setupClickHouseCdc({ + peerDbClient: { + async query() {}, + }, + clickHouseClient: { + async command() {}, + }, + templateSql: "missing = {{MISSING_VALUE}}", + templateValues: { + clickHouseDatabase: "peerdb", + clickHouseHost: "clickhouse", + clickHouseCredential: "clickhouse-fixture", + clickHousePort: 9000, + clickHouseUser: "default", + postgresDatabase: "health", + postgresHost: "db", + postgresCredential: "fixture", + postgresPort: 5432, + postgresUser: "health", + }, }), - ).toBe(`CREATE MIRROR IF NOT EXISTS dofek_metric_stream_cdc -FROM dofek_postgres TO dofek_clickhouse -WITH TABLE MAPPING -( - { - from: fitness.metric_stream, - to: metric_stream, - exclude: [device_id, source_type, vector] - } -) -WITH ( - do_initial_copy = true, - max_batch_size = 1000000, - sync_interval = 60, - publication_name = 'peerdb_metric_stream_publication', - soft_delete = true -)`); + ).rejects.toThrow("Unknown PeerDB SQL template placeholder: MISSING_VALUE"); + }); + + it("renders the checked-in metric stream CDC template", async () => { + const peerDbQueries: string[] = []; + const templateSql = await readFile("src/db/peerdb/metric-stream-cdc.sql", "utf8"); + + await setupClickHouseCdc({ + peerDbClient: { + async query(queryText) { + peerDbQueries.push(queryText); + }, + }, + clickHouseClient: { + async command() {}, + }, + templateSql, + templateValues: { + clickHouseDatabase: "peerdb", + clickHouseHost: "clickhouse", + clickHouseCredential: "clickhouse-fixture", + clickHousePort: 9000, + clickHouseUser: "default", + postgresDatabase: "health", + postgresHost: "db", + postgresCredential: "fixture", + postgresPort: 5432, + postgresUser: "health", + }, + }); + + expect(peerDbQueries[0]).toContain("CREATE PEER IF NOT EXISTS dofek_postgres"); + expect(peerDbQueries[0]).toContain("CREATE PEER IF NOT EXISTS dofek_clickhouse"); + expect(peerDbQueries[0]).toContain("CREATE MIRROR IF NOT EXISTS dofek_metric_stream_cdc"); + expect(peerDbQueries[0]).not.toContain("{{"); + }); + + it("configures PeerDB CDC from environment values and closes clients", async () => { + process.env.DATABASE_URL = credentialedUrl( + "postgres", + "health", + "pg'credential", + "postgres.example:6543", + "/fitness", + ); + process.env.CLICKHOUSE_URL = credentialedUrl( + "http", + "analytics", + "click\\credential", + "clickhouse.example:8123", + "", + ); + process.env.POSTGRES_PASSWORD = "peerdb fixture"; + + await setupClickHouseCdcFromEnv(); + + expect(peerDbClientMocks.Client).toHaveBeenCalledWith({ + connectionString: credentialedUrl( + "postgres", + "peerdb", + "peerdb fixture", + "peerdb:9900", + "/peerdb", + ), + }); + expect(clickHouseClientMocks.createClickHouseClientFromEnv).toHaveBeenCalled(); + expect(peerDbClientMocks.connect).toHaveBeenCalledTimes(1); + expect(clickHouseClientMocks.command).toHaveBeenCalledWith({ + query: "CREATE DATABASE IF NOT EXISTS peerdb", + }); + const peerDbQuery = String(peerDbClientMocks.query.mock.calls[0]?.[0]); + expect(peerDbQuery).toContain("host = 'postgres.example'"); + expect(peerDbQuery).toContain("port = '6543'"); + expect(peerDbQuery).toContain("password = 'pg\\'credential'"); + expect(peerDbQuery).toContain("host = 'clickhouse'"); + expect(peerDbQuery).toContain("password = 'click\\\\credential'"); + expect(peerDbQuery).not.toContain("{{"); + expect(peerDbClientMocks.end).toHaveBeenCalledTimes(1); + expect(clickHouseClientMocks.close).toHaveBeenCalledTimes(1); + }); + + it("fails loudly when required environment values are missing", async () => { + process.env.DATABASE_URL = credentialedUrl( + "postgres", + "health", + "fixture", + "postgres.example:6543", + "/fitness", + ); + process.env.CLICKHOUSE_URL = credentialedUrl( + "http", + "analytics", + "fixture", + "clickhouse.example:8123", + "", + ); + delete process.env.POSTGRES_PASSWORD; + + await expect(setupClickHouseCdcFromEnv()).rejects.toThrow( + "POSTGRES_PASSWORD environment variable is required", + ); + expect(peerDbClientMocks.Client).not.toHaveBeenCalled(); + }); + + it("requires ClickHouse credentials for PeerDB setup", async () => { + process.env.DATABASE_URL = credentialedUrl( + "postgres", + "health", + "fixture", + "postgres.example:6543", + "/fitness", + ); + process.env.CLICKHOUSE_URL = "http://analytics@clickhouse.example:8123"; + process.env.POSTGRES_PASSWORD = "peerdb fixture"; + + await expect(setupClickHouseCdcFromEnv()).rejects.toThrow( + "CLICKHOUSE_URL must include a password for PeerDB setup", + ); + expect(peerDbClientMocks.Client).not.toHaveBeenCalled(); }); }); diff --git a/src/db/clickhouse-cdc.ts b/src/db/clickhouse-cdc.ts index c5fe7fc1cb..a02f0dfe9d 100644 --- a/src/db/clickhouse-cdc.ts +++ b/src/db/clickhouse-cdc.ts @@ -1,48 +1,35 @@ +import { readFile } from "node:fs/promises"; import { Client } from "pg"; import { type ClickHouseCommandClient, createClickHouseClientFromEnv } from "./clickhouse.ts"; -export interface PostgresPeerConfig { - peerName: string; - host: string; - port: number; - user: string; - password: string; - database: string; -} - -export interface ClickHousePeerConfig { - peerName: string; - host: string; - port: number; - user: string; - password: string; - database: string; -} - -export interface MetricStreamMirrorConfig { - mirrorName: string; - sourcePeerName: string; - destinationPeerName: string; - publicationName: string; -} - interface PeerDbClient { query(queryText: string): Promise; } +export interface PeerDbSqlTemplateValues { + clickHouseDatabase: string; + clickHouseCredential: string; + clickHouseHost: string; + clickHousePort: number; + clickHouseUser: string; + postgresCredential: string; + postgresDatabase: string; + postgresHost: string; + postgresPort: number; + postgresUser: string; +} + interface SetupClickHouseCdcOptions { peerDbClient: PeerDbClient; clickHouseClient: ClickHouseCommandClient; - postgresPeer: PostgresPeerConfig; - clickHousePeer: ClickHousePeerConfig; - mirror: MetricStreamMirrorConfig; + templateSql: string; + templateValues: PeerDbSqlTemplateValues; } interface RuntimeConfig { peerDbUrl: string; - postgresPeer: PostgresPeerConfig; - clickHousePeer: ClickHousePeerConfig; - mirror: MetricStreamMirrorConfig; + templatePath: string; + templateValues: PeerDbSqlTemplateValues; } function peerDbStringLiteral(value: string): string { @@ -57,8 +44,11 @@ function requireEnv(name: string): string { return value; } -function buildDefaultPeerDbUrl(password: string): string { - return `postgres://peerdb:${encodeURIComponent(password)}@peerdb:9900/peerdb`; +function buildDefaultPeerDbUrl(credential: string): string { + const peerDbUrl = new URL("postgres://peerdb:9900/peerdb"); + peerDbUrl.username = "peerdb"; + peerDbUrl.password = credential; + return peerDbUrl.toString(); } function parseClickHouseUrl(urlString: string): URL { @@ -75,98 +65,72 @@ function parseClickHouseUrl(urlString: string): URL { function buildRuntimeConfig(): RuntimeConfig { const databaseUrl = new URL(requireEnv("DATABASE_URL")); const clickHouseUrl = parseClickHouseUrl(requireEnv("CLICKHOUSE_URL")); - const postgresPassword = requireEnv("POSTGRES_PASSWORD"); + const postgresCredential = requireEnv("POSTGRES_PASSWORD"); return { - peerDbUrl: buildDefaultPeerDbUrl(postgresPassword), - postgresPeer: { - peerName: "dofek_postgres", - host: databaseUrl.hostname, - port: Number(databaseUrl.port || 5432), - user: decodeURIComponent(databaseUrl.username), - password: decodeURIComponent(databaseUrl.password), - database: databaseUrl.pathname.replace(/^\//, ""), - }, - clickHousePeer: { - peerName: "dofek_clickhouse", - host: "clickhouse", - port: 9000, - user: decodeURIComponent(clickHouseUrl.username), - password: decodeURIComponent(clickHouseUrl.password), - database: "peerdb", - }, - mirror: { - mirrorName: "dofek_metric_stream_cdc", - sourcePeerName: "dofek_postgres", - destinationPeerName: "dofek_clickhouse", - publicationName: "peerdb_metric_stream_publication", + peerDbUrl: buildDefaultPeerDbUrl(postgresCredential), + templatePath: process.env.PEERDB_CDC_SQL_TEMPLATE_PATH ?? "src/db/peerdb/metric-stream-cdc.sql", + templateValues: { + clickHouseDatabase: "peerdb", + clickHouseCredential: decodeURIComponent(clickHouseUrl.password), + clickHouseHost: "clickhouse", + clickHousePort: 9000, + clickHouseUser: decodeURIComponent(clickHouseUrl.username), + postgresCredential: decodeURIComponent(databaseUrl.password), + postgresDatabase: databaseUrl.pathname.replace(/^\//, ""), + postgresHost: databaseUrl.hostname, + postgresPort: Number(databaseUrl.port || 5432), + postgresUser: decodeURIComponent(databaseUrl.username), }, }; } -export function buildPostgresPeerStatement(config: PostgresPeerConfig): string { - return `CREATE PEER IF NOT EXISTS ${config.peerName} FROM POSTGRES WITH -( - host = ${peerDbStringLiteral(config.host)}, - port = ${peerDbStringLiteral(String(config.port))}, - user = ${peerDbStringLiteral(config.user)}, - password = ${peerDbStringLiteral(config.password)}, - database = ${peerDbStringLiteral(config.database)} -)`; -} - -export function buildClickHousePeerStatement(config: ClickHousePeerConfig): string { - return `CREATE PEER IF NOT EXISTS ${config.peerName} FROM CLICKHOUSE WITH -( - host = ${peerDbStringLiteral(config.host)}, - port = ${config.port}, - user = ${peerDbStringLiteral(config.user)}, - password = ${peerDbStringLiteral(config.password)}, - database = ${peerDbStringLiteral(config.database)}, - disable_tls = true -)`; +function buildTemplateReplacements(values: PeerDbSqlTemplateValues): Record { + return { + CLICKHOUSE_DATABASE: peerDbStringLiteral(values.clickHouseDatabase), + CLICKHOUSE_CREDENTIAL: peerDbStringLiteral(values.clickHouseCredential), + CLICKHOUSE_HOST: peerDbStringLiteral(values.clickHouseHost), + CLICKHOUSE_PORT: String(values.clickHousePort), + CLICKHOUSE_USER: peerDbStringLiteral(values.clickHouseUser), + POSTGRES_CREDENTIAL: peerDbStringLiteral(values.postgresCredential), + POSTGRES_DATABASE: peerDbStringLiteral(values.postgresDatabase), + POSTGRES_HOST: peerDbStringLiteral(values.postgresHost), + POSTGRES_PORT: peerDbStringLiteral(String(values.postgresPort)), + POSTGRES_USER: peerDbStringLiteral(values.postgresUser), + }; } -export function buildMetricStreamMirrorStatement(config: MetricStreamMirrorConfig): string { - return `CREATE MIRROR IF NOT EXISTS ${config.mirrorName} -FROM ${config.sourcePeerName} TO ${config.destinationPeerName} -WITH TABLE MAPPING -( - { - from: fitness.metric_stream, - to: metric_stream, - exclude: [device_id, source_type, vector] - } -) -WITH ( - do_initial_copy = true, - max_batch_size = 1000000, - sync_interval = 60, - publication_name = ${peerDbStringLiteral(config.publicationName)}, - soft_delete = true -)`; +function renderPeerDbSqlTemplate(templateSql: string, values: PeerDbSqlTemplateValues): string { + const replacements = buildTemplateReplacements(values); + return templateSql.replaceAll(/\{\{([A-Z0-9_]+)\}\}/g, (_match, placeholderName: string) => { + const replacement = replacements[placeholderName]; + if (replacement === undefined) { + throw new Error(`Unknown PeerDB SQL template placeholder: ${placeholderName}`); + } + return replacement; + }); } export async function setupClickHouseCdc(options: SetupClickHouseCdcOptions): Promise { await options.clickHouseClient.command({ query: "CREATE DATABASE IF NOT EXISTS peerdb" }); - await options.peerDbClient.query(buildPostgresPeerStatement(options.postgresPeer)); - await options.peerDbClient.query(buildClickHousePeerStatement(options.clickHousePeer)); - await options.peerDbClient.query(buildMetricStreamMirrorStatement(options.mirror)); + await options.peerDbClient.query( + renderPeerDbSqlTemplate(options.templateSql, options.templateValues), + ); } export async function setupClickHouseCdcFromEnv(): Promise { const config = buildRuntimeConfig(); const peerDbClient = new Client({ connectionString: config.peerDbUrl }); const clickHouseClient = createClickHouseClientFromEnv(); + const templateSql = await readFile(config.templatePath, "utf8"); try { await peerDbClient.connect(); await setupClickHouseCdc({ peerDbClient, clickHouseClient, - postgresPeer: config.postgresPeer, - clickHousePeer: config.clickHousePeer, - mirror: config.mirror, + templateSql, + templateValues: config.templateValues, }); } finally { await peerDbClient.end(); diff --git a/src/db/clickhouse-migrations.test.ts b/src/db/clickhouse-migrations.test.ts index 907fed030b..8434cff2cb 100644 --- a/src/db/clickhouse-migrations.test.ts +++ b/src/db/clickhouse-migrations.test.ts @@ -1,13 +1,14 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; const pgClientMocks = vi.hoisted(() => ({ + Client: vi.fn(), connect: vi.fn(), end: vi.fn(), query: vi.fn(), })); vi.mock("pg", () => ({ - Client: vi.fn(() => pgClientMocks), + Client: pgClientMocks.Client, })); import { @@ -17,7 +18,7 @@ import { describe("buildClickHouseMigrationStatements", () => { it("keeps destructive cleanup and read-model creation in migration statements", () => { - const sql = buildClickHouseMigrationStatements("postgres://health:secret@db:5432/health").join( + const sql = buildClickHouseMigrationStatements("postgres://health:fixture@db:5432/health").join( "\n", ); @@ -25,20 +26,29 @@ describe("buildClickHouseMigrationStatements", () => { expect(sql).toContain("DROP TABLE IF EXISTS fitness.deduped_sensor"); expect(sql).toContain("DROP TABLE IF EXISTS analytics.deduped_sensor"); expect(sql).toContain("DROP DATABASE IF EXISTS postgres_fitness SYNC"); + expect(sql.match(/DROP DATABASE IF EXISTS postgres_fitness SYNC/g)).toHaveLength(2); expect(sql).toContain("CREATE TABLE IF NOT EXISTS postgres_fitness.metric_stream"); + expect(sql.match(/CREATE TABLE IF NOT EXISTS postgres_fitness.metric_stream/g)).toHaveLength(3); expect(sql).toContain("ENGINE = MergeTree"); expect(sql).not.toContain("ENGINE = MaterializedPostgreSQL"); expect(sql).not.toContain("materialized_postgresql_tables_list = 'metric_stream'"); expect(sql).toContain( - "ENGINE = PostgreSQL('db:5432', 'health', 'health', 'secret', 'clickhouse')", + "ENGINE = PostgreSQL('db:5432', 'health', 'health', 'fixture', 'clickhouse')", ); expect(sql).toContain("CREATE MATERIALIZED VIEW IF NOT EXISTS analytics.deduped_sensor"); + expect( + sql.match(/CREATE MATERIALIZED VIEW IF NOT EXISTS analytics.deduped_sensor/g), + ).toHaveLength(3); expect(sql).toContain("CREATE MATERIALIZED VIEW IF NOT EXISTS analytics.activity_summary"); + expect( + sql.match(/CREATE MATERIALIZED VIEW IF NOT EXISTS analytics.activity_summary/g), + ).toHaveLength(3); }); }); describe("runClickHouseMigrations", () => { beforeEach(() => { + pgClientMocks.Client.mockReset().mockImplementation(() => pgClientMocks); pgClientMocks.connect.mockReset().mockResolvedValue(undefined); pgClientMocks.end.mockReset().mockResolvedValue(undefined); pgClientMocks.query.mockReset().mockResolvedValue({ @@ -57,7 +67,7 @@ describe("runClickHouseMigrations", () => { })); const client = { command, query }; - const count = await runClickHouseMigrations(client, "postgres://health:secret@db:5432/health"); + const count = await runClickHouseMigrations(client, "postgres://health:fixture@db:5432/health"); expect(count).toBe(6); expect(command).toHaveBeenCalledWith({ query: "CREATE DATABASE IF NOT EXISTS fitness" }); @@ -99,6 +109,35 @@ describe("runClickHouseMigrations", () => { query: expect.stringContaining("INSERT INTO analytics.schema_migrations"), }), ); + const systemTableQueries = query.mock.calls.filter(([options]) => + String(options.query).includes("system.tables"), + ); + expect(systemTableQueries).toHaveLength(9); + expect(command).toHaveBeenCalledWith({ + query: expect.stringContaining( + "CREATE MATERIALIZED VIEW IF NOT EXISTS analytics.deduped_sensor", + ), + clickhouse_settings: { + allow_experimental_refreshable_materialized_view: 1, + }, + }); + expect(command).toHaveBeenCalledWith({ + query: expect.stringContaining( + "CREATE MATERIALIZED VIEW IF NOT EXISTS analytics.activity_summary", + ), + clickhouse_settings: { + allow_experimental_refreshable_materialized_view: 1, + }, + }); + }); + + it("fails when the ClickHouse client cannot query migration state", async () => { + await expect( + runClickHouseMigrations( + { command: vi.fn().mockResolvedValue(undefined) }, + "postgres://health:fixture@db:5432/health", + ), + ).rejects.toThrow("ClickHouse migrations require a query-capable client"); }); it("backfills native metric stream in Timescale chunk ranges", async () => { @@ -130,9 +169,14 @@ describe("runClickHouseMigrations", () => { })); const client = { command, query }; - const count = await runClickHouseMigrations(client, "postgres://health:secret@db:5432/health"); + const count = await runClickHouseMigrations(client, "postgres://health:fixture@db:5432/health"); expect(count).toBe(1); + expect(pgClientMocks.Client).toHaveBeenCalledWith({ + connectionString: "postgres://health:fixture@db:5432/health", + }); + expect(pgClientMocks.connect).toHaveBeenCalledTimes(1); + expect(pgClientMocks.end).toHaveBeenCalledTimes(1); expect(command).toHaveBeenCalledWith( expect.objectContaining({ query: expect.stringContaining("INSERT INTO postgres_fitness.metric_stream"), @@ -161,6 +205,127 @@ describe("runClickHouseMigrations", () => { expect(backfillStatements[1]).toContain( "metric_stream.recorded_at < toDateTime64('2026-04-22 12:00:00.000', 6, 'UTC')", ); + const completedChunkStatements = command.mock.calls + .map(([options]) => String(options.query)) + .filter((queryText) => + queryText.includes("INSERT INTO analytics.metric_stream_backfill_chunks"), + ); + expect(completedChunkStatements).toHaveLength(2); + expect(completedChunkStatements[0]).toContain( + "VALUES (toDateTime64('2026-04-22 00:00:00.000', 6, 'UTC'), toDateTime64('2026-04-22 06:00:00.000', 6, 'UTC'))", + ); + expect(completedChunkStatements[1]).toContain( + "VALUES (toDateTime64('2026-04-22 06:00:00.000', 6, 'UTC'), toDateTime64('2026-04-22 12:00:00.000', 6, 'UTC'))", + ); + }); + + it("skips native metric stream chunks already marked complete", async () => { + pgClientMocks.query.mockResolvedValue({ + rows: [ + { + lower_bound: "2026-04-22 00:00:00+00", + upper_bound: "2026-04-22 06:00:00+00", + }, + { + lower_bound: "2026-04-22 06:00:00+00", + upper_bound: "2026-04-22 12:00:00+00", + }, + ], + }); + const command = vi.fn().mockResolvedValue(undefined); + const query = vi.fn().mockImplementation(({ query: queryText }: { query: string }) => ({ + json: vi.fn().mockResolvedValue( + queryText.includes("system.tables") + ? [{ table_count: 1 }] + : queryText.includes("0006_backfill_native_metric_stream") + ? [{ migration_count: 0 }] + : queryText.includes("metric_stream_backfill_chunks") + ? [ + { + chunk_count: queryText.includes("2026-04-22 00:00:00.000") ? 1 : 0, + }, + ] + : [{ migration_count: 1 }], + ), + })); + + const count = await runClickHouseMigrations( + { command, query }, + "postgres://health:fixture@db:5432/health", + ); + + expect(count).toBe(1); + const backfillStatements = command.mock.calls + .map(([options]) => String(options.query)) + .filter((queryText) => queryText.includes("INSERT INTO postgres_fitness.metric_stream")); + expect(backfillStatements).toHaveLength(1); + expect(backfillStatements[0]).toContain( + "metric_stream.recorded_at >= toDateTime64('2026-04-22 06:00:00.000', 6, 'UTC')", + ); + }); + + it("does not create backfill tracking when Timescale has no metric stream chunks", async () => { + const command = vi.fn().mockResolvedValue(undefined); + const query = vi.fn().mockImplementation(({ query: queryText }: { query: string }) => ({ + json: vi + .fn() + .mockResolvedValue( + queryText.includes("system.tables") + ? [{ table_count: 1 }] + : queryText.includes("0006_backfill_native_metric_stream") + ? [{ migration_count: 0 }] + : [{ migration_count: 1 }], + ), + })); + + const count = await runClickHouseMigrations( + { command, query }, + "postgres://health:fixture@db:5432/health", + ); + + expect(count).toBe(1); + expect(command).not.toHaveBeenCalledWith( + expect.objectContaining({ + query: expect.stringContaining( + "CREATE TABLE IF NOT EXISTS analytics.metric_stream_backfill_chunks", + ), + }), + ); + expect(command).not.toHaveBeenCalledWith( + expect.objectContaining({ + query: expect.stringContaining("INSERT INTO postgres_fitness.metric_stream"), + }), + ); + }); + + it("rejects invalid Timescale metric stream chunk bounds", async () => { + pgClientMocks.query.mockResolvedValue({ + rows: [ + { + lower_bound: "not-a-timestamp", + upper_bound: "2026-04-22 06:00:00+00", + }, + ], + }); + const query = vi.fn().mockImplementation(({ query: queryText }: { query: string }) => ({ + json: vi + .fn() + .mockResolvedValue( + queryText.includes("system.tables") + ? [{ table_count: 1 }] + : queryText.includes("0006_backfill_native_metric_stream") + ? [{ migration_count: 0 }] + : [{ migration_count: 1 }], + ), + })); + + await expect( + runClickHouseMigrations( + { command: vi.fn().mockResolvedValue(undefined), query }, + "postgres://health:fixture@db:5432/health", + ), + ).rejects.toThrow("Invalid metric_stream chunk lower bound: not-a-timestamp"); + expect(pgClientMocks.end).toHaveBeenCalledTimes(1); }); it("skips already-applied ClickHouse migrations", async () => { @@ -170,7 +335,7 @@ describe("runClickHouseMigrations", () => { }); const client = { command, query }; - const count = await runClickHouseMigrations(client, "postgres://health:secret@db:5432/health"); + const count = await runClickHouseMigrations(client, "postgres://health:fixture@db:5432/health"); expect(count).toBe(0); expect(command).not.toHaveBeenCalledWith( diff --git a/src/db/peerdb/metric-stream-cdc.sql b/src/db/peerdb/metric-stream-cdc.sql new file mode 100644 index 0000000000..4d95cd8081 --- /dev/null +++ b/src/db/peerdb/metric-stream-cdc.sql @@ -0,0 +1,36 @@ +CREATE PEER IF NOT EXISTS dofek_postgres FROM POSTGRES WITH +( + host = {{POSTGRES_HOST}}, + port = {{POSTGRES_PORT}}, + user = {{POSTGRES_USER}}, + password = {{POSTGRES_CREDENTIAL}}, + database = {{POSTGRES_DATABASE}} +); + +CREATE PEER IF NOT EXISTS dofek_clickhouse FROM CLICKHOUSE WITH +( + host = {{CLICKHOUSE_HOST}}, + port = {{CLICKHOUSE_PORT}}, + user = {{CLICKHOUSE_USER}}, + password = {{CLICKHOUSE_CREDENTIAL}}, + database = {{CLICKHOUSE_DATABASE}}, + disable_tls = true +); + +CREATE MIRROR IF NOT EXISTS dofek_metric_stream_cdc +FROM dofek_postgres TO dofek_clickhouse +WITH TABLE MAPPING +( + { + from: fitness.metric_stream, + to: metric_stream, + exclude: [device_id, source_type, vector] + } +) +WITH ( + do_initial_copy = true, + max_batch_size = 1000000, + sync_interval = 60, + publication_name = 'peerdb_metric_stream_publication', + soft_delete = true +); diff --git a/src/db/setup-clickhouse-cdc.test.ts b/src/db/setup-clickhouse-cdc.test.ts new file mode 100644 index 0000000000..3a9b6b3920 --- /dev/null +++ b/src/db/setup-clickhouse-cdc.test.ts @@ -0,0 +1,32 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +vi.mock("./clickhouse-cdc.ts", () => ({ + setupClickHouseCdcFromEnv: vi.fn(), +})); + +vi.mock("../logger.ts", () => ({ + logger: { info: vi.fn(), error: vi.fn() }, +})); + +import { logger } from "../logger.ts"; +import { setupClickHouseCdcFromEnv } from "./clickhouse-cdc.ts"; +import { main } from "./setup-clickhouse-cdc.ts"; + +const mockSetupClickHouseCdcFromEnv = vi.mocked(setupClickHouseCdcFromEnv); +const mockLogger = vi.mocked(logger); + +describe("setup-clickhouse-cdc main()", () => { + beforeEach(() => { + mockSetupClickHouseCdcFromEnv.mockReset().mockResolvedValue(undefined); + mockLogger.info.mockReset(); + }); + + it("configures PeerDB CDC and logs success", async () => { + await main(); + + expect(mockSetupClickHouseCdcFromEnv).toHaveBeenCalledTimes(1); + expect(mockLogger.info).toHaveBeenCalledWith( + "[clickhouse-cdc] PeerDB metric_stream CDC mirror is configured", + ); + }); +});