Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
051ed7e
Fix ClickHouse bind mount provisioning
Asherlc Apr 30, 2026
1a5005e
Document ClickHouse deploy prerequisites
Asherlc Apr 30, 2026
465149f
Read ClickHouse password from deploy dotenv
Asherlc Apr 30, 2026
5337d4d
Run deploy migrations as named containers
Asherlc Apr 30, 2026
eb1889f
Add server-side migration timeout
Asherlc Apr 30, 2026
3dfff4b
Run deploy migrations detached
Asherlc Apr 30, 2026
c9e40cf
Apply ClickHouse memory before migrations
Asherlc Apr 30, 2026
ae8f086
Run deploy migrations without telemetry
Asherlc Apr 30, 2026
aac47bf
Document unresolved production migration
Asherlc Apr 30, 2026
d68d1a7
Backfill metric stream IDs in chunk batches
Asherlc Apr 30, 2026
029d40e
Backfill metric stream IDs by time window
Asherlc Apr 30, 2026
fd78d35
Backfill metric stream IDs by chunk range
Asherlc Apr 30, 2026
b6ef9d9
Fallback metric stream backfill on decompression limit
Asherlc Apr 30, 2026
1ff480b
Allow chunk backfill decompression in migration session
Asherlc Apr 30, 2026
d36e735
Defer metric stream primary key backfill
Asherlc Apr 30, 2026
0d4aa69
Encode ClickHouse password for stack deploy
Asherlc Apr 30, 2026
d062350
Bound stack deploy wait during rollout
Asherlc Apr 30, 2026
3c0bfb9
Guard web deploy rollbacks
Asherlc May 1, 2026
1b325f3
Backfill metric stream primary key
Asherlc May 1, 2026
25ceec5
Handle compressed metric stream backfill
Asherlc May 1, 2026
1c90645
Allow compressed metric stream backfill
Asherlc May 1, 2026
01a25fb
Backfill metric stream chunks resumably
Asherlc May 1, 2026
a035a10
Document metric stream backfill blocker
Asherlc May 1, 2026
d9b7224
Backfill metric stream ids by chunk table
Asherlc May 1, 2026
5ba814c
Suppress metric stream backfill triggers
Asherlc May 1, 2026
e1b2f55
Skip filled metric stream chunks
Asherlc May 1, 2026
260fed3
Document metric stream primary key rollout
Asherlc May 1, 2026
fe8481a
Reenable metric stream ClickHouse replication
Asherlc May 1, 2026
06e7a73
Wait longer for ClickHouse replicated tables
Asherlc May 1, 2026
eef3cbc
Backfill ClickHouse metric stream
Asherlc May 1, 2026
4f932fc
Backfill metric stream by Timescale chunks
Asherlc May 1, 2026
0c6ec49
Document ClickHouse metric stream backfill incident
Asherlc May 1, 2026
99e188d
Document read-only ClickHouse backfill failure
Asherlc May 1, 2026
a195da3
Document Timescale chunk CDC gap
Asherlc May 1, 2026
fa2a07e
Use native ClickHouse metric stream backfill
Asherlc May 1, 2026
c05c142
Add PeerDB metric stream CDC setup
Asherlc May 1, 2026
ecd51a7
Use PeerDB SQL template for metric stream CDC
Asherlc May 1, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
176 changes: 157 additions & 19 deletions .github/workflows/deploy-web-stack.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
1 change: 1 addition & 0 deletions cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
"Wreturn",
"timescale",
"timescaledb",
"peerdb",
"ClickHouse",
"CLICKHOUSE",
"clickhouse",
Expand Down
12 changes: 8 additions & 4 deletions deploy/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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_<id>`).
- **DB data path**: The `db` service bind-mounts Postgres data to `/mnt/dofek-data/postgres`.
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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.<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@<host>`.
3. Login to GHCR on the CI runner.
Expand All @@ -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.
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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
Expand Down
Loading
Loading