:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(devex): decide Django and product test selection in one job (#88265)
Julian Bez1503356e7e5e
diff --git a/.agents/skills/authoring-ci-workflows/SKILL.md b/.agents/skills/authoring-ci-workflows/SKILL.mdindex 68a118f850e1..69d82ab80762 100644--- a/.agents/skills/authoring-ci-workflows/SKILL.md+++ b/.agents/skills/authoring-ci-workflows/SKILL.md@@ -236,7 +236,7 @@ Details: `/depot-github-runners`.Most commits land before a PR is marked ready, and drafts can't merge — so heavy suites should run a narrowed subset on drafts and the full matrix on `ready_for_review` (the merge gate).Add `ready_for_review` to the `pull_request` types, and make aggregator "... Tests Pass" jobs treat `skipped` as success so drafts still report.-Foot-gun: if a `select-tests` job is cancelled mid-flight, its `mode` output is empty — normalize empty-mode **on a draft** to `skip`, or the draft grabs the full matrix and serializes the ready run behind it.+Foot-gun: if the job that selects tests is cancelled mid-flight, its `mode` output is empty — normalize empty-mode **on a draft** to `skip`, or the draft grabs the full matrix and serializes the ready run behind it.## Backwards-compat with unrebased PRsdiff --git a/.depot/workflows/ci-backend.yml b/.depot/workflows/ci-backend.ymlindex 462293fb1b72..e4487cec1b02 100644--- a/.depot/workflows/ci-backend.yml+++ b/.depot/workflows/ci-backend.yml@@ -17,7 +17,7 @@# additionally skips these on trunk-merge/** branches to save GITHUB_TOKEN budget;# the shadow strips them entirely, so that gating has nothing to mirror), snapshot# auto-commit (handle-snapshots), posthog-github-action telemetry (including the-# capture-test-selection job — select-tests still emits its telemetry outputs to+# capture-test-selection job — turbo-discover still emits its telemetry outputs to# stay apples-to-apples, they just have no consumer here),# --store-durations write, test-selection verdict, Trunk flaky-test quarantine# gate (canonical runs per-shard analytics-uploader steps that post to the@@ -515,6 +515,12 @@ jobs:runs-on: depot-ubuntu-24.04timeout-minutes: 20name: Discover product tests+ env:+ # Whether this run selects backend tests at all: a PR, off the merge queue's+ # trunk-merge/** run (that run is the merge gate and stays full), and without+ # the run-ci-backend label. turbo-discover.js reads it too, so a run that never+ # selects reports an empty mode rather than a selector error.+ SELECTION_APPLIES: ${{ github.event_name == 'pull_request' && !startsWith(github.head_ref, 'trunk-merge/') && !contains(github.event.pull_request.labels.*.name, 'run-ci-backend') && needs.changes.outputs.backend == 'true' }}outputs:run_legacy: ${{ steps.discover.outputs.run_legacy }}run_legacy_reason: ${{ steps.discover.outputs.run_legacy_reason }}@@ -523,6 +529,13 @@ jobs:schema_migrations_key: ${{ steps.schema-key.outputs.migrations_key }}schema_prefix_key: ${{ steps.schema-key.outputs.prefix_key }}django_shards: ${{ steps.discover.outputs.django_shards }}+ # Which Django tests this PR runs. Empty mode = this run does not select.+ mode: ${{ steps.discover.outputs.mode }}+ # The rest of that decision (segment file lists, run_poe, run_temporal,+ # segment_shards) as one JSON object; consumers read it with fromJSON.+ selection: ${{ steps.discover.outputs.selection }}+ # The posthog-ci-test-selection event properties, as one JSON object.+ telemetry: ${{ steps.discover.outputs.telemetry }}steps:- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2with:@@ -614,7 +627,15 @@ jobs:key: posthog-segment-durations-${{ github.run_id }}restore-keys: |posthog-segment-durations--+ # The backend test selector picks the Django tests this PR needs, and on a legacy+ # diff its product list narrows the product matrix too: turbo-discover.js cannot+ # see which products a posthog/ or ee/ edit reaches, and the selector can, because+ # it follows the import graph into products/. Both matrices read one verdict, so+ # they can never disagree about whether the selection is trustworthy.+ # Only on a legacy diff: turbo-discover.js trusts the selection only when the paths+ # filter saw a legacy edit, and falls back without a selector run otherwise. The+ # DISABLE_BACKEND_TEST_SELECTION kill switch skips the run too; the script still+ # reports the `disabled` reason from its own env.- name: Prefer a junit-scaled union over an unscaled cache copy# Transition guard: the timing caches only carry junit-scaled product# magnitudes once the updated timing workflow has run. Until then the@@ -638,12 +659,49 @@ jobs:elseecho "Restored union already junit-scaled"fi++ - name: Install uv+ # Optional setup: a failure here must fall back to the full matrices like a+ # selector failure does, not fail the job that gates every test job.+ continue-on-error: true+ if: env.SELECTION_APPLIES == 'true' && needs.changes.outputs.legacy == 'true' && vars.DISABLE_BACKEND_TEST_SELECTION != 'true'+ uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0+ with:+ version: '0.11.28'++ - name: Run the backend test selector+ id: select+ # A selector failure or hang must not fail this job, which gates every test job+ # in the workflow — turbo-discover.js falls back to the full matrices instead.+ # The step timeout bounds a hang well inside the job's, so the fallback still+ # reaches the matrices rather than taking the whole job down with it.+ continue-on-error: true+ timeout-minutes: 8+ if: env.SELECTION_APPLIES == 'true' && needs.changes.outputs.legacy == 'true' && vars.DISABLE_BACKEND_TEST_SELECTION != 'true'+ env:+ BASE_REF: ${{ github.event.pull_request.base.ref }}+ shell: bash+ run: |+ set -euo pipefail+ uv run tools/snob_backend_test_selection_shadow.py \+ --base-ref "origin/$BASE_REF" \+ > /tmp/selection.json+- name: Discover products to testid: discoverenv:# On pushes to master, always run everything.# On PRs, use the path filter to detect legacy changes.LEGACY_CHANGED: ${{ github.event_name != 'pull_request' || needs.changes.outputs.legacy }}+ # Empty when the selector did not run or failed, which falls back to the+ # full matrices on a ready PR and skips them on a draft.+ SELECTION_JSON: ${{ steps.select.outcome == 'success' && '/tmp/selection.json' || '' }}+ # Kill switch — set the DISABLE_BACKEND_TEST_SELECTION repo variable to put+ # every PR back on the full matrices without a code change.+ SELECTION_DISABLED: ${{ vars.DISABLE_BACKEND_TEST_SELECTION || 'false' }}+ # A draft has a later ready run to defer to, so an untrusted selection skips+ # the heavy matrices there instead of running all of them.+ PR_DRAFT: ${{ github.event.pull_request.draft }}SCHEMA_CHANGED: ${{ github.event_name != 'pull_request' || needs.changes.outputs.schema }}TURBO_SCM_BASE: ${{ github.event_name == 'pull_request' && format('origin/{0}', github.event.pull_request.base.ref) || '' }}TURBO_SCM_HEAD: ${{ github.sha }}@@ -659,279 +717,11 @@ jobs:echo "run_legacy=$(echo "$RESULT" | jq -r '.run_legacy')" >> $GITHUB_OUTPUTecho "run_legacy_reason=$(echo "$RESULT" | jq -r '.run_legacy_reason // empty')" >> "$GITHUB_OUTPUT"echo "django_shards=$(echo "$RESULT" | jq -c '.django_shards // empty')" >> $GITHUB_OUTPUT+ echo "$RESULT" | jq -r '"mode=\(.selection.mode)", "selection=\(.selection | tojson)", "telemetry=\(.telemetry | tojson)"' >> "$GITHUB_OUTPUT"- # Pick which Django tests to run on a PR. Both drafts and ready PRs get the- # snob-selected subset; the difference is what happens when selection can't be- # trusted (product->legacy cascade, turbo-discover or selector failure, a- # selector full-run signal). A ready PR then runs the full matrices, a draft- # skips them and defers to its ready run — the pre-selection draft behavior.- # Master pushes and the queue's trunk-merge/** run never reach this job, so- # what gates master is still a full run.- # hogli-lint: not-a-required-gate - selects PR coverage and emits no required check.- #- # 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]- # Pushes 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 PR.- # Trunk's merge-queue branches open as draft PRs, but their run IS the- # merge gate, so they must never get the narrowed selection.- # run_legacy=false means the django job below is skipped outright, so there- # is no matrix left to narrow — only the exact string skips, which keeps an- # empty output (turbo-discover skipped or failed) on the selecting path.- if: |- github.event_name == 'pull_request' &&- !startsWith(github.head_ref, 'trunk-merge/') &&- !contains(github.event.pull_request.labels.*.name, 'run-ci-backend') &&- needs.changes.outputs.backend == 'true' &&- needs.turbo-discover.outputs.run_legacy != 'false'- runs-on: depot-ubuntu-24.04- # Headroom over checkout + uv + the selector's whole-tree parse. A timeout here- # leaves MODE empty, which on a ready PR means the full matrix — the worst case.- timeout-minutes: 10- 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 }}- compat_files: ${{ steps.classify.outputs.compat_files }}- run_poe: ${{ steps.classify.outputs.run_poe }}- run_temporal: ${{ steps.classify.outputs.run_temporal }}- # Kept apples-to-apples with canonical, though the shadow strips the- # capture job that consumes them (posthog-github-action telemetry).- narrowed: ${{ steps.classify.outputs.narrowed }}- skip_reason: ${{ steps.classify.outputs.skip_reason }}- changed_file_count: ${{ steps.classify.outputs.changed_file_count }}- selected_test_count: ${{ steps.classify.outputs.selected_test_count }}- full_run_reasons_count: ${{ steps.classify.outputs.full_run_reasons_count }}- selected_test_seconds: ${{ steps.classify.outputs.selected_test_seconds }}- skipped_test_seconds: ${{ steps.classify.outputs.skipped_test_seconds }}- # Shards per segment for a narrowed run; build_django_matrix reads them as-is.- segment_shards: ${{ steps.classify.outputs.segment_shards }}- run_legacy: ${{ steps.fallback.outputs.run_legacy }}- run_legacy_reason: ${{ steps.fallback.outputs.run_legacy_reason }}- turbo_result: ${{ steps.fallback.outputs.turbo_result }}- steps:- # Ahead of the checkout on purpose: this reads job outputs only, and when it- # decides selection can't be trusted, cloning the repo would just delay the- # full matrix that is about to run instead.- - name: Decide whether selection can be trusted- id: fallback- env:- RUN_LEGACY: ${{ needs.turbo-discover.outputs.run_legacy }}- RUN_LEGACY_REASON: ${{ needs.turbo-discover.outputs.run_legacy_reason }}- TURBO_RESULT: ${{ needs.turbo-discover.result }}- DISABLED: ${{ vars.DISABLE_BACKEND_TEST_SELECTION || 'false' }}- shell: bash- run: |- set -euo pipefail- skip=false- reason=untrusted- if [[ "$DISABLED" == "true" ]]; then- # Kill switch — set the DISABLE_BACKEND_TEST_SELECTION repo variable to- # put every PR back on the full matrices without a code change. Its own- # reason string, so flipping it during an incident stays distinguishable- # from a genuine cascade in the selection telemetry.- skip=true- reason=disabled- elif [[ "$RUN_LEGACY" == "true" && "$RUN_LEGACY_REASON" != "legacy_changed" ]]; then- # turbo-discover inferred legacy impact from a product, contract, or- # schema change rather than seeing a direct edit. The diff-based selector- # cannot see that cascade, so its subset would be incomplete.- # A direct legacy edit is the selector's home turf and is deliberately not- # untrusted here — the selector's own FULL_RUN_PATTERNS decide when a- # legacy change is too broad to narrow.- skip=true- elif [[ "$TURBO_RESULT" != "success" && "$TURBO_RESULT" != "skipped" ]]; then- # Conservative — turbo-discover failed.- skip=true- fi- echo "skip=$skip" >> "$GITHUB_OUTPUT"- echo "reason=$reason" >> "$GITHUB_OUTPUT"- # Surface the raw inputs too, so the telemetry can audit the decision.- echo "run_legacy=${RUN_LEGACY:-}" >> "$GITHUB_OUTPUT"- echo "run_legacy_reason=${RUN_LEGACY_REASON:-}" >> "$GITHUB_OUTPUT"- echo "turbo_result=${TURBO_RESULT:-}" >> "$GITHUB_OUTPUT"-- - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2- if: steps.fallback.outputs.skip == 'false'- with:- fetch-depth: 1000- filter: blob:none-- - name: Install uv- if: steps.fallback.outputs.skip == 'false'- uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0- with:- version: '0.11.28'-- - 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 the fallback mode- # for this PR 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 }}- FALLBACK_REASON: ${{ steps.fallback.outputs.reason }}- SELECT_OUTCOME: ${{ steps.select.outcome }}- # Guards the empty-selection backstop below. select-tests only runs on- # pull_request, so the bare filter output is the whole story here.- LEGACY_CHANGED: ${{ needs.changes.outputs.legacy }}- # What an untrusted selection falls back to. A ready PR has no later- # run to defer to, so it must run everything; a draft still skips and- # leans on the ready run, which is the cheaper of the two mistakes.- FALLBACK_MODE: ${{ github.event.pull_request.draft && 'skip' || 'full' }}- shell: bash- run: |- set -euo pipefail- # Selection telemetry, kept apples-to-apples with canonical (the shadow- # strips the capture job that consumes these, per the header).- emit_metrics() {- local changed="" selected="" reasons="" selected_seconds="" skipped_seconds=""- if [[ -s /tmp/selection.json ]]; then- changed=$(jq -r '.changed_file_count // empty' /tmp/selection.json)- selected=$(jq -r '.combined.count // empty' /tmp/selection.json)- reasons=$(jq -r '.ast.full_run_reasons | length' /tmp/selection.json)- selected_seconds=$(jq -r '.durations.selected_seconds // empty' /tmp/selection.json)- skipped_seconds=$(jq -r '.durations.skipped_seconds // empty' /tmp/selection.json)- fi- {- echo "narrowed=$1"- echo "skip_reason=$2"- echo "changed_file_count=$changed"- echo "selected_test_count=$selected"- echo "full_run_reasons_count=$reasons"- echo "selected_test_seconds=$selected_seconds"- echo "skipped_test_seconds=$skipped_seconds"- } >> "$GITHUB_OUTPUT"- }-- # Untrusted selection runs the full matrices on a ready PR and skips- # them on a draft (the pre-selection draft behavior).- fall_back() {- echo "mode=$FALLBACK_MODE" >> "$GITHUB_OUTPUT"- echo "core_files=" >> "$GITHUB_OUTPUT"- echo "poe_files=" >> "$GITHUB_OUTPUT"- echo "temporal_files=" >> "$GITHUB_OUTPUT"- echo "compat_files=" >> "$GITHUB_OUTPUT"- echo "run_poe=false" >> "$GITHUB_OUTPUT"- echo "run_temporal=false" >> "$GITHUB_OUTPUT"- emit_metrics false "$1"- }-- if [[ "$FALLBACK_SKIP" == "true" ]]; then- fall_back "${FALLBACK_REASON:-untrusted}"- exit 0- fi-- if [[ "$SELECT_OUTCOME" != "success" ]] || [[ ! -s /tmp/selection.json ]]; then- echo "::warning::shadow selector did not produce output; falling back to mode=$FALLBACK_MODE"- fall_back selector_error- 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 (mode=$FALLBACK_MODE):"- jq -r '.ast.full_run_reasons[]' /tmp/selection.json- fall_back full_run_requested- 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 on): posthog ee/ (minus posthog/temporal, posthog/dags,- # common/hogvm/python/test, posthog/test/repo_invariants)- # POE-off safeguard: posthog/clickhouse, posthog/queries, ee/clickhouse/,- # products/product_analytics/backend/tests/api,- # posthog/api/test/dashboards/test_dashboard.py- # Temporal: posthog/temporal, products/signals/backend/emission- # Compat: CLICKHOUSE_COMPAT_PYTEST_TARGETS (posthog/clickhouse, ee/clickhouse)- # Files outside posthog/ and ee/ (e.g. products/foo/backend/test_*) are not in this- # matrix. turbo-tests handles them, including the temporal suites of- # batch_exports, managed_warehouse, tasks and warehouse_sources, because every- # shard starts the temporal profile, so running them there costs nothing- # extra. Keep this list in sync with PRODUCTS_RUNNING_TEMPORAL_IN_JOB and- # DJANGO_SEGMENTS in turbo-discover.js.- core=()- poe=()- temporal=()- compat=()- while IFS= read -r f; do- [[ -z "$f" ]] && continue- # Compat overlaps the POE scope rather than partitioning with it, so- # it is collected separately from the segment case below. Driven by the- # same env var the compat pytest invocation uses, so widening one can't- # silently under-select the other.- for compat_target in $CLICKHOUSE_COMPAT_PYTEST_TARGETS; do- if [[ "$f" == "${compat_target%/}/"* ]]; then- compat+=("$f")- break- fi- done- case "$f" in- posthog/temporal/*|products/signals/backend/emission/*)- temporal+=("$f")- ;;- posthog/clickhouse/*|posthog/queries/*|ee/clickhouse/*|products/product_analytics/backend/tests/api/*|posthog/api/test/dashboards/test_dashboard.py)- poe+=("$f")- core+=("$f")- ;;- posthog/dags/*|common/hogvm/python/test/*|posthog/test/repo_invariants/*)- # Explicitly --ignore'd by the Core invocation; nothing to do.- ;;- posthog/*|ee/*)- core+=("$f")- ;;- esac- done < <(jq -r '.combined.tests[]?' /tmp/selection.json)-- # Backstop: a diff that touched legacy code but selected no Django test at- # all means the selector had no rule for it, not that there is nothing to- # run — a non-Python legacy file (C++ parser sources, a JSON config) reaches- # no import edge. Narrowing to zero would silently gate on nothing, so treat- # it as untrusted. FULL_RUN_PATTERNS covers the known cases; this catches the- # ones that get added to the `legacy` paths filter and forgotten there.- # Products-only diffs legitimately select nothing here and are not legacy.- if [[ "$LEGACY_CHANGED" == "true" && ${#core[@]} -eq 0 && ${#temporal[@]} -eq 0 ]]; then- echo "::warning::legacy files changed but no Django test was selected; falling back to mode=$FALLBACK_MODE"- fall_back empty_selection- exit 0- fi-- echo "mode=selected" >> "$GITHUB_OUTPUT"- echo "core_files=${core[*]:-}" >> "$GITHUB_OUTPUT"- echo "poe_files=${poe[*]:-}" >> "$GITHUB_OUTPUT"- echo "temporal_files=${temporal[*]:-}" >> "$GITHUB_OUTPUT"- echo "compat_files=${compat[*]:-}" >> "$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"- # Shards per narrowed segment: turbo-discover's per-shard budget applied- # to the selected tests' recorded seconds. Degrades to 1 per segment.- echo "segment_shards=$(node .github/scripts/selected-django-shards.js /tmp/selection.json)" >> "$GITHUB_OUTPUT"- emit_metrics true ""-- echo "Selected: ${#core[@]} core, ${#poe[@]} POE-eligible, ${#temporal[@]} temporal, ${#compat[@]} compat"+ # Depot shadow note: canonical uploads /tmp/selection.json for its+ # test-selection-verdict job. The shadow strips that job and all artifact+ # uploads, so there is no Upload selection artifact step here.build-product-test-matrix:name: Build product test matrix@@ -1580,7 +1370,7 @@ jobs:exit 1build_django_matrix:name: Build Django matrix- needs: [changes, get_clickhouse_versions, turbo-discover, select-tests]+ needs: [changes, get_clickhouse_versions, turbo-discover]if: |!cancelled() &&needs.changes.outputs.backend == 'true' &&@@ -1596,14 +1386,14 @@ 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 }}- COMPAT_FILES: ${{ needs.select-tests.outputs.compat_files }}- SEGMENT_SHARDS: ${{ needs.select-tests.outputs.segment_shards }}+ MODE: ${{ needs.turbo-discover.outputs.mode }}+ RUN_POE: ${{ fromJSON(needs.turbo-discover.outputs.selection || '{}').run_poe }}+ RUN_TEMPORAL: ${{ fromJSON(needs.turbo-discover.outputs.selection || '{}').run_temporal }}+ CORE_FILES: ${{ fromJSON(needs.turbo-discover.outputs.selection || '{}').core_files }}+ COMPAT_FILES: ${{ fromJSON(needs.turbo-discover.outputs.selection || '{}').compat_files }}+ SEGMENT_SHARDS: ${{ fromJSON(needs.turbo-discover.outputs.selection || '{}').segment_shards }}# A trunk-merge/** PR opens as a draft but is the merge gate, and- # select-tests deliberately does not run for it. Reporting it as a+ # turbo-discover deliberately does not select for it. Reporting it as a# draft here would turn that empty MODE into "skip" and build an# empty matrix, so the queue would merge having run no Django tests# at all. Not-draft makes the empty MODE fall through to the full@@ -1617,9 +1407,9 @@ jobs:# :NOTE: Keep shard counts/group ranges in sync with historical Django matrix tuning.# Consult #team-devex before changing.- # A draft PR must never fall back to the full matrix. select-tests sets+ # A draft PR must never fall back to the full matrix. turbo-discover sets# MODE to "skip"/"full"/"selected"; an empty MODE on a- # draft means select-tests was cancelled or failed (typically+ # draft means turbo-discover was cancelled or failed (typically# ready_for_review superseding it mid-flight). Skip here and defer to the# ready run. The run-ci-backend label intentionally forces full on a draft.if [[ -z "$MODE" && "$IS_DRAFT" == "true" && "$FORCE_FULL" != "true" ]]; then@@ -1636,11 +1426,10 @@ jobs:fiif [[ "$MODE" == "selected" ]]; then# Selected mode: run only the segments that have selected files. Shard- # counts come from select-tests, where selected-django-shards.js applied- # turbo-discover's per-shard budget to the selected tests' recorded- # seconds. A wide selection therefore spreads over several jobs instead- # of running to the job timeout in one. No counts means one shard per- # segment.+ # counts come from turbo-discover, which applies its per-shard budget to+ # the selected tests' recorded seconds. A wide selection therefore+ # spreads over several jobs instead of running to the job timeout in+ # one. No counts means one shard per segment.segment_shards="${SEGMENT_SHARDS:-}"[[ -z "$segment_shards" ]] && segment_shards='{"core": 1, "poe": 1, "temporal": 1}'@@ -1899,8 +1688,7 @@ jobs:echo "include=$include" >> "$GITHUB_OUTPUT"echo "Django matrix size: $(jq -r 'length' <<< "$include") (mode=$MODE)"django:- needs:- [changes, turbo-discover, detect-snapshot-mode, get_clickhouse_versions, build_django_matrix, select-tests]+ needs: [changes, turbo-discover, detect-snapshot-mode, get_clickhouse_versions, build_django_matrix]# Run legacy pytest if:# 1. Legacy code directly changed (ee/, posthog/)# 2. OR product changes affect legacy code (turbo-discover outputs run_legacy=true)@@ -2225,15 +2013,15 @@ jobs:# flip from one that predates it.PERSON_ON_EVENTS_V2_ENABLED: ${{ !matrix.person-on-events && !matrix.compat && 'true' || 'false' }}CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA: ${{ matrix.new-events-schema && 'true' || 'false' }}- MODE: ${{ needs.select-tests.outputs.mode }}- CORE_FILES: ${{ needs.select-tests.outputs.core_files }}- POE_FILES: ${{ needs.select-tests.outputs.poe_files }}- COMPAT_FILES: ${{ needs.select-tests.outputs.compat_files }}+ MODE: ${{ needs.turbo-discover.outputs.mode }}+ CORE_FILES: ${{ fromJSON(needs.turbo-discover.outputs.selection || '{}').core_files }}+ POE_FILES: ${{ fromJSON(needs.turbo-discover.outputs.selection || '{}').poe_files }}+ COMPAT_FILES: ${{ fromJSON(needs.turbo-discover.outputs.selection || '{}').compat_files }}# devex: measure core (posthog/ee) coverage on PRs to size the gap vs products. sysmon = low overhead.COVERAGE_CORE: sysmon# Mirrors canonical: the coverage report skips narrowed runs, so# instrumenting one is pure overhead.- COV_ARGS: ${{ github.event_name == 'pull_request' && needs.select-tests.outputs.mode != 'selected' && '--cov=posthog --cov=ee --cov-config=.github/coverage-core.cfg --cov-report=xml:coverage-core.xml' || '' }}+ COV_ARGS: ${{ github.event_name == 'pull_request' && needs.turbo-discover.outputs.mode != 'selected' && '--cov=posthog --cov=ee --cov-config=.github/coverage-core.cfg --cov-report=xml:coverage-core.xml' || '' }}shell: 'signal-fanout bash --noprofile --norc -eo pipefail {0}'run: |unset GITHUB_TOKEN # reserved var injected by Depot CI; can't override via env: (see workflow env note)@@ -2361,8 +2149,8 @@ jobs: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 || '' }}CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA: ${{ matrix.new-events-schema && 'true' || 'false' }}- MODE: ${{ needs.select-tests.outputs.mode }}- TEMPORAL_FILES: ${{ needs.select-tests.outputs.temporal_files }}+ MODE: ${{ needs.turbo-discover.outputs.mode }}+ TEMPORAL_FILES: ${{ fromJSON(needs.turbo-discover.outputs.selection || '{}').temporal_files }}run: |unset GITHUB_TOKEN # reserved var injected by Depot CI; can't override via env: (see workflow env note)set +ediff --git a/.github/scripts/selected-django-shards.js b/.github/scripts/selected-django-shards.jsdeleted file mode 100644index 2db6f7b49d45..000000000000--- a/.github/scripts/selected-django-shards.js+++ /dev/null@@ -1,44 +0,0 @@-// Sizes the Django shards of a narrowed (test-selection) run in ci-backend.yml.-//-// Reads the shadow selector's JSON and applies turbo-discover's calculateShards-// to the selected tests' recorded seconds, so a narrowed segment gets the same-// per-shard budget as the full matrix — target wall clock, per-segment overhead,-// safety factor and cap all stay defined in turbo-discover.js. Sizing from the-// selection's own recorded seconds also keeps a skewed selection honest: picking-// the heavy half of a segment costs more shards than picking the light half.-//-// The floor is 1 instead of DJANGO_MIN_SHARDS: a narrow selection should stay a-// single job. Anything missing or unreadable degrades to 1 shard per segment,-// which is what the matrix assumed for every narrowed run before this existed.-//-// Usage: node selected-django-shards.js /tmp/selection.json-// Prints e.g. {"core":1,"poe":1,"temporal":6}--const fs = require('fs')-const path = require('path')-const { calculateShards, DJANGO_OVERHEAD_SECONDS_BY_SEGMENT } = require(path.join(__dirname, 'turbo-discover.js'))--// Selector segment key -> Django matrix segment name.-const MATRIX_NAME_BY_SEGMENT = { core: 'Core', poe: 'CorePOE', temporal: 'Temporal' }--function selectedShards(selection) {- const seconds = selection?.durations?.selected_seconds_by_segment ?? {}- const shards = {}- for (const [segment, matrixName] of Object.entries(MATRIX_NAME_BY_SEGMENT)) {- const overhead = DJANGO_OVERHEAD_SECONDS_BY_SEGMENT[matrixName]- shards[segment] = calculateShards(Number(seconds[segment]) || 0, overhead, 1)- }- return shards-}--module.exports = { selectedShards }--if (require.main === module) {- let selection = {}- try {- selection = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'))- } catch {- // Fall through to the 1-shard-per-segment default.- }- process.stdout.write(JSON.stringify(selectedShards(selection)))-}diff --git a/.github/scripts/selected-django-shards.test.js b/.github/scripts/selected-django-shards.test.jsdeleted file mode 100644index b460c61cc386..000000000000--- a/.github/scripts/selected-django-shards.test.js+++ /dev/null@@ -1,36 +0,0 @@-const { test } = require('node:test')-const assert = require('node:assert')-const { execFileSync } = require('node:child_process')-const path = require('path')--const { selectedShards } = require('./selected-django-shards.js')--test('applies the full-matrix budget to the selected seconds of each segment', () => {- // Work budget per shard is (target wall - segment overhead), same as the full- // matrix: Core ceil(5000 / (900 - 295)) = 9, Temporal ceil(900 / (900 - 182)) = 2.- // POE floors at 1 despite nothing selected.- const selection = { durations: { selected_seconds_by_segment: { core: 5000, poe: 0, temporal: 900 } } }- assert.deepStrictEqual(selectedShards(selection), { core: 9, poe: 1, temporal: 2 })-})--test('floors at one shard, below the full-run minimum of three', () => {- const selection = { durations: { selected_seconds_by_segment: { core: 30, poe: 30, temporal: 30 } } }- assert.deepStrictEqual(selectedShards(selection), { core: 1, poe: 1, temporal: 1 })-})--test('caps at the full-run maximum', () => {- const selection = { durations: { selected_seconds_by_segment: { core: 10_000_000 } } }- assert.strictEqual(selectedShards(selection).core, 50)-})--test('degrades to one shard per segment on missing or malformed selector output', () => {- for (const selection of [{}, { durations: {} }, { durations: { selected_seconds_by_segment: { core: 'wat' } } }]) {- assert.deepStrictEqual(selectedShards(selection), { core: 1, poe: 1, temporal: 1 })- }-})--test('the CLI prints the one-shard default when the selection file is unreadable', () => {- const script = path.join(__dirname, 'selected-django-shards.js')- const stdout = execFileSync('node', [script, '/nonexistent/selection.json'], { encoding: 'utf8' })- assert.deepStrictEqual(JSON.parse(stdout), { core: 1, poe: 1, temporal: 1 })-})diff --git a/.github/scripts/turbo-discover-selection.test.js b/.github/scripts/turbo-discover-selection.test.jsnew file mode 100644index 000000000000..eb0802275ba6--- /dev/null+++ b/.github/scripts/turbo-discover-selection.test.js@@ -0,0 +1,163 @@+// Run with: node --test .github/scripts/turbo-discover-selection.test.js+//+// Covers the backend test selection verdict: which Django tests run, how many shards+// they get, and which products stay in the matrix. All three read one decision, so a+// branch that regresses here silently changes what a PR is gated on.++const { test } = require('node:test')+const assert = require('node:assert/strict')+const { decideSelection, narrowedProducts, selectedShards } = require('./turbo-discover')++const segments = (extra) => ({ core: [], poe: [], temporal: [], compat: [], ...extra })++const selectionFixture = (extra) => ({+ changed_file_count: 3,+ ast: { full_run_reasons: [] },+ combined: {+ count: 2,+ products: [],+ segments: segments({ core: ['posthog/models/test_a.py'] }),+ },+ durations: {+ selected_seconds: 120,+ skipped_seconds: 4500,+ selected_seconds_by_segment: { core: 0, poe: 0, temporal: 0 },+ },+ ...extra,+})++// A legacy-diff PR that the selector narrowed — the case every branch below departs from.+const decide = (overrides) =>+ decideSelection({+ applies: true,+ disabled: false,+ draft: false,+ legacyChanged: true,+ runLegacy: true,+ runLegacyReason: 'legacy_changed',+ selection: selectionFixture(),+ ...overrides,+ })++test('a run that does not select leaves an empty mode for every consumer to default on', () => {+ for (const overrides of [{ applies: false }, { runLegacy: false, runLegacyReason: '' }]) {+ const decision = decide(overrides)+ assert.equal(decision.mode, '')+ assert.equal(decision.narrowed, null)+ assert.equal(decision.segment_shards, null)+ assert.equal(decision.changed_file_count, null)+ }+})++test('a ready PR falls back to the full matrices and a draft skips them', () => {+ assert.equal(decide({ disabled: true }).mode, 'full')+ assert.equal(decide({ disabled: true, draft: true }).mode, 'skip')+})++test('each distrusted input has its own reason, so telemetry can tell them apart', () => {+ const cases = [+ [{ disabled: true }, 'disabled'],+ [{ runLegacyReason: 'contract_cascade' }, 'untrusted'],+ [{ runLegacyReason: 'schema' }, 'untrusted'],+ [{ selection: null }, 'selector_error'],+ [{ selection: selectionFixture({ ast: { full_run_reasons: ['posthog/settings/base.py'] } }) }, 'full_run_requested'],+ [{ selection: selectionFixture({ combined: { count: 0, products: [], segments: segments() } }) }, 'empty_selection'],+ ]+ for (const [overrides, reason] of cases) {+ const decision = decide(overrides)+ assert.equal(decision.skip_reason, reason)+ assert.equal(decision.narrowed, false)+ assert.equal(decision.mode, 'full')+ assert.equal(decision.core_files, '')+ assert.equal(decision.run_poe, false)+ assert.equal(decision.run_temporal, false)+ }+})++test('the kill switch wins over a selection the selector was happy with', () => {+ // Ordered first on purpose: flipping it during an incident must not depend on why+ // the run would otherwise have been trusted.+ assert.equal(decide({ disabled: true, runLegacyReason: 'contract_cascade' }).skip_reason, 'disabled')+})++test('a fallback still reports the counts the selector produced', () => {+ const decision = decide({ selection: selectionFixture({ ast: { full_run_reasons: ['a', 'b'] } }) })+ assert.equal(decision.full_run_reasons_count, 2)+ assert.equal(decision.changed_file_count, 3)+ assert.equal(decision.selected_test_seconds, 120)+ assert.equal(decision.skipped_test_seconds, 4500)+})++test('a selected run hands each matrix leg its own file list', () => {+ const decision = decide({+ selection: selectionFixture({+ combined: {+ count: 4,+ products: [],+ segments: {+ core: ['posthog/models/test_a.py', 'posthog/clickhouse/test_b.py'],+ poe: ['posthog/clickhouse/test_b.py'],+ temporal: ['posthog/temporal/tests/test_c.py'],+ compat: ['posthog/clickhouse/test_b.py'],+ },+ },+ durations: { selected_seconds_by_segment: { core: 5000, poe: 0, temporal: 900 } },+ }),+ })++ assert.equal(decision.mode, 'selected')+ assert.equal(decision.narrowed, true)+ assert.equal(decision.skip_reason, '')+ assert.equal(decision.core_files, 'posthog/models/test_a.py posthog/clickhouse/test_b.py')+ assert.equal(decision.poe_files, 'posthog/clickhouse/test_b.py')+ assert.equal(decision.temporal_files, 'posthog/temporal/tests/test_c.py')+ assert.equal(decision.compat_files, 'posthog/clickhouse/test_b.py')+ assert.equal(decision.run_poe, true)+ assert.equal(decision.run_temporal, true)+ assert.deepEqual(decision.segment_shards, { core: 9, poe: 1, temporal: 2 })+})++test('a selection with no temporal file does not start the temporal leg', () => {+ const decision = decide()+ assert.equal(decision.mode, 'selected')+ assert.equal(decision.run_poe, false)+ assert.equal(decision.run_temporal, false)+ assert.equal(decision.temporal_files, '')+})++test('applies the full-matrix budget to the selected seconds of each segment', () => {+ // Work budget per shard is (target wall - segment overhead), same as the full+ // matrix: Core ceil(5000 / (900 - 295)) = 9, Temporal ceil(900 / (900 - 182)) = 2.+ // POE floors at 1 despite nothing selected.+ const selection = { durations: { selected_seconds_by_segment: { core: 5000, poe: 0, temporal: 900 } } }+ assert.deepEqual(selectedShards(selection), { core: 9, poe: 1, temporal: 2 })+})++test('shard counts floor at one, below the full-run minimum of three, and cap at the maximum', () => {+ const small = { durations: { selected_seconds_by_segment: { core: 30, poe: 30, temporal: 30 } } }+ assert.deepEqual(selectedShards(small), { core: 1, poe: 1, temporal: 1 })+ assert.equal(selectedShards({ durations: { selected_seconds_by_segment: { core: 10_000_000 } } }).core, 50)+})++test('shard counts degrade to one per segment on missing or malformed selector output', () => {+ for (const selection of [{}, { durations: {} }, { durations: { selected_seconds_by_segment: { core: 'wat' } } }]) {+ assert.deepEqual(selectedShards(selection), { core: 1, poe: 1, temporal: 1 })+ }+})++const products = ['batch-exports', 'logs', 'signals', 'tasks', 'warehouse-sources']++test('keeps the must-run set plus what the selector reached, in product directory form', () => {+ const selection = { combined: { products: ['warehouse_sources', 'logs'] } }+ assert.deepEqual(narrowedProducts(products, ['tasks'], selection), ['logs', 'tasks', 'warehouse-sources'])+})++test('a selection that reaches no product runs only the must-run set, which may be nothing', () => {+ assert.deepEqual(narrowedProducts(products, ['signals'], { combined: { products: [] } }), ['signals'])+ assert.deepEqual(narrowedProducts(products, [], { combined: { products: [] } }), [])+})++test('products outside the matrix are ignored', () => {+ const selection = { combined: { products: ['not_a_product'] } }+ assert.deepEqual(narrowedProducts(products, ['gone'], selection), [])+})diff --git a/.github/scripts/turbo-discover.js b/.github/scripts/turbo-discover.jsindex 6f40a59d69fd..5c2d78a02a74 100644--- a/.github/scripts/turbo-discover.js+++ b/.github/scripts/turbo-discover.js@@ -14,11 +14,23 @@// Durations come from .test_durations (maintained by pytest-split).// DEDICATED_BUCKET_PRODUCTS opt out of grouping and always run alone.//+// Backend test selection: the selector's output (SELECTION_JSON) decides which+// Django tests run and, on a legacy diff, which products stay in the matrix. One+// verdict feeds both, so the two matrices can never disagree about whether the+// selection is trustworthy.+//// Input: LEGACY_CHANGED env var ("true"/"false")// SCHEMA_CHANGED env var ("true"/"false") — when set and LEGACY_CHANGED// is false, schema-impact.js narrows the matrix to products that// depend on the affected posthog.schema types.-// Output: JSON on stdout: { matrix, run_legacy, django_shards }+// SELECTION_JSON — path to the backend test selector's output, empty when+// it did not run or failed.+// SELECTION_APPLIES ("true"/"false") — whether this run is one that selects+// at all; false leaves the Django matrix alone.+// SELECTION_DISABLED ("true"/"false") — the DISABLE_BACKEND_TEST_SELECTION+// kill switch.+// PR_DRAFT ("true"/"false") — what an untrusted selection falls back to.+// Output: JSON on stdout: { matrix, run_legacy, django_shards, selection }// Diagnostics on stderrconst { execFileSync } = require('child_process')@@ -193,6 +205,21 @@ function affectedArgs(taskName) {return args}+// Turbo's affected query for one task, null when it fails. The caller decides whether+// that is fatal (a products-only diff has nothing else to go on) or only disables the+// narrowed product matrix on a legacy diff.+function queryAffectedTasks(taskName) {+ try {+ return parseAffectedTasks(runTurbo(affectedArgs(taskName)))+ } catch (e) {+ console.error(`::warning::turbo affected query for ${taskName} failed: ${e.message}`)+ if (e.stderr) {+ console.error(e.stderr.toString().slice(0, 1000))+ }+ return null+ }+}+function logAffectedReasons(label, tasks) {const reasons = {}for (const task of tasks) {@@ -430,10 +457,82 @@ function loadTachModuleGraph() {}}+// Products that transitively depend on `products` per tach.toml, or null when the+// graph cannot be read. Callers treat null as "unknown dependents" and widen.+function tachDependentProducts(products, allProductSet) {+ const tachGraph = loadTachModuleGraph()+ if (tachGraph === null) {+ return null+ }+ return tachDependents(products, tachGraph).filter((p) => allProductSet.has(p))+}++// Products a schema change reaches, [] for a purely additive change, or null when+// the schema diff is unavailable and every product has to run.+function schemaAffectedProducts() {+ const impact = analyzeSchemaImpact({ scmBase: process.env.TURBO_SCM_BASE })+ console.error(`Schema impact: ${JSON.stringify({ kind: impact.kind, counts: impact.counts, reason: impact.reason })}`)+ if (impact.kind === 'fallback') {+ return null+ }+ if (impact.kind !== 'impacting') {+ console.error('Schema change is purely additive — no extra products needed')+ return []+ }+ console.error(`Schema-affected products: ${JSON.stringify(impact.affectedProducts)}`)+ if (impact.wildcardProducts && impact.wildcardProducts.length > 0) {+ console.error(+ `Products with unresolved schema module imports (always tested): ${JSON.stringify(impact.wildcardProducts)}`+ )+ }+ return impact.affectedProducts+}++// The products a legacy diff must test whatever the backend test selector reached: the+// ones Turbo saw change, their tach dependents, and the ones a schema change reaches.+// Null when any of that is unknowable, which callers must treat as "do not narrow".+function legacyMustRunProducts(affectedTasks, allProductSet, schemaChanged) {+ const affected = getAffectedTaskProducts(affectedTasks)+ const dependents = tachDependentProducts(affected, allProductSet)+ if (dependents === null) {+ return null+ }+ const schemaProducts = schemaChanged ? schemaAffectedProducts() : []+ if (schemaProducts === null) {+ return null+ }+ return [...new Set([...affected, ...dependents, ...schemaProducts])]+}++// The backend test selector's output (tools/snob_backend_test_selection_shadow.py), or+// null when it is absent or unreadable.+function loadSelection(path) {+ if (!path) {+ return null+ }+ try {+ return JSON.parse(fs.readFileSync(path, 'utf-8'))+ } catch (e) {+ console.error(`::warning::Could not read the backend test selection at ${path} (${e.message}) — the full matrices will run`)+ return null+ }+}++// Products to test on a legacy diff once the selection is trusted: the must-run set+// plus the products the selector reached through the import graph. Callers narrow only+// on a `selected` verdict, so the trust rules live in decideSelection, not here.+function narrowedProducts(products, mustRunProducts, selection) {+ const selected = ((selection.combined && selection.combined.products) || []).map(moduleToProduct)+ const keep = new Set([...mustRunProducts, ...selected])+ console.error(`Products reached by the backend test selector: ${JSON.stringify(selected)}`)+ return products.filter((p) => keep.has(p))+}+// Strips non-finite values so a single corrupted entry can't NaN-poison the// matrix (Math.ceil(NaN) silently propagates through sort/compare, making a// product vanish from packing without an error). Returns null when the file is// absent or is not a JSON object.+function loadDurationsFile(file) {let parsedtry {@@ -728,6 +827,142 @@ function calculateShards(totalWorkSeconds, overheadSeconds, minShards = DJANGO_Mreturn Math.max(minShards, Math.min(DJANGO_MAX_SHARDS, shards))}+// Selector segment key -> Django matrix segment name.+const MATRIX_NAME_BY_SEGMENT = { core: 'Core', poe: 'CorePOE', temporal: 'Temporal' }++// Shards per segment for a narrowed run: the full matrix's per-shard budget applied to+// the selected tests' recorded seconds, so a wide selection spreads over several jobs+// instead of running to the job timeout in one. Sizing from the selection's own seconds+// keeps a skewed selection honest — picking the heavy half of a segment costs more+// shards than picking the light half. The floor is 1 rather than DJANGO_MIN_SHARDS: a+// narrow selection should stay a single job. Anything missing degrades to 1.+function selectedShards(selection) {+ const seconds = selection?.durations?.selected_seconds_by_segment ?? {}+ const shards = {}+ for (const [segment, matrixName] of Object.entries(MATRIX_NAME_BY_SEGMENT)) {+ const overhead = DJANGO_OVERHEAD_SECONDS_BY_SEGMENT[matrixName]+ shards[segment] = calculateShards(Number(seconds[segment]) || 0, overhead, 1)+ }+ return shards+}++// Counts the telemetry reports, whether or not the selection was used. Null throughout+// when the selector produced nothing to read.+function selectionMetrics(selection) {+ return {+ changed_file_count: selection?.changed_file_count ?? null,+ selected_test_count: selection?.combined?.count ?? null,+ full_run_reasons_count: selection ? (selection.ast?.full_run_reasons ?? []).length : null,+ selected_test_seconds: selection?.durations?.selected_seconds ?? null,+ skipped_test_seconds: selection?.durations?.skipped_seconds ?? null,+ }+}++// What a run with nothing selected hands each matrix leg.+function emptySegments() {+ return {+ core_files: '',+ poe_files: '',+ temporal_files: '',+ compat_files: '',+ run_poe: false,+ run_temporal: false,+ segment_shards: null,+ }+}++// An untrusted selection runs the full matrices on a ready PR and skips them on a draft,+// which is the pre-selection draft behavior: a draft has a later ready run to defer to,+// and skipping is the cheaper of the two mistakes.+function fallbackSelection(fallbackMode, reason, selection) {+ console.error(`Backend test selection not used (${reason}) — Django matrix mode=${fallbackMode}`)+ return { mode: fallbackMode, narrowed: false, skip_reason: reason, ...emptySegments(), ...selectionMetrics(selection) }+}++// Which Django tests this run should execute, and whether the product matrix may narrow.+// Pure: every input is an argument, so each branch is unit-tested rather than inferred+// from a workflow run.+// applies this run selects at all (a PR, off the merge queue, no force label)+// disabled the DISABLE_BACKEND_TEST_SELECTION kill switch+// draft fall back by skipping rather than by running everything+// legacyChanged the paths filter saw an edit under posthog/ or ee/+// runLegacy whether the Django suite runs, and why+// selection the selector's parsed output, null when it did not produce one+function decideSelection({ applies, disabled, draft, legacyChanged, runLegacy, runLegacyReason, selection }) {+ if (!applies || runLegacy === false) {+ // Nothing to narrow: either the event never selects, or the Django suite is+ // skipped outright. An empty mode leaves every consumer on its own default.+ return { mode: '', narrowed: null, skip_reason: '', ...emptySegments(), ...selectionMetrics(null) }+ }+ const fallbackMode = draft ? 'skip' : 'full'+ if (disabled) {+ // Its own reason string, so flipping the kill switch during an incident stays+ // distinguishable from a genuine cascade in the selection telemetry.+ return fallbackSelection(fallbackMode, 'disabled', selection)+ }+ if (runLegacy && runLegacyReason !== 'legacy_changed') {+ // Legacy impact was inferred from a product, contract, or schema change rather+ // than seen as a direct edit. The diff-based selector cannot see that cascade, so+ // its subset would be incomplete. A direct legacy edit is the selector's home+ // turf and is deliberately trusted — its own FULL_RUN_PATTERNS decide when a+ // legacy change is too broad to narrow.+ return fallbackSelection(fallbackMode, 'untrusted', selection)+ }+ if (!selection) {+ return fallbackSelection(fallbackMode, 'selector_error', selection)+ }+ const fullRunReasons = selection.ast?.full_run_reasons ?? []+ if (fullRunReasons.length > 0) {+ console.error(`Selector requested a full run:\n ${fullRunReasons.join('\n ')}`)+ return fallbackSelection(fallbackMode, 'full_run_requested', selection)+ }+ const segments = selection.combined?.segments ?? {}+ const core = segments.core ?? []+ const poe = segments.poe ?? []+ const temporal = segments.temporal ?? []+ const compat = segments.compat ?? []+ if (legacyChanged && core.length === 0 && temporal.length === 0) {+ // A diff that touched legacy code but selected no Django test at all means the+ // selector had no rule for it, not that there is nothing to run — a non-Python+ // legacy file (C++ parser sources, a JSON config) reaches no import edge.+ // Narrowing to zero would silently gate on nothing. FULL_RUN_PATTERNS covers the+ // known cases; this catches the ones added to the `legacy` paths filter and+ // forgotten there. Products-only diffs legitimately select nothing and are not legacy.+ return fallbackSelection(fallbackMode, 'empty_selection', selection)+ }+ console.error(`Selected: ${core.length} core, ${poe.length} POE-eligible, ${temporal.length} temporal, ${compat.length} compat`)+ return {+ mode: 'selected',+ narrowed: true,+ skip_reason: '',+ core_files: core.join(' '),+ poe_files: poe.join(' '),+ temporal_files: temporal.join(' '),+ compat_files: compat.join(' '),+ run_poe: poe.length > 0,+ run_temporal: temporal.length > 0,+ segment_shards: selectedShards(selection),+ ...selectionMetrics(selection),+ }+}++// The run identity the selection telemetry event carries, from the runner's own env.+function runContext() {+ let prNumber = null+ try {+ prNumber = JSON.parse(fs.readFileSync(process.env.GITHUB_EVENT_PATH, 'utf-8')).pull_request?.number ?? null+ } catch {+ // Not a GitHub run, or no event payload: the fields stay null.+ }+ return {+ event_type: process.env.GITHUB_EVENT_NAME ?? null,+ branch: process.env.GITHUB_HEAD_REF || process.env.GITHUB_REF_NAME || null,+ sha: process.env.GITHUB_SHA ?? null,+ pr_number: prNumber,+ run_id: process.env.GITHUB_RUN_ID ?? null,+ }+}+function buildDjangoShards(durations, ranNodeIds = {}) {const result = {}for (const [segment] of Object.entries(DJANGO_SEGMENTS)) {@@ -809,9 +1044,11 @@ function buildMatrix(products, durations, productsScaled = false) {return matrix}-// Exported for unit tests, plus the Django sizing pieces that-// selected-django-shards.js reuses so narrowed runs share one budget.+// Exported for unit tests.module.exports = {+ narrowedProducts,+ decideSelection,+ selectedShards,calculateShards,pruneDeadDurations,getSegmentDuration,@@ -839,15 +1076,12 @@ if (require.main === module) {const legacyChanged = process.env.LEGACY_CHANGED === 'true'const schemaChanged = process.env.SCHEMA_CHANGED === 'true'+const selection = loadSelection(process.env.SELECTION_JSON)let allTestTasks, affectedTestTasks, affectedContractTasks, contractTaskstry {allTestTasks = parseTurboTasks(runTurbo(['run', 'backend:test', '--dry-run=json']))if (!legacyChanged) {- console.error(`Turbo affected base: ${process.env.TURBO_SCM_BASE || '(default)'}`)- console.error(`Turbo affected head: ${process.env.TURBO_SCM_HEAD || '(default)'}`)- affectedTestTasks = parseAffectedTasks(runTurbo(affectedArgs('backend:test')))- affectedContractTasks = parseAffectedTasks(runTurbo(affectedArgs('backend:contract-check')))contractTasks = parseTurboTasks(runTurbo(['run', 'backend:contract-check', '--dry-run=json']))}} catch (e) {@@ -857,6 +1091,20 @@ try {}process.exit(1)}+console.error(`Turbo affected base: ${process.env.TURBO_SCM_BASE || '(default)'}`)+console.error(`Turbo affected head: ${process.env.TURBO_SCM_HEAD || '(default)'}`)+if (!legacyChanged) {+ affectedTestTasks = queryAffectedTasks('backend:test')+ affectedContractTasks = queryAffectedTasks('backend:contract-check')+ if (affectedTestTasks === null || affectedContractTasks === null) {+ console.error('turbo discovery failed')+ process.exit(1)+ }+} else if (process.env.SELECTION_JSON) {+ // A legacy diff with a backend test selection still asks which products changed:+ // that set seeds the narrowed product matrix. A failed query only disables it.+ affectedTestTasks = queryAffectedTasks('backend:test')+}const allProducts = getAllProducts(allTestTasks)const allProductSet = new Set(allProducts)@@ -866,12 +1114,19 @@ let runLegacy// (which the diff-based selector handles) from an inferred product->legacy cascade// (which it cannot see). Empty when runLegacy is false.let runLegacyReason = ''+// On a legacy diff the full product matrix is the fallback. Given a backend test+// selection, the matrix narrows to these products plus the ones the selector reached+// through the import graph. Null when that narrowing is not safe.+let mustRunProducts = nullif (legacyChanged) {console.error('Legacy code changed — testing all products')products = allProductsrunLegacy = truerunLegacyReason = 'legacy_changed'+ if (affectedTestTasks) {+ mustRunProducts = legacyMustRunProducts(affectedTestTasks, allProductSet, schemaChanged)+ }} else {const isolatedProducts = getIsolatedProducts(contractTasks)const affectedProducts = getAffectedTaskProducts(affectedTestTasks)@@ -899,15 +1154,14 @@ if (legacyChanged) {console.error(`Isolated product contracts changed: ${JSON.stringify(affectedContracts)} — Django will run`)runLegacy = truerunLegacyReason = 'contract_cascade'- const tachGraph = loadTachModuleGraph()- if (tachGraph === null) {+ const dependents = tachDependentProducts(affectedContracts, allProductSet)+ if (dependents === null) {// Fail toward over-testing, like the quarantine loaders above: without the// graph we cannot know which products depend on the changed contract, and// guessing "none" silently recreates the gap this cascade exists to close.console.error('Dependent cascade unavailable — testing all products rather than risk skipping a dependent')products = allProducts} else {- const dependents = tachDependents(affectedContracts, tachGraph).filter((p) => allProductSet.has(p))if (dependents.length > 0) {console.error(`Dependent products cascaded in via tach.toml: ${JSON.stringify(dependents)} (transitively depend on ${JSON.stringify(affectedContracts)})`@@ -927,29 +1181,16 @@ if (legacyChanged) {}if (schemaChanged) {- const impact = analyzeSchemaImpact({ scmBase: process.env.TURBO_SCM_BASE })- console.error(`Schema impact: ${JSON.stringify({ kind: impact.kind, counts: impact.counts, reason: impact.reason })}`)- if (impact.kind === 'fallback') {- console.error(`Schema diff unavailable (${impact.reason}) — falling back to all products + Django`)+ const schemaProducts = schemaAffectedProducts()+ if (schemaProducts === null) {+ console.error('Schema diff unavailable — falling back to all products + Django')products = allProducts- runLegacy = true- runLegacyReason = 'schema'} else {- if (impact.kind === 'impacting') {- console.error(`Schema-affected products: ${JSON.stringify(impact.affectedProducts)}`)- if (impact.wildcardProducts && impact.wildcardProducts.length > 0) {- console.error(- `Products with unresolved schema module imports (always tested): ${JSON.stringify(impact.wildcardProducts)}`- )- }- products = [...new Set([...products, ...impact.affectedProducts])].sort()- } else {- console.error('Schema change is purely additive — no extra products needed')- }- // Core (posthog/, ee/, etc.) imports schema heavily; always run Django on schema changes.- runLegacy = true- runLegacyReason = 'schema'+ products = [...new Set([...products, ...schemaProducts])].sort()}+ // Core (posthog/, ee/, etc.) imports schema heavily; always run Django on schema changes.+ runLegacy = true+ runLegacyReason = 'schema'}}@@ -974,6 +1215,7 @@ if (quarantinedProducts.size > 0) {// never sees .test_quarantine.json as a product input). Django's side of the same// invariant is carried by FULL_RUN_PATTERNS in the backend test selector, since a// legacy diff no longer implies a full Django run on its own.+const liftedProducts = []if (process.env.TURBO_SCM_BASE) {const baseQuarantined = loadBaseQuarantinedSkipProducts(process.env.TURBO_SCM_BASE, todayISO)const allProductSet = new Set(allProducts)@@ -983,10 +1225,32 @@ if (process.env.TURBO_SCM_BASE) {if (!allProductSet.has(name) || productSet.has(name)) {continue}console.error(`Quarantine lifted for '${name}' since ${process.env.TURBO_SCM_BASE} — forced into matrix`)products.push(name)+ liftedProducts.push(name)}products.sort()}+const selectionDecision = decideSelection({+ applies: process.env.SELECTION_APPLIES === 'true',+ disabled: process.env.SELECTION_DISABLED === 'true',+ draft: process.env.PR_DRAFT === 'true',+ legacyChanged,+ runLegacy,+ runLegacyReason,+ selection,+})++// Narrow the legacy-diff matrix after every drop and lift above, so narrowing can only+// remove products. The matrix is then packed from the narrowed list.+const productCountBeforeNarrowing = products.length+let productMatrixNarrowed = false+if (mustRunProducts !== null && selectionDecision.mode === 'selected') {+ const mustRun = [...new Set([...mustRunProducts, ...liftedProducts])].sort()+ console.error(`Products that must run if the matrix is narrowed: ${JSON.stringify(mustRun)}`)+ products = narrowedProducts(products, mustRun, selection)+ productMatrixNarrowed = true+}+console.error(`Products to test: ${JSON.stringify(products)}`)console.error(`Run legacy (Django): ${runLegacy}${runLegacyReason ? ` (${runLegacyReason})` : ''}`)@@ -1002,11 +1266,39 @@ const ranNodeIds = loadRanNodeIds()console.error('\nDjango shard calculation:')const djangoShards = buildDjangoShards(durations, ranNodeIds)+const { mode, core_files, poe_files, temporal_files, compat_files, run_poe, run_temporal, segment_shards, ...metrics } =+ selectionDecisionconst result = {matrix: buildMatrix(products, durations, productsScaled),run_legacy: runLegacy,run_legacy_reason: runLegacyReason,django_shards: djangoShards,+ // What the Django matrix jobs read, as one job output; segment_shards stays a JSON+ // string because build_django_matrix parses it itself.+ selection: {+ mode,+ core_files,+ poe_files,+ temporal_files,+ compat_files,+ run_poe,+ run_temporal,+ segment_shards: segment_shards ? JSON.stringify(segment_shards) : '',+ },+ // The posthog-ci-test-selection event, ready for the capture-test-selection job.+ telemetry: {+ suite: 'backend',+ mode,+ run_poe,+ run_temporal,+ ...metrics,+ run_legacy: runLegacy,+ run_legacy_reason: runLegacyReason,+ product_matrix_narrowed: productMatrixNarrowed,+ product_count: products.length,+ product_count_full: productCountBeforeNarrowing,+ ...runContext(),+ },}// eslint-disable-next-line no-consoleprocess.stdout.write(JSON.stringify(result) + '\n')diff --git a/.github/scripts/turbo-discover.test.js b/.github/scripts/turbo-discover.test.jsindex 301d982be569..69776f696934 100644--- a/.github/scripts/turbo-discover.test.js+++ b/.github/scripts/turbo-discover.test.js@@ -3,9 +3,8 @@// Pins turbo-discover's DJANGO_SEGMENTS table to the Django pytest invocations// in ci-backend.yml. The table sizes the shards each segment gets, so a segment// listing paths the workflow no longer runs (or missing ones it does) budgets-// wall time for a run that never happens, and the select-tests classify step-// routes selected files to a matrix leg that ignores them. Both workflow copies-// are read: the Depot mirror runs the same matrix and drifts on its own.+// wall time for a run that never happens. Both workflow copies are read: the+// Depot mirror runs the same matrix and drifts on its own.//// Reads the workflow rather than a fixture on purpose — the workflow is the one// side that can drift, and there is nothing else to compare the table against.@@ -68,45 +67,6 @@ function parseTemporalTargets(text) {return invocation[1].split(/\s+/)}-// Each classify arm is `pattern|pattern)` followed by its body up to `;;`. The-// body says which segment the arm feeds; an arm that appends nothing is a path-// the Core invocation ignores.-function parseClassifyArms(block) {- const arms = { core: [], poe: [], temporal: [], ignored: [] }- let patterns = null- let body = ''- for (const line of block.split('\n')) {- const trimmed = line.trim()- if (trimmed.startsWith('#')) {- continue- }- if (patterns === null) {- if (trimmed.endsWith(')')) {- patterns = trimmed.slice(0, -1).split('|')- }- continue- }- if (trimmed !== ';;') {- body += trimmed- continue- }- const prefixes = patterns.map((pattern) => pattern.replace(/\*$/, ''))- if (body.includes('temporal+=')) {- arms.temporal.push(...prefixes)- } else if (body.includes('poe+=')) {- arms.poe.push(...prefixes)- } else if (body.includes('core+=')) {- arms.core.push(...prefixes)- } else {- arms.ignored.push(...prefixes)- }- patterns = null- body = ''- }- assert.ok(arms.temporal.length && arms.poe.length && arms.core.length, 'classify arms not parsed')- return arms-}-for (const workflow of WORKFLOWS) {const text = fs.readFileSync(path.join(REPO_ROOT, workflow), 'utf8')const core = parseCoreStep(text)@@ -122,28 +82,12 @@ for (const workflow of WORKFLOWS) {assert.deepEqual(sorted(DJANGO_SEGMENTS[segment].exclude), sorted(paths.exclude.map(toPrefix)))})}-- // The classify step is the third copy of the partition: it routes each- // selected file to a matrix leg, so an arm naming a path the pytest- // invocation does not run sends tests to a leg that ignores them.- test(`the select-tests classify arms match the segments in ${workflow}`, () => {- const arms = parseClassifyArms(section(text, 'case "$f" in', 'esac'))-- assert.deepEqual(sorted(arms.temporal), sorted(DJANGO_SEGMENTS.Temporal.include))- assert.deepEqual(sorted(arms.poe), sorted(DJANGO_SEGMENTS.CorePOE.include))- assert.deepEqual(sorted(arms.core), sorted(DJANGO_SEGMENTS.Core.include))- // The temporal arm comes first, so the paths it claims from inside the- // Core scope are excluded from Core alongside the ignored arm's.- const claimedFromCore = arms.temporal.filter((prefix) =>- DJANGO_SEGMENTS.Core.include.some((include) => prefix.startsWith(include))- )- assert.deepEqual(sorted([...arms.ignored, ...claimedFromCore]), sorted(DJANGO_SEGMENTS.Core.exclude))- })}-// The backend test selector is the fourth copy of the partition: it routes each-// selected test file to a segment so the verdict can say which matrix leg missed-// it. Its prefix tuples are plain literals, read here the same way the workflow is.+// The backend test selector is the third copy of the partition: it routes each+// selected test file to a segment, so a prefix it no longer shares with the pytest+// invocation sends selected tests to a leg that ignores them. Its prefix tuples are+// plain literals, read here the same way the workflow is.const SELECTOR = 'tools/snob_backend_test_selection_shadow.py'function pythonTuple(text, name) {diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.ymlindex 263bb47284b6..937acb18ff30 100644--- a/.github/workflows/ci-backend.yml+++ b/.github/workflows/ci-backend.yml@@ -17,6 +17,8 @@ on:# for fast feedback, draft or ready. When selection can't be trusted, a# ready PR falls back to the full matrices and a draft skips them instead,# deferring to its ready run. turbo-tests (product tests) still skip drafts.+ # On a legacy diff the product matrix is narrowed the same way: the products the+ # selector reached plus the ones Turbo saw change (see turbo-discover).# The merge queue's trunk-merge/** run and master pushes always run the full# matrices, and the queue run is what actually gates master. To force the# full matrices on a PR, add the `run-ci-backend` label. Cheap checks still@@ -401,6 +403,12 @@ jobs:runs-on: depot-ubuntu-24.04timeout-minutes: 20name: Discover product tests+ env:+ # Whether this run selects backend tests at all: a PR, off the merge queue's+ # trunk-merge/** run (that run is the merge gate and stays full), and without+ # the run-ci-backend label. turbo-discover.js reads it too, so a run that never+ # selects reports an empty mode rather than a selector error.+ SELECTION_APPLIES: ${{ github.event_name == 'pull_request' && !startsWith(github.head_ref, 'trunk-merge/') && !contains(github.event.pull_request.labels.*.name, 'run-ci-backend') && needs.changes.outputs.backend == 'true' }}outputs:run_legacy: ${{ steps.discover.outputs.run_legacy }}run_legacy_reason: ${{ steps.discover.outputs.run_legacy_reason }}@@ -409,6 +417,13 @@ jobs:schema_migrations_key: ${{ steps.schema-key.outputs.migrations_key }}schema_prefix_key: ${{ steps.schema-key.outputs.prefix_key }}django_shards: ${{ steps.discover.outputs.django_shards }}+ # Which Django tests this PR runs. Empty mode = this run does not select.+ mode: ${{ steps.discover.outputs.mode }}+ # The rest of that decision (segment file lists, run_poe, run_temporal,+ # segment_shards) as one JSON object; consumers read it with fromJSON.+ selection: ${{ steps.discover.outputs.selection }}+ # The posthog-ci-test-selection event properties, as one JSON object.+ telemetry: ${{ steps.discover.outputs.telemetry }}steps:- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2@@ -572,12 +587,57 @@ jobs:# GitHub allows re-runs for 30 days.retention-days: 30+ # The backend test selector picks the Django tests this PR needs, and on a legacy+ # diff its product list narrows the product matrix too: turbo-discover.js cannot+ # see which products a posthog/ or ee/ edit reaches, and the selector can, because+ # it follows the import graph into products/. Both matrices read one verdict, so+ # they can never disagree about whether the selection is trustworthy.+ # Only on a legacy diff: turbo-discover.js trusts the selection only when the paths+ # filter saw a legacy edit, and falls back without a selector run otherwise. The+ # DISABLE_BACKEND_TEST_SELECTION kill switch skips the run too; the script still+ # reports the `disabled` reason from its own env.+ - name: Install uv+ # Optional setup: a failure here must fall back to the full matrices like a+ # selector failure does, not fail the job that gates every test job.+ continue-on-error: true+ if: env.SELECTION_APPLIES == 'true' && needs.changes.outputs.legacy == 'true' && vars.DISABLE_BACKEND_TEST_SELECTION != 'true'+ uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0+ with:+ version: '0.11.28'++ - name: Run the backend test selector+ id: select+ # A selector failure or hang must not fail this job, which gates every test job+ # in the workflow — turbo-discover.js falls back to the full matrices instead.+ # The step timeout bounds a hang well inside the job's, so the fallback still+ # reaches the matrices rather than taking the whole job down with it.+ continue-on-error: true+ timeout-minutes: 8+ if: env.SELECTION_APPLIES == 'true' && needs.changes.outputs.legacy == 'true' && vars.DISABLE_BACKEND_TEST_SELECTION != 'true'+ env:+ BASE_REF: ${{ github.event.pull_request.base.ref }}+ shell: bash+ run: |+ set -euo pipefail+ uv run tools/snob_backend_test_selection_shadow.py \+ --base-ref "origin/$BASE_REF" \+ > /tmp/selection.json+- name: Discover products to testid: discoverenv:# On pushes to master, always run everything.# On PRs, use the path filter to detect legacy changes.LEGACY_CHANGED: ${{ github.event_name != 'pull_request' || needs.changes.outputs.legacy }}+ # Empty when the selector did not run or failed, which falls back to the+ # full matrices on a ready PR and skips them on a draft.+ SELECTION_JSON: ${{ steps.select.outcome == 'success' && '/tmp/selection.json' || '' }}+ # Kill switch — set the DISABLE_BACKEND_TEST_SELECTION repo variable to put+ # every PR back on the full matrices without a code change.+ SELECTION_DISABLED: ${{ vars.DISABLE_BACKEND_TEST_SELECTION || 'false' }}+ # A draft has a later ready run to defer to, so an untrusted selection skips+ # the heavy matrices there instead of running all of them.+ PR_DRAFT: ${{ github.event.pull_request.draft }}SCHEMA_CHANGED: ${{ github.event_name != 'pull_request' || needs.changes.outputs.schema }}TURBO_SCM_BASE: ${{ github.event_name == 'pull_request' && format('origin/{0}', github.event.pull_request.base.ref) || '' }}TURBO_SCM_HEAD: ${{ github.sha }}@@ -593,278 +653,12 @@ jobs:echo "run_legacy=$(echo "$RESULT" | jq -r '.run_legacy')" >> $GITHUB_OUTPUTecho "run_legacy_reason=$(echo "$RESULT" | jq -r '.run_legacy_reason // empty')" >> "$GITHUB_OUTPUT"echo "django_shards=$(echo "$RESULT" | jq -c '.django_shards // empty')" >> $GITHUB_OUTPUT-- # Pick which Django tests to run on a PR. Both drafts and ready PRs get the- # snob-selected subset; the difference is what happens when selection can't be- # trusted (product->legacy cascade, turbo-discover or selector failure, a- # selector full-run signal). A ready PR then runs the full matrices, a draft- # skips them and defers to its ready run — the pre-selection draft behavior.- # Master pushes and the queue's trunk-merge/** run never reach this job, so- # what gates master is still a full run.- # hogli-lint: not-a-required-gate - selects PR coverage and emits no required check.- select-tests:- name: Select tests- needs: [changes, turbo-discover]- # Pushes 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 PR.- # Trunk's merge-queue branches open as draft PRs, but their run IS the- # merge gate, so they must never get the narrowed selection.- # run_legacy=false means the django job below is skipped outright, so there- # is no matrix left to narrow — only the exact string skips, which keeps an- # empty output (turbo-discover skipped or failed) on the selecting path.- if: |- github.event_name == 'pull_request' &&- !startsWith(github.head_ref, 'trunk-merge/') &&- !contains(github.event.pull_request.labels.*.name, 'run-ci-backend') &&- needs.changes.outputs.backend == 'true' &&- needs.turbo-discover.outputs.run_legacy != 'false'- # Depot, like every other pre-job this one shares the Django critical path with.- # It gates every PR now, not just drafts, so its checkout speed is on the wall.- runs-on: depot-ubuntu-24.04- # Headroom over checkout + uv + the selector's whole-tree parse. A timeout here- # leaves MODE empty, which on a ready PR means the full matrix — the worst case.- timeout-minutes: 10- 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 }}- compat_files: ${{ steps.classify.outputs.compat_files }}- run_poe: ${{ steps.classify.outputs.run_poe }}- run_temporal: ${{ steps.classify.outputs.run_temporal }}- # Telemetry for the capture-test-selection job below.- narrowed: ${{ steps.classify.outputs.narrowed }}- skip_reason: ${{ steps.classify.outputs.skip_reason }}- changed_file_count: ${{ steps.classify.outputs.changed_file_count }}- selected_test_count: ${{ steps.classify.outputs.selected_test_count }}- full_run_reasons_count: ${{ steps.classify.outputs.full_run_reasons_count }}- run_legacy: ${{ steps.fallback.outputs.run_legacy }}- run_legacy_reason: ${{ steps.fallback.outputs.run_legacy_reason }}- turbo_result: ${{ steps.fallback.outputs.turbo_result }}- selected_test_seconds: ${{ steps.classify.outputs.selected_test_seconds }}- skipped_test_seconds: ${{ steps.classify.outputs.skipped_test_seconds }}- # Shards per segment for a narrowed run; build_django_matrix reads them as-is.- segment_shards: ${{ steps.classify.outputs.segment_shards }}- steps:- # Ahead of the checkout on purpose: this reads job outputs only, and when it- # decides selection can't be trusted, cloning the repo would just delay the- # full matrix that is about to run instead.- - name: Decide whether selection can be trusted- id: fallback- env:- RUN_LEGACY: ${{ needs.turbo-discover.outputs.run_legacy }}- RUN_LEGACY_REASON: ${{ needs.turbo-discover.outputs.run_legacy_reason }}- TURBO_RESULT: ${{ needs.turbo-discover.result }}- DISABLED: ${{ vars.DISABLE_BACKEND_TEST_SELECTION || 'false' }}- shell: bash- run: |- set -euo pipefail- skip=false- reason=untrusted- if [[ "$DISABLED" == "true" ]]; then- # Kill switch — set the DISABLE_BACKEND_TEST_SELECTION repo variable to- # put every PR back on the full matrices without a code change. Its own- # reason string, so flipping it during an incident stays distinguishable- # from a genuine cascade in the selection telemetry.- skip=true- reason=disabled- elif [[ "$RUN_LEGACY" == "true" && "$RUN_LEGACY_REASON" != "legacy_changed" ]]; then- # turbo-discover inferred legacy impact from a product, contract, or- # schema change rather than seeing a direct edit. The diff-based selector- # cannot see that cascade, so its subset would be incomplete.- # A direct legacy edit is the selector's home turf and is deliberately not- # untrusted here — the selector's own FULL_RUN_PATTERNS decide when a- # legacy change is too broad to narrow.- skip=true- elif [[ "$TURBO_RESULT" != "success" && "$TURBO_RESULT" != "skipped" ]]; then- # Conservative — turbo-discover failed.- skip=true- fi- echo "skip=$skip" >> "$GITHUB_OUTPUT"- echo "reason=$reason" >> "$GITHUB_OUTPUT"- # Surface the raw inputs too, so the telemetry can audit the decision.- echo "run_legacy=${RUN_LEGACY:-}" >> "$GITHUB_OUTPUT"- echo "run_legacy_reason=${RUN_LEGACY_REASON:-}" >> "$GITHUB_OUTPUT"- echo "turbo_result=${TURBO_RESULT:-}" >> "$GITHUB_OUTPUT"-- - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2- if: steps.fallback.outputs.skip == 'false'- with:- fetch-depth: 1000- filter: blob:none-- - name: Install uv- if: steps.fallback.outputs.skip == 'false'- uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0- with:- version: '0.11.28'-- - 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 the fallback mode- # for this PR 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 }}- FALLBACK_REASON: ${{ steps.fallback.outputs.reason }}- SELECT_OUTCOME: ${{ steps.select.outcome }}- # Guards the empty-selection backstop below. select-tests only runs on- # pull_request, so the bare filter output is the whole story here.- LEGACY_CHANGED: ${{ needs.changes.outputs.legacy }}- # What an untrusted selection falls back to. A ready PR has no later- # run to defer to, so it must run everything; a draft still skips and- # leans on the ready run, which is the cheaper of the two mistakes.- FALLBACK_MODE: ${{ github.event.pull_request.draft && 'skip' || 'full' }}- shell: bash- run: |- set -euo pipefail- # Selection telemetry (see the capture-test-selection job). Best-effort- # from the selector JSON when it exists; narrowed=false marks a fallback.- emit_metrics() {- local changed="" selected="" reasons="" selected_seconds="" skipped_seconds=""- if [[ -s /tmp/selection.json ]]; then- changed=$(jq -r '.changed_file_count // empty' /tmp/selection.json)- selected=$(jq -r '.combined.count // empty' /tmp/selection.json)- reasons=$(jq -r '.ast.full_run_reasons | length' /tmp/selection.json)- selected_seconds=$(jq -r '.durations.selected_seconds // empty' /tmp/selection.json)- skipped_seconds=$(jq -r '.durations.skipped_seconds // empty' /tmp/selection.json)- fi- {- echo "narrowed=$1"- echo "skip_reason=$2"- echo "changed_file_count=$changed"- echo "selected_test_count=$selected"- echo "full_run_reasons_count=$reasons"- echo "selected_test_seconds=$selected_seconds"- echo "skipped_test_seconds=$skipped_seconds"- } >> "$GITHUB_OUTPUT"- }-- # Untrusted selection runs the full matrices on a ready PR and skips- # them on a draft (the pre-selection draft behavior).- fall_back() {- echo "mode=$FALLBACK_MODE" >> "$GITHUB_OUTPUT"- echo "core_files=" >> "$GITHUB_OUTPUT"- echo "poe_files=" >> "$GITHUB_OUTPUT"- echo "temporal_files=" >> "$GITHUB_OUTPUT"- echo "compat_files=" >> "$GITHUB_OUTPUT"- echo "run_poe=false" >> "$GITHUB_OUTPUT"- echo "run_temporal=false" >> "$GITHUB_OUTPUT"- emit_metrics false "$1"- }-- if [[ "$FALLBACK_SKIP" == "true" ]]; then- fall_back "${FALLBACK_REASON:-untrusted}"- exit 0- fi-- if [[ "$SELECT_OUTCOME" != "success" ]] || [[ ! -s /tmp/selection.json ]]; then- echo "::warning::shadow selector did not produce output; falling back to mode=$FALLBACK_MODE"- fall_back selector_error- 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 (mode=$FALLBACK_MODE):"- jq -r '.ast.full_run_reasons[]' /tmp/selection.json- fall_back full_run_requested- 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 on): posthog ee/ (minus posthog/temporal, posthog/dags,- # common/hogvm/python/test, posthog/test/repo_invariants)- # POE-off safeguard: posthog/clickhouse, posthog/queries, ee/clickhouse/,- # products/product_analytics/backend/tests/api,- # posthog/api/test/dashboards/test_dashboard.py- # Temporal: posthog/temporal, products/signals/backend/emission- # Compat: CLICKHOUSE_COMPAT_PYTEST_TARGETS (posthog/clickhouse, ee/clickhouse)- # Files outside posthog/ and ee/ (e.g. products/foo/backend/test_*) are not in this- # matrix. turbo-tests handles them, including the temporal suites of- # batch_exports, managed_warehouse, tasks and warehouse_sources, because every- # shard starts the temporal profile, so running them there costs nothing- # extra. Keep this list in sync with PRODUCTS_RUNNING_TEMPORAL_IN_JOB and- # DJANGO_SEGMENTS in turbo-discover.js.- core=()- poe=()- temporal=()- compat=()- while IFS= read -r f; do- [[ -z "$f" ]] && continue- # Compat overlaps the POE scope rather than partitioning with it, so- # it is collected separately from the segment case below. Driven by the- # same env var the compat pytest invocation uses, so widening one can't- # silently under-select the other.- for compat_target in $CLICKHOUSE_COMPAT_PYTEST_TARGETS; do- if [[ "$f" == "${compat_target%/}/"* ]]; then- compat+=("$f")- break- fi- done- case "$f" in- posthog/temporal/*|products/signals/backend/emission/*)- temporal+=("$f")- ;;- posthog/clickhouse/*|posthog/queries/*|ee/clickhouse/*|products/product_analytics/backend/tests/api/*|posthog/api/test/dashboards/test_dashboard.py)- poe+=("$f")- core+=("$f")- ;;- posthog/dags/*|common/hogvm/python/test/*|posthog/test/repo_invariants/*)- # Explicitly --ignore'd by the Core invocation; nothing to do.- ;;- posthog/*|ee/*)- core+=("$f")- ;;- esac- done < <(jq -r '.combined.tests[]?' /tmp/selection.json)-- # Backstop: a diff that touched legacy code but selected no Django test at- # all means the selector had no rule for it, not that there is nothing to- # run — a non-Python legacy file (C++ parser sources, a JSON config) reaches- # no import edge. Narrowing to zero would silently gate on nothing, so treat- # it as untrusted. FULL_RUN_PATTERNS covers the known cases; this catches the- # ones that get added to the `legacy` paths filter and forgotten there.- # Products-only diffs legitimately select nothing here and are not legacy.- if [[ "$LEGACY_CHANGED" == "true" && ${#core[@]} -eq 0 && ${#temporal[@]} -eq 0 ]]; then- echo "::warning::legacy files changed but no Django test was selected; falling back to mode=$FALLBACK_MODE"- fall_back empty_selection- exit 0- fi-- echo "mode=selected" >> "$GITHUB_OUTPUT"- echo "core_files=${core[*]:-}" >> "$GITHUB_OUTPUT"- echo "poe_files=${poe[*]:-}" >> "$GITHUB_OUTPUT"- echo "temporal_files=${temporal[*]:-}" >> "$GITHUB_OUTPUT"- echo "compat_files=${compat[*]:-}" >> "$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"- # Shards per narrowed segment: turbo-discover's per-shard budget applied- # to the selected tests' recorded seconds. Degrades to 1 per segment.- echo "segment_shards=$(node .github/scripts/selected-django-shards.js /tmp/selection.json)" >> "$GITHUB_OUTPUT"- emit_metrics true ""-- echo "Selected: ${#core[@]} core, ${#poe[@]} POE-eligible, ${#temporal[@]} temporal, ${#compat[@]} compat"+ echo "$RESULT" | jq -r '"mode=\(.selection.mode)", "selection=\(.selection | tojson)", "telemetry=\(.telemetry | tojson)"' >> "$GITHUB_OUTPUT"- name: Upload selection artifact+ # test-selection-verdict reads it instead of running the selector again. An+ # upload failure must not fail this job; the verdict regenerates the selection.+ continue-on-error: trueif: always() && steps.select.outcome == 'success'uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0with:@@ -2469,7 +2263,7 @@ jobs:build_django_matrix:name: Build Django matrix- needs: [changes, get_clickhouse_versions, turbo-discover, select-tests]+ needs: [changes, get_clickhouse_versions, turbo-discover]if: |!cancelled() &&needs.changes.outputs.backend == 'true' &&@@ -2485,14 +2279,14 @@ 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 }}- COMPAT_FILES: ${{ needs.select-tests.outputs.compat_files }}- SEGMENT_SHARDS: ${{ needs.select-tests.outputs.segment_shards }}+ MODE: ${{ needs.turbo-discover.outputs.mode }}+ RUN_POE: ${{ fromJSON(needs.turbo-discover.outputs.selection || '{}').run_poe }}+ RUN_TEMPORAL: ${{ fromJSON(needs.turbo-discover.outputs.selection || '{}').run_temporal }}+ CORE_FILES: ${{ fromJSON(needs.turbo-discover.outputs.selection || '{}').core_files }}+ COMPAT_FILES: ${{ fromJSON(needs.turbo-discover.outputs.selection || '{}').compat_files }}+ SEGMENT_SHARDS: ${{ fromJSON(needs.turbo-discover.outputs.selection || '{}').segment_shards }}# A trunk-merge/** PR opens as a draft but is the merge gate, and- # select-tests deliberately does not run for it. Reporting it as a+ # turbo-discover deliberately does not select for it. Reporting it as a# draft here would turn that empty MODE into "skip" and build an# empty matrix, so the queue would merge having run no Django tests# at all. Not-draft makes the empty MODE fall through to the full@@ -2509,7 +2303,7 @@ jobs:# :NOTE: Keep shard counts/group ranges in sync with historical Django matrix tuning.# Consult #team-devex before changing.- # A draft PR must never fall back to the full matrix. select-tests sets+ # A draft PR must never fall back to the full matrix. turbo-discover sets# MODE to "skip"/"full"/"selected"; an empty MODE on a# draft means it was cancelled or failed (typically ready_for_review# superseding it mid-flight). Without this, the draft builds the full@@ -2532,11 +2326,10 @@ jobs:if [[ "$MODE" == "selected" ]]; then# Selected mode: run only the segments that have selected files. Shard- # counts come from select-tests, where selected-django-shards.js applied- # turbo-discover's per-shard budget to the selected tests' recorded- # seconds. A wide selection therefore spreads over several jobs instead- # of running to the job timeout in one. No counts means one shard per- # segment.+ # counts come from turbo-discover, which applies its per-shard budget to+ # the selected tests' recorded seconds. A wide selection therefore+ # spreads over several jobs instead of running to the job timeout in+ # one. No counts means one shard per segment.segment_shards="${SEGMENT_SHARDS:-}"[[ -z "$segment_shards" ]] && segment_shards='{"core": 1, "poe": 1, "temporal": 1}'@@ -2799,8 +2592,7 @@ jobs:echo "Django matrix size: $(jq -r 'length' <<< "$include") (mode=$MODE)"django:- needs:- [changes, turbo-discover, detect-snapshot-mode, get_clickhouse_versions, build_django_matrix, select-tests]+ needs: [changes, turbo-discover, detect-snapshot-mode, get_clickhouse_versions, build_django_matrix]# Run legacy pytest if:# 1. Legacy code directly changed (ee/, posthog/)# 2. OR product changes affect legacy code (turbo-discover outputs run_legacy=true)@@ -3249,16 +3041,16 @@ jobs:# flip from one that predates it.PERSON_ON_EVENTS_V2_ENABLED: ${{ !matrix.person-on-events && !matrix.compat && 'true' || 'false' }}CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA: ${{ matrix.new-events-schema && 'true' || 'false' }}- MODE: ${{ needs.select-tests.outputs.mode }}- CORE_FILES: ${{ needs.select-tests.outputs.core_files }}- POE_FILES: ${{ needs.select-tests.outputs.poe_files }}- COMPAT_FILES: ${{ needs.select-tests.outputs.compat_files }}+ MODE: ${{ needs.turbo-discover.outputs.mode }}+ CORE_FILES: ${{ fromJSON(needs.turbo-discover.outputs.selection || '{}').core_files }}+ POE_FILES: ${{ fromJSON(needs.turbo-discover.outputs.selection || '{}').poe_files }}+ COMPAT_FILES: ${{ fromJSON(needs.turbo-discover.outputs.selection || '{}').compat_files }}# devex: measure core (posthog/ee) coverage on PRs to size the gap vs products. sysmon = low overhead.COVERAGE_CORE: sysmon# backend-coverage-report skips narrowed runs (patch coverage would read# as false gaps), so instrumenting one just costs time and uploads an# artifact nothing reads.- COV_ARGS: ${{ github.event_name == 'pull_request' && needs.select-tests.outputs.mode != 'selected' && '--cov=posthog --cov=ee --cov-config=.github/coverage-core.cfg --cov-report=xml:coverage-core.xml' || '' }}+ COV_ARGS: ${{ github.event_name == 'pull_request' && needs.turbo-discover.outputs.mode != 'selected' && '--cov=posthog --cov=ee --cov-config=.github/coverage-core.cfg --cov-report=xml:coverage-core.xml' || '' }}# 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@@ -3368,7 +3160,7 @@ jobs:- name: Upload core coverageuses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0- if: ${{ always() && github.event_name == 'pull_request' && needs.select-tests.outputs.mode != 'selected' && matrix.segment == 'Core' }}+ if: ${{ always() && github.event_name == 'pull_request' && needs.turbo-discover.outputs.mode != 'selected' && matrix.segment == 'Core' }}with:name: coverage-core-${{ strategy.job-index }}path: coverage-core.xml@@ -3418,8 +3210,8 @@ jobs: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 || '' }}CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA: ${{ matrix.new-events-schema && 'true' || 'false' }}- MODE: ${{ needs.select-tests.outputs.mode }}- TEMPORAL_FILES: ${{ needs.select-tests.outputs.temporal_files }}+ MODE: ${{ needs.turbo-discover.outputs.mode }}+ TEMPORAL_FILES: ${{ fromJSON(needs.turbo-discover.outputs.selection || '{}').temporal_files }}run: |set +e# Pick the split algorithm and granularity at runtime: optimal_chunks +@@ -3943,7 +3735,7 @@ jobs:echo "All backend and product checks passed."test-selection-verdict:- needs: [django, turbo-tests, changes, select-tests]+ needs: [django, turbo-tests, changes, turbo-discover]name: Test selection verdict# changes is skipped on no-ci drafts — no tests ran, nothing to verdict.if: ${{ !cancelled() && github.event_name == 'pull_request' && needs.changes.result != 'skipped' }}@@ -3983,9 +3775,9 @@ jobs:[[ "$d" == "$latest" ]] || rm -rf "$d"done- # Reuse the selection artifact from the select-tests job rather than+ # Reuse the selection artifact from the turbo-discover 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+ # produced (the selector did not run or failed) — the next step# regenerates it so we still get a shadow verdict for those PRs.- name: Download selection artifactid: download-selection@@ -4078,18 +3870,18 @@ jobs:capture-test-selection:name: Capture test selection- needs: [select-tests]+ needs: [turbo-discover]runs-on: ubuntu-latesttimeout-minutes: 5- # select-tests only runs on internal PRs; fire only when it actually- # produced a decision. DevEx project only, mirroring monitor-github-rate-limit;- # continue-on-error so telemetry never reds CI. Skipped on forks/Dependabot,- # which never have the secret (and where select-tests didn't run anyway).+ # An empty mode means this run never selected, so there is no decision to report.+ # DevEx project only, mirroring monitor-github-rate-limit; continue-on-error so+ # telemetry never reds CI. Skipped on forks/Dependabot, which never have the secret.if: |!cancelled() && github.run_attempt == '1'&& github.actor != 'dependabot[bot]'&& github.event.pull_request.head.repo.full_name == 'PostHog/posthog'- && needs.select-tests.result == 'success'+ && needs.turbo-discover.result == 'success'+ && needs.turbo-discover.outputs.mode != ''steps:- name: Capture test selection to DevEx PostHogcontinue-on-error: true@@ -4097,28 +3889,7 @@ jobs:with:posthog-token: ${{ secrets.POSTHOG_DEVEX_PROJECT_API_TOKEN }}event: 'posthog-ci-test-selection'- properties: |- {- "suite": "backend",- "mode": ${{ toJSON(needs.select-tests.outputs.mode) }},- "narrowed": ${{ needs.select-tests.outputs.narrowed || 'false' }},- "skip_reason": ${{ toJSON(needs.select-tests.outputs.skip_reason || '') }},- "changed_file_count": ${{ needs.select-tests.outputs.changed_file_count || 'null' }},- "selected_test_count": ${{ needs.select-tests.outputs.selected_test_count || 'null' }},- "full_run_reasons_count": ${{ needs.select-tests.outputs.full_run_reasons_count || 'null' }},- "run_legacy": ${{ toJSON(needs.select-tests.outputs.run_legacy || '') }},- "run_legacy_reason": ${{ toJSON(needs.select-tests.outputs.run_legacy_reason || '') }},- "turbo_result": ${{ toJSON(needs.select-tests.outputs.turbo_result || '') }},- "selected_test_seconds": ${{ needs.select-tests.outputs.selected_test_seconds || 'null' }},- "skipped_test_seconds": ${{ needs.select-tests.outputs.skipped_test_seconds || 'null' }},- "run_poe": ${{ needs.select-tests.outputs.run_poe || 'false' }},- "run_temporal": ${{ needs.select-tests.outputs.run_temporal || 'false' }},- "event_type": ${{ toJSON(github.event_name) }},- "branch": ${{ toJSON(github.head_ref || github.ref_name) }},- "sha": ${{ toJSON(github.sha) }},- "pr_number": ${{ github.event.pull_request.number || 'null' }},- "run_id": ${{ toJSON(github.run_id) }}- }+ properties: ${{ needs.turbo-discover.outputs.telemetry }}report-test-timings:name: Report per-test traces@@ -4187,7 +3958,7 @@ jobs:backend-coverage-report:name: Backend coverage report- needs: [turbo-tests, django_tests, select-tests]+ needs: [turbo-tests, django_tests, turbo-discover]runs-on: ubuntu-latestcontinue-on-error: true # report-only, never block a PRtimeout-minutes: 10@@ -4208,7 +3979,7 @@ jobs:!cancelled() &&github.event_name == 'pull_request' &&github.event.pull_request.draft == false &&- needs.select-tests.outputs.mode != 'selected' &&+ needs.turbo-discover.outputs.mode != 'selected' &&github.event.pull_request.head.repo.full_name == 'PostHog/posthog' &&(needs.turbo-tests.result != 'skipped' || needs.django_tests.result != 'skipped')steps:diff --git a/tools/snob_backend_test_selection_shadow.py b/tools/snob_backend_test_selection_shadow.pyindex c3f26033c162..42b966342fb4 100755--- a/tools/snob_backend_test_selection_shadow.py+++ b/tools/snob_backend_test_selection_shadow.py@@ -30,7 +30,7 @@ would cover a failure mode we have not actually observed, at the cost of thenarrowing on a very common kind of PR.Outputs JSON to stdout. The "shadow" in the filename is historical — ci-backend's-select-tests job now acts on this output, so a test this misses is a test that does not+turbo-discover job now acts on this output, so a test this misses is a test that does notrun on the PR. Recall beats precision: when in doubt, add a FULL_RUN_PATTERNS entry."""@@ -612,7 +612,7 @@ _CORE_IGNORED_PREFIXES = ("posthog/dags/", "common/hogvm/python/test/", "posthogdef segments_for_test_file(path: str) -> frozenset[str]:"""Which Django matrix segments run a given test file. Mirrors the Core/POE/Temporal- partition in ci-backend.yml's select-tests `classify` step — POE files run in both the+ partition of the pytest invocations in ci-backend.yml — POE files run in both theCore matrix and the legacy-mode safeguard matrix (the allowlist that keeps the joinedperson mode covered), so they belong to both segments. An emptyresult means no narrowable matrix runs the file (a product/turbo test, or an explicitly@@ -629,12 +629,32 @@ def segments_for_test_file(path: str) -> frozenset[str]:return frozenset()+def compat_prefixes() -> tuple[str, ...]:+ """Path prefixes the ClickHouse compat matrix re-runs, from the same env var that+ feeds its pytest invocation, so widening one cannot silently under-select the other."""+ return tuple(f"{target.rstrip('/')}/" for target in os.environ.get("CLICKHOUSE_COMPAT_PYTEST_TARGETS", "").split())+++def selected_files_by_segment(test_files: list[str]) -> dict[str, list[str]]:+ """Selected test files per Django matrix segment. turbo-discover.js hands each list+ to the matching pytest invocation, so a file that lands in no segment runs nowhere.+ Compat overlaps the POE scope rather than partitioning with it, so it is collected+ alongside the Core/POE/Temporal partition instead of inside it."""+ prefixes = compat_prefixes()+ by_segment: dict[str, list[str]] = {"core": [], "poe": [], "temporal": [], "compat": []}+ for path in test_files:+ for segment in segments_for_test_file(path):+ by_segment[segment].append(path)+ if prefixes and path.startswith(prefixes):+ by_segment["compat"].append(path)+ return by_segment++def selected_seconds_by_segment(test_files: list[str], durations: dict[str, float]) -> dict[str, int]:"""Selected test-execution seconds per Django matrix segment.- .github/scripts/selected-django-shards.js runs these through turbo-discover's shard- sizing, so a narrowed run gets the same per-shard budget as a full one instead of a- fixed single shard. POE files count in both core and poe, matching the two matrix- legs that run them."""+ turbo-discover.js runs these through its shard sizing, so a narrowed run gets the same+ per-shard budget as a full one instead of a fixed single shard. POE files count in both+ core and poe, matching the two matrix legs that run them."""return {segment: round(estimate_duration([f for f in test_files if segment in segments_for_test_file(f)], durations))for segment in ("core", "poe", "temporal")@@ -677,6 +697,10 @@ def build_result(base_ref: str) -> dict[str, object]:"combined": {"tests": combined_tests,"count": len(combined_tests),+ # Product directories with a selected test file. ci-backend narrows the+ # product matrix to them on a legacy diff.+ "products": sorted({p for p in map(_product_name, combined_tests) if p}),+ "segments": selected_files_by_segment(combined_tests),"duration_seconds": round(selected_seconds),},"durations": {diff --git a/tools/test_snob_backend_test_selection_shadow.py b/tools/test_snob_backend_test_selection_shadow.pyindex db13b0a7dad6..200ee9a06161 100644--- a/tools/test_snob_backend_test_selection_shadow.py+++ b/tools/test_snob_backend_test_selection_shadow.py@@ -1,5 +1,6 @@from __future__ import annotations+import osimport sysimport tempfileimport importlib.util@@ -7,6 +8,7 @@ from pathlib import Pathfrom types import ModuleTypeimport unittest+from unittest import mockfrom parameterized import parameterized@@ -308,6 +310,43 @@ class TestSnobBackendTestSelectionShadow(unittest.TestCase):self.assertEqual(selection.segments_for_test_file(path), frozenset(expected))+ @parameterized.expand(+ [+ (+ "compat_targets_set",+ "posthog/clickhouse ee/clickhouse",+ ["ee/clickhouse/test_g.py", "posthog/clickhouse/test_b.py"],+ ),+ ("no_compat_targets", "", []),+ ]+ )+ def test_selected_files_by_segment_reads_compat_targets_from_the_env(+ self, _name: str, targets: str, expected_compat: list[str]+ ) -> None:+ selection = _load_selection_module()++ selected = [+ "ee/clickhouse/test_g.py",+ "posthog/clickhouse/test_b.py",+ "posthog/dags/test_e.py",+ "posthog/models/test_a.py",+ "posthog/temporal/tests/test_c.py",+ "products/warehouse_sources/backend/test_d.py",+ ]++ with mock.patch.dict(os.environ, {"CLICKHOUSE_COMPAT_PYTEST_TARGETS": targets}):+ by_segment = selection.selected_files_by_segment(selected)++ self.assertEqual(+ by_segment,+ {+ "core": ["ee/clickhouse/test_g.py", "posthog/clickhouse/test_b.py", "posthog/models/test_a.py"],+ "poe": ["ee/clickhouse/test_g.py", "posthog/clickhouse/test_b.py"],+ "temporal": ["posthog/temporal/tests/test_c.py"],+ "compat": expected_compat,+ },+ )+def test_narrowable_baseline_excludes_turbo_product_tests(self) -> None:selection = _load_selection_module()