-
Notifications
You must be signed in to change notification settings - Fork 2.4k
1744 lines (1561 loc) · 87.3 KB
/
ci-backend.yml
File metadata and controls
1744 lines (1561 loc) · 87.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This workflow runs all of our backend django tests.
#
# If these tests get too slow, look at increasing concurrency and re-timing the tests by manually dispatching
# .github/workflows/ci-backend-update-test-timing.yml action
name: Backend CI
on:
push:
branches:
- master
workflow_dispatch:
inputs:
clickhouseServerVersion:
description: ClickHouse server version. Leave blank for default
type: string
pull_request:
merge_group:
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
env:
SECRET_KEY: '6b01eee4f945ca25045b5aab440b953461faf08693a9abbf1166dc7c6b9772da' # unsafe - for testing only
DATABASE_URL: 'postgres://posthog:posthog@localhost:5432/posthog'
REDIS_URL: 'redis://localhost'
CLICKHOUSE_HOST: 'localhost'
CLICKHOUSE_SECURE: 'False'
CLICKHOUSE_VERIFY: 'False'
TEST: 1
CLICKHOUSE_SERVER_IMAGE_VERSION: ${{ github.event.inputs.clickhouseServerVersion || '' }}
CLICKHOUSE_COMPAT_PYTEST_TARGETS: 'posthog/clickhouse ee/clickhouse'
OBJECT_STORAGE_ENABLED: 'True'
OBJECT_STORAGE_ENDPOINT: 'http://localhost:19000'
OBJECT_STORAGE_ACCESS_KEY_ID: 'object_storage_root_user'
OBJECT_STORAGE_SECRET_ACCESS_KEY: 'object_storage_root_password'
UV_HTTP_TIMEOUT: 120
# tests would intermittently fail in GH actions
# with exit code 134 _after passing_ all tests
# this appears to fix it
# absolute wild tbh https://stackoverflow.com/a/75503402
DISPLAY: ':99.0'
# this is a fake key so this workflow can run for external contributors as they do not have access to secrets (that we don't need here)
OIDC_RSA_PRIVATE_KEY: ${{ vars.OIDC_RSA_FAKE_PRIVATE_KEY }}
RUNS_ON_INTERNAL_PR: ${{ github.event_name != 'pull_request' || github.event.pull_request.head.repo.fork == false }}
SANDBOX_JWT_PRIVATE_KEY: ${{ vars.OIDC_RSA_FAKE_PRIVATE_KEY }}
permissions:
contents: read
pull-requests: write
jobs:
# Job to decide if we should run backend ci
# See https://github.com/dorny/paths-filter#conditional-execution for more details
changes:
runs-on: ubuntu-latest
timeout-minutes: 5
name: Determine need to run backend and migration checks
# Set job outputs to values from filter step
outputs:
backend: ${{ steps.filter.outputs.backend || 'true' }}
backend_files: ${{ steps.filter.outputs.backend_files }}
migrations: ${{ steps.filter.outputs.migrations || 'true' }}
migrations_files: ${{ steps.filter.outputs.migrations_files }}
tasks_temporal: ${{ steps.filter.outputs.tasks_temporal || 'true' }}
llm_gateway: ${{ steps.filter.outputs.llm_gateway || 'true' }}
openapi_types: ${{ steps.filter.outputs.openapi_types || 'true' }}
products: ${{ steps.filter.outputs.products || 'true' }}
legacy: ${{ steps.filter.outputs.legacy || 'true' }}
steps:
# For pull requests it's not necessary to checkout the code, but we
# also want this to run on master so we need to checkout
- uses: actions/checkout@v6
with:
clean: false
- name: Clean up data directories with container permissions
run: |
# Use docker to clean up files created by containers
[ -d "data" ] && docker run --rm -v "$(pwd)/data:/data" alpine sh -c "rm -rf /data/seaweedfs /data/minio" || true
continue-on-error: true
- uses: dorny/paths-filter@de90cc6fb38fc0963ad72b210f1f284cd68cea36 # v3.0.2
id: filter
if: github.event_name != 'push' # Run all tests on master push
with:
list-files: 'escape'
filters: |
backend:
# Avoid running backend tests for irrelevant changes
# NOTE: we are at risk of missing a dependency here. We could make
# the dependencies more clear if we separated the backend/frontend
# code completely
# really we should ignore ee/frontend/** but dorny doesn't support that
# - '!ee/frontend/**'
# including the negated rule appears to work
# but makes it always match because the checked file always isn't `ee/frontend/**` 🙈
- 'ee/**/*'
- 'common/**/*'
- 'posthog/**/*'
- 'products/**/backend/**/*'
- 'bin/*.py'
- pyproject.toml
- uv.lock
- requirements.txt
- requirements-dev.txt
- mypy.ini
- pytest.ini
- .test_durations # Used for pytest-split sharding
- frontend/src/queries/schema.json # Used for generating schema.py
- rust/feature-flags/src/properties/property_models.rs # Operator parity check
- common/plugin_transpiler/src # Used for transpiling plugins
# Make sure we run if someone is explicitly changing the workflow
- .github/workflows/ci-backend.yml
- .github/clickhouse-versions.json
# We use docker compose for tests, make sure we rerun on
# changes to docker-compose.dev.yml e.g. dependency
# version changes
- docker-compose.dev.yml
- docker-compose.profiles.yml
- docker-compose.base.yml
- bin/wait-for-docker
- bin/ci-wait-for-docker
- frontend/public/email/*
- 'docker/clickhouse/**'
legacy:
# Non-product backend code — when only products/ change,
# turbo-discover diffs backend:test vs backend:contract-check
# to detect isolated products and decide whether Django runs.
# Everything from backend: EXCEPT products/**/backend/**/*
- 'ee/**/*'
- 'common/**/*'
- 'posthog/**/*'
- 'bin/*.py'
- pyproject.toml
- uv.lock
- requirements.txt
- requirements-dev.txt
- mypy.ini
- pytest.ini
- .test_durations
- frontend/src/queries/schema.json
- rust/feature-flags/src/properties/property_models.rs
- common/plugin_transpiler/src
- .github/workflows/ci-backend.yml
- .github/clickhouse-versions.json
- docker-compose.dev.yml
- docker-compose.profiles.yml
- docker-compose.base.yml
- bin/wait-for-docker
- bin/ci-wait-for-docker
- frontend/public/email/*
- 'docker/clickhouse/**'
migrations:
- 'docker/clickhouse/**'
- 'posthog/migrations/*.py'
- 'products/*/backend/migrations/*.py'
- 'products/*/migrations/*.py' # Legacy structure
- 'rust/persons_migrations/*.sql'
- 'rust/bin/migrate-persons'
tasks_temporal:
- 'products/tasks/backend/temporal/**/*'
llm_gateway:
- 'services/llm-gateway/**/*'
openapi_types:
# Generated OpenAPI types - validate they match schema
- 'frontend/src/generated/**/*'
- 'products/*/frontend/generated/**/*'
- 'services/mcp/src/generated/**/*'
- 'services/mcp/src/api/generated.ts'
# Generation tooling - changes here could affect output
- 'tools/openapi-codegen/**/*'
- 'services/mcp/scripts/lib/**'
- 'frontend/bin/generate-openapi-types.mjs'
- 'frontend/src/lib/api-orval-mutator.ts'
- 'services/mcp/scripts/**/*'
- 'services/mcp/definitions/**/*.yaml'
- 'products/*/mcp/**/*.yaml'
- 'services/mcp/src/tools/generated/**/*'
- 'services/mcp/schema/generated-tool-definitions.json'
- 'services/mcp/schema/tool-definitions-all.json'
detect-snapshot-mode:
name: Detect snapshot mode
runs-on: ubuntu-latest
timeout-minutes: 5
needs: [changes]
if: needs.changes.outputs.backend == 'true'
outputs:
mode: ${{ steps.detect.outputs.mode }}
steps:
- name: Detect mode
id: detect
env:
PR_REPO: ${{ github.event.pull_request.head.repo.full_name }}
REPO: ${{ github.repository }}
HAS_NO_SNAPSHOT_LABEL: ${{ contains(github.event.pull_request.labels.*.name, 'no-snapshot-update') }}
AUTHOR: ${{ github.actor }}
run: |
if [ "$PR_REPO" != "$REPO" ] && [ -n "$PR_REPO" ]; then
echo "mode=check" >> $GITHUB_OUTPUT
echo "Fork detected - running in CHECK mode (no commits allowed)"
elif [ "$HAS_NO_SNAPSHOT_LABEL" == "true" ]; then
echo "mode=check" >> $GITHUB_OUTPUT
echo "::notice::🔍 Running in CHECK mode - 'no-snapshot-update' label detected"
else
echo "Workflow triggered by: $AUTHOR"
# Dependabot is excluded - it creates new PRs that may need snapshot updates
# Other bots (github-actions, posthog-bot) commit snapshots and must use CHECK mode to avoid loops
if [[ "$AUTHOR" != "dependabot[bot]" ]] && \
([[ "$AUTHOR" == *"github-actions"* ]] || [[ "$AUTHOR" == *"[bot]"* ]] || [[ "$AUTHOR" == "posthog-bot" ]]); then
echo "mode=check" >> $GITHUB_OUTPUT
echo "::notice::🔍 Running in CHECK mode - snapshots must match exactly"
else
echo "mode=update" >> $GITHUB_OUTPUT
echo "::notice::🔄 Running in UPDATE mode - snapshots can be updated"
fi
fi
# Fast pre-job: determines which products need testing and if Django should run
# Only needs pnpm + node — no Python, Docker, or services
# Runs on depot for turbo remote cache access (cache status drives Django gating)
turbo-discover:
needs: changes
if: needs.changes.outputs.backend == 'true'
runs-on: depot-ubuntu-latest
timeout-minutes: 5
name: Discover product tests
outputs:
run_legacy: ${{ steps.discover.outputs.run_legacy }}
matrix: ${{ steps.discover.outputs.matrix }}
steps:
- uses: actions/checkout@v6
- name: Setup pnpm
uses: pnpm/action-setup@a7487c7e89a18df4991f7f222e4898a00d66ddda # v4.1.0
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: 20
cache: pnpm
cache-dependency-path: |
pnpm-lock.yaml
.github/workflows/ci-backend.yml
- name: Install pnpm dependencies
run: pnpm install --frozen-lockfile --filter=@posthog/root
- name: Discover products to test
id: discover
env:
# On pushes to master, always run everything.
# On PRs, use the path filter to detect legacy changes.
LEGACY_CHANGED: ${{ github.event_name != 'pull_request' || needs.changes.outputs.legacy }}
run: |
# turbo-discover.js diffs backend:test vs backend:contract-check
# to detect isolated products. Non-isolated product changes trigger
# the full suite (all products + Django).
RESULT=$(node .github/scripts/turbo-discover.js)
echo "Result: $RESULT"
echo "matrix=$(echo "$RESULT" | jq -c '.matrix')" >> $GITHUB_OUTPUT
echo "run_legacy=$(echo "$RESULT" | jq -r '.run_legacy')" >> $GITHUB_OUTPUT
# Keep contract-check remote cache warm for future runs
./node_modules/.bin/turbo run backend:contract-check --output-logs=errors-only 2>/dev/null || true
# Runs product tests in parallel — one matrix job per group
# Each job gets its own runner + Docker stack, so no shared DB conflicts
# Small products (< 50 tests) are grouped into a single job to avoid setup overhead
turbo-tests:
needs: [changes, turbo-discover, detect-snapshot-mode]
if: >-
always() &&
needs.turbo-discover.result == 'success' &&
needs.turbo-discover.outputs.matrix != '[]' &&
needs.turbo-discover.outputs.matrix != ''
runs-on: depot-ubuntu-latest
timeout-minutes: 30
name: Product tests (${{ matrix.group }})
strategy:
fail-fast: false
matrix:
include: ${{ fromJson(needs.turbo-discover.outputs.matrix) }}
steps:
- uses: actions/checkout@v6
# Start Docker early (before dependency installs) so containers can pull
# images and initialize while we install deps. This matches the pattern
# used by core-tests/django which achieves ~1s wait times.
- name: Clean up data directories
run: |
[ -d "data" ] && docker run --rm -v "$(pwd)/data:/data" alpine sh -c "rm -rf /data/seaweedfs /data/minio" || true
continue-on-error: true
- name: Start services
env:
COMPOSE_FILE: docker-compose.dev.yml:docker-compose.profiles.yml
COMPOSE_PROFILES: temporal,azure
CLICKHOUSE_SERVER_IMAGE: clickhouse/clickhouse-server:25.8.12.129
run: |
cp posthog/user_scripts/latest_user_defined_function.xml docker/clickhouse/user_defined_function.xml
bin/ci-wait-for-docker launch --background --down
- name: Setup pnpm
uses: pnpm/action-setup@a7487c7e89a18df4991f7f222e4898a00d66ddda # v4.1.0
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: 20
cache: pnpm
cache-dependency-path: |
pnpm-lock.yaml
.github/workflows/ci-backend.yml
- name: Install pnpm dependencies
run: pnpm install --frozen-lockfile --filter=@posthog/root
- name: Set up Python
uses: actions/setup-python@v6
with:
python-version: 3.12.12
token: ${{ secrets.POSTHOG_BOT_PAT }}
- name: Install uv
id: setup-uv
uses: astral-sh/setup-uv@61cb8a9741eeb8a550a1b8544337180c0fc8476b # v7.2.0
with:
version: '0.10.2' # pinned: unpinned setup-uv calls GH API on every job, exhausts rate limit
enable-cache: true
cache-dependency-glob: uv.lock
save-cache: ${{ github.ref == 'refs/heads/master' }}
- name: Install SAML dependencies
if: steps.setup-uv.outputs.cache-hit != 'true'
run: sudo apt-get update && sudo apt-get install -y libxml2-dev libxmlsec1-dev libxmlsec1-openssl
- name: Install Rust
uses: dtolnay/rust-toolchain@0b1efabc08b657293548b77fb76cc02d26091c7e
with:
toolchain: 1.91.1
components: cargo
- name: Cache Rust dependencies
uses: Swatinem/rust-cache@779680da715d629ac1d338a641029a2f4372abb5 # v2.8.2
with:
shared-key: 'v2-rust-backend'
workspaces: rust
save-if: ${{ github.ref == 'refs/heads/master' }}
- name: Install sqlx-cli
uses: ./.github/actions/setup-sqlx-cli
- name: Install Python dependencies
run: UV_PROJECT_ENVIRONMENT=$pythonLocation uv sync --frozen --dev
- name: Add Kafka and ClickHouse to /etc/hosts
run: echo "127.0.0.1 kafka clickhouse" | sudo tee -a /etc/hosts
- name: Set up needed files
run: |
mkdir -p frontend/dist
touch frontend/dist/index.html frontend/dist/layout.html frontend/dist/exporter.html
./bin/download-mmdb
- name: Wait for Docker services
env:
COMPOSE_FILE: docker-compose.dev.yml:docker-compose.profiles.yml
COMPOSE_PROFILES: temporal,azure
CLICKHOUSE_SERVER_IMAGE: clickhouse/clickhouse-server:25.8.12.129
run: bin/ci-wait-for-docker wait
- name: Register Temporal search attributes
run: |
bin/wait-for-docker temporal
python manage.py register_temporal_search_attributes
- name: Run product tests
# --force: discover already decided this product needs testing, skip turbo cache
# --log-order=stream: stream pytest output live instead of buffering until completion
# pytest_args: optional pytest-split flags for sharded products (e.g. "-- --splits 3 --group 1")
env:
# --reuse-db: keep the test database between sequential product runs to avoid
# ClickHouse drop/create race conditions with ReplicatedMergeTree ZK metadata.
# On master, also collect timing data for pytest-split sharding.
PYTEST_ADDOPTS: >-
--reuse-db
${{ needs.detect-snapshot-mode.outputs.mode == 'update' && '--snapshot-update' || '' }}
${{ github.ref == 'refs/heads/master' && '--store-durations --durations-path ../../.test_durations' || '' }}
run: pnpm turbo run backend:test ${{ matrix.filters }} --concurrency=1 --output-logs=full --force --log-order=stream ${{ matrix.pytest_args }}
- name: Upload timing data
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
if: ${{ github.ref == 'refs/heads/master' }}
with:
name: timing_data-Products-${{ strategy.job-index }}
path: .test_durations
include-hidden-files: true
retention-days: 2
- name: Verify new snapshots for flakiness
if: ${{ always() && needs.detect-snapshot-mode.outputs.mode == 'update' && github.event.pull_request.head.repo.full_name == 'PostHog/posthog' }}
shell: bash
run: |
.github/scripts/verify-new-snapshots.sh
- name: Generate snapshot patch
if: ${{ always() && needs.detect-snapshot-mode.outputs.mode == 'update' && github.event.pull_request.head.repo.full_name == 'PostHog/posthog' }}
shell: bash
run: |
mkdir -p /tmp/patches
git add -N '*.ambr' || true
if ! git diff --quiet '*.ambr' 2>/dev/null; then
git diff --binary --full-index '*.ambr' > /tmp/patches/backend-Products-${{ strategy.job-index }}.patch
echo "Generated patch with $(wc -l < /tmp/patches/backend-Products-${{ strategy.job-index }}.patch) lines"
else
echo "No snapshot changes to patch"
fi
- name: Upload snapshot patch
if: ${{ always() && needs.detect-snapshot-mode.outputs.mode == 'update' && github.event.pull_request.head.repo.full_name == 'PostHog/posthog' }}
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
with:
name: snapshot-patch-Products-${{ strategy.job-index }}
path: /tmp/patches/
if-no-files-found: ignore
retention-days: 1
# Lightweight repo-wide checks that only need Python + uv (no Docker/DB).
# Consolidates checks that previously each spun up their own runner.
repo-checks:
needs: [changes]
if: needs.changes.outputs.backend == 'true'
timeout-minutes: 10
name: Repo checks
runs-on: depot-ubuntu-latest
steps:
- uses: actions/checkout@v6
- name: Set up Python
uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
with:
python-version: 3.12.12
- name: Install uv
uses: astral-sh/setup-uv@eac588ad8def6316056a12d4907a9d4d84ff7a3b # v7.3.0
with:
version: '0.10.2' # pinned: unpinned setup-uv calls GH API on every job, exhausts rate limit
- name: Install Python dependencies
run: UV_PROJECT_ENVIRONMENT=$pythonLocation uv sync --frozen --dev
- name: Lint product structure
run: ./bin/hogli product:lint --all
- name: Check IDOR model coverage
run: python .github/scripts/check-idor-model-coverage.py
- name: Check operator parity
run: python .github/scripts/check-operator-parity.py
- name: Check module boundaries (tach)
run: tach check
# Migration validation and OpenAPI type generation.
# This job needs Docker + DB — it checks out master first to run baseline
# migrations, then checks out the PR branch. All steps after the PR checkout
# require Django + DB. Lightweight checks belong in repo-checks above.
check-migrations:
needs: [changes]
if: needs.changes.outputs.backend == 'true' || needs.changes.outputs.openapi_types == 'true'
timeout-minutes: 20
name: Validate migrations and OpenAPI types
runs-on: depot-ubuntu-latest
steps:
- uses: actions/checkout@v6
with:
clean: false
- name: Clean up data directories with container permissions
run: |
# Use docker to clean up files created by containers
[ -d "data" ] && docker run --rm -v "$(pwd)/data:/data" alpine sh -c "rm -rf /data/seaweedfs /data/minio" || true
continue-on-error: true
- name: Stop/Start stack with Docker Compose
env:
COMPOSE_FILE: docker-compose.dev.yml:docker-compose.profiles.yml
COMPOSE_PROFILES: temporal,azure
run: |
bin/ci-wait-for-docker launch --background --down
- name: Set up Python
uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
with:
python-version: 3.12.12
- name: Install uv
id: setup-uv
uses: astral-sh/setup-uv@eac588ad8def6316056a12d4907a9d4d84ff7a3b # v7.3.0
with:
version: '0.10.2' # pinned: unpinned setup-uv calls GH API on every job, exhausts rate limit
enable-cache: true
cache-dependency-glob: uv.lock
save-cache: ${{ github.ref == 'refs/heads/master' }}
- name: Install SAML (python3-saml) dependencies
if: steps.setup-uv.outputs.cache-hit != 'true'
run: |
sudo apt-get update
sudo apt-get install libxml2-dev libxmlsec1-dev libxmlsec1-openssl
- name: Install Rust
uses: dtolnay/rust-toolchain@0b1efabc08b657293548b77fb76cc02d26091c7e
with:
toolchain: 1.91.1
components: cargo
- name: Cache Rust dependencies
uses: Swatinem/rust-cache@779680da715d629ac1d338a641029a2f4372abb5 # v2.8.2
with:
shared-key: 'v2-rust-backend'
workspaces: rust
save-if: ${{ github.ref == 'refs/heads/master' }}
- name: Install sqlx-cli
uses: ./.github/actions/setup-sqlx-cli
- name: Preserve CI Docker helper during rollout
run: |
# Temporary during rollout: this job checks out `master`,
# which does not include the latest Docker wait helpers yet.
cp bin/ci-wait-for-docker /tmp/ci-wait-for-docker
chmod +x /tmp/ci-wait-for-docker
cp bin/wait-for-docker /tmp/wait-for-docker
chmod +x /tmp/wait-for-docker
# First running migrations from master, to simulate the real-world scenario
- name: Checkout master
uses: actions/checkout@v6
with:
ref: master
clean: false
- name: Restore CI Docker helper during rollout
run: |
# Temporary during rollout: restore the helpers after the
# checkout to `master` removes them from the workspace.
cp /tmp/ci-wait-for-docker bin/ci-wait-for-docker
chmod +x bin/ci-wait-for-docker
cp /tmp/wait-for-docker bin/wait-for-docker
chmod +x bin/wait-for-docker
- name: Install python dependencies for master
run: |
UV_PROJECT_ENVIRONMENT=.venv-master uv sync --frozen --dev
- name: Wait for Docker services
env:
COMPOSE_FILE: docker-compose.dev.yml:docker-compose.profiles.yml
COMPOSE_PROFILES: temporal,azure
run: bin/ci-wait-for-docker wait
- name: Run migrations up to master
run: |
# Run Django migrations first (excluding managed=False models)
.venv-master/bin/python manage.py migrate
# Then run persons migrations using sqlx; comment out until we've merged
# DATABASE_URL="postgres://posthog:posthog@localhost:5432/posthog_persons" \
# sqlx database create
# DATABASE_URL="postgres://posthog:posthog@localhost:5432/posthog_persons" \
# sqlx migrate run --source rust/persons_migrations/
# Get app token early so it can be passed to checkout below.
# This sets the git extraheader to the app token instead of GITHUB_TOKEN,
# which is required for the OpenAPI type commit push to trigger CI.
- name: Get app token for OpenAPI type commits
if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == 'PostHog/posthog'
id: openapi-app-token
uses: getsentry/action-github-app-token@d4b5da6c5e37703f8c3b3e43abb5705b46e159cc # v3.0.0
with:
app_id: ${{ secrets.GH_APP_POSTHOG_TESTS_APP_ID }}
private_key: ${{ secrets.GH_APP_POSTHOG_TESTS_PRIVATE_KEY }}
# Now we can consider this PR's migrations
- name: Checkout this PR
uses: actions/checkout@v6
with:
# For same-repo PRs, checkout the actual branch (not the merge commit)
# so OpenAPI type generation can be committed directly. Fork PRs fall
# back to the default merge commit (auto-commit bails out for forks).
ref: ${{ (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == 'PostHog/posthog') && github.event.pull_request.head.ref || github.ref }}
clean: false
# Use app token so the git extraheader is set correctly for the OpenAPI
# type commit push later — GITHUB_TOKEN pushes don't trigger CI.
token: ${{ steps.openapi-app-token.outputs.token || github.token }}
- name: Install python dependencies for this PR
run: |
UV_PROJECT_ENVIRONMENT=$pythonLocation uv sync --frozen --dev
- name: Check migrations and post SQL comment
if: github.event_name == 'pull_request' && needs.changes.outputs.migrations == 'true'
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
CHANGED_FILES: ${{ needs.changes.outputs.migrations_files }}
BASE_SHA: ${{ github.event.pull_request.base.sha }}
run: |
# If no migration files changed, exit
if [ -z "$CHANGED_FILES" ]; then
echo "No migration files changed"
exit 0
fi
if [ -z "$BASE_SHA" ]; then
echo "::warning::BASE_SHA is empty — all changed migrations will be treated as new"
else
# Ensure the base commit is available for comparison
git fetch --no-tags --prune --depth=1 origin "$BASE_SHA" || echo "::warning::Could not fetch base SHA $BASE_SHA — all changed migrations will be shown as new"
fi
# Initialize comment body for SQL changes
COMMENT_BODY="## Migration SQL Changes\n\nHey 👋, we've detected some migrations on this PR. Here's the SQL output for each migration, make sure they make sense:\n\n"
HAS_NEW_MIGRATIONS=false
# Process each changed migration file (excluding Rust migrations)
for file in $CHANGED_FILES; do
# Skip Rust migrations as they're handled separately by sqlx
if [[ $file =~ rust/persons_migrations ]]; then
continue
fi
if [[ $file =~ migrations/([0-9]+)_ ]]; then
migration_number="${BASH_REMATCH[1]}"
# Get app name by looking at the directory structure
# For new structure products/user_interviews/backend/migrations, we want user_interviews
# For old structure products/user_interviews/migrations, we want user_interviews
if [[ $file =~ products/([^/]+)/backend/migrations/ ]]; then
app_name="${BASH_REMATCH[1]}"
else
app_name=$(echo $file | sed -E 's|^([^/]+/)*([^/]+)/migrations/.*|\2|')
fi
# Only show SQL for new migrations, not modifications to existing ones
if git cat-file -e "$BASE_SHA:$file" 2>/dev/null; then
echo "Skipping $file (already exists on base branch)"
continue
fi
HAS_NEW_MIGRATIONS=true
echo "Checking migration $migration_number for app $app_name"
# Get SQL output
SQL_OUTPUT=$(python manage.py sqlmigrate $app_name $migration_number)
# Add to comment body
COMMENT_BODY+="#### [\`$file\`](https:\/\/github.com\/${{ github.repository }}\/blob\/${{ github.sha }}\/$file)\n\`\`\`sql\n$SQL_OUTPUT\n\`\`\`\n\n"
fi
done
# Get existing comments (needed for both update and cleanup)
COMMENTS=$(curl -s -H "Authorization: token $GITHUB_TOKEN" \
-H "Accept: application/vnd.github.v3+json" \
"https://api.github.com/repos/${{ github.repository }}/issues/${{ github.event.pull_request.number }}/comments")
# Extract comment ID if exists
SQL_COMMENT_ID=$(echo "$COMMENTS" | jq -r '.[] | select(.body | startswith("## Migration SQL Changes")) | .id' | head -1)
# If no new migrations, clean up any stale comment and exit
if [ "$HAS_NEW_MIGRATIONS" = false ]; then
echo "No new migrations to show (all changed files already exist on base branch)"
if [ -n "$SQL_COMMENT_ID" ]; then
echo "Deleting stale SQL comment $SQL_COMMENT_ID"
curl -X DELETE \
-H "Authorization: token $GITHUB_TOKEN" \
-H "Accept: application/vnd.github.v3+json" \
"https://api.github.com/repos/${{ github.repository }}/issues/comments/$SQL_COMMENT_ID"
fi
exit 0
fi
# Add timestamp and commit SHA to SQL changes
TIMESTAMP=$(date -u '+%Y-%m-%d %H:%M UTC')
COMMIT_SHA="${{ github.event.pull_request.head.sha }}"
COMMIT_SHORT="${COMMIT_SHA:0:7}"
COMMENT_BODY+="\n*Last updated: $TIMESTAMP ([${COMMIT_SHORT}](https://github.com/${{ github.repository }}/commit/${COMMIT_SHA}))*"
# Convert \n into actual newlines
COMMENT_BODY=$(printf '%b' "$COMMENT_BODY")
COMMENT_BODY_JSON=$(jq -n --arg body "$COMMENT_BODY" '{body: $body}')
if [ -n "$SQL_COMMENT_ID" ]; then
# Update existing comment
echo "Updating existing SQL comment $SQL_COMMENT_ID"
curl -X PATCH \
-H "Authorization: token $GITHUB_TOKEN" \
-H "Accept: application/vnd.github.v3+json" \
"https://api.github.com/repos/${{ github.repository }}/issues/comments/$SQL_COMMENT_ID" \
-d "$COMMENT_BODY_JSON"
else
# Post new SQL comment to PR
echo "Posting new SQL comment to PR"
curl -X POST \
-H "Authorization: token $GITHUB_TOKEN" \
-H "Accept: application/vnd.github.v3+json" \
"https://api.github.com/repos/${{ github.repository }}/issues/${{ github.event.pull_request.number }}/comments" \
-d "$COMMENT_BODY_JSON"
fi
- name: Run migration risk analysis and post comment
if: github.event_name == 'pull_request'
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
# Get risk analysis for all unapplied migrations (including third-party)
set +e # Don't exit immediately on error
RISK_ANALYSIS=$(python manage.py analyze_migration_risk --fail-on-blocked 2>/dev/null)
EXIT_CODE=$?
set -e # Re-enable exit on error
# Save analysis to file for artifact upload
if [ -n "$RISK_ANALYSIS" ]; then
echo "$RISK_ANALYSIS" > migration_analysis.md
fi
# Get existing comments
COMMENTS=$(curl -s -H "Authorization: token $GITHUB_TOKEN" \
-H "Accept: application/vnd.github.v3+json" \
"https://api.github.com/repos/${{ github.repository }}/issues/${{ github.event.pull_request.number }}/comments")
# Extract comment ID if exists
COMMENT_ID=$(echo "$COMMENTS" | jq -r '.[] | select(.body | startswith("## 🔍 Migration Risk Analysis")) | .id' | head -1)
if [ -n "$RISK_ANALYSIS" ] && echo "$RISK_ANALYSIS" | grep -q "Summary:"; then
# Add timestamp and commit SHA to analysis
TIMESTAMP=$(date -u '+%Y-%m-%d %H:%M UTC')
COMMIT_SHA="${{ github.event.pull_request.head.sha }}"
COMMIT_SHORT="${COMMIT_SHA:0:7}"
RISK_COMMENT="## 🔍 Migration Risk Analysis\n\nWe've analyzed your migrations for potential risks.\n\n$RISK_ANALYSIS\n\n*Last updated: $TIMESTAMP ([${COMMIT_SHORT}](https://github.com/${{ github.repository }}/commit/${COMMIT_SHA}))*"
RISK_COMMENT=$(printf '%b' "$RISK_COMMENT")
RISK_COMMENT_JSON=$(jq -n --arg body "$RISK_COMMENT" '{body: $body}')
if [ -n "$COMMENT_ID" ]; then
# Update existing comment
echo "Updating existing risk analysis comment $COMMENT_ID"
curl -X PATCH \
-H "Authorization: token $GITHUB_TOKEN" \
-H "Accept: application/vnd.github.v3+json" \
"https://api.github.com/repos/${{ github.repository }}/issues/comments/$COMMENT_ID" \
-d "$RISK_COMMENT_JSON"
else
# Create new comment if none exists
echo "Posting new risk analysis comment to PR"
curl -X POST \
-H "Authorization: token $GITHUB_TOKEN" \
-H "Accept: application/vnd.github.v3+json" \
"https://api.github.com/repos/${{ github.repository }}/issues/${{ github.event.pull_request.number }}/comments" \
-d "$RISK_COMMENT_JSON"
fi
elif [ -n "$COMMENT_ID" ]; then
# No migrations to analyze but comment exists - delete it
echo "Deleting risk analysis comment (no migrations to analyze)"
curl -X DELETE \
-H "Authorization: token $GITHUB_TOKEN" \
-H "Accept: application/vnd.github.v3+json" \
"https://api.github.com/repos/${{ github.repository }}/issues/comments/$COMMENT_ID"
else
echo "No migrations to analyze and no existing comment"
fi
# Fail the job if there were blocked migrations
if [ $EXIT_CODE -ne 0 ]; then
exit $EXIT_CODE
fi
- name: Upload migration analysis artifact
if: always() && github.event_name == 'pull_request'
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
with:
name: migration-analysis
path: migration_analysis.md
if-no-files-found: ignore
- name: Run migrations for this PR
run: |
# Run Django migrations first (excluding managed=False models)
python manage.py migrate
# Then run persons migrations using sqlx
DATABASE_URL="postgres://posthog:posthog@localhost:5432/posthog_persons" \
sqlx migrate run --source rust/persons_migrations/
- name: Dump migrated schema
if: github.event_name == 'push'
run: |
set -e
set -o pipefail
# Dump schema + django_migrations data so Django knows which migrations are applied
# Run pg_dump inside container to ensure version match (host has pg_dump 16, container has 15)
(docker compose -f docker-compose.dev.yml exec -T db pg_dump --schema-only --clean -U posthog posthog && \
docker compose -f docker-compose.dev.yml exec -T db pg_dump --data-only --table=django_migrations -U posthog posthog) | gzip > schema.sql.gz
# Verify the dump is valid
gunzip -t schema.sql.gz
- name: Upload migrated schema artifact
if: github.event_name == 'push'
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
with:
name: migrated-schema
path: schema.sql.gz
retention-days: 90
- name: Check migrations
# Skip migration safety check on master push (no migration_files from path filter)
if: github.event_name != 'push'
env:
MIGRATIONS_FILES: ${{ needs.changes.outputs.migrations_files }}
run: |
DATABASE_URL="postgres://posthog:posthog@localhost:5432/posthog_persons" \
sqlx migrate info --source rust/persons_migrations/
python manage.py makemigrations --check --dry-run
git fetch origin master
# Check migration safety using old SQL-based checker (still uses stdin from git diff)
echo "$MIGRATIONS_FILES" | grep -v migrations/0001_ | grep -v 'rust/persons_migrations' | python manage.py test_migrations_are_safe
- name: Check CH migrations
run: |
# Same as above, except now for CH looking at files that were added in posthog/clickhouse/migrations/
git diff --name-status origin/master..HEAD | grep "A\sposthog/clickhouse/migrations/" | grep -v README | awk '{print $2}' | python manage.py test_ch_migrations_are_safe
- name: Install pnpm
uses: pnpm/action-setup@a7487c7e89a18df4991f7f222e4898a00d66ddda # v4.1.0
- name: Fix node-gyp permissions
run: chmod +x ~/setup-pnpm/node_modules/.pnpm/pnpm@*/node_modules/pnpm/dist/node_modules/node-gyp/gyp/gyp_main.py
- name: Set up Node.js
uses: actions/setup-node@v6
with:
node-version: 24.13.0
cache: pnpm
cache-dependency-path: |
pnpm-lock.yaml
.github/workflows/ci-backend.yml
- name: Install package.json dependencies with pnpm
env:
npm_config_fetch_retries: 3
npm_config_fetch_retry_mintimeout: 10000
npm_config_fetch_retry_maxtimeout: 60000
run: pnpm --filter=@posthog/root --filter=@posthog/frontend... --filter=@posthog/mcp... install --frozen-lockfile
- name: Add OpenAPI Problem Matcher
run: echo "::add-matcher::.github/openapi-problem-matcher.json"
- name: Check and update OpenAPI types
env:
EVENT_NAME: ${{ github.event_name }}
HEAD_REPO: ${{ github.event.pull_request.head.repo.full_name }}
BRANCH: ${{ github.event.pull_request.head.ref }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
REPOSITORY: ${{ github.repository }}
PR_NUMBER: ${{ github.event.pull_request.number }}
APP_TOKEN: ${{ steps.openapi-app-token.outputs.token }}
GH_TOKEN: ${{ steps.openapi-app-token.outputs.token }}
run: |
./bin/hogli build:openapi
pnpm --filter=@posthog/mcp run scaffold-yaml -- --sync-all
if git diff --exit-code; then
echo "OpenAPI types are up to date"
exit 0
fi
echo "OpenAPI types are out of date"
# On non-PR builds or fork PRs, fail with instructions
if [ "$EVENT_NAME" != "pull_request" ] || \
[ "$HEAD_REPO" != "PostHog/posthog" ]; then
echo ""
echo "::error::OpenAPI types are out of date!"
echo ""
echo "The TypeScript API types in products/*/frontend/generated/ are auto-generated"
echo "from Django serializers and views. When you modify the backend API, you need"
echo "to regenerate these types."
echo ""
echo "To fix, run locally: hogli build:openapi"
echo "Then commit the updated generated files."
echo ""
echo "More info: https://posthog.com/handbook/engineering/type-system"
echo ""
echo "Questions? #team-devex on Slack"
exit 1
fi
echo "::notice::Committing updated OpenAPI types to PR branch"
# Verify branch hasn't advanced since CI started
CURRENT_SHA=$(git ls-remote origin "refs/heads/$BRANCH" | cut -f1)
if [ "$CURRENT_SHA" != "$HEAD_SHA" ]; then
echo "::warning::Branch advanced during workflow ($HEAD_SHA -> $CURRENT_SHA) — skipping auto-commit"
echo "The new commit will trigger its own workflow run."
exit 0
fi
# Disable auto-merge before pushing to prevent unreviewed code from merging
gh pr merge --disable-auto "$PR_NUMBER" || echo "Auto-merge was not enabled"
# Unset any lingering extraheader so the app token in the remote URL
# is definitely used for the push.
git config --unset-all http.https://github.com/.extraheader || true
git remote set-url origin "https://x-access-token:${APP_TOKEN}@github.com/${REPOSITORY}.git"
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git add frontend/src/generated/
git add products/*/frontend/generated/ 2>/dev/null || true
git add products/*/mcp/*.yaml 2>/dev/null || true
git add services/mcp/definitions/*.yaml 2>/dev/null || true
git add services/mcp/src/api/generated.ts 2>/dev/null || true
git add services/mcp/src/generated/ 2>/dev/null || true
git add services/mcp/schema/generated-tool-definitions.json 2>/dev/null || true
git add services/mcp/schema/tool-definitions-all.json 2>/dev/null || true
git add services/mcp/src/tools/generated/ 2>/dev/null || true
git commit -m "chore: update OpenAPI generated types"
git push origin "$BRANCH"
echo "::notice::Pushed updated OpenAPI types to $BRANCH"
build_django_matrix:
name: Build Django matrix
needs: [changes, get_clickhouse_versions]
if: needs.changes.outputs.backend == 'true'
runs-on: ubuntu-latest
timeout-minutes: 5
outputs:
include: ${{ steps.build.outputs.include }}
steps:
- name: Build matrix include list
id: build
env:
OLDEST_SUPPORTED_IMAGE: ${{ needs.get_clickhouse_versions.outputs.oldest_supported_image }}
COMPAT_MATRIX_JSON: ${{ needs.get_clickhouse_versions.outputs.compat_matrix }}
run: |
# :NOTE: Keep shard counts/group ranges in sync with historical Django matrix tuning.
# Consult #team-devex before changing.
core=$(jq -cn --arg image "$OLDEST_SUPPORTED_IMAGE" '
[range(1; 39) | {
segment: "Core",
"person-on-events": false,
"python-version": "3.12.12",
"clickhouse-server-image": $image,
concurrency: 38,
group: .,
artifact_key: ("core-" + (.|tostring)),
compat: false
}]
')
core_persons_on_events=$(jq -cn --arg image "$OLDEST_SUPPORTED_IMAGE" '
[range(1; 8) | {
segment: "Core",
"person-on-events": true,
"python-version": "3.12.12",
"clickhouse-server-image": $image,
concurrency: 7,
group: .,
artifact_key: ("core-poe-" + (.|tostring)),
compat: false
}]
')
temporal=$(jq -cn --arg image "$OLDEST_SUPPORTED_IMAGE" '
[range(1; 8) | {
segment: "Temporal",
"person-on-events": false,
"python-version": "3.12.12",
"clickhouse-server-image": $image,
concurrency: 7,
group: .,
artifact_key: ("temporal-" + (.|tostring)),
compat: false
}]
')
compat_source="${COMPAT_MATRIX_JSON:-[]}"
compat=$(jq -cn --argjson compat "$compat_source" '
[
$compat
| to_entries[]
| .value + {
segment: "Core",
"person-on-events": false,
"python-version": "3.12.12",
compat: true,
artifact_key: ("compat-" + ((.key + 1)|tostring))
}
]
')
include=$(jq -cn \
--argjson core "$core" \
--argjson core_persons_on_events "$core_persons_on_events" \
--argjson temporal "$temporal" \