:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
perf(ci): prime agent skills db from the schema cache (#85845)
Raúl Negrón-Oterodda9c463cb52
diff --git a/.agents/skills/authoring-ci-workflows/SKILL.md b/.agents/skills/authoring-ci-workflows/SKILL.mdindex 152bba058506..68a118f850e1 100644--- a/.agents/skills/authoring-ci-workflows/SKILL.md+++ b/.agents/skills/authoring-ci-workflows/SKILL.md@@ -220,6 +220,12 @@ Route through the shared composites rather than hand-rolling `actions/cache`: `.One canonical key per artifact; gate saves to master or key deliberately per-ref.PR-scoped cache writes nobody else can read just fragment the 10 GB LRU cap.+**Any job that runs `manage.py migrate` against a fresh Postgres must restore the master schema dump first**, keeping the migrate as a seconds-long top-up.+A from-scratch replay of the full migration history grows with every migration merged and already costs more than most jobs' `timeout-minutes`, so an uncached migrate is a timeout that hasn't fired yet ([agent-skills cancelled at 30 min with the checks green](https://github.com/PostHog/posthog/actions/runs/32250956659/job/96061773764)).+Copy the three steps (compute keys, `actions/cache/restore`, prime) from `ci-agent-skills.yml` for compose-stack jobs or `ci-rust-flags-integration.yml` for service-container jobs; `hogli db:restore-schema-fresh` reads `TARGET_DB` to pick the database.+A miss falls through to the full migrate, so the restore is never a correctness risk.+The only sanctioned exception is a job whose purpose is validating the migration history itself (ci-backend's `check-migrations`), where a restored dump would mask what it checks.+## Runners`depot-ubuntu-<version>[-<vCPU>]` for build/compute-heavy jobs (the `-4`/`-8` suffix bumps CPU from the 2-vCPU default); GitHub-hosted for light jobs.@@ -250,5 +256,6 @@ Roll out a new blocking lint the same way: ship `continue-on-error`, clear the i- [ ] High-volume API calls on a dedicated App token with `|| github.token` fork fallback.- [ ] Fork PRs handled: secret-needing steps guarded with the same-repo `if:`; no secret-injecting build runs on forks.- [ ] Caching through the shared composites; writes gated to master.+- [ ] Any job running `manage.py migrate` restores the master schema dump first, with the migrate as top-up (see Caching).- [ ] Prod image push / deploy dispatch gated per `/gating-production-deploys`.- [ ] `bin/hogli lint:workflows` and `actionlint` pass locally.diff --git a/.github/workflows/ci-agent-skills.yml b/.github/workflows/ci-agent-skills.ymlindex 1d3f576281d9..c5dce4f13cd2 100644--- a/.github/workflows/ci-agent-skills.yml+++ b/.github/workflows/ci-agent-skills.yml@@ -66,6 +66,84 @@ jobs:steps:- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ with:+ # Deep enough to reach the PR's merge base, which keys the schema cache below.+ fetch-depth: 1000+ filter: blob:none++ - name: Fetch base branch for merge-base computation+ if: github.event_name == 'pull_request'+ env:+ BASE_REF: ${{ github.event.pull_request.base.ref }}+ # Scoped, blob-less, no-tags: without an explicit refspec, git fetch+ # falls back to remote.origin.fetch and pulls every branch.+ run: git fetch --no-tags --depth=1000 --filter=blob:none origin "$BASE_REF:refs/remotes/origin/$BASE_REF"++ - name: Compute schema cache keys+ id: schema-key+ # Restores the schema dump ci-backend saves on master pushes, so the+ # migrate step below only tops up what is newer instead of replaying the+ # full migration history. On a PR the migration-set key is the merge-base's;+ # on a master push it is HEAD's. A cache miss falls through to a full+ # migrate, so an absent or wrong key is never a correctness risk.+ env:+ BASE_REF: ${{ github.event.pull_request.base.ref }}+ IS_PUSH: ${{ github.event_name == 'push' }}+ # Manual cache-bust knob. Keep in sync with SCHEMA_CACHE_EPOCH in+ # ci-backend.yml, which saves these caches on master pushes.+ SCHEMA_CACHE_EPOCH: v2+ run: |+ if [ "$IS_PUSH" = "true" ]; then+ # Pushed commit is checked out directly: no merge commit, no base ref.+ # The per-SHA key would point at this same push's cache (saved+ # concurrently by ci-backend, so racy); rely on the stable+ # migration-set key below.+ REF=HEAD+ else+ # HEAD is the synthetic merge commit; HEAD^2 is the PR branch tip.+ MERGE_BASE=$(git merge-base HEAD^2 "origin/${BASE_REF}" 2>/dev/null || echo "")+ if [ -z "$MERGE_BASE" ]; then+ echo "key=" >> $GITHUB_OUTPUT+ echo "migrations_key=" >> $GITHUB_OUTPUT+ echo "::notice::merge-base not found (branch too stale?), so the schema cache is skipped"+ exit 0+ fi+ # Routing decides which app labels reach the dump, so an edited routing+ # config matches no master dump: drop both keys and migrate from scratch.+ DB_ROUTING_BASE=$(git ls-tree -r --format='%(objectname) %(path)' "$MERGE_BASE" -- products/db_routing.yaml posthog/product_db_config.py posthog/product_db_router.py)+ DB_ROUTING_HEAD=$(git ls-tree -r --format='%(objectname) %(path)' HEAD -- products/db_routing.yaml posthog/product_db_config.py posthog/product_db_router.py)+ if [ "$DB_ROUTING_BASE" != "$DB_ROUTING_HEAD" ]; then+ echo "key=" >> $GITHUB_OUTPUT+ echo "migrations_key=" >> $GITHUB_OUTPUT+ echo "::notice::db routing config or router differs from the merge base, so the schema cache is skipped"+ exit 0+ fi+ echo "key=posthog-schema-master-${MERGE_BASE}" >> $GITHUB_OUTPUT+ REF="$MERGE_BASE"+ fi+ # Last-resort restore prefix: matches the newest saved dump when the exact+ # keys miss. Gated on checkout age because a re-run of an old commit could+ # restore a dump newer than its code, which forward-only migrate cannot repair.+ HEAD_AGE_SECONDS=$(( $(date +%s) - $(git show -s --format=%ct HEAD) ))+ if [ "$HEAD_AGE_SECONDS" -lt 86400 ]; then+ echo "prefix_key=posthog-schema-mig-${SCHEMA_CACHE_EPOCH}-" >> $GITHUB_OUTPUT+ fi+ # Must match ci-backend.yml's save-side computation byte for byte or the key never hits.+ MIG_FILES=$(git ls-tree -r --format='%(objectname) %(path)' "$REF" \+ | grep -E '/migrations/[^/]+\.py$|^[0-9a-f]+ uv\.lock$' \+ | grep -vE '/(clickhouse|async_migrations)/migrations/' \+ | LC_ALL=C sort) || true+ # Routing decides which app labels are in the dump, so these inputs belong in the key.+ DB_ROUTING=$(git ls-tree -r --format='%(objectname) %(path)' "$REF" -- products/db_routing.yaml posthog/product_db_config.py posthog/product_db_router.py)+ PG_IMAGE=$(git show "${REF}:docker-compose.base.yml" 2>/dev/null \+ | grep -m1 -E '^[[:space:]]*image:[[:space:]]*postgres:' | tr -d '[:space:]')+ if [ -z "$MIG_FILES" ]; then+ echo "migrations_key=" >> $GITHUB_OUTPUT+ echo "::notice::no migration files matched, so restore falls back to the SHA schema key"+ else+ MIG_HASH=$(printf '%s\n%s\n%s' "$MIG_FILES" "$PG_IMAGE" "$DB_ROUTING" | sha256sum | cut -c1-40)+ echo "migrations_key=posthog-schema-mig-${SCHEMA_CACHE_EPOCH}-${MIG_HASH}" >> $GITHUB_OUTPUT+ fi- name: Log in to Docker Hubif: ${{ env.DOCKERHUB_USERNAME != '' && env.DOCKERHUB_TOKEN != '' }}@@ -126,6 +204,41 @@ jobs:WAIT_FOR_DOCKER_LAUNCH_RETRIES: 3run: bin/ci-wait-for-docker wait+ - name: Restore schema cache from master+ if: steps.schema-key.outputs.migrations_key != '' || steps.schema-key.outputs.key != ''+ uses: actions/cache/restore@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3+ with:+ path: schema.sql.gz+ # Prefer the shared content key; fall back to the exact merge-base SHA+ # key, then to the newest dump of any migration set.+ key: ${{ steps.schema-key.outputs.migrations_key || steps.schema-key.outputs.key }}+ restore-keys: |+ ${{ steps.schema-key.outputs.key }}+ ${{ steps.schema-key.outputs.prefix_key }}++ - name: Prime posthog from cached schema+ # db:restore-schema-fresh restores the dump and seeds the RunPython data a+ # schema-only dump lacks; the migrate step below layers anything newer on+ # top. On failure it leaves a fresh empty db, so migrate runs the full history.+ env:+ SECRET_KEY: '6b01eee4f945ca25045b5aab440b953461faf08693a9abbf1166dc7c6b9772da'+ DATABASE_URL: 'postgres://posthog:posthog@localhost:5432/posthog'+ REDIS_URL: 'redis://localhost'+ OBJECT_STORAGE_ENABLED: 'False'+ TEST: 1+ DEBUG: 1+ TARGET_DB: posthog+ run: |+ if [ ! -f schema.sql.gz ]; then+ echo "::notice::Schema cache miss, so the migrate step below runs the full history"+ exit 0+ fi+ mkdir -p .postgres-backups+ mv schema.sql.gz .postgres-backups/schema-latest.sql.gz+ if ! ./bin/hogli db:restore-schema-fresh; then+ echo "::warning::Schema restore failed (stale or incompatible cached dump?), so the migrate step below runs the full history"+ fi+- name: Run migrations and create test dataenv:SECRET_KEY: '6b01eee4f945ca25045b5aab440b953461faf08693a9abbf1166dc7c6b9772da'@@ -247,6 +360,41 @@ jobs:steps:- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ - name: Compute schema cache key+ id: schema-key+ # The pushed commit is checked out directly, so the migration-set key is+ # HEAD's. It matches the dump the previous master push saved unless this+ # push itself changed the migration set; a miss falls through to the full+ # migrate below, so an absent key is never a correctness risk.+ env:+ # Manual cache-bust knob. Keep in sync with SCHEMA_CACHE_EPOCH in+ # ci-backend.yml, which saves these caches on master pushes.+ SCHEMA_CACHE_EPOCH: v2+ run: |+ # Must match ci-backend.yml's save-side computation byte for byte or the key never hits.+ MIG_FILES=$(git ls-tree -r --format='%(objectname) %(path)' HEAD \+ | grep -E '/migrations/[^/]+\.py$|^[0-9a-f]+ uv\.lock$' \+ | grep -vE '/(clickhouse|async_migrations)/migrations/' \+ | LC_ALL=C sort) || true+ # Routing decides which app labels are in the dump, so these inputs belong in the key.+ DB_ROUTING=$(git ls-tree -r --format='%(objectname) %(path)' HEAD -- products/db_routing.yaml posthog/product_db_config.py posthog/product_db_router.py)+ PG_IMAGE=$(git show "HEAD:docker-compose.base.yml" 2>/dev/null \+ | grep -m1 -E '^[[:space:]]*image:[[:space:]]*postgres:' | tr -d '[:space:]')+ if [ -z "$MIG_FILES" ]; then+ echo "migrations_key=" >> $GITHUB_OUTPUT+ echo "::notice::no migration files matched, so migrate runs from scratch"+ else+ MIG_HASH=$(printf '%s\n%s\n%s' "$MIG_FILES" "$PG_IMAGE" "$DB_ROUTING" | sha256sum | cut -c1-40)+ echo "migrations_key=posthog-schema-mig-${SCHEMA_CACHE_EPOCH}-${MIG_HASH}" >> $GITHUB_OUTPUT+ fi+ # Last-resort restore prefix: matches the newest saved dump when the exact+ # key misses. Gated on checkout age because a re-run of an old commit could+ # restore a dump newer than its code, which forward-only migrate cannot repair.+ HEAD_AGE_SECONDS=$(( $(date +%s) - $(git show -s --format=%ct HEAD) ))+ if [ "$HEAD_AGE_SECONDS" -lt 86400 ]; then+ echo "prefix_key=posthog-schema-mig-${SCHEMA_CACHE_EPOCH}-" >> $GITHUB_OUTPUT+ fi+- name: Log in to Docker Hubif: ${{ env.DOCKERHUB_USERNAME != '' && env.DOCKERHUB_TOKEN != '' }}uses: docker/login-action@4907a6ddec9925e35a0a9e82d7399ccc52663121 # v4.1.0@@ -303,6 +451,38 @@ jobs:WAIT_FOR_DOCKER_LAUNCH_RETRIES: 3run: bin/ci-wait-for-docker wait+ - name: Restore schema cache from master+ if: steps.schema-key.outputs.migrations_key != ''+ uses: actions/cache/restore@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3+ with:+ path: schema.sql.gz+ key: ${{ steps.schema-key.outputs.migrations_key }}+ restore-keys: |+ ${{ steps.schema-key.outputs.prefix_key }}++ - name: Prime posthog from cached schema+ # db:restore-schema-fresh restores the dump and seeds the RunPython data a+ # schema-only dump lacks; the migrate step below layers anything newer on+ # top. On failure it leaves a fresh empty db, so migrate runs the full history.+ env:+ SECRET_KEY: '6b01eee4f945ca25045b5aab440b953461faf08693a9abbf1166dc7c6b9772da'+ DATABASE_URL: 'postgres://posthog:posthog@localhost:5432/posthog'+ REDIS_URL: 'redis://localhost'+ OBJECT_STORAGE_ENABLED: 'False'+ TEST: 1+ DEBUG: 1+ TARGET_DB: posthog+ run: |+ if [ ! -f schema.sql.gz ]; then+ echo "::notice::Schema cache miss, so the migrate step below runs the full history"+ exit 0+ fi+ mkdir -p .postgres-backups+ mv schema.sql.gz .postgres-backups/schema-latest.sql.gz+ if ! ./bin/hogli db:restore-schema-fresh; then+ echo "::warning::Schema restore failed (stale or incompatible cached dump?), so the migrate step below runs the full history"+ fi+- name: Run migrations and create test dataenv:SECRET_KEY: '6b01eee4f945ca25045b5aab440b953461faf08693a9abbf1166dc7c6b9772da'