diff --git a/.github/workflows/deploy-web-stack.yml b/.github/workflows/deploy-web-stack.yml index c76d908525..ae25e63434 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: @@ -247,13 +254,20 @@ jobs: docker pull "ghcr.io/asherlc/dofek:${IMAGE_TAG}" docker pull "ghcr.io/asherlc/dofek-ml:${IMAGE_TAG}" docker pull "postgres:18-alpine" + docker pull "ghcr.io/peerdb-io/peerdb-server:stable-v0.36.18" + docker pull "ghcr.io/peerdb-io/flow-api:stable-v0.36.18" + docker pull "ghcr.io/peerdb-io/flow-snapshot-worker:stable-v0.36.18" + docker pull "ghcr.io/peerdb-io/flow-worker:stable-v0.36.18" + docker pull "temporalio/auto-setup:1.29" + docker pull "temporalio/admin-tools:1.29" + docker pull "minio/minio:latest@sha256:14cea493d9a34af32f524e538b8346cf79f3321eff8e708c1e2960462bd8936e" - name: Validate host bind mount paths run: | docker run --rm \ --mount type=bind,source=/mnt/dofek-data,target=/mnt/dofek-data,readonly \ postgres:18-alpine sh -euc ' - for path in /mnt/dofek-data/postgres /mnt/dofek-data/clickhouse /mnt/dofek-data/databasus /mnt/dofek-data/redis; do + for path in /mnt/dofek-data/postgres /mnt/dofek-data/clickhouse /mnt/dofek-data/databasus /mnt/dofek-data/redis /mnt/dofek-data/peerdb-catalog /mnt/dofek-data/peerdb-minio; do if [ ! -d "$path" ]; then echo "::error::Required host bind mount path is missing: $path" exit 1 @@ -323,41 +337,165 @@ jobs: sleep 5 done + - name: Ensure ClickHouse resource limits + run: | + 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: | + 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 }} 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));' - )" - 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." + 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}..." + cleanup_migration_container + docker run --detach --name "$migration_container" --network "${STACK_NAME}_default" \ + --env-file "$INFISICAL_ENV_FILE" \ + --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' + + 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 - migration_exit_code=$? - echo "Migration attempt ${attempt}/12 failed (exit code ${migration_exit_code})." + + 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 + 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" + cleanup_migration_container + echo "::error::Migration failed" + exit 1 + fi + + - name: Deploy stack + env: + IMAGE_TAG: ${{ steps.resolve.outputs.tag }} + run: | + 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 + + 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: Wait for PeerDB + run: | + for attempt in $(seq 1 36); do + peerdb_output=$(timeout 15s docker run --rm --network "${STACK_NAME}_default" \ + --env-file "$INFISICAL_ENV_FILE" \ + postgres:18-alpine sh -euc \ + "PGPASSWORD=\"\$POSTGRES_PASSWORD\" \ + psql --host=peerdb --port=9900 --username=peerdb --dbname=peerdb --no-align --tuples-only --quiet \ + --command \"SELECT 1;\"" 2>&1 || true) + peerdb_state="$(printf '%s\n' "$peerdb_output" | tail -n 1 | tr -d '[:space:]')" + if [ "$peerdb_state" = "1" ]; then + echo "PeerDB is reachable." + break + fi + if [ "$attempt" -eq 36 ]; then + echo "::error::PeerDB did not become reachable within 180s" + printf '%s\n' "$peerdb_output" exit 1 fi - echo "Migration attempt $attempt failed; retrying in 5s..." + echo "PeerDB readiness attempt ${attempt}/36: retrying in 5s..." sleep 5 done - - name: Deploy stack + - name: Configure ClickHouse CDC 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" + docker run --rm --network "${STACK_NAME}_default" \ + --env-file "$INFISICAL_ENV_FILE" \ + --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/setup-clickhouse-cdc.ts' - name: Plan materialized view sync id: view_sync_plan diff --git a/README.md b/README.md index 858ad47a70..678f436f83 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, with scalar `metric_stream` rows copied from Postgres through the tracked ClickHouse migration path. PeerDB is deployed as the internal CDC path from Postgres to ClickHouse, with the first mirror landing in `peerdb.metric_stream` for validation before production analytics switch to it. 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/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 f8c1c1dd17..9e5bbc1f69 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -9,7 +9,8 @@ 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. 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). + - **PeerDB**: Runs internally in the swarm as the Postgres-to-ClickHouse CDC service. Its first `metric_stream` mirror writes to `peerdb.metric_stream`; production analytics keep reading the migrated native copy until that initial snapshot is verified. - **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 +48,8 @@ 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 by ClickHouse change-data capture. +- PeerDB uses an internal catalog Postgres service, Temporal, worker services, and a private MinIO staging bucket. Its persistent catalog and staging data live under `/mnt/dofek-data/peerdb-catalog` and `/mnt/dofek-data/peerdb-minio`. - `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. @@ -125,6 +127,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. 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. @@ -137,9 +140,10 @@ 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: + 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 - an applied migration was marked with `-- requires_materialized_view_refresh` and has not yet been acknowledged by a successful sync diff --git a/deploy/server.tf b/deploy/server.tf index 19ae756c51..92885ccfd7 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-v6", hcloud_volume.dofek_data[0].id, ] @@ -145,7 +145,7 @@ resource "terraform_data" "data_volume_mount_alias" { "target=/mnt/HC_Volume_${hcloud_volume.dofek_data[0].id}", "if [ ! -d \"$target\" ]; then echo \"Expected mounted volume path missing: $target\" >&2; exit 1; fi", "ln -sfn \"$target\" /mnt/dofek-data", - "mkdir -p /mnt/dofek-data/postgres /mnt/dofek-data/clickhouse /mnt/dofek-data/databasus /mnt/dofek-data/redis", + "mkdir -p /mnt/dofek-data/postgres /mnt/dofek-data/clickhouse /mnt/dofek-data/databasus /mnt/dofek-data/redis /mnt/dofek-data/peerdb-catalog /mnt/dofek-data/peerdb-minio", "source_path=$(docker volume inspect -f '{{ .Mountpoint }}' dofek_databasus_data 2>/dev/null || true); if [ -n \"$source_path\" ] && [ -d \"$source_path\" ] && [ -z \"$(find /mnt/dofek-data/databasus -mindepth 1 -print -quit)\" ] && [ -n \"$(find \"$source_path\" -mindepth 1 -print -quit)\" ]; then cp -a \"$source_path\"/. /mnt/dofek-data/databasus/; fi", "source_path=$(docker volume inspect -f '{{ .Mountpoint }}' dofek_redis_data 2>/dev/null || true); if [ -n \"$source_path\" ] && [ -d \"$source_path\" ] && [ -z \"$(find /mnt/dofek-data/redis -mindepth 1 -print -quit)\" ] && [ -n \"$(find \"$source_path\" -mindepth 1 -print -quit)\" ]; then cp -a \"$source_path\"/. /mnt/dofek-data/redis/; fi", ] @@ -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-v4", hcloud_volume.dofek_staging_data[0].id, ] @@ -173,7 +173,7 @@ resource "terraform_data" "staging_data_volume_mount_alias" { "target=/mnt/HC_Volume_${hcloud_volume.dofek_staging_data[0].id}", "if [ ! -d \"$target\" ]; then echo \"Expected mounted volume path missing: $target\" >&2; exit 1; fi", "ln -sfn \"$target\" /mnt/dofek-data", - "mkdir -p /mnt/dofek-data/postgres /mnt/dofek-data/clickhouse /mnt/dofek-data/databasus /mnt/dofek-data/redis", + "mkdir -p /mnt/dofek-data/postgres /mnt/dofek-data/clickhouse /mnt/dofek-data/databasus /mnt/dofek-data/redis /mnt/dofek-data/peerdb-catalog /mnt/dofek-data/peerdb-minio", "source_path=$(docker volume inspect -f '{{ .Mountpoint }}' dofek-staging_redis_data 2>/dev/null || true); if [ -n \"$source_path\" ] && [ -d \"$source_path\" ] && [ -z \"$(find /mnt/dofek-data/redis -mindepth 1 -print -quit)\" ] && [ -n \"$(find \"$source_path\" -mindepth 1 -print -quit)\" ]; then cp -a \"$source_path\"/. /mnt/dofek-data/redis/; fi", ] } diff --git a/deploy/stack.yml b/deploy/stack.yml index c6eaac8aec..e1f1cf3ec1 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} @@ -177,7 +177,108 @@ services: deploy: resources: limits: - memory: 1G + memory: 2G + + peerdb-catalog: + image: postgres:18-alpine + environment: + PGUSER: postgres + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD is required} + POSTGRES_DB: postgres + POSTGRES_INITDB_ARGS: --locale=C.UTF-8 + volumes: + - /mnt/dofek-data/peerdb-catalog:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U postgres -d postgres"] + interval: 10s + timeout: 30s + retries: 5 + start_period: 60s + + peerdb-temporal: + image: temporalio/auto-setup:1.29 + environment: + DB: postgres12 + DB_PORT: "5432" + POSTGRES_USER: postgres + POSTGRES_PWD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD is required} + POSTGRES_SEEDS: peerdb-catalog + DYNAMIC_CONFIG_FILE_PATH: config/dynamicconfig/development-sql.yaml + healthcheck: + test: ["CMD", "tctl", "--address", "127.0.0.1:7233", "workflow", "list"] + interval: 10s + timeout: 10s + retries: 12 + start_period: 60s + + peerdb-temporal-admin-tools: + image: temporalio/admin-tools:1.29 + environment: + TEMPORAL_ADDRESS: peerdb-temporal:7233 + TEMPORAL_CLI_ADDRESS: peerdb-temporal:7233 + TEMPORAL_CLI_SHOW_STACKS: "1" + + peerdb-minio: + image: minio/minio:latest@sha256:14cea493d9a34af32f524e538b8346cf79f3321eff8e708c1e2960462bd8936e + environment: + MINIO_ROOT_USER: _peerdb_minioadmin + MINIO_ROOT_PASSWORD: _peerdb_minioadmin + PEERDB_CLICKHOUSE_AWS_S3_BUCKET_NAME: peerdbbucket + volumes: + - /mnt/dofek-data/peerdb-minio:/data + entrypoint: > + /bin/sh -euc " + minio server /data --console-address=:36987 & + sleep 2; + mc alias set peerdb-minio http://peerdb-minio:9000 $$MINIO_ROOT_USER $$MINIO_ROOT_PASSWORD; + mc mb --ignore-existing peerdb-minio/$$PEERDB_CLICKHOUSE_AWS_S3_BUCKET_NAME; + wait + " + + peerdb-flow-api: + image: ghcr.io/peerdb-io/flow-api:stable-v0.36.18 + environment: &peerdb-flow-environment + PEERDB_CATALOG_HOST: peerdb-catalog + PEERDB_CATALOG_PORT: "5432" + PEERDB_CATALOG_USER: postgres + PEERDB_CATALOG_PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD is required} + PEERDB_CATALOG_DATABASE: postgres + TEMPORAL_HOST_PORT: peerdb-temporal:7233 + TEMPORAL_CLIENT_CERT: "" + TEMPORAL_CLIENT_KEY: "" + PEERDB_TEMPORAL_NAMESPACE: default + PEERDB_ALLOWED_TARGETS: "" + PEERDB_CLICKHOUSE_AWS_CREDENTIALS_AWS_ACCESS_KEY_ID: _peerdb_minioadmin + PEERDB_CLICKHOUSE_AWS_CREDENTIALS_AWS_SECRET_ACCESS_KEY: _peerdb_minioadmin + PEERDB_CLICKHOUSE_AWS_CREDENTIALS_AWS_REGION: us-east-1 + PEERDB_CLICKHOUSE_AWS_CREDENTIALS_AWS_ENDPOINT_URL_S3: http://peerdb-minio:9000 + PEERDB_CLICKHOUSE_AWS_S3_BUCKET_NAME: peerdbbucket + AWS_ACCESS_KEY_ID: "" + AWS_SECRET_ACCESS_KEY: "" + AWS_REGION: "" + AWS_ENDPOINT: "" + + peerdb-flow-snapshot-worker: + image: ghcr.io/peerdb-io/flow-snapshot-worker:stable-v0.36.18 + environment: *peerdb-flow-environment + + peerdb-flow-worker: + image: ghcr.io/peerdb-io/flow-worker:stable-v0.36.18 + environment: *peerdb-flow-environment + + peerdb: + image: ghcr.io/peerdb-io/peerdb-server:stable-v0.36.18 + stop_signal: SIGINT + environment: + PEERDB_CATALOG_HOST: peerdb-catalog + PEERDB_CATALOG_PORT: "5432" + PEERDB_CATALOG_USER: postgres + PEERDB_CATALOG_PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD is required} + PEERDB_CATALOG_DATABASE: postgres + PEERDB_PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD is required} + PEERDB_FLOW_SERVER_ADDRESS: grpc://peerdb-flow-api:8112 + RUST_LOG: info + RUST_BACKTRACE: "1" databasus: image: databasus/databasus:v3.32.1 diff --git a/docs/README.md b/docs/README.md index 0b315b4a83..2160eb2171 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, native backfill, and PeerDB CDC target. - [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..0b2437ea5f 100644 --- a/docs/clickhouse-metric-stream.md +++ b/docs/clickhouse-metric-stream.md @@ -1,16 +1,22 @@ # 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 +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. +PeerDB is the CDC path for ongoing Postgres-to-ClickHouse replication, with its +first mirror landing in `peerdb.metric_stream` for validation before analytics +switch to that source. ```text Postgres/Timescale fitness.metric_stream - | - | ClickHouse MaterializedPostgreSQL - v + | | + | chunk-range native backfill + | | PeerDB CDC mirror + v v ClickHouse postgres_fitness.metric_stream +ClickHouse peerdb.metric_stream (validation target) | | refreshable materialized view v @@ -25,7 +31,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,20 +63,37 @@ 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`: a ClickHouse-native `MergeTree` scalar copy + of the raw metric stream. +- `peerdb.metric_stream`: the PeerDB CDC target for ongoing changes. It is not + the active analytics source until the initial snapshot has been verified + against Postgres and the native backfill table. - `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`. -Postgres must run with `wal_level=logical`, `max_replication_slots`, and -`max_wal_senders` enabled so ClickHouse can subscribe to changes. +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 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 +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`. 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 a873ed1837..84844ff6be 100644 --- a/docs/production-incident-baseline.md +++ b/docs/production-incident-baseline.md @@ -1502,3 +1502,617 @@ 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`. + +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. + +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. + +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 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. + +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. +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. + +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. + +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. 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. + +## 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. + +### 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. + +### 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. + +### 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. + +### 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. + +### 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. + +### 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`. + +### 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. + +## 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. + +## 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. + +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 +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. 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. + +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 + +`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. + +## 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. +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 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 + +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. + +## 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 + +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 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. + +## 2026-05-01: PeerDB CDC Setup Added for Metric Stream + +### Symptoms + +The ClickHouse metric stream read path had a native chunk backfill, but no +long-running CDC service for new Postgres/Timescale `fitness.metric_stream` +changes. + +### Evidence + +ClickHouse and PeerDB documentation point to PeerDB/ClickPipes for Postgres CDC +into ClickHouse. The Timescale-specific guidance calls out that hypertable +changes are chunk-level changes, so a robust CDC path must understand Timescale +chunks instead of treating the hypertable root as the only published relation. + +### Root Cause + +The earlier ClickHouse `MaterializedPostgreSQL` approach did not handle the +Timescale hypertable/chunk model correctly, and the native ClickHouse backfill +only covered historical batch copy. + +### Fix or Mitigation + +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 + +PeerDB must deploy successfully and complete its initial snapshot before +analytics can switch to `peerdb.metric_stream`. The next operational step is to +compare row counts and recent-row freshness between Postgres, +`postgres_fitness.metric_stream`, and `peerdb.metric_stream`, then cut +`analytics.deduped_sensor` over in a separate migration. diff --git a/docs/superpowers/plans/2026-05-01-peerdb-clickhouse-cdc.md b/docs/superpowers/plans/2026-05-01-peerdb-clickhouse-cdc.md new file mode 100644 index 0000000000..c3f659625b --- /dev/null +++ b/docs/superpowers/plans/2026-05-01-peerdb-clickhouse-cdc.md @@ -0,0 +1,79 @@ +# PeerDB ClickHouse CDC Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Deploy self-hosted PeerDB and configure a CDC mirror from Postgres `fitness.metric_stream` into ClickHouse. + +**Architecture:** PeerDB runs internally in the Docker Swarm with its own catalog Postgres, Temporal services, workers, and transient MinIO stage. A one-shot TypeScript setup command creates the Postgres peer, ClickHouse peer, and `metric_stream` CDC mirror after the stack deploys. The first rollout writes into `peerdb.metric_stream` only; analytics reads remain on the current native ClickHouse backfill until the PeerDB initial snapshot is verified. + +**Tech Stack:** TypeScript, `pg`, `@clickhouse/client`, Docker Swarm, PeerDB `v0.36.18`, Temporal, MinIO, TimescaleDB, ClickHouse. + +--- + +### Task 1: Add PeerDB CDC Setup Logic + +**Files:** +- Create: `src/db/clickhouse-cdc.ts` +- Create: `src/db/clickhouse-cdc.test.ts` +- Create: `src/db/setup-clickhouse-cdc.ts` + +- [ ] Write tests for generated PeerDB SQL: + - Postgres peer uses `db:5432`, user `health`, database `health`. + - ClickHouse peer uses native port `9000`, database `peerdb`, and `disable_tls = true`. + - Mirror maps `{ from: fitness.metric_stream, to: metric_stream, exclude: [device_id, source_type, vector] }`. + - Mirror has `do_initial_copy = true`, `soft_delete = true`, and a deterministic publication name. + +- [ ] Implement string builders and `setupClickHouseCdc()`: + - Create ClickHouse database `peerdb`. + - Run `CREATE PEER IF NOT EXISTS` for Postgres and ClickHouse. + - Run `CREATE MIRROR IF NOT EXISTS dofek_metric_stream_cdc`. + - Fail loudly when required environment variables are missing. + +- [ ] Add a direct-run entrypoint in `src/db/setup-clickhouse-cdc.ts`. + +### Task 2: Add PeerDB Services To Swarm + +**Files:** +- Modify: `deploy/stack.yml` +- Modify: `deploy/server.tf` +- Modify: `.github/workflows/deploy-web-stack.yml` +- Modify: `deploy/README.md` + +- [ ] Add internal services: + - `peerdb-catalog` + - `peerdb-temporal` + - `peerdb-temporal-admin-tools` + - `peerdb-flow-api` + - `peerdb-flow-snapshot-worker` + - `peerdb-flow-worker` + - `peerdb` + - `peerdb-minio` + +- [ ] Add bind mounts: + - `/mnt/dofek-data/peerdb-catalog` + - `/mnt/dofek-data/peerdb-minio` + +- [ ] Update Terraform provisioners and the workflow bind-mount validation to create and verify those paths. + +- [ ] Add post-deploy workflow steps: + - Wait for PeerDB SQL on `peerdb:9900`. + - Run `src/db/setup-clickhouse-cdc.ts` in a one-shot app container on the swarm network. + +### Task 3: Verify And Document + +**Files:** +- Modify: `docs/clickhouse-metric-stream.md` +- Modify: `docs/production-incident-baseline.md` +- Modify: `README.md` + +- [ ] Document that `peerdb.metric_stream` is the CDC target and `postgres_fitness.metric_stream` remains the active analytics source until snapshot validation. + +- [ ] Run: + - `pnpm vitest run src/db/clickhouse-cdc.test.ts` + - `pnpm lint` + - `pnpm tsc --noEmit` + - `cd packages/server && pnpm tsc --noEmit` + - `cd packages/web && pnpm tsc --noEmit` + - `docker stack config -c deploy/stack.yml` + +- [ ] Commit and push. 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 6ce61ec018..e01717aff5 100644 --- a/drizzle/0009_metric_stream_id_not_null_primary_key.sql +++ b/drizzle/0009_metric_stream_id_not_null_primary_key.sql @@ -174,6 +174,9 @@ BEGIN END; $$; --> statement-breakpoint +ALTER TABLE fitness.metric_stream +ALTER COLUMN id SET NOT NULL; +--> statement-breakpoint -- squawk-ignore constraint-missing-not-valid -- squawk-ignore adding-serial-primary-key-field -- Timescale hypertables reject the recommended CREATE INDEX CONCURRENTLY and diff --git a/drizzle/0010_oauth_token_primary_key.sql b/drizzle/0010_oauth_token_primary_key.sql index 16d137f24a..684a9596fa 100644 --- a/drizzle/0010_oauth_token_primary_key.sql +++ b/drizzle/0010_oauth_token_primary_key.sql @@ -1,3 +1,8 @@ +ALTER TABLE fitness.oauth_token + ALTER COLUMN user_id SET NOT NULL; + +--> statement-breakpoint + DO $$ BEGIN IF NOT EXISTS ( 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 new file mode 100644 index 0000000000..394b915863 --- /dev/null +++ b/src/db/clickhouse-cdc.test.ts @@ -0,0 +1,259 @@ +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; + }); + + 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("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", + }, + }), + ).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 new file mode 100644 index 0000000000..a02f0dfe9d --- /dev/null +++ b/src/db/clickhouse-cdc.ts @@ -0,0 +1,139 @@ +import { readFile } from "node:fs/promises"; +import { Client } from "pg"; +import { type ClickHouseCommandClient, createClickHouseClientFromEnv } from "./clickhouse.ts"; + +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; + templateSql: string; + templateValues: PeerDbSqlTemplateValues; +} + +interface RuntimeConfig { + peerDbUrl: string; + templatePath: string; + templateValues: PeerDbSqlTemplateValues; +} + +function peerDbStringLiteral(value: string): string { + return `'${value.replaceAll("\\", "\\\\").replaceAll("'", "\\'")}'`; +} + +function requireEnv(name: string): string { + const value = process.env[name]; + if (!value) { + throw new Error(`${name} environment variable is required`); + } + return value; +} + +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 { + const url = new URL(urlString); + if (!url.username) { + throw new Error("CLICKHOUSE_URL must include a username for PeerDB setup"); + } + if (!url.password) { + throw new Error("CLICKHOUSE_URL must include a password for PeerDB setup"); + } + return url; +} + +function buildRuntimeConfig(): RuntimeConfig { + const databaseUrl = new URL(requireEnv("DATABASE_URL")); + const clickHouseUrl = parseClickHouseUrl(requireEnv("CLICKHOUSE_URL")); + const postgresCredential = requireEnv("POSTGRES_PASSWORD"); + + return { + 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), + }, + }; +} + +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), + }; +} + +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( + 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, + templateSql, + templateValues: config.templateValues, + }); + } finally { + await peerDbClient.end(); + await clickHouseClient.close?.(); + } +} diff --git a/src/db/clickhouse-migrations.test.ts b/src/db/clickhouse-migrations.test.ts index 167d17991c..8434cff2cb 100644 --- a/src/db/clickhouse-migrations.test.ts +++ b/src/db/clickhouse-migrations.test.ts @@ -1,4 +1,16 @@ -import { describe, expect, it, vi } from "vitest"; +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: pgClientMocks.Client, +})); + import { buildClickHouseMigrationStatements, runClickHouseMigrations, @@ -6,25 +18,44 @@ 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", ); 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("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 = MaterializedPostgreSQL('db:5432', 'health', 'health', 'secret')", - ); - 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({ + rows: [], + }); + }); + 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 }) => ({ @@ -36,9 +67,9 @@ 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(2); + 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( @@ -51,6 +82,21 @@ 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).not.toHaveBeenCalledWith( + expect.objectContaining({ + query: expect.stringContaining("ENGINE = MaterializedPostgreSQL"), + }), + ); expect(command).toHaveBeenCalledWith( expect.objectContaining({ query: expect.stringContaining( @@ -63,6 +109,223 @@ 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 () => { + 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: 0 }] + : [{ migration_count: 1 }], + ), + })); + const client = { command, query }; + + 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"), + }), + ); + 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')", + ); + 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 () => { @@ -72,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/clickhouse-migrations.ts b/src/db/clickhouse-migrations.ts index 62b271231e..4ac83b097a 100644 --- a/src/db/clickhouse-migrations.ts +++ b/src/db/clickhouse-migrations.ts @@ -1,6 +1,9 @@ +import { Client } from "pg"; import { buildClickHouseBootstrapStatements, + buildClickHousePlaceholderBootstrapStatements, type ClickHouseCommandClient, + parsePostgresConnectionForClickHouse, waitForClickHouseTable, } from "./clickhouse.ts"; @@ -8,11 +11,30 @@ interface MigrationCountRow { migration_count: number | string; } +interface MetricStreamBackfillChunkRow { + lower_bound: string; + upper_bound: string; +} + +interface MetricStreamBackfillChunkCountRow { + chunk_count: number | string; +} + 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", @@ -34,12 +56,42 @@ 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", + ...buildClickHousePlaceholderBootstrapStatements(postgresConnectionString), + ], + }, + { + id: "0004_reenable_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), + ], + }, + { + id: "0005_backfill_materialized_metric_stream", + statements: [], + }, + { + id: "0006_backfill_native_metric_stream", + run: replaceNativeMetricStreamAndBackfill, + }, ]; } export function buildClickHouseMigrationStatements(postgresConnectionString: string): string[] { - return clickHouseMigrations(postgresConnectionString).flatMap( - (migration) => migration.statements, + return clickHouseMigrations(postgresConnectionString).flatMap((migration) => + "statements" in migration ? migration.statements : [], ); } @@ -74,8 +126,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})`, @@ -86,6 +142,162 @@ ORDER BY id`, return appliedCount; } +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 { + await waitForClickHouseTable(client, "postgres_fitness", "metric_stream"); + const chunks = await fetchMetricStreamBackfillChunks(postgresConnectionString); + if (chunks.length === 0) { + return; + } + + const postgresMetricStreamSource = + buildPostgresMetricStreamTableFunction(postgresConnectionString); + 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)`, + }); + + 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)) { + continue; + } + await client.command({ + query: buildMetricStreamBackfillStatement(postgresMetricStreamSource, chunkStart, chunkEnd), + }); + await client.command({ + query: `INSERT INTO analytics.metric_stream_backfill_chunks (lower_bound, upper_bound) +VALUES (${clickHouseDateTimeLiteral(chunkStart)}, ${clickHouseDateTimeLiteral(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 fetchMetricStreamBackfillChunks( + postgresConnectionString: string, +): Promise { + const postgresClient = new Client({ connectionString: postgresConnectionString }); + try { + await postgresClient.connect(); + const result = await postgresClient.query(` + SELECT + 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; + } 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, + channel, + activity_id, + scalar, + id +) +SELECT + metric_stream.recorded_at, + metric_stream.user_id, + metric_stream.provider_id, + metric_stream.channel, + metric_stream.activity_id, + metric_stream.scalar, + 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, @@ -100,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 2409c396d5..4f98afb916 100644 --- a/src/db/clickhouse.test.ts +++ b/src/db/clickhouse.test.ts @@ -20,17 +20,18 @@ describe("parsePostgresConnectionForClickHouse", () => { }); describe("buildClickHouseBootstrapStatements", () => { - it("creates native Postgres bridges and a ClickHouse deduped sensor view", () => { + it("creates native metric stream source 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("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')", ); @@ -115,4 +116,27 @@ describe("waitForClickHouseTable", () => { waitForClickHouseTable({ command: vi.fn().mockResolvedValue(undefined) }, "analytics", "foo"), ).rejects.toThrow("ClickHouse table verification requires a query-capable client"); }); + + it("waits for ClickHouse tables that appear after startup", 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 a10f9c7e22..cbe6e90fa0 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; @@ -66,18 +68,42 @@ export function parsePostgresConnectionForClickHouse( } export function buildClickHouseBootstrapStatements(postgresConnectionString: string): string[] { + return buildClickHouseBootstrapStatementsForNativeMetricStream(postgresConnectionString); +} + +export function buildClickHousePlaceholderBootstrapStatements( + postgresConnectionString: string, +): string[] { + return buildClickHouseBootstrapStatementsForNativeMetricStream(postgresConnectionString); +} + +function buildClickHouseBootstrapStatementsForNativeMetricStream( + postgresConnectionString: string, +): 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 = [ + "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'), + channel String, + provider_id String, + scalar Nullable(Float32) +) +ENGINE = MergeTree +ORDER BY (user_id, activity_id, channel, recorded_at, id) +SETTINGS allow_nullable_key = 1`, + ]; 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'`, + ...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 @@ -477,7 +503,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, 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", + ); + }); +}); diff --git a/src/db/setup-clickhouse-cdc.ts b/src/db/setup-clickhouse-cdc.ts new file mode 100644 index 0000000000..0bfb37576f --- /dev/null +++ b/src/db/setup-clickhouse-cdc.ts @@ -0,0 +1,20 @@ +import { logger } from "../logger.ts"; +import { setupClickHouseCdcFromEnv } from "./clickhouse-cdc.ts"; + +export async function main(): Promise { + await setupClickHouseCdcFromEnv(); + logger.info("[clickhouse-cdc] PeerDB metric_stream CDC mirror is configured"); +} + +const isDirectRun = + typeof process.argv[1] === "string" && + import.meta.url.endsWith(process.argv[1].replace(/.*\//, "")); + +if (isDirectRun) { + main() + .then(() => process.exit(0)) + .catch((error) => { + logger.error(`[clickhouse-cdc] ${error}`); + process.exit(1); + }); +}