Skip to content

: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.

ci: run selected tests in draft, full suite when PR ready (#58053)

Georges-Antoine Assi48be89bbbf9d
diff --git a/.depot/workflows/ci-backend.yml b/.depot/workflows/ci-backend.yml
index 6e44ea91bd30..35685949c791 100644
--- a/.depot/workflows/ci-backend.yml
+++ b/.depot/workflows/ci-backend.yml
@@ -42,9 +42,11 @@ on:
description: ClickHouse server version. Leave blank for default
type: string
pull_request:
- # Heavy test matrices (django, turbo-tests) skip drafts; ready_for_review
- # re-triggers them when a PR leaves draft. Add the `run-ci-backend` label
- # (labeled/unlabeled re-trigger) to force them on a draft. Mirrors canonical.
+ # Draft PRs run the snob-selected Django subset (≤3 shards); turbo-tests
+ # still skip drafts. Ready PRs run the full matrices — the merge gate —
+ # and ready_for_review re-triggers them when a PR leaves draft. Add the
+ # `run-ci-backend` label (labeled/unlabeled re-trigger) to force the full
+ # matrices on a draft. Mirrors canonical.
types: [opened, synchronize, reopened, ready_for_review, labeled, unlabeled]
merge_group:
concurrency:
@@ -332,6 +334,164 @@ jobs:
echo "matrix=$(echo "$RESULT" | jq -c '.matrix')" >> $GITHUB_OUTPUT
echo "run_legacy=$(echo "$RESULT" | jq -r '.run_legacy')" >> $GITHUB_OUTPUT
echo "django_shards=$(echo "$RESULT" | jq -c '.django_shards // empty')" >> $GITHUB_OUTPUT
+
+ # Pick which Django tests to run on draft PRs. Drafts get the snob-selected
+ # subset for fast feedback; the full matrix runs once the PR is marked ready
+ # for review, and that ready run is the merge gate. When selection can't be
+ # trusted on a draft (legacy graph impact, turbo-discover or selector failure,
+ # a selector full-run signal), the draft skips the heavy matrices entirely —
+ # the pre-selection draft behavior — and defers to the ready full run.
+ #
+ # Depot shadow note: canonical uploads /tmp/selection.json for its
+ # test-selection-verdict job. The depot shadow strips that job (and all
+ # artifact uploads), so this job has no Upload selection artifact step.
+ select-tests:
+ name: Select tests
+ needs: [changes, turbo-discover]
+ # Only draft PRs do selective runs; ready PRs and non-PR events (push,
+ # merge_group) always run full, which build_django_matrix falls back to
+ # when select-tests is skipped (empty MODE). The run-ci-backend label
+ # forces the full matrices on a draft.
+ if: |
+ github.event_name == 'pull_request' &&
+ github.event.pull_request.draft == true &&
+ !contains(github.event.pull_request.labels.*.name, 'run-ci-backend') &&
+ needs.changes.outputs.backend == 'true'
+ runs-on: depot-ubuntu-latest
+ timeout-minutes: 5
+ outputs:
+ mode: ${{ steps.classify.outputs.mode }}
+ core_files: ${{ steps.classify.outputs.core_files }}
+ poe_files: ${{ steps.classify.outputs.poe_files }}
+ temporal_files: ${{ steps.classify.outputs.temporal_files }}
+ run_poe: ${{ steps.classify.outputs.run_poe }}
+ run_temporal: ${{ steps.classify.outputs.run_temporal }}
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ with:
+ fetch-depth: 1000
+ filter: blob:none
+
+ - name: Install uv
+ uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0
+ with:
+ version: '0.11.14'
+
+ - name: Decide whether selection can be trusted
+ id: fallback
+ env:
+ RUN_LEGACY: ${{ needs.turbo-discover.outputs.run_legacy }}
+ TURBO_RESULT: ${{ needs.turbo-discover.result }}
+ shell: bash
+ run: |
+ set -euo pipefail
+ skip=false
+ if [[ "$RUN_LEGACY" == "true" ]]; then
+ # turbo-discover detected product->legacy graph impact; the
+ # diff-based selector can't see this, so its subset would be
+ # incomplete. Skip the draft matrices; the ready run is full.
+ skip=true
+ elif [[ "$TURBO_RESULT" != "success" && "$TURBO_RESULT" != "skipped" ]]; then
+ # Conservative — turbo-discover failed.
+ skip=true
+ fi
+ echo "skip=$skip" >> "$GITHUB_OUTPUT"
+
+ - name: Run shadow selector
+ id: select
+ # continue-on-error so a selector or git fetch failure doesn't fail this
+ # job — a failed select-tests would leave MODE empty and build_django_matrix
+ # would fall back to an expensive full matrix on a draft. Classify reads
+ # steps.select.outcome (pre-continue-on-error) and emits mode=skip instead.
+ continue-on-error: true
+ if: steps.fallback.outputs.skip == 'false'
+ env:
+ BASE_REF: ${{ github.event.pull_request.base.ref }}
+ shell: bash
+ run: |
+ set -euo pipefail
+ git fetch --no-tags --depth=1000 --filter=blob:none origin "$BASE_REF:refs/remotes/origin/$BASE_REF"
+ uv run tools/snob_backend_test_selection_shadow.py \
+ --base-ref "origin/$BASE_REF" \
+ > /tmp/selection.json
+
+ - name: Classify selection into segments
+ id: classify
+ env:
+ FALLBACK_SKIP: ${{ steps.fallback.outputs.skip }}
+ SELECT_OUTCOME: ${{ steps.select.outcome }}
+ shell: bash
+ run: |
+ set -euo pipefail
+ # Untrusted selection on a draft skips the heavy matrices (the
+ # pre-selection draft behavior); the ready-for-review run is full.
+ fall_back_to_skip() {
+ echo "mode=skip" >> "$GITHUB_OUTPUT"
+ echo "core_files=" >> "$GITHUB_OUTPUT"
+ echo "poe_files=" >> "$GITHUB_OUTPUT"
+ echo "temporal_files=" >> "$GITHUB_OUTPUT"
+ echo "run_poe=false" >> "$GITHUB_OUTPUT"
+ echo "run_temporal=false" >> "$GITHUB_OUTPUT"
+ }
+
+ if [[ "$FALLBACK_SKIP" == "true" ]]; then
+ fall_back_to_skip
+ exit 0
+ fi
+
+ if [[ "$SELECT_OUTCOME" != "success" ]] || [[ ! -s /tmp/selection.json ]]; then
+ echo "::warning::shadow selector did not produce output; draft skips heavy matrices (full run happens on ready for review)"
+ fall_back_to_skip
+ exit 0
+ fi
+
+ full_run_reasons=$(jq -r '.ast.full_run_reasons | length' /tmp/selection.json)
+ if [[ "$full_run_reasons" -gt 0 ]]; then
+ echo "Selector requested a full run; draft defers it to ready for review:"
+ jq -r '.ast.full_run_reasons[]' /tmp/selection.json
+ fall_back_to_skip
+ exit 0
+ fi
+
+ # Partition selected files by the Django segment that owns them.
+ # Mirrors the positional path arguments in the Run Core / Run Temporal pytest invocations:
+ # Core (POE off): posthog ee/ (minus posthog/temporal, posthog/dags)
+ # Core POE on: posthog/clickhouse, posthog/queries, posthog/api/test/test_insight*,
+ # posthog/api/test/dashboards/test_dashboard.py, ee/clickhouse/
+ # Temporal: posthog/temporal, products/{batch_exports,tasks}/backend/temporal
+ # Files outside posthog/ and ee/ (e.g. products/foo/backend/test_*) are not in this
+ # matrix — turbo-tests handles them.
+ core=()
+ poe=()
+ temporal=()
+ while IFS= read -r f; do
+ [[ -z "$f" ]] && continue
+ case "$f" in
+ posthog/temporal/*|products/batch_exports/backend/tests/temporal/*|products/tasks/backend/temporal/*)
+ temporal+=("$f")
+ ;;
+ posthog/clickhouse/*|posthog/queries/*|ee/clickhouse/*|products/product_analytics/backend/api/test/*|posthog/api/test/test_insight*|posthog/api/test/dashboards/test_dashboard.py)
+ poe+=("$f")
+ core+=("$f")
+ ;;
+ posthog/dags/*|common/hogvm/python/test/*)
+ # Explicitly --ignore'd by the Core invocation; nothing to do.
+ ;;
+ posthog/*|ee/*)
+ core+=("$f")
+ ;;
+ esac
+ done < <(jq -r '.combined.tests[]?' /tmp/selection.json)
+
+ echo "mode=selected" >> "$GITHUB_OUTPUT"
+ echo "core_files=${core[*]:-}" >> "$GITHUB_OUTPUT"
+ echo "poe_files=${poe[*]:-}" >> "$GITHUB_OUTPUT"
+ echo "temporal_files=${temporal[*]:-}" >> "$GITHUB_OUTPUT"
+ echo "run_poe=$([[ ${#poe[@]} -gt 0 ]] && echo true || echo false)" >> "$GITHUB_OUTPUT"
+ echo "run_temporal=$([[ ${#temporal[@]} -gt 0 ]] && echo true || echo false)" >> "$GITHUB_OUTPUT"
+
+ echo "Selected: ${#core[@]} core, ${#poe[@]} POE-eligible, ${#temporal[@]} temporal"
+
# 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
@@ -676,7 +836,7 @@ jobs:
exit 1
build_django_matrix:
name: Build Django matrix
- needs: [changes, get_clickhouse_versions, turbo-discover]
+ needs: [changes, get_clickhouse_versions, turbo-discover, select-tests]
if: |
always() &&
needs.changes.outputs.backend == 'true' &&
@@ -692,74 +852,135 @@ jobs:
OLDEST_SUPPORTED_IMAGE: ${{ needs.get_clickhouse_versions.outputs.oldest_supported_image }}
COMPAT_MATRIX_JSON: ${{ needs.get_clickhouse_versions.outputs.compat_matrix }}
DJANGO_SHARDS_JSON: ${{ needs.turbo-discover.outputs.django_shards }}
+ MODE: ${{ needs.select-tests.outputs.mode }}
+ RUN_POE: ${{ needs.select-tests.outputs.run_poe }}
+ RUN_TEMPORAL: ${{ needs.select-tests.outputs.run_temporal }}
+ CORE_FILES: ${{ needs.select-tests.outputs.core_files }}
run: |
- # Auto-shard counts from turbo-discover (Amdahl's law on .test_durations).
- # Falls back to hardcoded defaults if turbo-discover failed or data is missing.
- CORE_SHARDS=38
- CORE_POE_SHARDS=7
- TEMPORAL_SHARDS=7
- if [ -n "$DJANGO_SHARDS_JSON" ] && echo "$DJANGO_SHARDS_JSON" | jq -e '.Core.shards' > /dev/null 2>&1; then
- CORE_SHARDS=$(echo "$DJANGO_SHARDS_JSON" | jq -r '.Core.shards')
- CORE_POE_SHARDS=$(echo "$DJANGO_SHARDS_JSON" | jq -r '.CorePOE.shards')
- TEMPORAL_SHARDS=$(echo "$DJANGO_SHARDS_JSON" | jq -r '.Temporal.shards')
- echo "Auto-sharding: Core=$CORE_SHARDS, CorePOE=$CORE_POE_SHARDS, Temporal=$TEMPORAL_SHARDS"
- else
- echo "::warning::Django shard auto-sizing unavailable, using defaults: Core=$CORE_SHARDS, CorePOE=$CORE_POE_SHARDS, Temporal=$TEMPORAL_SHARDS"
+ # :NOTE: Keep shard counts/group ranges in sync with historical Django matrix tuning.
+ # Consult #team-devex before changing.
+ if [[ "$MODE" == "skip" ]]; then
+ # Draft PR where selection couldn't be trusted: skip the heavy
+ # matrices and defer to the full run on ready for review.
+ echo "include=[]" >> "$GITHUB_OUTPUT"
+ echo "Django matrix size: 0 (mode=skip)"
+ exit 0
fi
+ if [[ "$MODE" == "selected" ]]; then
+ # Selected mode: collapse to one shard per active segment, skip
+ # segments with no selected files, drop compat entirely.
+ core_count=0
+ [[ -n "$CORE_FILES" ]] && core_count=1
+ core=$(jq -cn --arg image "$OLDEST_SUPPORTED_IMAGE" --argjson n "$core_count" '
+ [range(1; $n + 1) | {
+ segment: "Core",
+ "person-on-events": false,
+ "python-version": "3.13.13",
+ "clickhouse-server-image": $image,
+ concurrency: 1,
+ group: 1,
+ artifact_key: "core-1",
+ compat: false
+ }]
+ ')
+ poe_count=0
+ [[ "$RUN_POE" == "true" ]] && poe_count=1
+ core_persons_on_events=$(jq -cn --arg image "$OLDEST_SUPPORTED_IMAGE" --argjson n "$poe_count" '
+ [range(1; $n + 1) | {
+ segment: "Core",
+ "person-on-events": true,
+ "python-version": "3.13.13",
+ "clickhouse-server-image": $image,
+ concurrency: 1,
+ group: 1,
+ artifact_key: "core-poe-1",
+ compat: false
+ }]
+ ')
+ temporal_count=0
+ [[ "$RUN_TEMPORAL" == "true" ]] && temporal_count=1
+ temporal=$(jq -cn --arg image "$OLDEST_SUPPORTED_IMAGE" --argjson n "$temporal_count" '
+ [range(1; $n + 1) | {
+ segment: "Temporal",
+ "person-on-events": false,
+ "python-version": "3.13.13",
+ "clickhouse-server-image": $image,
+ concurrency: 1,
+ group: 1,
+ artifact_key: "temporal-1",
+ compat: false
+ }]
+ ')
+ compat="[]"
+ else
+ # Full run: auto-shard counts from turbo-discover (Amdahl's law on .test_durations).
+ # Falls back to hardcoded defaults if turbo-discover failed or data is missing.
+ CORE_SHARDS=38
+ CORE_POE_SHARDS=7
+ TEMPORAL_SHARDS=7
+ if [ -n "$DJANGO_SHARDS_JSON" ] && echo "$DJANGO_SHARDS_JSON" | jq -e '.Core.shards' > /dev/null 2>&1; then
+ CORE_SHARDS=$(echo "$DJANGO_SHARDS_JSON" | jq -r '.Core.shards')
+ CORE_POE_SHARDS=$(echo "$DJANGO_SHARDS_JSON" | jq -r '.CorePOE.shards')
+ TEMPORAL_SHARDS=$(echo "$DJANGO_SHARDS_JSON" | jq -r '.Temporal.shards')
+ echo "Auto-sharding: Core=$CORE_SHARDS, CorePOE=$CORE_POE_SHARDS, Temporal=$TEMPORAL_SHARDS"
+ else
+ echo "::warning::Django shard auto-sizing unavailable, using defaults: Core=$CORE_SHARDS, CorePOE=$CORE_POE_SHARDS, Temporal=$TEMPORAL_SHARDS"
+ fi
- core=$(jq -cn --arg image "$OLDEST_SUPPORTED_IMAGE" --argjson shards "$CORE_SHARDS" '
- [range(1; $shards + 1) | {
- segment: "Core",
- "person-on-events": false,
- "python-version": "3.13.13",
- "clickhouse-server-image": $image,
- concurrency: $shards,
- group: .,
- artifact_key: ("core-" + (.|tostring)),
- compat: false
- }]
- ')
-
- core_persons_on_events=$(jq -cn --arg image "$OLDEST_SUPPORTED_IMAGE" --argjson shards "$CORE_POE_SHARDS" '
- [range(1; $shards + 1) | {
- segment: "Core",
- "person-on-events": true,
- "python-version": "3.13.13",
- "clickhouse-server-image": $image,
- concurrency: $shards,
- group: .,
- artifact_key: ("core-poe-" + (.|tostring)),
- compat: false
- }]
- ')
-
- temporal=$(jq -cn --arg image "$OLDEST_SUPPORTED_IMAGE" --argjson shards "$TEMPORAL_SHARDS" '
- [range(1; $shards + 1) | {
- segment: "Temporal",
- "person-on-events": false,
- "python-version": "3.13.13",
- "clickhouse-server-image": $image,
- concurrency: $shards,
- group: .,
- artifact_key: ("temporal-" + (.|tostring)),
- compat: false
- }]
- ')
+ core=$(jq -cn --arg image "$OLDEST_SUPPORTED_IMAGE" --argjson shards "$CORE_SHARDS" '
+ [range(1; $shards + 1) | {
+ segment: "Core",
+ "person-on-events": false,
+ "python-version": "3.13.13",
+ "clickhouse-server-image": $image,
+ concurrency: $shards,
+ group: .,
+ artifact_key: ("core-" + (.|tostring)),
+ compat: false
+ }]
+ ')
- compat_source="${COMPAT_MATRIX_JSON:-[]}"
- compat=$(jq -cn --argjson compat "$compat_source" '
- [
- $compat
- | to_entries[]
- | .value + {
+ core_persons_on_events=$(jq -cn --arg image "$OLDEST_SUPPORTED_IMAGE" --argjson shards "$CORE_POE_SHARDS" '
+ [range(1; $shards + 1) | {
segment: "Core",
+ "person-on-events": true,
+ "python-version": "3.13.13",
+ "clickhouse-server-image": $image,
+ concurrency: $shards,
+ group: .,
+ artifact_key: ("core-poe-" + (.|tostring)),
+ compat: false
+ }]
+ ')
+
+ temporal=$(jq -cn --arg image "$OLDEST_SUPPORTED_IMAGE" --argjson shards "$TEMPORAL_SHARDS" '
+ [range(1; $shards + 1) | {
+ segment: "Temporal",
"person-on-events": false,
"python-version": "3.13.13",
- compat: true,
- artifact_key: ("compat-" + ((.key + 1)|tostring))
- }
- ]
- ')
+ "clickhouse-server-image": $image,
+ concurrency: $shards,
+ 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.13.13",
+ compat: true,
+ artifact_key: ("compat-" + ((.key + 1)|tostring))
+ }
+ ]
+ ')
+ fi
include=$(jq -cn \
--argjson core "$core" \
@@ -769,19 +990,20 @@ jobs:
'$core + $core_persons_on_events + $temporal + $compat')
echo "include=$include" >> "$GITHUB_OUTPUT"
- echo "Django matrix size: $(jq -r 'length' <<< "$include")"
+ echo "Django matrix size: $(jq -r 'length' <<< "$include") (mode=$MODE)"
django:
- needs: [changes, turbo-discover, get_clickhouse_versions, build_django_matrix]
+ needs: [changes, turbo-discover, get_clickhouse_versions, build_django_matrix, select-tests]
# Run legacy pytest if:
# 1. Legacy code directly changed (ee/, posthog/)
# 2. OR product changes affect legacy code (turbo-discover outputs run_legacy=true)
# 3. OR turbo-discover itself failed (conservative: run Django on detection failure)
+ # The non-empty include guard covers drafts in skip mode and selected runs
+ # that chose zero files — an empty matrix would otherwise fail the job.
if: |
always() &&
- (github.event.pull_request.draft != true ||
- contains(github.event.pull_request.labels.*.name, 'run-ci-backend')) &&
needs.changes.outputs.backend == 'true' &&
needs.build_django_matrix.result == 'success' &&
+ needs.build_django_matrix.outputs.include != '[]' &&
(needs.changes.outputs.legacy == 'true' ||
needs.turbo-discover.outputs.run_legacy == 'true' ||
(needs.turbo-discover.result != 'success' && needs.turbo-discover.result != 'skipped'))
@@ -1000,31 +1222,51 @@ jobs:
if: ${{ needs.changes.outputs.backend == 'true' && matrix.segment == 'Core' }}
env:
PERSON_ON_EVENTS_V2_ENABLED: ${{ matrix.person-on-events && 'true' || 'false' }}
+ MODE: ${{ needs.select-tests.outputs.mode }}
+ CORE_FILES: ${{ needs.select-tests.outputs.core_files }}
+ POE_FILES: ${{ needs.select-tests.outputs.poe_files }}
shell: bash
run: | # async_migrations covered in ci-async-migrations.yml
unset GITHUB_TOKEN # reserved var injected by Depot CI; can't override via env: (see workflow env note)
set +e
- pytest -v --tb=short --reuse-db -o junit_duration_report=call ${{
- matrix.compat
- && env.CLICKHOUSE_COMPAT_PYTEST_TARGETS
- || (
- matrix.person-on-events
- && './posthog/clickhouse/ ./posthog/queries/ ./products/product_analytics/backend/api/test/ ./posthog/api/test/dashboards/test_dashboard.py'
- || 'posthog'
- )
- }} ${{ matrix.compat && '' || (matrix.person-on-events && 'ee/clickhouse/' || 'ee/') }} -m "not async_migrations" \
- --ignore=posthog/temporal \
- --ignore=posthog/dags \
- --ignore=common/hogvm/python/test \
- ${{ matrix.person-on-events && '--ignore=posthog/hogql_queries' || '' }} \
- ${{ matrix.person-on-events && '--ignore=posthog/hogql' || '' }} \
- --snapshot-update --snapshot-warn-unused \
- --splits ${{ matrix.concurrency }} --group ${{ matrix.group }} \
- --durations=1000 --durations-min=1.0 \
- --splitting-algorithm=duration_based_chunks \
- --reruns 2 --reruns-delay 1 \
- -r fEsxX \
- --junitxml=junit-core.xml
+ if [[ "$MODE" == "selected" ]]; then
+ # Selected mode: run only the test files chosen by the snob shadow selector.
+ # No --splits/--group (no sharding), no --reruns (selected runs should fail
+ # loud so flaky tests get fixed instead of masked; the ready-for-review full
+ # run has reruns). Snapshot flags kept to match the depot shadow's full branch.
+ if [[ "${{ matrix.person-on-events }}" == "true" ]]; then
+ targets="$POE_FILES"
+ else
+ targets="$CORE_FILES"
+ fi
+ # shellcheck disable=SC2086
+ pytest -v --tb=short --reuse-db -o junit_duration_report=call $targets -m "not async_migrations" \
+ --snapshot-update --snapshot-warn-unused \
+ -r fEsxX \
+ --junitxml=junit-core.xml
+ else
+ pytest -v --tb=short --reuse-db -o junit_duration_report=call ${{
+ matrix.compat
+ && env.CLICKHOUSE_COMPAT_PYTEST_TARGETS
+ || (
+ matrix.person-on-events
+ && './posthog/clickhouse/ ./posthog/queries/ ./products/product_analytics/backend/api/test/ ./posthog/api/test/dashboards/test_dashboard.py'
+ || 'posthog'
+ )
+ }} ${{ matrix.compat && '' || (matrix.person-on-events && 'ee/clickhouse/' || 'ee/') }} -m "not async_migrations" \
+ --ignore=posthog/temporal \
+ --ignore=posthog/dags \
+ --ignore=common/hogvm/python/test \
+ ${{ matrix.person-on-events && '--ignore=posthog/hogql_queries' || '' }} \
+ ${{ matrix.person-on-events && '--ignore=posthog/hogql' || '' }} \
+ --snapshot-update --snapshot-warn-unused \
+ --splits ${{ matrix.concurrency }} --group ${{ matrix.group }} \
+ --durations=1000 --durations-min=1.0 \
+ --splitting-algorithm=duration_based_chunks \
+ --reruns 2 --reruns-delay 1 \
+ -r fEsxX \
+ --junitxml=junit-core.xml
+ fi
exit_code=$?
set -e
if [ $exit_code -eq 5 ]; then
@@ -1066,6 +1308,8 @@ jobs:
AWS_S3_ALLOW_UNSAFE_RENAME: 'true'
MODAL_TOKEN_ID: ${{ needs.changes.outputs.tasks_temporal == 'true' && secrets.MODAL_TOKEN_ID || '' }}
MODAL_TOKEN_SECRET: ${{ needs.changes.outputs.tasks_temporal == 'true' && secrets.MODAL_TOKEN_SECRET || '' }}
+ MODE: ${{ needs.select-tests.outputs.mode }}
+ TEMPORAL_FILES: ${{ needs.select-tests.outputs.temporal_files }}
run: |
unset GITHUB_TOKEN # reserved var injected by Depot CI; can't override via env: (see workflow env note)
set +e
@@ -1074,20 +1318,35 @@ jobs:
# (verified via boto3 LIST/CREATE/HEAD), so root cause is env-specific and not yet
# isolated (tracked for follow-up). All three tests below run that materialize path; the
# two timeout tests fail downstream (hogql_table never reached). Canonical GHA still runs them.
- # No per-test pytest --timeout; rely on the job-level timeout-minutes as the single
- # safety net (matches canonical — the per-test guillotine added nothing over it,
- # since --timeout-method=thread os._exit()s the whole process anyway).
- pytest -v --tb=short --reuse-db -o junit_duration_report=call posthog/temporal products/batch_exports/backend/tests/temporal products/tasks/backend/temporal -m "not async_migrations" \
- --deselect "posthog/temporal/tests/data_modeling/test_run_workflow.py::test_run_workflow_with_minio_bucket" \
- --deselect "posthog/temporal/tests/data_modeling/test_run_workflow.py::test_run_workflow_timeout_does_not_pause_schedule_without_consecutive_failures" \
- --deselect "posthog/temporal/tests/data_modeling/test_run_workflow.py::test_run_workflow_timeout_pauses_schedule_after_5_consecutive_failures" \
- --snapshot-update --snapshot-warn-unused \
- --splits ${{ matrix.concurrency }} --group ${{ matrix.group }} \
- --durations=100 --durations-min=1.0 \
- --splitting-algorithm=duration_based_chunks \
- --reruns 2 --reruns-delay 1 \
- -r fEsxX \
- --junitxml=junit-temporal.xml
+ # The --deselect guards stay on both branches so a selected run can't re-enable them.
+ if [[ "$MODE" == "selected" ]]; then
+ # Selected mode: no sharding, no --reruns (fail loud; the ready full
+ # run still reruns). See the core selected branch for the rationale. Snapshot
+ # flags kept to match the depot shadow's full branch.
+ # shellcheck disable=SC2086
+ pytest -v --tb=short --reuse-db -o junit_duration_report=call $TEMPORAL_FILES -m "not async_migrations" \
+ --deselect "posthog/temporal/tests/data_modeling/test_run_workflow.py::test_run_workflow_with_minio_bucket" \
+ --deselect "posthog/temporal/tests/data_modeling/test_run_workflow.py::test_run_workflow_timeout_does_not_pause_schedule_without_consecutive_failures" \
+ --deselect "posthog/temporal/tests/data_modeling/test_run_workflow.py::test_run_workflow_timeout_pauses_schedule_after_5_consecutive_failures" \
+ --snapshot-update --snapshot-warn-unused \
+ -r fEsxX \
+ --junitxml=junit-temporal.xml
+ else
+ # No per-test pytest --timeout; rely on the job-level timeout-minutes as the single
+ # safety net (matches canonical — the per-test guillotine added nothing over it,
+ # since --timeout-method=thread os._exit()s the whole process anyway).
+ pytest -v --tb=short --reuse-db -o junit_duration_report=call posthog/temporal products/batch_exports/backend/tests/temporal products/tasks/backend/temporal -m "not async_migrations" \
+ --deselect "posthog/temporal/tests/data_modeling/test_run_workflow.py::test_run_workflow_with_minio_bucket" \
+ --deselect "posthog/temporal/tests/data_modeling/test_run_workflow.py::test_run_workflow_timeout_does_not_pause_schedule_without_consecutive_failures" \
+ --deselect "posthog/temporal/tests/data_modeling/test_run_workflow.py::test_run_workflow_timeout_pauses_schedule_after_5_consecutive_failures" \
+ --snapshot-update --snapshot-warn-unused \
+ --splits ${{ matrix.concurrency }} --group ${{ matrix.group }} \
+ --durations=100 --durations-min=1.0 \
+ --splitting-algorithm=duration_based_chunks \
+ --reruns 2 --reruns-delay 1 \
+ -r fEsxX \
+ --junitxml=junit-temporal.xml
+ fi
exit_code=$?
set -e
if [ $exit_code -eq 5 ]; then
diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.yml
index 29027cb114b6..71b69492c768 100644
--- a/.github/workflows/ci-backend.yml
+++ b/.github/workflows/ci-backend.yml
@@ -13,8 +13,10 @@ on:
description: ClickHouse server version. Leave blank for default
type: string
pull_request:
- # Heavy test matrices (django, turbo-tests) skip drafts; ready_for_review
- # re-triggers them when a PR leaves draft. To force them on a draft, add the
+ # Draft PRs run the snob-selected Django subset (≤3 shards) for fast feedback;
+ # turbo-tests (product tests) still skip drafts. Ready PRs run the full
+ # matrices — that full run is the merge gate, and ready_for_review re-triggers
+ # it when a PR leaves draft. To force the full matrices on a draft, add the
# `run-ci-backend` label — labeled/unlabeled re-trigger the run so the matrices
# start without needing a new push. Cheap checks still run on drafts.
types: [opened, synchronize, reopened, ready_for_review, labeled, unlabeled]
@@ -440,6 +442,168 @@ jobs:
echo "run_legacy=$(echo "$RESULT" | jq -r '.run_legacy')" >> $GITHUB_OUTPUT
echo "django_shards=$(echo "$RESULT" | jq -c '.django_shards // empty')" >> $GITHUB_OUTPUT
+ # Pick which Django tests to run on draft PRs. Drafts get the snob-selected
+ # subset for fast feedback; the full matrix runs once the PR is marked ready
+ # for review, and that ready run is the merge gate. When selection can't be
+ # trusted on a draft (legacy graph impact, turbo-discover or selector failure,
+ # a selector full-run signal), the draft skips the heavy matrices entirely —
+ # the pre-selection draft behavior — and defers to the ready full run.
+ select-tests:
+ name: Select tests
+ needs: [changes, turbo-discover]
+ # Only draft PRs do selective runs; ready PRs and non-PR events (push,
+ # merge_group) always run full, which build_django_matrix falls back to
+ # when select-tests is skipped (empty MODE). The run-ci-backend label
+ # forces the full matrices on a draft.
+ if: |
+ github.event_name == 'pull_request' &&
+ github.event.pull_request.draft == true &&
+ !contains(github.event.pull_request.labels.*.name, 'run-ci-backend') &&
+ needs.changes.outputs.backend == 'true'
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ outputs:
+ mode: ${{ steps.classify.outputs.mode }}
+ core_files: ${{ steps.classify.outputs.core_files }}
+ poe_files: ${{ steps.classify.outputs.poe_files }}
+ temporal_files: ${{ steps.classify.outputs.temporal_files }}
+ run_poe: ${{ steps.classify.outputs.run_poe }}
+ run_temporal: ${{ steps.classify.outputs.run_temporal }}
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ with:
+ fetch-depth: 1000
+ filter: blob:none
+
+ - name: Install uv
+ uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0
+ with:
+ version: '0.11.14'
+
+ - name: Decide whether selection can be trusted
+ id: fallback
+ env:
+ RUN_LEGACY: ${{ needs.turbo-discover.outputs.run_legacy }}
+ TURBO_RESULT: ${{ needs.turbo-discover.result }}
+ shell: bash
+ run: |
+ set -euo pipefail
+ skip=false
+ if [[ "$RUN_LEGACY" == "true" ]]; then
+ # turbo-discover detected product->legacy graph impact; the
+ # diff-based selector can't see this, so its subset would be
+ # incomplete. Skip the draft matrices; the ready run is full.
+ skip=true
+ elif [[ "$TURBO_RESULT" != "success" && "$TURBO_RESULT" != "skipped" ]]; then
+ # Conservative — turbo-discover failed.
+ skip=true
+ fi
+ echo "skip=$skip" >> "$GITHUB_OUTPUT"
+
+ - name: Run shadow selector
+ id: select
+ # continue-on-error so a selector or git fetch failure doesn't fail this
+ # job — a failed select-tests would leave MODE empty and build_django_matrix
+ # would fall back to an expensive full matrix on a draft. Classify reads
+ # steps.select.outcome (pre-continue-on-error) and emits mode=skip instead.
+ continue-on-error: true
+ if: steps.fallback.outputs.skip == 'false'
+ env:
+ BASE_REF: ${{ github.event.pull_request.base.ref }}
+ shell: bash
+ run: |
+ set -euo pipefail
+ git fetch --no-tags --depth=1000 --filter=blob:none origin "$BASE_REF:refs/remotes/origin/$BASE_REF"
+ uv run tools/snob_backend_test_selection_shadow.py \
+ --base-ref "origin/$BASE_REF" \
+ > /tmp/selection.json
+
+ - name: Classify selection into segments
+ id: classify
+ env:
+ FALLBACK_SKIP: ${{ steps.fallback.outputs.skip }}
+ SELECT_OUTCOME: ${{ steps.select.outcome }}
+ shell: bash
+ run: |
+ set -euo pipefail
+ # Untrusted selection on a draft skips the heavy matrices (the
+ # pre-selection draft behavior); the ready-for-review run is full.
+ fall_back_to_skip() {
+ echo "mode=skip" >> "$GITHUB_OUTPUT"
+ echo "core_files=" >> "$GITHUB_OUTPUT"
+ echo "poe_files=" >> "$GITHUB_OUTPUT"
+ echo "temporal_files=" >> "$GITHUB_OUTPUT"
+ echo "run_poe=false" >> "$GITHUB_OUTPUT"
+ echo "run_temporal=false" >> "$GITHUB_OUTPUT"
+ }
+
+ if [[ "$FALLBACK_SKIP" == "true" ]]; then
+ fall_back_to_skip
+ exit 0
+ fi
+
+ if [[ "$SELECT_OUTCOME" != "success" ]] || [[ ! -s /tmp/selection.json ]]; then
+ echo "::warning::shadow selector did not produce output; draft skips heavy matrices (full run happens on ready for review)"
+ fall_back_to_skip
+ exit 0
+ fi
+
+ full_run_reasons=$(jq -r '.ast.full_run_reasons | length' /tmp/selection.json)
+ if [[ "$full_run_reasons" -gt 0 ]]; then
+ echo "Selector requested a full run; draft defers it to ready for review:"
+ jq -r '.ast.full_run_reasons[]' /tmp/selection.json
+ fall_back_to_skip
+ exit 0
+ fi
+
+ # Partition selected files by the Django segment that owns them.
+ # Mirrors the positional path arguments in the Run Core / Run Temporal pytest invocations:
+ # Core (POE off): posthog ee/ (minus posthog/temporal, posthog/dags)
+ # Core POE on: posthog/clickhouse, posthog/queries, posthog/api/test/test_insight*,
+ # posthog/api/test/dashboards/test_dashboard.py, ee/clickhouse/
+ # Temporal: posthog/temporal, products/{batch_exports,tasks}/backend/temporal
+ # Files outside posthog/ and ee/ (e.g. products/foo/backend/test_*) are not in this
+ # matrix — turbo-tests handles them.
+ core=()
+ poe=()
+ temporal=()
+ while IFS= read -r f; do
+ [[ -z "$f" ]] && continue
+ case "$f" in
+ posthog/temporal/*|products/batch_exports/backend/tests/temporal/*|products/tasks/backend/temporal/*)
+ temporal+=("$f")
+ ;;
+ posthog/clickhouse/*|posthog/queries/*|ee/clickhouse/*|products/product_analytics/backend/api/test/*|posthog/api/test/test_insight*|posthog/api/test/dashboards/test_dashboard.py)
+ poe+=("$f")
+ core+=("$f")
+ ;;
+ posthog/dags/*|common/hogvm/python/test/*)
+ # Explicitly --ignore'd by the Core invocation; nothing to do.
+ ;;
+ posthog/*|ee/*)
+ core+=("$f")
+ ;;
+ esac
+ done < <(jq -r '.combined.tests[]?' /tmp/selection.json)
+
+ echo "mode=selected" >> "$GITHUB_OUTPUT"
+ echo "core_files=${core[*]:-}" >> "$GITHUB_OUTPUT"
+ echo "poe_files=${poe[*]:-}" >> "$GITHUB_OUTPUT"
+ echo "temporal_files=${temporal[*]:-}" >> "$GITHUB_OUTPUT"
+ echo "run_poe=$([[ ${#poe[@]} -gt 0 ]] && echo true || echo false)" >> "$GITHUB_OUTPUT"
+ echo "run_temporal=$([[ ${#temporal[@]} -gt 0 ]] && echo true || echo false)" >> "$GITHUB_OUTPUT"
+
+ echo "Selected: ${#core[@]} core, ${#poe[@]} POE-eligible, ${#temporal[@]} temporal"
+
+ - name: Upload selection artifact
+ if: always() && steps.select.outcome == 'success'
+ uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
+ with:
+ name: select-tests-output
+ path: /tmp/selection.json
+ if-no-files-found: ignore
+ retention-days: 14
+
# 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
@@ -768,7 +932,7 @@ jobs:
token: ${{ steps.app-token.outputs.token || github.token }}
- name: Install uv
- uses: astral-sh/setup-uv@eac588ad8def6316056a12d4907a9d4d84ff7a3b # v7.3.0
+ uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0
with:
version: '0.11.14'
@@ -1478,7 +1642,7 @@ jobs:
- name: Install uv
id: setup-uv
- uses: astral-sh/setup-uv@eac588ad8def6316056a12d4907a9d4d84ff7a3b # v7.3.0
+ uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0
with:
version: '0.11.14' # pinned: unpinned setup-uv calls GH API on every job, exhausts rate limit
enable-cache: true
@@ -1642,7 +1806,7 @@ jobs:
build_django_matrix:
name: Build Django matrix
- needs: [changes, get_clickhouse_versions, turbo-discover]
+ needs: [changes, get_clickhouse_versions, turbo-discover, select-tests]
if: |
always() &&
needs.changes.outputs.backend == 'true' &&
@@ -1658,75 +1822,136 @@ jobs:
OLDEST_SUPPORTED_IMAGE: ${{ needs.get_clickhouse_versions.outputs.oldest_supported_image }}
COMPAT_MATRIX_JSON: ${{ needs.get_clickhouse_versions.outputs.compat_matrix }}
DJANGO_SHARDS_JSON: ${{ needs.turbo-discover.outputs.django_shards }}
+ MODE: ${{ needs.select-tests.outputs.mode }}
+ RUN_POE: ${{ needs.select-tests.outputs.run_poe }}
+ RUN_TEMPORAL: ${{ needs.select-tests.outputs.run_temporal }}
+ CORE_FILES: ${{ needs.select-tests.outputs.core_files }}
DATA_IMPORT_SOURCES_ONLY: ${{ needs.changes.outputs.data_import_sources_only }}
run: |
- # Auto-shard counts from turbo-discover (Amdahl's law on .test_durations).
- # Falls back to hardcoded defaults if turbo-discover failed or data is missing.
- CORE_SHARDS=38
- CORE_POE_SHARDS=7
- TEMPORAL_SHARDS=7
- if [ -n "$DJANGO_SHARDS_JSON" ] && echo "$DJANGO_SHARDS_JSON" | jq -e '.Core.shards' > /dev/null 2>&1; then
- CORE_SHARDS=$(echo "$DJANGO_SHARDS_JSON" | jq -r '.Core.shards')
- CORE_POE_SHARDS=$(echo "$DJANGO_SHARDS_JSON" | jq -r '.CorePOE.shards')
- TEMPORAL_SHARDS=$(echo "$DJANGO_SHARDS_JSON" | jq -r '.Temporal.shards')
- echo "Auto-sharding: Core=$CORE_SHARDS, CorePOE=$CORE_POE_SHARDS, Temporal=$TEMPORAL_SHARDS"
- else
- echo "::warning::Django shard auto-sizing unavailable, using defaults: Core=$CORE_SHARDS, CorePOE=$CORE_POE_SHARDS, Temporal=$TEMPORAL_SHARDS"
+ # :NOTE: Keep shard counts/group ranges in sync with historical Django matrix tuning.
+ # Consult #team-devex before changing.
+ if [[ "$MODE" == "skip" ]]; then
+ # Draft PR where selection couldn't be trusted: skip the heavy
+ # matrices and defer to the full run on ready for review.
+ echo "include=[]" >> "$GITHUB_OUTPUT"
+ echo "Django matrix size: 0 (mode=skip)"
+ exit 0
fi
+ if [[ "$MODE" == "selected" ]]; then
+ # Selected mode: collapse to one shard per active segment, skip
+ # segments with no selected files, drop compat entirely.
+ core_count=0
+ [[ -n "$CORE_FILES" ]] && core_count=1
+ core=$(jq -cn --arg image "$OLDEST_SUPPORTED_IMAGE" --argjson n "$core_count" '
+ [range(1; $n + 1) | {
+ segment: "Core",
+ "person-on-events": false,
+ "python-version": "3.13.13",
+ "clickhouse-server-image": $image,
+ concurrency: 1,
+ group: 1,
+ artifact_key: "core-1",
+ compat: false
+ }]
+ ')
+ poe_count=0
+ [[ "$RUN_POE" == "true" ]] && poe_count=1
+ core_persons_on_events=$(jq -cn --arg image "$OLDEST_SUPPORTED_IMAGE" --argjson n "$poe_count" '
+ [range(1; $n + 1) | {
+ segment: "Core",
+ "person-on-events": true,
+ "python-version": "3.13.13",
+ "clickhouse-server-image": $image,
+ concurrency: 1,
+ group: 1,
+ artifact_key: "core-poe-1",
+ compat: false
+ }]
+ ')
+ temporal_count=0
+ [[ "$RUN_TEMPORAL" == "true" ]] && temporal_count=1
+ temporal=$(jq -cn --arg image "$OLDEST_SUPPORTED_IMAGE" --argjson n "$temporal_count" '
+ [range(1; $n + 1) | {
+ segment: "Temporal",
+ "person-on-events": false,
+ "python-version": "3.13.13",
+ "clickhouse-server-image": $image,
+ concurrency: 1,
+ group: 1,
+ artifact_key: "temporal-1",
+ compat: false
+ }]
+ ')
+ compat="[]"
+ else
+ # Full run: auto-shard counts from turbo-discover (Amdahl's law on .test_durations).
+ # Falls back to hardcoded defaults if turbo-discover failed or data is missing.
+ CORE_SHARDS=38
+ CORE_POE_SHARDS=7
+ TEMPORAL_SHARDS=7
+ if [ -n "$DJANGO_SHARDS_JSON" ] && echo "$DJANGO_SHARDS_JSON" | jq -e '.Core.shards' > /dev/null 2>&1; then
+ CORE_SHARDS=$(echo "$DJANGO_SHARDS_JSON" | jq -r '.Core.shards')
+ CORE_POE_SHARDS=$(echo "$DJANGO_SHARDS_JSON" | jq -r '.CorePOE.shards')
+ TEMPORAL_SHARDS=$(echo "$DJANGO_SHARDS_JSON" | jq -r '.Temporal.shards')
+ echo "Auto-sharding: Core=$CORE_SHARDS, CorePOE=$CORE_POE_SHARDS, Temporal=$TEMPORAL_SHARDS"
+ else
+ echo "::warning::Django shard auto-sizing unavailable, using defaults: Core=$CORE_SHARDS, CorePOE=$CORE_POE_SHARDS, Temporal=$TEMPORAL_SHARDS"
+ fi
- core=$(jq -cn --arg image "$OLDEST_SUPPORTED_IMAGE" --argjson shards "$CORE_SHARDS" '
- [range(1; $shards + 1) | {
- segment: "Core",
- "person-on-events": false,
- "python-version": "3.13.13",
- "clickhouse-server-image": $image,
- concurrency: $shards,
- group: .,
- artifact_key: ("core-" + (.|tostring)),
- compat: false
- }]
- ')
-
- core_persons_on_events=$(jq -cn --arg image "$OLDEST_SUPPORTED_IMAGE" --argjson shards "$CORE_POE_SHARDS" '
- [range(1; $shards + 1) | {
- segment: "Core",
- "person-on-events": true,
- "python-version": "3.13.13",
- "clickhouse-server-image": $image,
- concurrency: $shards,
- group: .,
- artifact_key: ("core-poe-" + (.|tostring)),
- compat: false
- }]
- ')
-
- temporal=$(jq -cn --arg image "$OLDEST_SUPPORTED_IMAGE" --argjson shards "$TEMPORAL_SHARDS" '
- [range(1; $shards + 1) | {
- segment: "Temporal",
- "person-on-events": false,
- "python-version": "3.13.13",
- "clickhouse-server-image": $image,
- concurrency: $shards,
- group: .,
- artifact_key: ("temporal-" + (.|tostring)),
- compat: false
- }]
- ')
-
- compat_source="${COMPAT_MATRIX_JSON:-[]}"
- compat=$(jq -cn --argjson compat "$compat_source" '
- [
- $compat
- | to_entries[]
- | .value + {
+ core=$(jq -cn --arg image "$OLDEST_SUPPORTED_IMAGE" --argjson shards "$CORE_SHARDS" '
+ [range(1; $shards + 1) | {
+ segment: "Core",
+ "person-on-events": false,
+ "python-version": "3.13.13",
+ "clickhouse-server-image": $image,
+ concurrency: $shards,
+ group: .,
+ artifact_key: ("core-" + (.|tostring)),
+ compat: false
+ }]
+ ')
+
+ core_persons_on_events=$(jq -cn --arg image "$OLDEST_SUPPORTED_IMAGE" --argjson shards "$CORE_POE_SHARDS" '
+ [range(1; $shards + 1) | {
segment: "Core",
+ "person-on-events": true,
+ "python-version": "3.13.13",
+ "clickhouse-server-image": $image,
+ concurrency: $shards,
+ group: .,
+ artifact_key: ("core-poe-" + (.|tostring)),
+ compat: false
+ }]
+ ')
+
+ temporal=$(jq -cn --arg image "$OLDEST_SUPPORTED_IMAGE" --argjson shards "$TEMPORAL_SHARDS" '
+ [range(1; $shards + 1) | {
+ segment: "Temporal",
"person-on-events": false,
"python-version": "3.13.13",
- compat: true,
- artifact_key: ("compat-" + ((.key + 1)|tostring))
- }
- ]
- ')
+ "clickhouse-server-image": $image,
+ concurrency: $shards,
+ 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.13.13",
+ compat: true,
+ artifact_key: ("compat-" + ((.key + 1)|tostring))
+ }
+ ]
+ ')
+ fi
if [ "$DATA_IMPORT_SOURCES_ONLY" = "true" ]; then
# Only data warehouse import sources changed — the Temporal
@@ -1743,20 +1968,22 @@ jobs:
fi
echo "include=$include" >> "$GITHUB_OUTPUT"
- echo "Django matrix size: $(jq -r 'length' <<< "$include")"
+ echo "Django matrix size: $(jq -r 'length' <<< "$include") (mode=$MODE)"
django:
- needs: [changes, turbo-discover, detect-snapshot-mode, get_clickhouse_versions, build_django_matrix]
+ needs:
+ [changes, turbo-discover, detect-snapshot-mode, get_clickhouse_versions, build_django_matrix, select-tests]
# Run legacy pytest if:
# 1. Legacy code directly changed (ee/, posthog/)
# 2. OR product changes affect legacy code (turbo-discover outputs run_legacy=true)
# 3. OR turbo-discover itself failed (conservative: run Django on detection failure)
+ # The non-empty include guard covers drafts in skip mode and selected runs
+ # that chose zero files — an empty matrix would otherwise fail the job.
if: |
always() &&
- (github.event.pull_request.draft != true ||
- contains(github.event.pull_request.labels.*.name, 'run-ci-backend')) &&
needs.changes.outputs.backend == 'true' &&
needs.build_django_matrix.result == 'success' &&
+ needs.build_django_matrix.outputs.include != '[]' &&
(needs.changes.outputs.legacy == 'true' ||
needs.turbo-discover.outputs.run_legacy == 'true' ||
(needs.turbo-discover.result != 'success' && needs.turbo-discover.result != 'skipped'))
@@ -2024,6 +2251,9 @@ jobs:
if: ${{ needs.changes.outputs.backend == 'true' && matrix.segment == 'Core' }}
env:
PERSON_ON_EVENTS_V2_ENABLED: ${{ matrix.person-on-events && 'true' || 'false' }}
+ MODE: ${{ needs.select-tests.outputs.mode }}
+ CORE_FILES: ${{ needs.select-tests.outputs.core_files }}
+ POE_FILES: ${{ needs.select-tests.outputs.poe_files }}
# Wrap bash with signal-fanout so the runner's cancel signal is
# propagated to the entire process tree (incl. pytest). Without
# this, GHA only signals the top-level bash and pytest survives
@@ -2032,28 +2262,45 @@ jobs:
shell: 'signal-fanout bash --noprofile --norc -eo pipefail {0}'
run: | # async_migrations covered in ci-async-migrations.yml
set +e
- pytest -v --tb=short --reuse-db -o junit_duration_report=call ${{
- matrix.compat
- && env.CLICKHOUSE_COMPAT_PYTEST_TARGETS
- || (
- matrix.person-on-events
- && './posthog/clickhouse/ ./posthog/queries/ ./products/product_analytics/backend/api/test/ ./posthog/api/test/dashboards/test_dashboard.py'
- || 'posthog'
- )
- }} ${{ matrix.compat && '' || (matrix.person-on-events && 'ee/clickhouse/' || 'ee/') }} -m "not async_migrations" \
- --ignore=posthog/temporal \
- --ignore=posthog/dags \
- --ignore=common/hogvm/python/test \
- ${{ matrix.person-on-events && '--ignore=posthog/hogql_queries' || '' }} \
- ${{ matrix.person-on-events && '--ignore=posthog/hogql' || '' }} \
- --splits ${{ matrix.concurrency }} --group ${{ matrix.group }} \
- --durations=1000 --durations-min=1.0 --store-durations \
- --pytest-durations=100 \
- --splitting-algorithm=duration_based_chunks \
- --reruns 2 --reruns-delay 1 \
- -r fEsxX \
- --junitxml=junit-core.xml \
- $PYTEST_ARGS
+ if [[ "$MODE" == "selected" ]]; then
+ # Selected mode: run only the test files chosen by the snob shadow selector.
+ # No --splits/--group (no sharding), no --store-durations (don't pollute timing
+ # data with a partial run), no --reruns (selected runs should fail loud so flaky
+ # tests get fixed instead of masked; the ready-for-review full run has reruns).
+ if [[ "${{ matrix.person-on-events }}" == "true" ]]; then
+ targets="$POE_FILES"
+ else
+ targets="$CORE_FILES"
+ fi
+ # shellcheck disable=SC2086
+ pytest -v --tb=short --reuse-db -o junit_duration_report=call $targets -m "not async_migrations" \
+ -r fEsxX \
+ --junitxml=junit-core.xml \
+ $PYTEST_ARGS
+ else
+ pytest -v --tb=short --reuse-db -o junit_duration_report=call ${{
+ matrix.compat
+ && env.CLICKHOUSE_COMPAT_PYTEST_TARGETS
+ || (
+ matrix.person-on-events
+ && './posthog/clickhouse/ ./posthog/queries/ ./products/product_analytics/backend/api/test/ ./posthog/api/test/dashboards/test_dashboard.py'
+ || 'posthog'
+ )
+ }} ${{ matrix.compat && '' || (matrix.person-on-events && 'ee/clickhouse/' || 'ee/') }} -m "not async_migrations" \
+ --ignore=posthog/temporal \
+ --ignore=posthog/dags \
+ --ignore=common/hogvm/python/test \
+ ${{ matrix.person-on-events && '--ignore=posthog/hogql_queries' || '' }} \
+ ${{ matrix.person-on-events && '--ignore=posthog/hogql' || '' }} \
+ --splits ${{ matrix.concurrency }} --group ${{ matrix.group }} \
+ --durations=1000 --durations-min=1.0 --store-durations \
+ --pytest-durations=100 \
+ --splitting-algorithm=duration_based_chunks \
+ --reruns 2 --reruns-delay 1 \
+ -r fEsxX \
+ --junitxml=junit-core.xml \
+ $PYTEST_ARGS
+ fi
exit_code=$?
set -e
if [ $exit_code -eq 5 ]; then
@@ -2099,23 +2346,36 @@ jobs:
AWS_S3_ALLOW_UNSAFE_RENAME: 'true'
MODAL_TOKEN_ID: ${{ needs.changes.outputs.tasks_temporal == 'true' && secrets.MODAL_TOKEN_ID || '' }}
MODAL_TOKEN_SECRET: ${{ needs.changes.outputs.tasks_temporal == 'true' && secrets.MODAL_TOKEN_SECRET || '' }}
+ MODE: ${{ needs.select-tests.outputs.mode }}
+ TEMPORAL_FILES: ${{ needs.select-tests.outputs.temporal_files }}
run: |
set +e
- # No per-test pytest --timeout; rely on the job-level timeout-minutes
- # as the single safety net. The per-test guillotine added nothing
- # over it (--timeout-method=thread os._exit()s the whole process
- # anyway, so the shard dies either way) and was the reason the
- # transaction=True overhead in async tests looked like "the
- # timeout problem" instead of a per-test cost worth fixing.
- pytest -v --tb=short --reuse-db -o junit_duration_report=call posthog/temporal products/batch_exports/backend/tests/temporal products/tasks/backend/temporal -m "not async_migrations" \
- --splits ${{ matrix.concurrency }} --group ${{ matrix.group }} \
- --durations=100 --durations-min=1.0 --store-durations \
- --pytest-durations=100 \
- --splitting-algorithm=duration_based_chunks \
- --reruns 2 --reruns-delay 1 \
- -r fEsxX \
- --junitxml=junit-temporal.xml \
- $PYTEST_ARGS
+ if [[ "$MODE" == "selected" ]]; then
+ # Selected mode: no sharding, no --store-durations (don't pollute
+ # timing data with a partial run), no --reruns (fail loud; the ready
+ # full run still reruns). See the core selected branch for the rationale.
+ # shellcheck disable=SC2086
+ pytest -v --tb=short --reuse-db -o junit_duration_report=call $TEMPORAL_FILES -m "not async_migrations" \
+ -r fEsxX \
+ --junitxml=junit-temporal.xml \
+ $PYTEST_ARGS
+ else
+ # No per-test pytest --timeout; rely on the job-level timeout-minutes
+ # as the single safety net. The per-test guillotine added nothing
+ # over it (--timeout-method=thread os._exit()s the whole process
+ # anyway, so the shard dies either way) and was the reason the
+ # transaction=True overhead in async tests looked like "the
+ # timeout problem" instead of a per-test cost worth fixing.
+ pytest -v --tb=short --reuse-db -o junit_duration_report=call posthog/temporal products/batch_exports/backend/tests/temporal products/tasks/backend/temporal -m "not async_migrations" \
+ --splits ${{ matrix.concurrency }} --group ${{ matrix.group }} \
+ --durations=100 --durations-min=1.0 --store-durations \
+ --pytest-durations=100 \
+ --splitting-algorithm=duration_based_chunks \
+ --reruns 2 --reruns-delay 1 \
+ -r fEsxX \
+ --junitxml=junit-temporal.xml \
+ $PYTEST_ARGS
+ fi
exit_code=$?
set -e
if [ $exit_code -eq 5 ]; then
@@ -2398,7 +2658,7 @@ jobs:
echo "All backend and product checks passed."
test-selection-verdict:
- needs: [django, turbo-tests, changes]
+ needs: [django, turbo-tests, changes, select-tests]
name: Test selection verdict
if: always() && github.event_name == 'pull_request'
runs-on: ubuntu-latest
@@ -2423,6 +2683,18 @@ jobs:
path: /tmp/junit-results/
continue-on-error: true
+ # Reuse the selection artifact from the select-tests job rather than
+ # re-running the snob script. Falls through if the artifact wasn't
+ # produced (select-tests forced full mode or failed) — the next step
+ # regenerates it so we still get a shadow verdict for those PRs.
+ - name: Download selection artifact
+ id: download-selection
+ continue-on-error: true
+ uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0
+ with:
+ name: select-tests-output
+ path: /tmp/verdict/
+
- name: Run test selection and verdict
env:
BASE_REF: ${{ github.event.pull_request.base.ref }}
@@ -2433,16 +2705,18 @@ jobs:
set -euo pipefail
mkdir -p /tmp/verdict
- # Fetch the *current* tip of the base branch, not pull_request.base.sha:
- # base.sha is captured at webhook time and goes stale if the branch
- # later merges a newer master, which makes `base.sha...HEAD` balloon
- # to include every merged-in master change.
- git fetch --no-tags --depth=1000 --filter=blob:none origin "$BASE_REF:refs/remotes/origin/$BASE_REF"
-
- uv run tools/snob_backend_test_selection_shadow.py \
- --base-ref "origin/$BASE_REF" \
- --pretty \
- > /tmp/verdict/selection.json
+ if [[ ! -s /tmp/verdict/selection.json ]]; then
+ # Fetch the *current* tip of the base branch, not pull_request.base.sha:
+ # base.sha is captured at webhook time and goes stale if the branch
+ # later merges a newer master, which makes `base.sha...HEAD` balloon
+ # to include every merged-in master change.
+ git fetch --no-tags --depth=1000 --filter=blob:none origin "$BASE_REF:refs/remotes/origin/$BASE_REF"
+
+ uv run tools/snob_backend_test_selection_shadow.py \
+ --base-ref "origin/$BASE_REF" \
+ --pretty \
+ > /tmp/verdict/selection.json
+ fi
uv run tools/test_selection_verdict.py \
/tmp/verdict/selection.json \
diff --git a/.github/workflows/ci-frontend.yml b/.github/workflows/ci-frontend.yml
index 49267a03931b..1353b9d942ed 100644
--- a/.github/workflows/ci-frontend.yml
+++ b/.github/workflows/ci-frontend.yml
@@ -1,6 +1,12 @@
name: Frontend CI
on:
pull_request:
+ # Draft PRs run a narrowed jest selection; ready PRs run the full matrix
+ # (the merge gate). ready_for_review re-triggers the full run on the
+ # current head when a PR leaves draft. To force the full matrix on a
+ # draft, add the `run-ci-frontend` label — labeled/unlabeled re-trigger
+ # the run so it starts without needing a new push.
+ types: [opened, synchronize, reopened, ready_for_review, labeled, unlabeled]
merge_group:
push:
branches:
@@ -100,6 +106,125 @@ jobs:
- webpack.config.js
- stylelint*
+ # Pick which jest tests to run on draft PRs by passing changed files to
+ # `jest --findRelatedTests` (jest's resolver walks the import graph for us).
+ # Skipped on ready PRs, master push, and merge_group; the jest job falls back
+ # to its full FOSS×EE × chunk matrix in those cases. The ready-for-review
+ # full run is the merge gate. The run-ci-frontend label forces the full
+ # matrix on a draft. When selection can't be trusted on a draft (config
+ # change, oversized diff, selector failure), the draft skips jest entirely
+ # and defers to the ready full run.
+ select-jest-tests:
+ name: Select jest tests
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ needs: changes
+ if: |
+ always() && needs.changes.outputs.frontend_code == 'true'
+ && github.event_name == 'pull_request'
+ && github.event.pull_request.draft == true
+ && !contains(github.event.pull_request.labels.*.name, 'run-ci-frontend')
+ outputs:
+ mode: ${{ steps.classify.outputs.mode }}
+ matrix: ${{ steps.classify.outputs.matrix }}
+ should_run: ${{ steps.classify.outputs.should_run }}
+ changed_files: ${{ steps.classify.outputs.changed_files }}
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ with:
+ fetch-depth: 1000
+ filter: blob:none
+
+ - name: Compute changed files
+ id: diff
+ continue-on-error: true
+ env:
+ BASE_REF: ${{ github.event.pull_request.base.ref }}
+ run: |
+ set -euo pipefail
+ git fetch --no-tags --depth=1000 --filter=blob:none origin "$BASE_REF:refs/remotes/origin/$BASE_REF"
+ # `...` resolves against the merge-base so files merged in from base
+ # don't inflate the diff (mirrors find-affected-stories / snob).
+ git diff --name-only "origin/$BASE_REF...HEAD" > /tmp/changed.txt
+ wc -l < /tmp/changed.txt
+
+ - name: Build narrowed matrix
+ id: classify
+ env:
+ DIFF_OUTCOME: ${{ steps.diff.outcome }}
+ run: |
+ set -euo pipefail
+
+ # Untrusted selection on a draft skips jest entirely (should_run=false
+ # gates the jest job off); the ready-for-review full run is the gate.
+ # Use this whenever the selector can't reason about the diff — a
+ # narrowed run it can't vouch for would be false confidence, and a
+ # full run on every draft push is the spend this selection avoids.
+ # The run-ci-frontend label forces the full matrix on a draft.
+ fall_back_to_skip() {
+ echo "mode=skip" >> "$GITHUB_OUTPUT"
+ echo 'matrix={"include":[]}' >> "$GITHUB_OUTPUT"
+ echo "should_run=false" >> "$GITHUB_OUTPUT"
+ echo "changed_files=" >> "$GITHUB_OUTPUT"
+ }
+
+ if [[ "$DIFF_OUTCOME" != "success" ]] || [[ ! -s /tmp/changed.txt ]]; then
+ echo "::warning::could not derive changed files; draft skips jest (full run happens on ready for review)"
+ fall_back_to_skip
+ exit 0
+ fi
+
+ changed_count=$(wc -l < /tmp/changed.txt)
+ if [[ "$changed_count" -gt 200 ]]; then
+ echo "::notice::diff has $changed_count files (>200); draft skips jest (full run happens on ready for review)"
+ fall_back_to_skip
+ exit 0
+ fi
+
+ # Skip when jest config / build / lock files change — these
+ # invalidate jest's resolver, transformer cache, or test discovery
+ # in ways `--findRelatedTests` can't see, so no narrowed run can be
+ # trusted. Pattern matches mirror the frontend_code paths-filter
+ # in `changes`.
+ while IFS= read -r f; do
+ case "$f" in
+ jest.*.ts|babel.config.js|tsconfig.json|tsconfig.*.json|\
+ package.json|pnpm-lock.yaml|webpack.config.js|\
+ .github/workflows/ci-frontend.yml|.nvmrc)
+ echo "::notice::config change ($f); draft skips jest (full run happens on ready for review)"
+ fall_back_to_skip
+ exit 0
+ ;;
+ esac
+ done < /tmp/changed.txt
+
+ # Filter the diff to source files jest can resolve. Any code under
+ # frontend/, products/, common/, ee/frontend/ — anything else (docs,
+ # workflows, backend) doesn't reach the jest module graph.
+ CHANGED_FILES=$(grep -E '^(frontend/|products/|common/|ee/frontend/)' /tmp/changed.txt | grep -E '\.(ts|tsx|js|jsx|mjs|cjs)$' | tr '\n' ' ' | sed 's/ $//')
+
+ if [[ -z "$CHANGED_FILES" ]]; then
+ # No frontend source changes (e.g. PR only edits backend or docs)
+ # but `frontend_code` paths-filter still flagged the PR. Skip jest.
+ echo "mode=selective" >> "$GITHUB_OUTPUT"
+ echo 'matrix={"include":[]}' >> "$GITHUB_OUTPUT"
+ echo "should_run=false" >> "$GITHUB_OUTPUT"
+ echo "changed_files=" >> "$GITHUB_OUTPUT"
+ echo "Selective mode: no frontend source files changed, skipping jest"
+ exit 0
+ fi
+
+ # Selective mode: single EE-tree job, no chunk sharding. The FOSS
+ # structural check (ee/ removed) only matters when ee imports are
+ # touched; defer that to the ready-for-review full run. --findRelatedTests
+ # walks jest's import graph from these files and runs the matching
+ # *.test.* files.
+ echo "mode=selective" >> "$GITHUB_OUTPUT"
+ echo 'matrix={"include":[{"segment":"EE","chunk":1}]}' >> "$GITHUB_OUTPUT"
+ echo "should_run=true" >> "$GITHUB_OUTPUT"
+ echo "changed_files=$CHANGED_FILES" >> "$GITHUB_OUTPUT"
+ echo "Selective mode: $(echo "$CHANGED_FILES" | wc -w) frontend source files"
+
frontend-format:
name: Frontend formatting
needs: changes
@@ -394,16 +519,20 @@ jobs:
jest:
runs-on: ubuntu-latest
timeout-minutes: 15
- needs: changes
- if: needs.changes.outputs.frontend_code == 'true'
+ needs: [changes, select-jest-tests]
+ if: |
+ always() && needs.changes.outputs.frontend_code == 'true'
+ && needs.select-jest-tests.outputs.should_run != 'false'
name: Jest test (${{ matrix.segment }} - ${{ matrix.chunk }})
-
strategy:
# If one test fails, still run the others
fail-fast: false
- matrix:
- segment: ['FOSS', 'EE']
- chunk: [1, 2]
+ # On draft PRs, select-jest-tests may narrow this to a single EE job
+ # running only the tests reachable from changed frontend source files,
+ # or skip jest entirely (should_run=false) when selection can't be
+ # trusted. On ready PRs, master push, and merge_group it's skipped, so
+ # we fall back to the full FOSS×EE × chunk fanout (the merge gate).
+ matrix: ${{ fromJson(needs.select-jest-tests.outputs.matrix || '{"segment":["FOSS","EE"],"chunk":[1,2]}') }}
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
@@ -443,11 +572,26 @@ jobs:
key: node-cache-${{ runner.os }}-${{ runner.arch }}-pnpm-${{ hashFiles('pnpm-lock.yaml') }}
- name: Test with Jest
- run: bin/turbo run test --filter=@posthog/frontend -- --maxWorkers=2
env:
NODE_OPTIONS: --max-old-space-size=16384
SHARD_INDEX: ${{ matrix.chunk }}
SHARD_COUNT: 2
+ MODE: ${{ needs.select-jest-tests.outputs.mode }}
+ CHANGED_FILES: ${{ needs.select-jest-tests.outputs.changed_files }}
+ run: |
+ if [ "$MODE" = "selective" ]; then
+ # --findRelatedTests walks jest's import graph from the changed
+ # source files and runs the matching tests. No --shard: single
+ # job runs the entire selected set.
+ pnpm --filter=@posthog/frontend build:products
+ # shellcheck disable=SC2086
+ pnpm --filter=@posthog/frontend exec jest \
+ --testPathPattern='(frontend/|products/|common/)' \
+ --forceExit \
+ --findRelatedTests $CHANGED_FILES
+ else
+ bin/turbo run test --filter=@posthog/frontend -- --maxWorkers=2
+ fi
calculate-running-time:
name: Calculate running time
diff --git a/.github/workflows/ci-mcp.yml b/.github/workflows/ci-mcp.yml
index b4e10c35239b..d4bb53424e94 100644
--- a/.github/workflows/ci-mcp.yml
+++ b/.github/workflows/ci-mcp.yml
@@ -473,6 +473,24 @@ jobs:
mkdir -p .postgres-backups
mv schema.sql.gz .postgres-backups/schema-latest.sql.gz
./bin/hogli db:restore-test-db
+ # The dump is produced by ci-backend.yml, where TEST=1 activates
+ # ProductDBRouter and routes the apps in products/db_routing.yaml to
+ # separate databases: their tables are absent from the dump, but
+ # django_migrations still records their migrations as applied. This job
+ # configures no product DBs, so those apps live on the default DB —
+ # drop their migration records so migrate below replays them from 0001
+ # and actually creates the tables.
+ APPS=$(python - <<'EOF'
+ import yaml
+ with open("products/db_routing.yaml") as f:
+ routes = yaml.safe_load(f)["routes"]
+ print(",".join(sorted({"'%s'" % r["app_label"] for r in routes})))
+ EOF
+ )
+ if [ -n "$APPS" ]; then
+ docker compose -f docker-compose.dev.yml exec -T db psql -U posthog posthog \
+ -c "DELETE FROM django_migrations WHERE app IN ($APPS);"
+ fi
- name: Run migrations
run: |
diff --git a/.github/workflows/ci-storybook.yml b/.github/workflows/ci-storybook.yml
index f43c72237514..80e57421c882 100644
--- a/.github/workflows/ci-storybook.yml
+++ b/.github/workflows/ci-storybook.yml
@@ -1,6 +1,12 @@
name: Storybook
on:
pull_request:
+ # Draft PRs run a narrowed visual-regression matrix (affected stories only);
+ # ready PRs run the full chromium matrix (the merge gate). ready_for_review
+ # re-triggers the full run on the current head when a PR leaves draft. To
+ # force the full matrix on a draft, add the `run-ci-frontend` label —
+ # labeled/unlabeled re-trigger the run so it starts without needing a push.
+ types: [opened, synchronize, reopened, ready_for_review, labeled, unlabeled]
merge_group:
push:
branches:
@@ -155,9 +161,9 @@ jobs:
path: common/storybook/dist
retention-days: 1
- # Consumed by the shadow-story-selection job below. Uploaded
- # separately so the 20-shard visual-regression matrix doesn't pay
- # to download it.
+ # Consumed by the select-stories job below. Uploaded separately so
+ # the visual-regression matrix doesn't pay to download it on every
+ # shard.
- name: Upload module-graph artifact
if: always()
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
@@ -171,20 +177,43 @@ jobs:
name: Create Visual Review run
runs-on: ubuntu-latest
timeout-minutes: 5
- needs: [changes, build-storybook]
- if: needs.changes.outputs.frontend == 'true' && (github.event.pull_request.head.repo.full_name == github.repository || github.event_name == 'push')
+ needs: [changes, build-storybook, select-stories]
+ # always() so vr-setup still runs when select-stories is skipped (ready PRs,
+ # master push, merge_group). Without it, GitHub treats a skipped need as a
+ # skip-cascade and vr-setup wouldn't run when we still want it to.
+ if: |
+ always()
+ && needs.changes.outputs.frontend == 'true'
+ && needs.build-storybook.result == 'success'
+ && needs.select-stories.outputs.should_run != 'false'
+ && (github.event.pull_request.head.repo.full_name == github.repository || github.event_name == 'push')
outputs:
run_id: ${{ steps.create.outputs.run_id }}
steps:
+ # Head checkout supplies the PR's snapshot baseline; the VR CLI itself is
+ # built from the base branch below.
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
ref: ${{ github.event.pull_request.head.sha || github.sha }}
repository: ${{ github.event.pull_request.head.repo.full_name || github.repository }}
sparse-checkout: |
.nvmrc
+ frontend/snapshots.yml
+ sparse-checkout-cone-mode: false
+
+ # Build the VR CLI from the base branch, not the PR head. A workflow edit
+ # reaches every open PR immediately (it runs PR-merged-with-base), but a CLI
+ # change only lands on a branch once it rebases — so building from head can
+ # feed an old binary flags this workflow added (e.g. --partial), failing the
+ # run. Pinning to base.ref keeps the CLI in lockstep with the workflow. The
+ # tsconfig rootDir is the parent dir, so the generated types must come along.
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ with:
+ ref: ${{ github.event.pull_request.base.ref || github.sha }}
+ path: vr-cli
+ sparse-checkout: |
products/visual_review/cli
products/visual_review/frontend/generated/api.schemas.ts
- frontend/snapshots.yml
sparse-checkout-cone-mode: false
- name: Set up Node.js
@@ -194,7 +223,7 @@ jobs:
token: ${{ github.token }}
- name: Install VR CLI
- run: cd products/visual_review/cli && npm ci && npm run build && npm link
+ run: cd vr-cli/products/visual_review/cli && npm ci && npm run build && npm link
- name: Create VR run
id: create
@@ -206,9 +235,13 @@ jobs:
# PRs are gating ("review"); master pushes are tracking-only ("observe") since
# there's no PR to approve and we don't want master runs to block or prompt for approval.
VR_PURPOSE: ${{ github.event_name == 'push' && 'observe' || 'review' }}
+ # Selective storybook runs only render a subset of stories. Without --partial,
+ # VR would flag every untouched baseline identifier as removed.
+ VR_PARTIAL: ${{ needs.select-stories.outputs.mode == 'selective' && '--partial' || '' }}
# Recorded on the run so the VR UI can re-trigger this job via the GitHub API.
JOB_CHECK_RUN_ID: ${{ job.check_run_id }}
run: |
+ # shellcheck disable=SC2086
RUN_ID=$(vr run create \
--type storybook \
--baseline frontend/snapshots.yml \
@@ -216,17 +249,19 @@ jobs:
--commit "$VR_COMMIT" \
--pr "$VR_PR" \
--purpose "$VR_PURPOSE" \
- --token "$VR_TOKEN")
+ --token "$VR_TOKEN" \
+ $VR_PARTIAL)
echo "run_id=$RUN_ID" >> $GITHUB_OUTPUT
visual-regression:
name: Visual regression tests - ${{ matrix.browser }} (${{ matrix.shard }}/${{ matrix.shard_count }})
runs-on: ${{ matrix.browser == 'webkit' && 'depot-ubuntu-latest' || 'ubuntu-latest' }}
- needs: [changes, build-storybook, vr-setup]
+ needs: [changes, build-storybook, vr-setup, select-stories]
if: >-
always()
&& needs.changes.outputs.frontend == 'true'
&& needs.build-storybook.result == 'success'
+ && needs.select-stories.outputs.should_run != 'false'
timeout-minutes: 60
container:
image: ghcr.io/posthog/playwright:v1.60.0
@@ -234,10 +269,12 @@ jobs:
fail-fast: false
# Shard counts and worker config (maxWorkers in common/storybook/package.json)
# are tuned for runner CPU — consult #team-devex before changing.
- # Matrix is built dynamically in the `changes` job: chromium-only on PRs,
- # chromium + webkit on master pushes. Storybook CI is skipped entirely on
- # merge_group (the `changes` job gates on event_name != 'merge_group').
- matrix: ${{ fromJson(needs.changes.outputs.matrix) }}
+ # On draft PRs, select-stories may narrow the matrix to a single chromium
+ # shard running just the affected story files. On ready PRs and master push
+ # it's skipped, so we fall back to changes.outputs.matrix (ready PRs:
+ # full chromium; master push: chromium + webkit).
+ # Storybook CI is skipped entirely on merge_group (changes.if).
+ matrix: ${{ fromJson(needs.select-stories.outputs.matrix || needs.changes.outputs.matrix) }}
env:
NODE_OPTIONS: --max-old-space-size=16384
OPT_OUT_CAPTURE: 1
@@ -342,13 +379,33 @@ jobs:
env:
HOME: /root
STORYBOOK_SKIP_TAGS: 'test-skip,test-skip-${{ matrix.browser }}'
+ MODE: ${{ needs.select-stories.outputs.mode }}
+ AFFECTED_FILES: ${{ needs.select-stories.outputs.affected_files }}
run: |
- pnpm --filter=@posthog/storybook test:visual:ci:update --browsers ${{ matrix.browser }} --shard ${{ matrix.shard }}/${{ matrix.shard_count }}
+ if [ "$MODE" = "selective" ]; then
+ # test-storybook is jest-based; positional path args filter the run to
+ # only those story files. Single shard, so --shard 1/1 is a no-op.
+ # shellcheck disable=SC2086
+ pnpm --filter=@posthog/storybook test:visual:ci:update --browsers ${{ matrix.browser }} --shard ${{ matrix.shard }}/${{ matrix.shard_count }} -- $AFFECTED_FILES
+ else
+ pnpm --filter=@posthog/storybook test:visual:ci:update --browsers ${{ matrix.browser }} --shard ${{ matrix.shard }}/${{ matrix.shard_count }}
+ fi
+
+ # Upload snapshots to Visual Review (runs in parallel across shards).
+ # Build the CLI from the base branch (see vr-setup for the rationale).
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ if: always() && needs.vr-setup.outputs.run_id != ''
+ with:
+ ref: ${{ github.event.pull_request.base.ref || github.sha }}
+ path: vr-cli
+ sparse-checkout: |
+ products/visual_review/cli
+ products/visual_review/frontend/generated/api.schemas.ts
+ sparse-checkout-cone-mode: false
- # Upload snapshots to Visual Review (runs in parallel across shards)
- name: Install VR CLI
if: always() && needs.vr-setup.outputs.run_id != ''
- run: cd products/visual_review/cli && npm ci && npm run build && npm link
+ run: cd vr-cli/products/visual_review/cli && npm ci && npm run build && npm link
- name: Upload snapshots to Visual Review
if: always() && needs.vr-setup.outputs.run_id != ''
@@ -477,17 +534,36 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 15
needs: [visual-regression, vr-setup]
- if: needs.vr-setup.outputs.run_id != '' && needs.visual-regression.result == 'success'
+ # always() so the skipped select-stories job (transitively in the needs
+ # chain on ready PRs) doesn't skip-propagate past the always() jobs above
+ # and leave the VR run uncompleted with its commit status stuck pending.
+ # Legit skips still work: no-VR cases leave run_id empty, and a failed or
+ # cancelled matrix fails the result == 'success' check.
+ if: |
+ always()
+ && needs.vr-setup.outputs.run_id != ''
+ && needs.visual-regression.result == 'success'
steps:
+ # Head checkout supplies the PR's snapshot baseline; the VR CLI itself is
+ # built from the base branch below.
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
ref: ${{ github.event.pull_request.head.sha || github.sha }}
repository: ${{ github.event.pull_request.head.repo.full_name || github.repository }}
sparse-checkout: |
.nvmrc
+ frontend/snapshots.yml
+ sparse-checkout-cone-mode: false
+
+ # Build the VR CLI from the base branch, not the PR head (see vr-setup
+ # for the rationale).
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ with:
+ ref: ${{ github.event.pull_request.base.ref || github.sha }}
+ path: vr-cli
+ sparse-checkout: |
products/visual_review/cli
products/visual_review/frontend/generated/api.schemas.ts
- frontend/snapshots.yml
sparse-checkout-cone-mode: false
- name: Set up Node.js
@@ -497,7 +573,7 @@ jobs:
token: ${{ github.token }}
- name: Install VR CLI
- run: cd products/visual_review/cli && npm ci && npm run build && npm link
+ run: cd vr-cli/products/visual_review/cli && npm ci && npm run build && npm link
- name: Complete Visual Review run
# On master pushes the run was created with --purpose observe (tracking-only),
@@ -556,18 +632,29 @@ jobs:
status-job: 'Visual regression tests pass'
# Shadow measurement: reports which stories could have rendered differently
- # given the PR's changed files, using the webpack module graph emitted by
- # common/storybook/.storybook/main.ts's ModuleGraphPlugin. Does not gate
- # PRs and does not affect visual-regression selection. Data is used to
- # evaluate whether real test selection is worth pursuing.
- shadow-story-selection:
- name: Shadow story selection
+ # Pick the visual-regression matrix on draft PRs based on which stories the
+ # webpack module graph (emitted by ModuleGraphPlugin) says are affected
+ # by the diff. On ready PRs and master push this job is skipped and
+ # visual-regression falls back to needs.changes.outputs.matrix (the full
+ # suite). The ready-for-review full run is the merge gate — storybook
+ # already skips merge_group entirely (changes.if). The run-ci-frontend
+ # label forces the full matrix on a draft. When selection can't be trusted
+ # on a draft, visual-regression is skipped and deferred to the ready run.
+ select-stories:
+ name: Story selection
runs-on: ubuntu-latest
timeout-minutes: 5
needs: [changes, build-storybook]
if: |
always() && needs.changes.outputs.frontend == 'true'
&& github.event_name == 'pull_request'
+ && github.event.pull_request.draft == true
+ && !contains(github.event.pull_request.labels.*.name, 'run-ci-frontend')
+ outputs:
+ mode: ${{ steps.classify.outputs.mode }}
+ matrix: ${{ steps.classify.outputs.matrix }}
+ should_run: ${{ steps.classify.outputs.should_run }}
+ affected_files: ${{ steps.classify.outputs.affected_files }}
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
@@ -611,11 +698,63 @@ jobs:
COMPACT=$(node -e 'const d = JSON.parse(require("fs").readFileSync("/tmp/selection-result.json", "utf8")); delete d.affected_stories; delete d.unresolved_changed_files; process.stdout.write(JSON.stringify(d))')
echo "result=$COMPACT" >> "$GITHUB_OUTPUT"
+ - name: Build narrowed matrix
+ id: classify
+ env:
+ SELECT_OUTCOME: ${{ steps.selection.outcome }}
+ run: |
+ set -euo pipefail
+
+ # Untrusted selection on a draft skips visual-regression entirely
+ # (should_run=false gates vr-setup and the test matrix off); the
+ # ready-for-review full run is the gate. A skipped draft can't
+ # trade green-by-default for green-by-skipping: drafts can't
+ # merge, and ready re-runs the full suite. The run-ci-frontend
+ # label forces the full matrix on a draft.
+ fall_back_to_skip() {
+ echo "mode=skip" >> "$GITHUB_OUTPUT"
+ echo 'matrix={"include":[]}' >> "$GITHUB_OUTPUT"
+ echo "should_run=false" >> "$GITHUB_OUTPUT"
+ echo "affected_files=" >> "$GITHUB_OUTPUT"
+ }
+
+ if [[ "$SELECT_OUTCOME" != "success" ]] || [[ ! -s /tmp/selection-result.json ]]; then
+ echo "::warning::story selector did not produce output; draft skips visual-regression (full run happens on ready for review)"
+ fall_back_to_skip
+ exit 0
+ fi
+
+ MODE=$(jq -r '.mode' /tmp/selection-result.json)
+ if [[ "$MODE" != "selective" ]]; then
+ echo "Selector declined to narrow (mode=$MODE); draft skips visual-regression (full run happens on ready for review)"
+ fall_back_to_skip
+ exit 0
+ fi
+
+ COUNT=$(jq -r '.affected_story_count' /tmp/selection-result.json)
+ if [[ "$COUNT" -eq 0 ]]; then
+ # Selective mode found zero affected stories — skip visual-regression entirely.
+ echo "mode=selective" >> "$GITHUB_OUTPUT"
+ echo 'matrix={"include":[]}' >> "$GITHUB_OUTPUT"
+ echo "should_run=false" >> "$GITHUB_OUTPUT"
+ echo "affected_files=" >> "$GITHUB_OUTPUT"
+ echo "Selective mode: 0 affected stories, skipping visual-regression"
+ exit 0
+ fi
+
+ # Selective with affected stories: collapse to one chromium shard.
+ AFFECTED_FILES=$(jq -r '.affected_stories | join(" ")' /tmp/selection-result.json)
+ echo "mode=selective" >> "$GITHUB_OUTPUT"
+ echo 'matrix={"include":[{"browser":"chromium","shard":1,"shard_count":1}]}' >> "$GITHUB_OUTPUT"
+ echo "should_run=true" >> "$GITHUB_OUTPUT"
+ echo "affected_files=$AFFECTED_FILES" >> "$GITHUB_OUTPUT"
+ echo "Selective mode: $COUNT affected story files"
+
- name: Write summary
if: steps.selection.outcome == 'success'
env:
RESULT: ${{ steps.selection.outputs.result }}
- CURRENT_SHARDS: 20
+ CURRENT_SHARDS: 16
SHARD_OVERHEAD_MINUTES: 3
run: |
MODE=$(echo "$RESULT" | jq -r '.mode')
@@ -623,9 +762,10 @@ jobs:
if [ "$MODE" = "selective" ]; then
COUNT=$(echo "$RESULT" | jq -r '.affected_story_count')
- SHARDS=$(echo "$RESULT" | jq -r '.suggested_shards')
AFFECTED_DUR=$(echo "$RESULT" | jq -r '.affected_duration_seconds')
TOTAL_DUR=$(echo "$RESULT" | jq -r '.total_duration_seconds')
+ # Selected mode collapses to a single chromium shard (see classify step).
+ SHARDS=1
SAVED_STORIES=$((TOTAL - COUNT))
SAVED_SHARDS=$((CURRENT_SHARDS - SHARDS))
@@ -634,7 +774,7 @@ jobs:
SAVED_MINUTES=$((FULL_MINUTES - SELECTIVE_MINUTES))
cat >> "$GITHUB_STEP_SUMMARY" << EOF
- ## Shadow story selection
+ ## Story selection
| Metric | Full run | Selective | Saved |
|---|---|---|---|
@@ -643,19 +783,17 @@ jobs:
| Est. CI minutes | ~${FULL_MINUTES} | ~${SELECTIVE_MINUTES} | **~${SAVED_MINUTES}** |
| Est. render time | ${TOTAL_DUR}s | ${AFFECTED_DUR}s | **$((TOTAL_DUR - AFFECTED_DUR))s** |
- > Shadow-only — no effect on CI. Predictor: webpack module graph from build-storybook.
+ > Predictor: webpack module graph from build-storybook. Master push runs the full suite.
EOF
- echo "SHADOW_METRICS: $(echo "$RESULT" | jq -c '{mode, affected: .affected_story_count, total: .total_story_count, shards: .suggested_shards, current_shards: '$CURRENT_SHARDS', affected_dur: .affected_duration_seconds, total_dur: .total_duration_seconds}')"
+ echo "SELECTION_METRICS: $(echo "$RESULT" | jq -c '{mode, affected: .affected_story_count, total: .total_story_count, current_shards: '$CURRENT_SHARDS', affected_dur: .affected_duration_seconds, total_dur: .total_duration_seconds}')"
else
REASON=$(echo "$RESULT" | jq -r '.reason // "unknown"')
cat >> "$GITHUB_STEP_SUMMARY" << EOF
- ## Shadow story selection
+ ## Story selection
**Full run required:** $REASON
Total stories: $TOTAL
-
- > Shadow-only — no effect on CI.
EOF
- echo "SHADOW_METRICS: $(echo "$RESULT" | jq -c '{mode, reason, total: .total_story_count}')"
+ echo "SELECTION_METRICS: $(echo "$RESULT" | jq -c '{mode, reason, total: .total_story_count}')"
fi
diff --git a/products/visual_review/backend/classifier.py b/products/visual_review/backend/classifier.py
index 34476cab663a..bf9b9be70644 100644
--- a/products/visual_review/backend/classifier.py
+++ b/products/visual_review/backend/classifier.py
@@ -21,6 +21,7 @@ class SnapshotClassifier:
run: Run,
baseline: dict[str, str],
tolerated_lookup: dict[tuple[str, str, str], ToleratedHash],
+ is_partial: bool = False,
):
self.run = run
self.repo_id = run.repo_id
@@ -29,6 +30,9 @@ class SnapshotClassifier:
self.tolerated_lookup = tolerated_lookup
self.snapshots_qs = run.snapshots.using(WRITER_DB)
self.artifact_cache: dict[str, Artifact] = {}
+ # Caller-supplied so the client-controlled flag can be fenced
+ # server-side rather than read from run.is_partial. See complete_run.
+ self.is_partial = is_partial
def classify(self) -> None:
self.stamp_baseline_hashes()
@@ -144,6 +148,11 @@ class SnapshotClassifier:
"""Detect baseline identifiers missing from the run and create REMOVED rows."""
if not self.baseline:
return
+ if self.is_partial:
+ # Partial runs only render a subset of the suite. The omitted
+ # baseline identifiers haven't been deleted, they just weren't
+ # exercised — leave them untouched.
+ return
produced = set(self.snapshots_qs.values_list("identifier", flat=True))
removed = [
RunSnapshot(
diff --git a/products/visual_review/backend/facade/api.py b/products/visual_review/backend/facade/api.py
index 9dfca32de0a5..2a3d4e23878e 100644
--- a/products/visual_review/backend/facade/api.py
+++ b/products/visual_review/backend/facade/api.py
@@ -354,6 +354,7 @@ def create_run(input: contracts.CreateRunInput, team_id: int) -> contracts.Creat
removed_identifiers=list(input.removed_identifiers),
purpose=input.purpose,
metadata=_sanitize_run_metadata(input.metadata),
+ is_partial=input.is_partial,
)
upload_targets = [
diff --git a/products/visual_review/backend/facade/contracts.py b/products/visual_review/backend/facade/contracts.py
index e5000d3acea6..b712f35fd3f6 100644
--- a/products/visual_review/backend/facade/contracts.py
+++ b/products/visual_review/backend/facade/contracts.py
@@ -53,6 +53,10 @@ class CreateRunInput:
purpose: str = "review"
# Run-level metadata (pr_title, ci_job_url, base_branch, etc.)
metadata: dict = field(default_factory=dict)
+ # True when CI only rendered a subset of the suite.
+ # Tells the classifier to leave omitted baseline identifiers alone instead
+ # of marking them as removed.
+ is_partial: bool = False
@dataclass(frozen=True)
diff --git a/products/visual_review/backend/logic.py b/products/visual_review/backend/logic.py
index adf32f12ee87..b8b9e5565c8c 100644
--- a/products/visual_review/backend/logic.py
+++ b/products/visual_review/backend/logic.py
@@ -467,6 +467,26 @@ def _get_default_branch(github: GitHubIntegration, repo_full_name: str) -> str:
return "master"
+def _run_is_on_default_branch(repo: Repo, branch: str) -> bool:
+ """Whether this run targets the repo's GitHub default branch.
+
+ Fences the client-supplied ``is_partial`` flag: the default branch holds
+ the authoritative full baseline, so a partial run there must not skip
+ removed-baseline detection. Resolves the default branch server-side from
+ GitHub. Returns ``False`` when it can't be determined (no integration) —
+ harmless, since the baseline fetch then returns empty and removal
+ detection short-circuits regardless.
+ """
+ try:
+ github = get_github_integration_for_repo(repo)
+ if github.access_token_expired():
+ github.refresh_access_token()
+ except Exception:
+ logger.info("visual_review.no_github_integration", repo_id=str(repo.id))
+ return False
+ return branch == _get_default_branch(github, repo.repo_full_name)
+
+
def _resolve_baselines(repo, run_type: str, branch: str) -> dict[str, str]:
"""Fetch baseline content hashes from GitHub for snapshot comparison.
@@ -620,6 +640,7 @@ def create_run(
removed_identifiers: list[str] | None = None,
purpose: str = RunPurpose.REVIEW,
metadata: dict | None = None,
+ is_partial: bool = False,
) -> tuple[Run, list[dict]]:
"""
Create a new run with its snapshots.
@@ -630,6 +651,9 @@ def create_run(
baseline_hashes, unchanged_count, removed_identifiers are deprecated —
the backend fetches baselines from GitHub and computes everything.
Params kept for backward compat with older CLI versions.
+
+ is_partial tags the run as a subset; the classifier then leaves baseline
+ identifiers we didn't touch alone instead of marking them as removed.
"""
repo = get_repo(repo_id, team_id)
@@ -643,6 +667,7 @@ def create_run(
snapshots,
purpose,
metadata,
+ is_partial,
)
@@ -657,6 +682,7 @@ def _create_run_inner(
snapshots,
purpose,
metadata,
+ is_partial: bool = False,
) -> tuple[Run, list[dict]]:
# Supersede ALL old runs before inserting the new one. The unique
# partial index on (repo, branch, run_type) WHERE superseded_by IS NULL
@@ -686,6 +712,7 @@ def _create_run_inner(
purpose=purpose,
total_snapshots=len(snapshots),
metadata=metadata or {},
+ is_partial=is_partial,
)
# Fix up the sentinel pointers to reference the actual new run
@@ -866,7 +893,28 @@ def complete_run(run_id: UUID) -> Run:
).filter(Q(expires_at__isnull=True) | Q(expires_at__gt=now)):
tolerated_lookup[(t.identifier, t.baseline_hash, t.alternate_hash)] = t
- classifier = SnapshotClassifier(run, baseline, tolerated_lookup)
+ # is_partial is client-supplied and only suppresses removed-baseline
+ # detection. Never honor it on the default branch (authoritative full
+ # baseline), so a token can't hide deleted snapshots from the gate. Persist
+ # the correction so every downstream reader (status posting, UI) sees the
+ # effective value rather than the raw client claim.
+ #
+ # On PR branches honoring the client is deliberate, but a partial run must
+ # never satisfy the gating status context: _post_commit_status routes it to
+ # a separate non-gating "(partial)" context (see there). Branch protection
+ # keys off context + state, not the human-facing description, so a separate
+ # context is what actually keeps a one-flag subset run from turning the gate
+ # green — the description annotation alone does not.
+ if run.is_partial and _run_is_on_default_branch(repo, run.branch):
+ logger.warning(
+ "visual_review.is_partial_ignored_on_default_branch",
+ run_id=str(run.id),
+ branch=run.branch,
+ )
+ run.is_partial = False
+ run.save(using=WRITER_DB, update_fields=["is_partial"])
+
+ classifier = SnapshotClassifier(run, baseline, tolerated_lookup, is_partial=run.is_partial)
classifier.classify()
# Update total and counts from actual RunSnapshot rows
@@ -1478,12 +1526,27 @@ def _post_commit_status(
POST /repos/{owner}/{repo}/statuses/{sha}
state: "pending", "success", "failure", "error"
+
+ Partial runs (is_partial, client-supplied) suppress removed-baseline
+ detection on PR branches, so they must not be able to satisfy the gating
+ status context that branch protection evaluates. Branch protection keys off
+ the (context, state) pair, not the human-facing description, so a partial
+ run is posted to a separate "PostHog Visual Review / {run_type} (partial)"
+ context rather than the gating "PostHog Visual Review / {run_type}" one.
+ A subset run therefore can never turn the gated context green; a reviewer
+ must require the partial context explicitly to gate on partial runs. The
+ description is also annotated so the disclosure is visible to humans.
"""
if not repo.repo_full_name:
return
from .github import github_request
+ context = f"PostHog Visual Review / {run.run_type}"
+ if run.is_partial:
+ context = f"{context} (partial)"
+ description = f"{description} (partial run)"
+
try:
github = get_github_integration_for_repo(repo)
if github.access_token_expired():
@@ -1503,7 +1566,7 @@ def _post_commit_status(
json={
"state": state,
"description": description[:140],
- "context": f"PostHog Visual Review / {run.run_type}",
+ "context": context,
"target_url": target_url,
},
timeout=10,
diff --git a/products/visual_review/backend/migrations/0013_run_is_partial.py b/products/visual_review/backend/migrations/0013_run_is_partial.py
new file mode 100644
index 000000000000..e8cced125a70
--- /dev/null
+++ b/products/visual_review/backend/migrations/0013_run_is_partial.py
@@ -0,0 +1,15 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("visual_review", "0012_quarantined_identifier_source_run"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="run",
+ name="is_partial",
+ field=models.BooleanField(default=False),
+ ),
+ ]
diff --git a/products/visual_review/backend/migrations/max_migration.txt b/products/visual_review/backend/migrations/max_migration.txt
index f86df01092ba..08b26e5da0ca 100644
--- a/products/visual_review/backend/migrations/max_migration.txt
+++ b/products/visual_review/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0012_quarantined_identifier_source_run
+0013_run_is_partial
diff --git a/products/visual_review/backend/models.py b/products/visual_review/backend/models.py
index 7091e55e983c..3eb30527e776 100644
--- a/products/visual_review/backend/models.py
+++ b/products/visual_review/backend/models.py
@@ -161,6 +161,9 @@ class Run(ProductTeamModel):
# e.g., {"pr_title": "...", "base_branch": "main", "ci_job_url": "..."}
metadata = models.JSONField(default=dict, blank=True)
+ # CI ran only a subset of the test suite
+ is_partial = models.BooleanField(default=False)
+
created_at = models.DateTimeField(auto_now_add=True)
completed_at = models.DateTimeField(null=True, blank=True)
diff --git a/products/visual_review/backend/tests/test_classifier.py b/products/visual_review/backend/tests/test_classifier.py
index 9fcddc1749ca..b5f9683eeadc 100644
--- a/products/visual_review/backend/tests/test_classifier.py
+++ b/products/visual_review/backend/tests/test_classifier.py
@@ -69,7 +69,7 @@ def _make_tolerated(repo: Repo, identifier: str, baseline_hash: str, alternate_h
def _classify(run: Run, baseline: dict[str, str], tolerated_lookup: dict | None = None) -> dict[str, RunSnapshot]:
- classifier = SnapshotClassifier(run, baseline, tolerated_lookup or {})
+ classifier = SnapshotClassifier(run, baseline, tolerated_lookup or {}, is_partial=run.is_partial)
classifier.classify()
return {s.identifier: s for s in run.snapshots.all()}
@@ -217,6 +217,17 @@ class TestRemovedClassification:
assert run.snapshots.filter(identifier="Gone").count() == 1
+ def test_partial_run_does_not_fabricate_removed_for_unrendered_baseline(self, repo):
+ _make_artifact(repo, "old_hash")
+ run = _make_run(repo, [{"identifier": "Kept", "current_hash": "h1"}], is_partial=True)
+
+ result = _classify(run, {"Kept": "h1", "Deleted": "old_hash"})
+
+ # Partial runs only render a subset of the suite, so a baseline identifier
+ # absent from the run was simply not exercised — not deleted.
+ assert "Deleted" not in result
+ assert run.snapshots.filter(identifier="Deleted").count() == 0
+
@pytest.mark.django_db(databases=PRODUCT_DATABASES)
class TestToleratedHashClassification:
diff --git a/products/visual_review/backend/tests/test_logic.py b/products/visual_review/backend/tests/test_logic.py
index 4d5114ec18d9..b7770d4dcdb4 100644
--- a/products/visual_review/backend/tests/test_logic.py
+++ b/products/visual_review/backend/tests/test_logic.py
@@ -351,6 +351,57 @@ class TestRunOperations:
removed = run.snapshots.get(identifier="deleted")
assert removed.result == SnapshotResult.REMOVED
+ def test_complete_run_partial_skips_removals_off_default_branch(self, repo, mocker):
+ run, _ = logic.create_run(
+ repo_id=repo.id,
+ team_id=repo.team_id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc",
+ branch="feature-x",
+ pr_number=7,
+ snapshots=[{"identifier": "kept", "content_hash": "h1"}],
+ is_partial=True,
+ )
+
+ mocker.patch(
+ "products.visual_review.backend.logic._resolve_baselines_with_merge_base",
+ return_value=({"kept": "h1", "deleted": "h2"}, 0),
+ )
+ mocker.patch("products.visual_review.backend.logic._run_is_on_default_branch", return_value=False)
+
+ completed = logic.complete_run(run.id)
+
+ assert completed.removed_count == 0
+ assert not run.snapshots.filter(identifier="deleted").exists()
+
+ def test_complete_run_partial_ignored_on_default_branch(self, repo, mocker):
+ run, _ = logic.create_run(
+ repo_id=repo.id,
+ team_id=repo.team_id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc",
+ branch="master",
+ pr_number=None,
+ snapshots=[{"identifier": "kept", "content_hash": "h1"}],
+ is_partial=True,
+ )
+
+ mocker.patch(
+ "products.visual_review.backend.logic._resolve_baselines_with_merge_base",
+ return_value=({"kept": "h1", "deleted": "h2"}, 0),
+ )
+ mocker.patch("products.visual_review.backend.logic._run_is_on_default_branch", return_value=True)
+
+ completed = logic.complete_run(run.id)
+
+ # is_partial must not suppress removal detection on the default branch.
+ assert completed.removed_count == 1
+ removed = run.snapshots.get(identifier="deleted")
+ assert removed.result == SnapshotResult.REMOVED
+ # The default-branch correction is persisted, so the run is no longer
+ # treated as partial anywhere downstream (status context, UI).
+ assert completed.is_partial is False
+
def test_complete_run_passes_commit_sha_to_baseline_resolution(self, repo, mocker):
"""complete_run passes run.commit_sha so default-branch baselines are pinned."""
run, _ = logic.create_run(
@@ -919,7 +970,40 @@ class TestCommitStatusChecks:
statuses = mock_github_api.status_checks
assert statuses[-1]["state"] == "success"
- assert "No visual changes" in statuses[-1]["description"]
+ assert statuses[-1]["description"] == "No visual changes"
+ # A full run posts to the gating context that branch protection evaluates.
+ assert statuses[-1]["context"] == "PostHog Visual Review / storybook"
+
+ def test_complete_run_partial_annotates_posted_status(self, github_repo, mock_github_api, mocker):
+ run, _ = logic.create_run(
+ repo_id=github_repo.id,
+ team_id=github_repo.team_id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc123",
+ branch="feature-x",
+ pr_number=7,
+ snapshots=[{"identifier": "snap", "content_hash": "same"}],
+ baseline_hashes={"snap": "same"},
+ is_partial=True,
+ )
+
+ mocker.patch(
+ "products.visual_review.backend.logic._resolve_baselines_with_merge_base",
+ return_value=({"snap": "same", "deleted": "h2"}, 0),
+ )
+ mocker.patch("products.visual_review.backend.logic._run_is_on_default_branch", return_value=False)
+ logic.complete_run(run.id)
+
+ # A partial run suppresses removal detection, so it must never satisfy
+ # the gating status context branch protection evaluates. It posts to a
+ # separate "(partial)" context instead, and the description discloses it.
+ statuses = mock_github_api.status_checks
+ assert statuses[-1]["state"] == "success"
+ assert statuses[-1]["description"] == "No visual changes (partial run)"
+ assert statuses[-1]["context"] == "PostHog Visual Review / storybook (partial)"
+ # The gating context is never posted green by a partial run.
+ gating_context = "PostHog Visual Review / storybook"
+ assert all(s["context"] != gating_context for s in statuses)
def test_complete_run_posts_comment_when_changes_detected(self, github_repo, mock_github_api, mocker):
github_repo.enable_pr_comments = True
@@ -1780,6 +1864,34 @@ class TestRerunGithubJob:
assert error is None
[email protected]_db(databases=PRODUCT_DATABASES)
+class TestRunIsOnDefaultBranch:
+ @pytest.fixture
+ def repo(self, team):
+ return logic.create_repo(team_id=team.id, repo_external_id=1234, repo_full_name="org/test-repo")
+
+ def _mock_github(self, mocker, default_branch="master"):
+ mock_github = mocker.MagicMock()
+ mock_github.access_token_expired.return_value = False
+ mocker.patch("products.visual_review.backend.logic.get_github_integration_for_repo", return_value=mock_github)
+ mocker.patch("products.visual_review.backend.logic._get_default_branch", return_value=default_branch)
+
+ def test_true_when_branch_matches_default(self, repo, mocker):
+ self._mock_github(mocker, default_branch="main")
+ assert logic._run_is_on_default_branch(repo, "main") is True
+
+ def test_false_when_branch_differs(self, repo, mocker):
+ self._mock_github(mocker, default_branch="main")
+ assert logic._run_is_on_default_branch(repo, "feature-x") is False
+
+ def test_false_when_no_github_integration(self, repo, mocker):
+ mocker.patch(
+ "products.visual_review.backend.logic.get_github_integration_for_repo",
+ side_effect=logic.GitHubIntegrationNotFoundError("none"),
+ )
+ assert logic._run_is_on_default_branch(repo, "master") is False
+
+
@pytest.mark.django_db(databases=PRODUCT_DATABASES)
class TestMergeBaseBaselineHealing:
"""Tests for _resolve_baselines_with_merge_base healing rebase-corrupted baselines."""
diff --git a/products/visual_review/cli/src/client.ts b/products/visual_review/cli/src/client.ts
index 3b46c2c9a645..52e54ed60569 100644
--- a/products/visual_review/cli/src/client.ts
+++ b/products/visual_review/cli/src/client.ts
@@ -119,6 +119,7 @@ export class VisualReviewClient {
prNumber?: number
purpose?: string
metadata?: Record<string, string>
+ isPartial?: boolean
}): Promise<CreateRunResultApi> {
const body: CreateRunInputApi = {
repo_id: input.repoId,
@@ -129,6 +130,7 @@ export class VisualReviewClient {
pr_number: input.prNumber,
purpose: input.purpose,
metadata: input.metadata,
+ is_partial: input.isPartial,
}
return this.request<CreateRunResultApi>('/visual_review/runs/', {
diff --git a/products/visual_review/cli/src/index.ts b/products/visual_review/cli/src/index.ts
index e98acec4e191..383b1a62fcc1 100644
--- a/products/visual_review/cli/src/index.ts
+++ b/products/visual_review/cli/src/index.ts
@@ -84,6 +84,10 @@ run.command('create')
.option('--token <value>', 'Personal API token')
.option('--cookie <value>', 'Session cookie')
.option('--purpose <purpose>', 'Run purpose: review or observe', 'review')
+ .option(
+ '--partial',
+ 'Mark the run as a subset. Identifiers in the baseline but not in this run are left untouched instead of flagged as removed.'
+ )
.action(async (options: RunCreateOptions) => {
if (!baselineExists(options.baseline)) {
process.exit(0)
@@ -178,6 +182,7 @@ interface RunCreateOptions {
token?: string
cookie?: string
purpose?: string
+ partial?: boolean
}
interface RunUploadOptions {
@@ -304,7 +309,7 @@ async function runCreate(options: RunCreateOptions): Promise<string> {
const commit = options.commit ?? getCurrentCommit()
log(
- `Creating run: type=${options.type}, branch=${branch}, commit=${commit.slice(0, 10)}, purpose=${options.purpose ?? 'review'}`
+ `Creating run: type=${options.type}, branch=${branch}, commit=${commit.slice(0, 10)}, purpose=${options.purpose ?? 'review'}${options.partial ? ', partial' : ''}`
)
const result = await client.createRun({
@@ -316,6 +321,7 @@ async function runCreate(options: RunCreateOptions): Promise<string> {
snapshots: [],
purpose: options.purpose,
metadata: collectCIMetadata(),
+ isPartial: options.partial,
})
log(`Run created: ${result.run_id}`)
diff --git a/products/visual_review/frontend/generated/api.schemas.ts b/products/visual_review/frontend/generated/api.schemas.ts
index b69e5c5f331b..9aade79ff911 100644
--- a/products/visual_review/frontend/generated/api.schemas.ts
+++ b/products/visual_review/frontend/generated/api.schemas.ts
@@ -274,6 +274,7 @@ export interface CreateRunInputApi {
removed_identifiers?: string[]
purpose?: string
metadata?: CreateRunInputApiMetadata
+ is_partial?: boolean
}
export type UploadTargetApiFields = { [key: string]: string }
diff --git a/products/visual_review/frontend/generated/api.zod.ts b/products/visual_review/frontend/generated/api.zod.ts
index c7c7ed31635b..e8c944cccbbd 100644
--- a/products/visual_review/frontend/generated/api.zod.ts
+++ b/products/visual_review/frontend/generated/api.zod.ts
@@ -98,6 +98,7 @@ export const VisualReviewRunsCreateBody = /* @__PURE__ */ zod.object({
removed_identifiers: zod.array(zod.string()).optional(),
purpose: zod.string().optional(),
metadata: zod.record(zod.string(), zod.unknown()).optional(),
+ is_partial: zod.boolean().optional(),
})
/**
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index b6836965a3bd..845414d41f33 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -12322,6 +12322,7 @@ export namespace Schemas {
removed_identifiers?: string[];
purpose?: string;
metadata?: CreateRunInputMetadata;
+ is_partial?: boolean;
}
export interface CreateRunResult {