: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
chore(ci): test native JSON events without doubling the suite (#106280)
Sandy Spicercbc6269077e8
diff --git a/.depot/workflows/ci-backend.yml b/.depot/workflows/ci-backend.ymlindex 36502261873a..9f19b1364bb0 100644--- a/.depot/workflows/ci-backend.yml+++ b/.depot/workflows/ci-backend.yml@@ -54,9 +54,9 @@# - Workflow-name expressions remain literal, so the role cannot switch names through a# variable; the cutover renames the workflow in a plain edit. The gate's hand-off `&&`# is safe only while its status remains optional.-# - events_json variants: gated on the test-new-events-schema label only; canonical also-# doubles the matrices on workflow_dispatch, but shadow dispatches stay legacy-only so-# trial runs match handed-off PR runs+# - events_json variants: the doubled matrices are gated on the test-new-events-schema label+# only; canonical also doubles them on workflow_dispatch, but a shadow dispatch runs the+# events_json rows instead, so trial runs match handed-off PR runs# - per-segment split plans (.test_durations.core/.temporal): the restore steps mirror# canonical but miss until the depot timing refresher saves those files to Depot Cache;# shards fall back to the union .test_durations@@ -143,6 +143,10 @@ on:# labeled/unlabeled triggers, so a label takes effect from the next push# or from ready_for_review. Every event, merge-queue PRs included, runs here# only when GitHub Actions hands it off (see the `wait-for-handoff` job).+ # The events_json leg runs wherever the legacy tests run, over the paths in+ # .github/new-events-schema-targets.txt, the same as canonical, so a routed PR+ # cannot pass here and fail the queue. The `test-new-events-schema` label runs+ # the doubled matrices in place of that leg.types: [opened, synchronize, reopened, ready_for_review]concurrency:# PRs: one active run per branch, cancel stale. Push: per-SHA so master@@ -445,6 +449,7 @@ jobs:- 'products/*/turbo.json'# Make sure we run if someone is explicitly changing the workflow- .depot/workflows/ci-backend.yml+ - .github/new-events-schema-targets.txt- .depot/actions/setup-uv/**- .github/clickhouse-versions.json# We use docker compose for tests, make sure we rerun on@@ -499,6 +504,7 @@ jobs:- 'products/*/manifest.tsx'- rust/feature-flags/src/properties/property_models.rs- .depot/workflows/ci-backend.yml+ - .github/new-events-schema-targets.txt- .depot/actions/setup-uv/**- .github/clickhouse-versions.json- docker-compose.dev.yml@@ -922,6 +928,7 @@ jobs:# 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 }}+ RUN_NEW_EVENTS_SCHEMA: ${{ contains(github.event.pull_request.labels.*.name, 'test-new-events-schema') }}SCHEMA_CHANGED: ${{ github.event_name != 'pull_request' || needs.changes.outputs.schema }}TURBO_SCM_HEAD: ${{ github.sha }}# Kill switch — drop comma-separated products from the matrix; empty = run all.@@ -1050,8 +1057,10 @@ jobs:id: buildenv:PRODUCT_MATRIX_JSON: ${{ needs.turbo-discover.outputs.matrix }}- # The new-events-schema variants double the matrix, so run them only on- # opted-in PRs.+ # The new-events-schema variants double the matrix, so they run only on+ # opted-in PRs. Other runs cover the product paths in+ # .github/new-events-schema-targets.txt with the Django matrix's+ # events_json rows.RUN_NEW_EVENTS_SCHEMA: ${{ contains(github.event.pull_request.labels.*.name, 'test-new-events-schema') }}run: |if [[ "$RUN_NEW_EVENTS_SCHEMA" == "true" ]]; then@@ -1402,6 +1411,9 @@ jobs:uses: ./.github/actions/trunk-quarantine-gatewith:junit-paths: trunk-junit/junit-product-*.xml+ # A native-JSON leg uploads under its own variant, so a failure in that mode+ # does not read as a flake of the legacy test with the same id.+ variant: ${{ matrix.new-events-schema && 'events-json' || '' }}previous-step-outcome: ${{ steps.run-product-tests.outcome }}token: ${{ secrets.TRUNK_API_TOKEN }}@@ -2409,9 +2421,19 @@ jobs:IS_DRAFT: ${{ github.event.pull_request.draft && !startsWith(github.head_ref, 'trunk-merge/') }}IS_PR_RUN: ${{ github.event_name == 'pull_request' && !startsWith(github.head_ref, 'trunk-merge/') }}FORCE_FULL: ${{ contains(github.event.pull_request.labels.*.name, 'run-ci-backend') }}- # The new-events-schema variants double the matrix, so run them only on- # opted-in PRs.+ # The new-events-schema variants double the matrix, so they run only on+ # opted-in PRs. Every other run takes the events_json rows, which cover+ # .github/new-events-schema-targets.txt only.RUN_NEW_EVENTS_SCHEMA: ${{ contains(github.event.pull_request.labels.*.name, 'test-new-events-schema') }}+ # Narrowed events_json paths and their shard count. Empty files on a run+ # that takes the whole list.+ JSON_TARGETS_FILES: ${{ fromJSON(needs.turbo-discover.outputs.selection || '{}').json_targets_files }}+ JSON_TARGETS_SHARDS: ${{ fromJSON(needs.turbo-discover.outputs.selection || '{}').json_targets_shards }}+ # Same rule as the django job's condition: the suite runs for a legacy+ # edit, for a product change that reaches legacy code, and when discovery+ # failed, which leaves run_legacy empty. Without it only the events_json+ # rows for the product matrix run.+ DJANGO_SUITE: ${{ needs.changes.outputs.legacy == 'true' || needs.turbo-discover.outputs.run_legacy != 'false' }}run: |# :NOTE: Keep shard counts/group ranges in sync with historical Django matrix tuning.# Consult #team-devex before changing.@@ -2433,7 +2455,20 @@ jobs:echo "Django matrix size: 0 (mode=skip)"exit 0fi- if [[ "$MODE" == "selected" ]]; then+ if [[ "$DJANGO_SUITE" != "true" ]]; then+ # A product change that reaches no legacy code skips the Django suite.+ # The product jobs read the legacy events table only, so the events_json+ # rows still run the listed paths of the products in the product matrix.+ core="[]"+ core_new_events_schema="[]"+ core_persons_on_events="[]"+ core_persons_on_events_new_schema="[]"+ temporal="[]"+ temporal_new_events_schema="[]"+ compat="[]"+ json_targets_count=0+ [[ -n "$JSON_TARGETS_FILES" ]] && json_targets_count="${JSON_TARGETS_SHARDS:-1}"+ elif [[ "$MODE" == "selected" ]]; then# Selected mode: run only the segments that have selected files. Shard# counts come from turbo-discover, which applies its per-shard budget to# the selected tests' recorded seconds. A wide selection therefore@@ -2551,20 +2586,28 @@ jobs:elsecompat="[]"fi+ # The narrowed events_json paths: selected files under a listed path,+ # plus the listed paths of the products in the narrowed product matrix.+ json_targets_count=0+ [[ -n "$JSON_TARGETS_FILES" ]] && json_targets_count="${JSON_TARGETS_SHARDS:-1}"else# Full run: auto-shard counts from turbo-discover (Amdahl's law on .test_durations).# Falls back to hardcoded defaults if turbo-discover failed or data is missing.CORE_SHARDS=38CORE_POE_SHARDS=7TEMPORAL_SHARDS=7+ JSON_TARGETS_FULL_SHARDS=5if [ -n "$DJANGO_SHARDS_JSON" ] && echo "$DJANGO_SHARDS_JSON" | jq -e '.Core.shards' > /dev/null 2>&1; thenCORE_SHARDS=$(echo "$DJANGO_SHARDS_JSON" | jq -r '.Core.shards')CORE_POE_SHARDS=$(echo "$DJANGO_SHARDS_JSON" | jq -r '.CorePOE.shards')TEMPORAL_SHARDS=$(echo "$DJANGO_SHARDS_JSON" | jq -r '.Temporal.shards')- echo "Auto-sharding: Core=$CORE_SHARDS, CorePOE=$CORE_POE_SHARDS, Temporal=$TEMPORAL_SHARDS"+ JSON_TARGETS_FULL_SHARDS=$(echo "$DJANGO_SHARDS_JSON" | jq -r --argjson fallback "$JSON_TARGETS_FULL_SHARDS" '.JsonTargets.shards // $fallback')+ echo "Auto-sharding: Core=$CORE_SHARDS, CorePOE=$CORE_POE_SHARDS, Temporal=$TEMPORAL_SHARDS, JsonTargets=$JSON_TARGETS_FULL_SHARDS"else- echo "::warning::Django shard auto-sizing unavailable, using defaults: Core=$CORE_SHARDS, CorePOE=$CORE_POE_SHARDS, Temporal=$TEMPORAL_SHARDS"+ echo "::warning::Django shard auto-sizing unavailable, using defaults: Core=$CORE_SHARDS, CorePOE=$CORE_POE_SHARDS, Temporal=$TEMPORAL_SHARDS, JsonTargets=$JSON_TARGETS_FULL_SHARDS"fi+ # A full run takes every listed events_json path.+ json_targets_count="$JSON_TARGETS_FULL_SHARDS"# The legacy-mode safeguard leg runs only where a regression must not# land: merge queue and master. Ordinary PR lanes run the@@ -2678,12 +2721,36 @@ jobs:fiif [[ "$RUN_NEW_EVENTS_SCHEMA" != "true" ]]; then+ # Without the schema copies, only the events_json rows below refresh+ # *.new_events_schema.ambr files, so a module outside+ # .github/new-events-schema-targets.txt lets its file go stale.echo "Skipping new-events-schema variants (RUN_NEW_EVENTS_SCHEMA is off)"core_new_events_schema="[]"core_persons_on_events_new_schema="[]"temporal_new_events_schema="[]"+ else+ # The doubled matrices exclude some curated paths, such as Dagster tests.+ # Discovery keeps only those paths so the other tests do not run a third time.+ json_targets_count="${JSON_TARGETS_SHARDS:-0}"fi+ # The events_json rows: Core jobs over the listed paths with the+ # native-JSON events table. They keep Core's person-on-events default.+ json_targets=$(jq -cn --arg image "$OLDEST_SUPPORTED_IMAGE" --argjson n "$json_targets_count" '+ [range(1; $n + 1) | {+ segment: "Core",+ "json-targets": true,+ "person-on-events": false,+ "new-events-schema": true,+ "python-version": "3.13.13",+ "clickhouse-server-image": $image,+ concurrency: $n,+ group: .,+ artifact_key: ("json-targets-" + (.|tostring)),+ compat: false+ }]+ ')+include=$(jq -cn \--argjson core "$core" \--argjson core_new_events_schema "$core_new_events_schema" \@@ -2692,7 +2759,8 @@ jobs:--argjson temporal "$temporal" \--argjson temporal_new_events_schema "$temporal_new_events_schema" \--argjson compat "$compat" \- '$core + $core_new_events_schema + $core_persons_on_events + $core_persons_on_events_new_schema + $temporal + $temporal_new_events_schema + $compat')+ --argjson json_targets "$json_targets" \+ '$core + $core_new_events_schema + $core_persons_on_events + $core_persons_on_events_new_schema + $temporal + $temporal_new_events_schema + $compat + $json_targets')echo "include=$include" >> "$GITHUB_OUTPUT"echo "Django matrix size: $(jq -r 'length' <<< "$include") (mode=$MODE)"@@ -2710,6 +2778,8 @@ jobs:# 1. Legacy code directly changed (ee/, posthog/)# 2. OR product changes affect legacy code (turbo-discover outputs run_legacy=true)# 3. OR turbo-discover itself failed (conservative: run Django on detection failure)+ # 4. OR a product-only change has events_json paths to run. build_django_matrix+ # then builds only the events_json rows, because the Django suite does not run.# The non-empty include guard covers drafts in skip mode and selected runs# that chose zero files — an empty matrix would otherwise fail the job.# A status function is required to inspect dependency results after failures.@@ -2721,11 +2791,12 @@ jobs:needs.build_django_matrix.outputs.include != '[]' &&(needs.changes.outputs.legacy == 'true' ||needs.turbo-discover.outputs.run_legacy == 'true' ||- (needs.turbo-discover.result != 'success' && needs.turbo-discover.result != 'skipped'))+ (needs.turbo-discover.result != 'success' && needs.turbo-discover.result != 'skipped') ||+ fromJSON(needs.turbo-discover.outputs.selection || '{}').json_targets_files != '')# increase for tmate testing# 45 to match canonical.timeout-minutes: 45- name: Django tests – ${{ matrix.segment }}${{ matrix.compat && ' compat' || '' }} (persons-on-events ${{ (matrix.segment == 'Core' && !matrix.person-on-events && !matrix.compat) && 'on' || 'off' }}, events schema ${{ matrix.new-events-schema && 'json' || 'legacy' }}), Py ${{ matrix.python-version }}, ${{ matrix.clickhouse-server-image }} (${{matrix.group}}/${{ matrix.concurrency }})+ name: Django tests – ${{ matrix.segment }}${{ matrix.compat && ' compat' || '' }}${{ matrix.json-targets && ' json-targets' || '' }} (persons-on-events ${{ (matrix.segment == 'Core' && !matrix.person-on-events && !matrix.compat) && 'on' || 'off' }}, events schema ${{ matrix.new-events-schema && 'json' || 'legacy' }}), Py ${{ matrix.python-version }}, ${{ matrix.clickhouse-server-image }} (${{matrix.group}}/${{ matrix.concurrency }})# Match canonical's runner size. The shadow restores the same master-primed# schema cache (turbo-discover key + check-migrations save), so shards skip# migrations exactly like canonical once Depot's cache is warmed by a master run.@@ -3153,11 +3224,15 @@ jobs: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 }}+ JSON_TARGETS: ${{ matrix.json-targets && 'true' || 'false' }}+ # The narrowed events_json paths. Empty when the row takes the whole list.+ JSON_TARGETS_FILES: ${{ fromJSON(needs.turbo-discover.outputs.selection || '{}').json_targets_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.turbo-discover.outputs.mode != 'selected' && '--cov=posthog --cov=ee --cov-config=.github/coverage-core.cfg --cov-report=' || '' }}+ # instrumenting one is pure overhead, and the events_json rows rerun+ # tests the legacy rows already measure.+ COV_ARGS: ${{ github.event_name == 'pull_request' && needs.turbo-discover.outputs.mode != 'selected' && !matrix.json-targets && '--cov=posthog --cov=ee --cov-config=.github/coverage-core.cfg --cov-report=' || '' }}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)@@ -3191,12 +3266,55 @@ jobs:SPLIT_GRANULARITY=(--split-granularity=file)# Scope the file-mode plan to Core's clean per-segment durations when the# pinned pytest-split supports it; only persons-on-events-off, non-compat Core- # matches the .core run-set, and a missing file falls back to the union.- if [ -f .test_durations.core ] && [[ "${{ matrix.person-on-events }}" != "true" ]] && [[ "${{ matrix.compat }}" != "true" ]] && python -c "from pytest_split.plugin import SUPPORTS_SPLIT_PLAN_PATH" 2>/dev/null; then+ # matches the .core run-set (the events_json rows do not), and a missing+ # file falls back to the union.+ if [ -f .test_durations.core ] && [[ "${{ matrix.person-on-events }}" != "true" ]] && [[ "${{ matrix.compat }}" != "true" ]] && [[ "$JSON_TARGETS" != "true" ]] && python -c "from pytest_split.plugin import SUPPORTS_SPLIT_PLAN_PATH" 2>/dev/null; thenSPLIT_GRANULARITY+=(--split-plan-path .test_durations.core)fifi- if [[ "$MODE" == "selected" ]]; then+ if [[ "$JSON_TARGETS" == "true" ]]; then+ # The events_json leg. The job checks out the PR head, and a head without+ # the list also predates the JSON-mode test fixes that came before it, so+ # its listed tests would fail on code the PR did not touch. The merge+ # queue's trunk-merge/** head always has the list, so the gate still runs.+ if [[ ! -f .github/new-events-schema-targets.txt ]]; then+ echo "::notice::The checked-out revision predates .github/new-events-schema-targets.txt, so the events_json leg runs nothing until this branch rebases onto master"+ exit 0+ fi+ # A narrowed run hands over its paths, and every other run takes the+ # whole list. Parse it the way turbo-discover.js does.+ if [[ -n "$JSON_TARGETS_FILES" ]]; then+ read -r -a json_candidates <<< "$JSON_TARGETS_FILES"+ else+ mapfile -t json_candidates < <(sed -e 's/#.*//' -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' -e 's:/*$::' -e '/^$/d' .github/new-events-schema-targets.txt)+ fi+ # The PR head can lack a path that the merged list names. pytest stops+ # with a usage error on a missing path, so skip that path and say so.+ json_targets=()+ for target in "${json_candidates[@]}"; do+ if [[ -e "$target" ]]; then+ json_targets+=("$target")+ else+ echo "::warning::events_json path $target does not exist in this checkout, so it does not run"+ fi+ done+ if [[ ${#json_targets[@]} -eq 0 ]]; then+ exit 0+ fi+ JSON_SPLIT=()+ if [[ "${{ matrix.concurrency }}" -gt 1 ]]; then+ JSON_SPLIT=(--splits "${{ matrix.concurrency }}" --group "${{ matrix.group }}"+ --splitting-algorithm="$SPLITTING_ALGORITHM" "${SPLIT_GRANULARITY[@]}")+ fi+ # No --store-durations, because the timing data describes legacy-table runs only.+ # shellcheck disable=SC2086+ pytest -v --tb=short --reuse-db -o junit_duration_report=call "${json_targets[@]}" -m "not async_migrations" \+ "${JSON_SPLIT[@]}" \+ "${RETRY_ARGS[@]}" -r fEsxXR \+ --junitxml=junit-core.xml \+ $COV_ARGS \+ $PYTEST_ARGS+ elif [[ "$MODE" == "selected" ]]; then# Selected mode: run only the test files chosen by the snob shadow selector.# Sharded only when build_django_matrix sized the segment above one# shard. One pytest retry mirrors canonical's budget.@@ -3403,7 +3521,7 @@ jobs:- name: Upload core coverageuses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0- if: ${{ needs.wait-for-handoff.outputs.handed_off == 'true' && (always() && github.event_name == 'pull_request' && needs.turbo-discover.outputs.mode != 'selected' && matrix.segment == 'Core') }}+ if: ${{ needs.wait-for-handoff.outputs.handed_off == 'true' && (always() && github.event_name == 'pull_request' && needs.turbo-discover.outputs.mode != 'selected' && matrix.segment == 'Core' && !matrix.json-targets) }}with:name: coverage-core-${{ strategy.job-index }}path: .coverage@@ -3490,6 +3608,9 @@ jobs:with:junit-paths: junit-core.xml,junit-core-retry-failures.xmlorg-slug: posthog-inc+ # A native-JSON row uploads under its own variant, so a failure in that mode+ # does not read as a flake of the legacy test with the same id.+ variant: ${{ matrix.new-events-schema && 'events-json' || '' }}cli-version: '0.15.4'quarantine: trueprevious-step-outcome: ${{ steps.run-core-tests.outcome }}@@ -3503,6 +3624,9 @@ jobs:with:junit-paths: junit-temporal.xml,junit-temporal-retry-failures.xmlorg-slug: posthog-inc+ # A native-JSON row uploads under its own variant, so a failure in that mode+ # does not read as a flake of the legacy test with the same id.+ variant: ${{ matrix.new-events-schema && 'events-json' || '' }}cli-version: '0.15.4'quarantine: trueprevious-step-outcome: ${{ steps.run-temporal-tests.outcome }}diff --git a/.github/new-events-schema-targets.txt b/.github/new-events-schema-targets.txtnew file mode 100644index 000000000000..62e6551cd81e--- /dev/null+++ b/.github/new-events-schema-targets.txt@@ -0,0 +1,66 @@+# Test paths that Backend CI runs a second time with CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA=true,+# against the native-JSON events table. The leg runs wherever the legacy tests run. A run of the+# full legacy matrix (the merge queue, the hourly master run, a PR the selector cannot narrow)+# takes every path. A narrowed PR run takes the paths its test selection reaches, plus the paths+# of the products whose tests it runs. A change to products alone takes those products' paths.+# The test-new-events-schema label doubles the backend suites. Listed paths those suites+# exclude still run here so the label does not reduce native-schema coverage.+#+# Only tests that read event properties can behave differently between the two events tables,+# so the list holds those directories plus the modules that own a *.new_events_schema.ambr+# snapshot. A module outside the list runs against the legacy table only, and its JSON snapshot+# goes stale. When you add a directory of tests that read event properties, add it here.+#+# One path per line, directory or file, relative to the repository root. A file under a listed+# directory needs no line of its own. Every path must hold at least one test module.+#+# products/experiments stays out until HogQL reads $feature/<key> from the $feature_flags map.+# Its tests fail against the native-JSON table until then.+# posthog/dags/tests/test_data_deletion_requests.py stays out because it calls the JSONDropKeys+# UDF, which the ClickHouse config of the Django test job does not define.++# HogQL, its query runners, and the ClickHouse layer below them+posthog/hogql+posthog/hogql_queries+posthog/session_recordings/queries+posthog/clickhouse/test+ee/clickhouse+products/customer_analytics/backend/hogql_queries+products/error_tracking/backend/hogql_queries+products/marketing_analytics/backend/hogql_queries+products/mcp_analytics/backend/tests/test_dashboard_series.py+products/mcp_analytics/backend/tests/test_harness_breakdown.py+products/mcp_analytics/backend/tests/test_missing_capabilities.py+products/mcp_analytics/backend/tests/test_model_breakdown.py+products/mcp_analytics/backend/tests/test_tool_quality_tables.py+products/mcp_analytics/backend/tests/test_tool_tables.py+products/product_analytics/backend/hogql_queries+products/web_analytics/backend/hogql_queries++# Code outside HogQL that builds events SQL itself and branches on the schema+posthog/dags/tests/test_deletes.py+posthog/models/team/test_production_event_activation.py+posthog/models/test/test_deletion_targets.py+posthog/tasks/test/test_ai_observability_usage_report.py+posthog/tasks/test/test_usage_report.py+posthog/temporal/tests/test_clickhouse.py+products/batch_exports/backend/tests/api/test_serializers.py+products/batch_exports/backend/tests/temporal/destinations/test_http_batch_export_workflow.py+products/batch_exports/backend/tests/temporal/pipeline/test_internal_stage.py+products/batch_exports/backend/tests/temporal/test_batch_exports.py+products/batch_exports/backend/tests/temporal/test_filters.py+products/batch_exports/backend/tests/temporal/test_record_batch_model.py+products/batch_exports/backend/tests/test_hogql_source.py+products/feature_flags/backend/test/test_request_usage.py++# Other modules that own a *.new_events_schema.ambr snapshot, so the snapshot bot keeps it current+posthog/api/test/test_event.py+posthog/api/test/test_properties_timeline.py+posthog/api/test/test_query.py+posthog/models/test/test_async_deletion_model.py+posthog/models/web_preaggregated/test_web_pre_aggregated_timezones.py+posthog/tasks/test/test_stop_surveys_reached_target.py+products/ai_observability/backend/api/test/test_personal_spend.py+products/revenue_analytics/backend/views/test/test_mrr_views.py+products/surveys/backend/api/test/test_survey.py+products/web_analytics/backend/test/test_heatmaps_api.pydiff --git a/.github/pull_request_template.md b/.github/pull_request_template.mdindex 03724592060b..ed414b321888 100644--- a/.github/pull_request_template.md+++ b/.github/pull_request_template.md@@ -60,7 +60,7 @@<!-- Definition of done (agents): not done until each gate below holds. Verify against the named artifact or skill — don't assume. Add gates as the PR touches more areas.- No duplicate: when this PR fixes something believed to be live on master, no open PR already fixes it. A broken master attracts parallel agents, so search before opening — `gh pr list --state open --search "<keywords>" --limit 20`, which lists drafts too, and most agent PRs start as drafts. Say here which PR you found and why this one is still needed, or that the search found nothing.- Patch coverage: the lines this PR changed are covered, or the uncovered ones are justified under "How did you test this code?". Don't pad untouched code to lift the number. Check the "🧪 Backend test coverage" PR comment (and its patch-coverage artifact).- - New events schema: classify the diff before opening the PR. Add `test-new-events-schema` for event ingestion or cleaning, event or property reads, generated event-table SQL, and schema-specific snapshots. Apply it while draft before ready-for-review. If the PR must open ready, apply it immediately and push another commit because label events do not start Backend CI. State the result under "How did you test this code?".+ - New events schema: Backend CI reruns the paths in `.github/new-events-schema-targets.txt` against the native-JSON events table. A new directory of tests that read event properties is added to that file. Add `test-new-events-schema` when the diff should run the whole backend suite on both tables: event ingestion or cleaning, or event reads whose tests are outside the list. Apply it while draft, or push another commit after labeling, because label events do not start Backend CI. State the result under "How did you test this code?".- Public artifact: nothing in this PR — code, fixtures and sample data, comments, commit messages, or this description — carries material from the agent session that isn't already public. If the work drew on a customer conversation, ticket, or log, say so here and state that the committed data is invented. Renaming people, hosts, and identifiers does not clear real material; see AGENTS.md "Public open source repo guidance".-->diff --git a/.github/scripts/turbo-discover-selection.test.js b/.github/scripts/turbo-discover-selection.test.jsindex b43b5c920237..d284791940cc 100644--- a/.github/scripts/turbo-discover-selection.test.js+++ b/.github/scripts/turbo-discover-selection.test.js@@ -6,7 +6,7 @@const { test } = require('node:test')const assert = require('node:assert/strict')-const { decideSelection, narrowedProducts, selectedShards } = require('./turbo-discover')+const { decideJsonTargets, decideSelection, narrowedProducts, selectedShards } = require('./turbo-discover')const segments = (extra) => ({ core: [], poe: [], temporal: [], compat: [], ...extra })@@ -161,3 +161,68 @@ test('products outside the matrix are ignored', () => {const selection = { combined: { products: ['not_a_product'] } }assert.deepEqual(narrowedProducts(products, ['gone'], selection), [])})++const JSON_TARGETS = [+ 'posthog/hogql',+ 'posthog/dags/tests/test_deletes.py',+ 'posthog/tasks/test/test_usage_report.py',+ 'products/batch_exports/backend/tests/test_hogql_source.py',+ 'products/web_analytics/backend/hogql_queries',+]++const jsonTargets = (overrides) =>+ decideJsonTargets({+ targets: JSON_TARGETS,+ mode: 'selected',+ runLegacy: true,+ selectedTests: [],+ products: [],+ ...overrides,+ })++test('the events_json leg runs the whole list, a narrowed list, or nothing', () => {+ const cases = [+ [{ mode: '' }, null],+ [{ mode: 'full' }, null],+ [{ mode: 'skip' }, []],+ [+ { mode: '', skippedProducts: ['batch-exports'] },+ [+ 'posthog/hogql',+ 'posthog/dags/tests/test_deletes.py',+ 'posthog/tasks/test/test_usage_report.py',+ 'products/web_analytics/backend/hogql_queries',+ ],+ ],+ [+ {+ selectedTests: [+ 'posthog/hogql/test/test_query.py',+ 'posthog/hogql_queries/test/test_query_runner.py',+ 'posthog/api/test/test_team.py',+ 'products/web_analytics/backend/hogql_queries/test/test_stats_table.py',+ ],+ products: ['batch-exports'],+ },+ ['posthog/hogql/test/test_query.py', 'products/batch_exports/backend/tests/test_hogql_source.py'],+ ],+ [+ { selectedTests: ['posthog/hogql/test/test_query.py'], products: ['batch-exports'], draft: true },+ ['posthog/hogql/test/test_query.py'],+ ],+ [{ selectedTests: ['posthog/api/test/test_team.py'], products: ['logs'] }, []],+ [{ mode: '', runLegacy: false, products: ['surveys', 'web-analytics'] }, ['products/web_analytics/backend/hogql_queries']],+ [{ mode: '', runLegacy: false, products: ['surveys'] }, []],+ [{ mode: 'full', doubled: true, products: ['batch-exports', 'web-analytics'] }, ['posthog/dags/tests/test_deletes.py']],+ [{ mode: 'skip', doubled: true }, []],+ [{ mode: '', runLegacy: false, products: ['web-analytics'], doubled: true }, []],+ [{ doubled: true, selectedTests: ['posthog/hogql/test/test_query.py'], products: ['web-analytics'] }, []],+ [+ { doubled: true, selectedTests: ['posthog/dags/tests/test_deletes.py', 'posthog/hogql/test/test_query.py'] },+ ['posthog/dags/tests/test_deletes.py'],+ ],+ ]+ for (const [overrides, expected] of cases) {+ assert.deepEqual(jsonTargets(overrides), expected, JSON.stringify(overrides))+ }+})diff --git a/.github/scripts/turbo-discover.js b/.github/scripts/turbo-discover.jsindex 9a21e8aeb249..7ed695ad6f80 100644--- a/.github/scripts/turbo-discover.js+++ b/.github/scripts/turbo-discover.js@@ -41,6 +41,8 @@// SELECTION_DISABLED ("true"/"false") — the DISABLE_BACKEND_TEST_SELECTION// kill switch.// PR_DRAFT ("true"/"false") — what an untrusted selection falls back to.+// .github/new-events-schema-targets.txt — the test paths of the events_json leg,+// which runs them against the native-JSON events table.// Output: JSON on stdout: { matrix, run_legacy, django_shards, selection }// Diagnostics on stderr@@ -169,6 +171,8 @@ const DJANGO_OVERHEAD_SECONDS_BY_SEGMENT = {Core: 295,CorePOE: 280,Temporal: 182,+ // The events_json leg is a Core job over its own path list, so it takes Core's overhead.+ JsonTargets: 295,}const DJANGO_MIN_SHARDS = 3const DJANGO_MAX_SHARDS = 50@@ -1046,8 +1050,46 @@ function getSegmentDuration(segment, durations, ranNodeIds = null) {return total}+// --- events_json leg ---+// The listed paths run a second time with CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA=true, as+// Core-style rows of the Django matrix. The file's header says what belongs in it.+const JSON_TARGETS_FILE = '.github/new-events-schema-targets.txt'++// The listed paths without comments, blank lines, or trailing slashes. A checkout that has+// no list yields no paths, and the leg then runs nothing.+function loadJsonTargets(file = JSON_TARGETS_FILE) {+ let text+ try {+ text = fs.readFileSync(file, 'utf-8')+ } catch {+ console.error(`::warning::${file} is missing, so the events_json leg runs no tests`)+ return []+ }+ return text+ .split('\n')+ .map((line) => line.replace(/#.*/, '').trim().replace(/\/+$/, ''))+ .filter(Boolean)+}++function isUnderPath(file, target) {+ return file === target || file.startsWith(`${target}/`)+}++// Recorded seconds of every node id under the given files and directories.+function pathsDuration(paths, durations) {+ if (!durations) {return 0}+ let total = 0+ for (const [test, dur] of Object.entries(durations)) {+ const file = test.split('::')[0]+ if (paths.some((target) => isUnderPath(file, target))) {+ total += dur+ }+ }+ return total+}+// Fallback shard counts used when .test_durations is missing.-const DJANGO_FALLBACK_SHARDS = { Core: 38, CorePOE: 7, Temporal: 7 }+const DJANGO_FALLBACK_SHARDS = { Core: 38, CorePOE: 7, Temporal: 7, JsonTargets: 5 }// A shard's wall is overhead + work/shards. Sizing solves that for the shared// TARGET_WALL_SECONDS: each shard carries (target - overhead) of work, so@@ -1230,6 +1272,74 @@ function decideSelection({ applies, disabled, draft, legacyChanged, runLegacy, r}}+function isUnderProduct(target, products) {+ return products.some((product) => target.startsWith(productPrefix(product)))+}++// The events_json paths a full run takes: the whole list, less the paths of products that+// SKIP_PRODUCT_TESTS or the quarantine file dropped from the product matrix.+function fullRunJsonTargets(targets, skippedProducts) {+ return targets.filter((target) => !isUnderProduct(target, skippedProducts))+}++// Which events_json paths this run executes. The leg follows the legacy tests. Null means+// the whole list at the full-run shard count. An array is the list to run, and an empty+// one means the leg does not run.+// mode the Django selection mode: 'selected', 'full', 'skip', or '' when this+// run does not select+// runLegacy whether the Django suite runs. When it does not, the leg still runs the+// paths of the products in the product matrix, because their own jobs+// read the legacy table only.+// selectedTests every test file the selector picked, product tests included+// products the product matrix after narrowing+// skippedProducts products that SKIP_PRODUCT_TESTS or the quarantine file dropped+// draft the PR is a draft. Only read in selected mode, the one mode that the+// merge queue's draft trunk-merge/** PR never reaches.+// doubled retain only paths the schema copies do not cover+function decideJsonTargets({+ targets, mode, runLegacy, selectedTests, products, skippedProducts = [], draft = false, doubled = false,+}) {+ if (doubled) {+ const paths = decideJsonTargets({ targets, mode, runLegacy, selectedTests, products, skippedProducts, draft })+ // Dagster tests are excluded from the doubled Django suites and have no product job.+ return (paths ?? targets).filter(+ (target) =>+ !isUnderProduct(target, products) &&+ !Object.values(DJANGO_SEGMENTS).some(+ (segment) =>+ segment.include.some((path) => isUnderPath(target, path.replace(/\/$/, ''))) &&+ !segment.exclude.some((path) => isUnderPath(target, path.replace(/\/$/, '')))+ )+ )+ }+ if (mode === 'skip') {+ return []+ }+ const productPaths = targets.filter((target) => isUnderProduct(target, products))+ if (!runLegacy) {+ return productPaths+ }+ if (mode !== 'selected') {+ const kept = fullRunJsonTargets(targets, skippedProducts)+ return kept.length === targets.length ? null : kept+ }+ // Product test files come in through productPaths instead, so that the leg tests the+ // same products as the product matrix. A draft runs no product tests, so it takes none.+ const legacyPaths = selectedTests.filter(+ (file) => !file.startsWith(PRODUCTS_DIR) && targets.some((target) => isUnderPath(file, target))+ )+ return [...new Set([...legacyPaths, ...(draft ? [] : productPaths)])].sort()+}++// Shards for a narrowed events_json leg: the full-run budget over the chosen paths' recorded+// seconds, floored at one like a selected Django segment.+function narrowedJsonTargetsShards(paths, durations) {+ if (paths.length === 0) {+ return 0+ }+ return calculateShards(pathsDuration(paths, durations), DJANGO_OVERHEAD_SECONDS_BY_SEGMENT.JsonTargets, 1)+}+// The run identity the selection telemetry event carries, from the runner's own env.function runContext() {let prNumber = null@@ -1247,20 +1357,25 @@ function runContext() {}}-function buildDjangoShards(durations, ranNodeIds = {}) {+function sizeDjangoSegment(segment, duration, durations, source) {+ const overhead = DJANGO_OVERHEAD_SECONDS_BY_SEGMENT[segment]+ const shards = durations ? calculateShards(duration, overhead) : DJANGO_FALLBACK_SHARDS[segment]+ const wall = overhead + duration / shards+ console.error(+ ` Django ${segment}: ${(duration / 60).toFixed(1)} min total, ${shards} shards (${durations ? source : 'fallback'}), ~${(wall / 60).toFixed(1)} min est. wall`+ )+ return { duration_seconds: duration, shards, estimated_wall_seconds: wall }+}++function buildDjangoShards(durations, ranNodeIds = {}, jsonTargets = []) {const result = {}for (const [segment] of Object.entries(DJANGO_SEGMENTS)) {- const overhead = DJANGO_OVERHEAD_SECONDS_BY_SEGMENT[segment]const ran = ranNodeIds[segment] || nullconst duration = getSegmentDuration(segment, durations, ran)- const shards = durations ? calculateShards(duration, overhead) : DJANGO_FALLBACK_SHARDS[segment]- const wall = overhead + duration / shards- result[segment] = { duration_seconds: duration, shards, estimated_wall_seconds: wall }- const source = durations ? (ran ? 'auto, junit-scoped' : 'auto, union') : 'fallback'- console.error(- ` Django ${segment}: ${(duration / 60).toFixed(1)} min total, ${shards} shards (${source}), ~${(wall / 60).toFixed(1)} min est. wall`- )+ result[segment] = sizeDjangoSegment(segment, duration, durations, ran ? 'auto, junit-scoped' : 'auto, union')}+ // No per-segment file records what the events_json leg ran, so it sizes from the union.+ result.JsonTargets = sizeDjangoSegment('JsonTargets', pathsDuration(jsonTargets, durations), durations, 'auto, union')return result}@@ -1364,6 +1479,8 @@ function buildMatrix(products, durations, productsScaled = false) {module.exports = {narrowedProducts,decideSelection,+ decideJsonTargets,+ loadJsonTargets,selectedShards,calculateShards,pruneDeadDurations,@@ -1635,8 +1752,24 @@ if (productsScaled) {const durations = pruneDeadDurations(rawDurations)const ranNodeIds = loadRanNodeIds()+const jsonTargets = loadJsonTargets()+const skippedProducts = [...new Set([...skipProducts, ...quarantinedProducts])]+const jsonTargetFiles = decideJsonTargets({+ targets: jsonTargets,+ mode: selectionDecision.mode,+ runLegacy,+ selectedTests: selection?.combined?.tests ?? [],+ products,+ skippedProducts,+ draft: process.env.PR_DRAFT === 'true',+ doubled: process.env.RUN_NEW_EVENTS_SCHEMA === 'true',+})+console.error('\nDjango shard calculation:')-const djangoShards = buildDjangoShards(durations, ranNodeIds)+const djangoShards = buildDjangoShards(durations, ranNodeIds, fullRunJsonTargets(jsonTargets, skippedProducts))+if (jsonTargetFiles !== null) {+ console.error(`events_json leg runs ${jsonTargetFiles.length} of ${jsonTargets.length} paths: ${JSON.stringify(jsonTargetFiles)}`)+}const { mode, core_files, poe_files, temporal_files, compat_files, run_poe, run_temporal, segment_shards, ...metrics } =selectionDecision@@ -1656,6 +1789,10 @@ const result = {run_poe,run_temporal,segment_shards: segment_shards ? JSON.stringify(segment_shards) : '',+ // Empty on a run that takes the whole list. A full run sizes from django_shards.JsonTargets+ // even when a skipped product shortens its list here.+ json_targets_files: jsonTargetFiles === null ? '' : jsonTargetFiles.join(' '),+ json_targets_shards: jsonTargetFiles === null ? '' : narrowedJsonTargetsShards(jsonTargetFiles, durations),},// The posthog-ci-test-selection event, ready for the capture-test-selection job.telemetry: {diff --git a/.github/scripts/turbo-discover.test.js b/.github/scripts/turbo-discover.test.jsindex 6e9e89e979db..62faf1f68135 100644--- a/.github/scripts/turbo-discover.test.js+++ b/.github/scripts/turbo-discover.test.js@@ -11,11 +11,12 @@const test = require('node:test')const assert = require('node:assert/strict')+const { execFileSync } = require('node:child_process')const fs = require('node:fs')const os = require('node:os')const path = require('node:path')-const { DJANGO_SEGMENTS, getIsolatedProducts } = require('./turbo-discover')+const { DJANGO_SEGMENTS, getIsolatedProducts, loadJsonTargets } = require('./turbo-discover')const REPO_ROOT = path.join(__dirname, '..', '..')const WORKFLOWS = ['.github/workflows/ci-backend.yml', '.depot/workflows/ci-backend.yml']@@ -159,3 +160,22 @@ test('isolation needs both the contract-check script and narrowed contract inputassert.deepEqual([...getIsolatedProducts(tasks, repoRoot)].sort(), ['declared', 'multi-word'])})++// The events_json rows skip a listed path that a checkout lacks, and pytest passes a path+// that collects nothing, so a typo, a moved directory, or a directory of runner modules alone+// would drop out of the leg without failing anything. The index covers the paths that the+// sparse checkout of this suite leaves out of the working tree.+test('every events_json path holds a test module', () => {+ const targets = loadJsonTargets(path.join(REPO_ROOT, '.github/new-events-schema-targets.txt'))+ assert.ok(targets.length > 0)+ for (const target of targets) {+ const tracked = execFileSync('git', ['ls-files', '-z', '--', target], { cwd: REPO_ROOT })+ .toString()+ .split('\0')+ .filter(Boolean)+ assert.ok(+ tracked.some((file) => /(^|\/)(test_[^/]*|[^/]*_test)\.py$/.test(file)),+ `${target} is listed but holds no test module`+ )+ }+})diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.ymlindex b33964393de5..5c22c2da1e64 100644--- a/.github/workflows/ci-backend.yml+++ b/.github/workflows/ci-backend.yml@@ -36,9 +36,13 @@ on:# so every unrelated label re-ran these matrices against a commit CI had# already covered. A label here takes effect from the next push, or from# ready_for_review.- # The `test-new-events-schema` label opts a PR into the doubled matrices that- # cover both events schemas. Apply it before a push or ready_for_review because- # label events do not start this workflow. Manual dispatches also run both modes.+ # The events_json leg runs wherever the legacy tests run, the hourly master run+ # included: the paths in .github/new-events-schema-targets.txt rerun against the+ # native-JSON events table, all of them on full runs and the reached ones on+ # narrowed runs. The `test-new-events-schema` label opts a PR into the doubled+ # matrices that run the whole suite in both events schemas, in place of that leg.+ # Apply it before a push or ready_for_review because label events do not start+ # this workflow. Manual dispatches also run both modes.types: [opened, synchronize, reopened, ready_for_review]concurrency:@@ -311,6 +315,7 @@ jobs:- 'products/*/turbo.json'# Make sure we run if someone is explicitly changing the workflow- .github/workflows/ci-backend.yml+ - .github/new-events-schema-targets.txt- .github/actions/setup-uv/**- .github/clickhouse-versions.json# We use docker compose for tests, make sure we rerun on@@ -365,6 +370,7 @@ jobs:- 'products/*/manifest.tsx'- rust/feature-flags/src/properties/property_models.rs- .github/workflows/ci-backend.yml+ - .github/new-events-schema-targets.txt- .github/actions/setup-uv/**- .github/clickhouse-versions.json- docker-compose.dev.yml@@ -817,6 +823,7 @@ jobs:# 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 }}+ RUN_NEW_EVENTS_SCHEMA: ${{ contains(github.event.pull_request.labels.*.name, 'test-new-events-schema') || github.event_name == 'workflow_dispatch' }}SCHEMA_CHANGED: ${{ github.event_name != 'pull_request' || needs.changes.outputs.schema }}TURBO_SCM_HEAD: ${{ github.sha }}# Kill switch — drop comma-separated products from the matrix; empty = run all.@@ -862,8 +869,10 @@ jobs:id: buildenv:PRODUCT_MATRIX_JSON: ${{ needs.turbo-discover.outputs.matrix }}- # The new-events-schema variants double the matrix, so run them only on- # opted-in PRs and manual dispatches.+ # The new-events-schema variants double the matrix, so they run only on+ # opted-in PRs and manual dispatches. Other runs cover the product paths+ # in .github/new-events-schema-targets.txt with the Django matrix's+ # events_json rows.RUN_NEW_EVENTS_SCHEMA: ${{ contains(github.event.pull_request.labels.*.name, 'test-new-events-schema') || github.event_name == 'workflow_dispatch' }}run: |if [[ "$RUN_NEW_EVENTS_SCHEMA" == "true" ]]; then@@ -1262,6 +1271,9 @@ jobs:uses: ./.github/actions/trunk-quarantine-gatewith:junit-paths: trunk-junit/junit-product-*.xml+ # A native-JSON leg uploads under its own variant, so a failure in that mode+ # does not read as a flake of the legacy test with the same id.+ variant: ${{ matrix.new-events-schema && 'events-json' || '' }}previous-step-outcome: ${{ steps.run-product-tests.outcome }}token: ${{ secrets.TRUNK_API_TOKEN }}@@ -2636,9 +2648,19 @@ jobs:IS_DRAFT: ${{ github.event.pull_request.draft && !startsWith(github.head_ref, 'trunk-merge/') }}IS_PR_RUN: ${{ github.event_name == 'pull_request' && !startsWith(github.head_ref, 'trunk-merge/') }}FORCE_FULL: ${{ contains(github.event.pull_request.labels.*.name, 'run-ci-backend') }}- # The new-events-schema variants double the matrix, so run them only on- # opted-in PRs and manual dispatches.+ # The new-events-schema variants double the matrix, so they run only on+ # opted-in PRs and manual dispatches. Every other run takes the+ # events_json rows, which cover .github/new-events-schema-targets.txt only.RUN_NEW_EVENTS_SCHEMA: ${{ contains(github.event.pull_request.labels.*.name, 'test-new-events-schema') || github.event_name == 'workflow_dispatch' }}+ # Narrowed events_json paths and their shard count. Empty files on a run+ # that takes the whole list.+ JSON_TARGETS_FILES: ${{ fromJSON(needs.turbo-discover.outputs.selection || '{}').json_targets_files }}+ JSON_TARGETS_SHARDS: ${{ fromJSON(needs.turbo-discover.outputs.selection || '{}').json_targets_shards }}+ # Same rule as the django job's condition: the suite runs for a legacy+ # edit, for a product change that reaches legacy code, and when discovery+ # failed, which leaves run_legacy empty. Without it only the events_json+ # rows for the product matrix run.+ DJANGO_SUITE: ${{ needs.changes.outputs.legacy == 'true' || needs.turbo-discover.outputs.run_legacy != 'false' }}run: |# :NOTE: Keep shard counts/group ranges in sync with historical Django matrix tuning.# Consult #team-devex before changing.@@ -2664,7 +2686,20 @@ jobs:exit 0fi- if [[ "$MODE" == "selected" ]]; then+ if [[ "$DJANGO_SUITE" != "true" ]]; then+ # A product change that reaches no legacy code skips the Django suite.+ # The product jobs read the legacy events table only, so the events_json+ # rows still run the listed paths of the products in the product matrix.+ core="[]"+ core_new_events_schema="[]"+ core_persons_on_events="[]"+ core_persons_on_events_new_schema="[]"+ temporal="[]"+ temporal_new_events_schema="[]"+ compat="[]"+ json_targets_count=0+ [[ -n "$JSON_TARGETS_FILES" ]] && json_targets_count="${JSON_TARGETS_SHARDS:-1}"+ elif [[ "$MODE" == "selected" ]]; then# Selected mode: run only the segments that have selected files. Shard# counts come from turbo-discover, which applies its per-shard budget to# the selected tests' recorded seconds. A wide selection therefore@@ -2782,20 +2817,28 @@ jobs:elsecompat="[]"fi+ # The narrowed events_json paths: selected files under a listed path,+ # plus the listed paths of the products in the narrowed product matrix.+ json_targets_count=0+ [[ -n "$JSON_TARGETS_FILES" ]] && json_targets_count="${JSON_TARGETS_SHARDS:-1}"else# Full run: auto-shard counts from turbo-discover (Amdahl's law on .test_durations).# Falls back to hardcoded defaults if turbo-discover failed or data is missing.CORE_SHARDS=38CORE_POE_SHARDS=7TEMPORAL_SHARDS=7+ JSON_TARGETS_FULL_SHARDS=5if [ -n "$DJANGO_SHARDS_JSON" ] && echo "$DJANGO_SHARDS_JSON" | jq -e '.Core.shards' > /dev/null 2>&1; thenCORE_SHARDS=$(echo "$DJANGO_SHARDS_JSON" | jq -r '.Core.shards')CORE_POE_SHARDS=$(echo "$DJANGO_SHARDS_JSON" | jq -r '.CorePOE.shards')TEMPORAL_SHARDS=$(echo "$DJANGO_SHARDS_JSON" | jq -r '.Temporal.shards')- echo "Auto-sharding: Core=$CORE_SHARDS, CorePOE=$CORE_POE_SHARDS, Temporal=$TEMPORAL_SHARDS"+ JSON_TARGETS_FULL_SHARDS=$(echo "$DJANGO_SHARDS_JSON" | jq -r --argjson fallback "$JSON_TARGETS_FULL_SHARDS" '.JsonTargets.shards // $fallback')+ echo "Auto-sharding: Core=$CORE_SHARDS, CorePOE=$CORE_POE_SHARDS, Temporal=$TEMPORAL_SHARDS, JsonTargets=$JSON_TARGETS_FULL_SHARDS"else- echo "::warning::Django shard auto-sizing unavailable, using defaults: Core=$CORE_SHARDS, CorePOE=$CORE_POE_SHARDS, Temporal=$TEMPORAL_SHARDS"+ echo "::warning::Django shard auto-sizing unavailable, using defaults: Core=$CORE_SHARDS, CorePOE=$CORE_POE_SHARDS, Temporal=$TEMPORAL_SHARDS, JsonTargets=$JSON_TARGETS_FULL_SHARDS"fi+ # A full run takes every listed events_json path.+ json_targets_count="$JSON_TARGETS_FULL_SHARDS"# The legacy-mode safeguard leg runs only where a regression must not# land: merge queue and master. Ordinary PR lanes run the@@ -2909,14 +2952,36 @@ jobs:fiif [[ "$RUN_NEW_EVENTS_SCHEMA" != "true" ]]; then- # With the schema copies paused, snapshot bot commits leave- # *.new_events_schema.ambr files untouched, so those go stale.+ # Without the schema copies, only the events_json rows below refresh+ # *.new_events_schema.ambr files, so a module outside+ # .github/new-events-schema-targets.txt lets its file go stale.echo "Skipping new-events-schema variants (RUN_NEW_EVENTS_SCHEMA is off)"core_new_events_schema="[]"core_persons_on_events_new_schema="[]"temporal_new_events_schema="[]"+ else+ # The doubled matrices exclude some curated paths, such as Dagster tests.+ # Discovery keeps only those paths so the other tests do not run a third time.+ json_targets_count="${JSON_TARGETS_SHARDS:-0}"fi+ # The events_json rows: Core jobs over the listed paths with the+ # native-JSON events table. They keep Core's person-on-events default.+ json_targets=$(jq -cn --arg image "$OLDEST_SUPPORTED_IMAGE" --argjson n "$json_targets_count" '+ [range(1; $n + 1) | {+ segment: "Core",+ "json-targets": true,+ "person-on-events": false,+ "new-events-schema": true,+ "python-version": "3.13.13",+ "clickhouse-server-image": $image,+ concurrency: $n,+ group: .,+ artifact_key: ("json-targets-" + (.|tostring)),+ compat: false+ }]+ ')+include=$(jq -cn \--argjson core "$core" \--argjson core_new_events_schema "$core_new_events_schema" \@@ -2925,7 +2990,8 @@ jobs:--argjson temporal "$temporal" \--argjson temporal_new_events_schema "$temporal_new_events_schema" \--argjson compat "$compat" \- '$core + $core_new_events_schema + $core_persons_on_events + $core_persons_on_events_new_schema + $temporal + $temporal_new_events_schema + $compat')+ --argjson json_targets "$json_targets" \+ '$core + $core_new_events_schema + $core_persons_on_events + $core_persons_on_events_new_schema + $temporal + $temporal_new_events_schema + $compat + $json_targets')echo "include=$include" >> "$GITHUB_OUTPUT"echo "Django matrix size: $(jq -r 'length' <<< "$include") (mode=$MODE)"@@ -2936,6 +3002,8 @@ jobs:# 1. Legacy code directly changed (ee/, posthog/)# 2. OR product changes affect legacy code (turbo-discover outputs run_legacy=true)# 3. OR turbo-discover itself failed (conservative: run Django on detection failure)+ # 4. OR a product-only change has events_json paths to run. build_django_matrix+ # then builds only the events_json rows, because the Django suite does not run.# The non-empty include guard covers drafts in skip mode and selected runs# that chose zero files — an empty matrix would otherwise fail the job.# A status function is required to inspect dependency results after failures.@@ -2947,12 +3015,13 @@ jobs:needs.build_django_matrix.outputs.include != '[]' &&(needs.changes.outputs.legacy == 'true' ||needs.turbo-discover.outputs.run_legacy == 'true' ||- (needs.turbo-discover.result != 'success' && needs.turbo-discover.result != 'skipped'))+ (needs.turbo-discover.result != 'success' && needs.turbo-discover.result != 'skipped') ||+ fromJSON(needs.turbo-discover.outputs.selection || '{}').json_targets_files != '')# increase for tmate testing# 45 for slow Temporal shards on master; keep <= deploy gate wait (container-images-cd.yml)timeout-minutes: 45- name: Django tests – ${{ matrix.segment }}${{ matrix.compat && ' compat' || '' }} (persons-on-events ${{ (matrix.segment == 'Core' && !matrix.person-on-events && !matrix.compat) && 'on' || 'off' }}, events schema ${{ matrix.new-events-schema && 'json' || 'legacy' }}), Py ${{ matrix.python-version }}, ${{ matrix.clickhouse-server-image }} (${{matrix.group}}/${{ matrix.concurrency }})+ name: Django tests – ${{ matrix.segment }}${{ matrix.compat && ' compat' || '' }}${{ matrix.json-targets && ' json-targets' || '' }} (persons-on-events ${{ (matrix.segment == 'Core' && !matrix.person-on-events && !matrix.compat) && 'on' || 'off' }}, events schema ${{ matrix.new-events-schema && 'json' || 'legacy' }}), Py ${{ matrix.python-version }}, ${{ matrix.clickhouse-server-image }} (${{matrix.group}}/${{ matrix.concurrency }})# Runner type is performance-critical — consult #team-devex before changingruns-on: depot-ubuntu-24.04@@ -3462,12 +3531,16 @@ jobs: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 }}+ JSON_TARGETS: ${{ matrix.json-targets && 'true' || 'false' }}+ # The narrowed events_json paths. Empty when the row takes the whole list.+ JSON_TARGETS_FILES: ${{ fromJSON(needs.turbo-discover.outputs.selection || '{}').json_targets_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.turbo-discover.outputs.mode != 'selected' && '--cov=posthog --cov=ee --cov-config=.github/coverage-core.cfg --cov-report=' || '' }}+ # artifact nothing reads. The events_json rows rerun tests the legacy+ # rows already measure, so they skip it as well.+ COV_ARGS: ${{ github.event_name == 'pull_request' && needs.turbo-discover.outputs.mode != 'selected' && !matrix.json-targets && '--cov=posthog --cov=ee --cov-config=.github/coverage-core.cfg --cov-report=' || '' }}# 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@@ -3508,14 +3581,56 @@ jobs:# (restored from the daily master cache) when the pinned pytest-split# supports it, so the plan isn't poisoned by the union .test_durations's# cross-segment tests — see AGENTS.md (CI). Only persons-on-events-off,- # non-compat Core matches the .core run-set; POE-on and compat run a- # different/narrower scope, and a cache miss with no committed file all- # fall back to scoping the union.- if [ -f .test_durations.core ] && [[ "${{ matrix.person-on-events }}" != "true" ]] && [[ "${{ matrix.compat }}" != "true" ]] && python -c "from pytest_split.plugin import SUPPORTS_SPLIT_PLAN_PATH" 2>/dev/null; then+ # non-compat Core matches the .core run-set; POE-on, compat, and the+ # events_json rows run a different/narrower scope, and a cache miss with+ # no committed file all fall back to scoping the union.+ if [ -f .test_durations.core ] && [[ "${{ matrix.person-on-events }}" != "true" ]] && [[ "${{ matrix.compat }}" != "true" ]] && [[ "$JSON_TARGETS" != "true" ]] && python -c "from pytest_split.plugin import SUPPORTS_SPLIT_PLAN_PATH" 2>/dev/null; thenSPLIT_GRANULARITY+=(--split-plan-path .test_durations.core)fifi- if [[ "$MODE" == "selected" ]]; then+ if [[ "$JSON_TARGETS" == "true" ]]; then+ # The events_json leg. The job checks out the PR head, and a head without+ # the list also predates the JSON-mode test fixes that came before it, so+ # its listed tests would fail on code the PR did not touch. The merge+ # queue's trunk-merge/** head always has the list, so the gate still runs.+ if [[ ! -f .github/new-events-schema-targets.txt ]]; then+ echo "::notice::The checked-out revision predates .github/new-events-schema-targets.txt, so the events_json leg runs nothing until this branch rebases onto master"+ exit 0+ fi+ # A narrowed run hands over its paths, and every other run takes the+ # whole list. Parse it the way turbo-discover.js does.+ if [[ -n "$JSON_TARGETS_FILES" ]]; then+ read -r -a json_candidates <<< "$JSON_TARGETS_FILES"+ else+ mapfile -t json_candidates < <(sed -e 's/#.*//' -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' -e 's:/*$::' -e '/^$/d' .github/new-events-schema-targets.txt)+ fi+ # The PR head can lack a path that the merged list names. pytest stops+ # with a usage error on a missing path, so skip that path and say so.+ json_targets=()+ for target in "${json_candidates[@]}"; do+ if [[ -e "$target" ]]; then+ json_targets+=("$target")+ else+ echo "::warning::events_json path $target does not exist in this checkout, so it does not run"+ fi+ done+ if [[ ${#json_targets[@]} -eq 0 ]]; then+ exit 0+ fi+ JSON_SPLIT=()+ if [[ "${{ matrix.concurrency }}" -gt 1 ]]; then+ JSON_SPLIT=(--splits "${{ matrix.concurrency }}" --group "${{ matrix.group }}"+ --splitting-algorithm="$SPLITTING_ALGORITHM" "${SPLIT_GRANULARITY[@]}")+ fi+ # No --store-durations, because the timing data describes legacy-table runs only.+ # shellcheck disable=SC2086+ pytest -v --tb=short --reuse-db -o junit_duration_report=call "${json_targets[@]}" -m "not async_migrations" \+ "${JSON_SPLIT[@]}" \+ "${RETRY_ARGS[@]}" -r fEsxXR \+ --junitxml=junit-core.xml \+ $COV_ARGS \+ $PYTEST_ARGS+ elif [[ "$MODE" == "selected" ]]; then# Selected mode: run only the test files chosen by the snob shadow selector.# Sharded only when build_django_matrix sized the segment above one shard,# no --store-durations (don't pollute timing data with a partial run).@@ -3581,7 +3696,7 @@ jobs:- name: Upload core coverageuses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0- if: ${{ always() && github.event_name == 'pull_request' && needs.turbo-discover.outputs.mode != 'selected' && matrix.segment == 'Core' }}+ if: ${{ always() && github.event_name == 'pull_request' && needs.turbo-discover.outputs.mode != 'selected' && matrix.segment == 'Core' && !matrix.json-targets }}with:name: coverage-core-${{ strategy.job-index }}path: .coverage@@ -3839,6 +3954,9 @@ jobs:with:junit-paths: junit-core.xml,junit-core-retry-failures.xmlorg-slug: posthog-inc+ # A native-JSON row uploads under its own variant, so a failure in that mode+ # does not read as a flake of the legacy test with the same id.+ variant: ${{ matrix.new-events-schema && 'events-json' || '' }}cli-version: '0.15.4'quarantine: trueprevious-step-outcome: ${{ steps.run-core-tests.outcome }}@@ -3851,6 +3969,9 @@ jobs:with:junit-paths: junit-temporal.xml,junit-temporal-retry-failures.xmlorg-slug: posthog-inc+ # A native-JSON row uploads under its own variant, so a failure in that mode+ # does not read as a flake of the legacy test with the same id.+ variant: ${{ matrix.new-events-schema && 'events-json' || '' }}cli-version: '0.15.4'quarantine: trueprevious-step-outcome: ${{ steps.run-temporal-tests.outcome }}diff --git a/.github/workflows/ci-scripts.yml b/.github/workflows/ci-scripts.ymlindex 68bd7d4ec8bb..4b3949786d9e 100644--- a/.github/workflows/ci-scripts.yml+++ b/.github/workflows/ci-scripts.yml@@ -13,9 +13,11 @@ on:# trunk-impacted-targets.test.js reads proto/ and fails on a tree the# table does not declare, so adding one has to run these tests.- proto/**- # turbo-discover.test.js pins the Django segment table to these.+ # turbo-discover.test.js pins the Django segment table to these, and checks+ # that every path in the events_json list exists.- .github/workflows/ci-backend.yml- .depot/workflows/ci-backend.yml+ - .github/new-events-schema-targets.txt# The backend test selector and its verdict script gate ci-backend.- tools/snob_backend_test_selection_shadow.py- tools/test_snob_backend_test_selection_shadow.pydiff --git a/AGENTS.md b/AGENTS.mdindex 77b272bc120b..99cf2b94274d 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -137,7 +137,7 @@ Examples:- CI uploads test results to Trunk Flaky Tests; the `trunk` MCP server in `.mcp.json` queries per-test flakiness on a PR or `master` (authenticate via `/mcp`, or a `TRUNK_API_TOKEN` bearer header when headless) — see `/debugging-ci-failures` and `/fixing-flaky-tests`- **A workflow edit reaches every open PR before those branches rebase.** It runs against the PR merged with master, but a companion change — a new dependency, file, or config — only arrives when the branch rebases. A workflow that starts requiring something unrebased branches lack fails every in-flight PR before its tests run. Make the new behavior degrade gracefully, or gate it. This has broken CI repeatedly.- Mechanical workflow rules (`timeout-minutes`, concurrency, dispatch budget, path filters, gate hygiene) are enforced by `hogli lint:workflows` and actionlint, which are the source of truth. `/authoring-ci-workflows` explains the reasoning behind each.-- **Agents must classify every PR for native-JSON event-table coverage before opening it.** Add `test-new-events-schema` when a diff changes event ingestion or cleaning, event or property reads, generated SQL over events, or schema-specific snapshots. Add the label while the PR is a draft so `ready_for_review` starts the run. If the PR must open ready, label it immediately and push another commit because label events do not start Backend CI. Leave unrelated PRs unlabeled because the label doubles the backend test matrices.+- **A directory of tests that read event properties belongs in `.github/new-events-schema-targets.txt`.** Backend CI reruns the listed paths against the native-JSON events table. A test outside the list runs on the legacy table only. Add the `test-new-events-schema` label when a diff needs the whole backend suite on both tables, such as an event ingestion change or event reads tested outside the list. Label while the PR is a draft, or push again after labeling, because label events do not start Backend CI.- **A pull request never publishes a package or release.** `[lint: github-actions-publish-on-pull-request]` A published version is public forever, and a pull request run executes code its author controls. Publish only from a `push` to `master`, a release tag, or a `workflow_dispatch` on `master`. A pull request run only builds and validates, for example with `--dry-run`. The semgrep rule cannot see a publisher inside a reusable workflow, so gate that job in the called workflow too. Never run a publish command by hand from a pull request branch. [`build-hogql-parser-npm.yml`](.github/workflows/build-hogql-parser-npm.yml) is the reference shape.## Securitydiff --git a/tools/snob_backend_test_selection_shadow.py b/tools/snob_backend_test_selection_shadow.pyindex fa674ec4a05f..b2f12f4c9182 100755--- a/tools/snob_backend_test_selection_shadow.py+++ b/tools/snob_backend_test_selection_shadow.py@@ -80,6 +80,8 @@ FULL_RUN_PATTERNS = (".test_quarantine.json",# CI / Docker infrastructure".github/workflows/ci-backend.yml",+ # A new path in the events_json list has to run on the PR that adds it.+ ".github/new-events-schema-targets.txt",".github/clickhouse-versions.json","docker-compose","docker/clickhouse/",diff --git a/tools/workflow-plan/tests/workflows.test.ts b/tools/workflow-plan/tests/workflows.test.tsindex 2995dedc6303..f37751b25c47 100644--- a/tools/workflow-plan/tests/workflows.test.ts+++ b/tools/workflow-plan/tests/workflows.test.ts@@ -234,6 +234,42 @@ const EXPECTATIONS: Expectation[] = [skipped: ['backend-coverage-report', 'dynamic-ci-filter'],}),+ // A product change that reaches no legacy code skips the Django suite, but the events_json+ // rows still run the changed products' listed paths, because product jobs read the legacy+ // events table only.+ backend(+ {+ name: 'product-only PR whose products have events_json paths',+ steps: {+ changes: { filter: pathsFilter({ backend: true, legacy: false }) },+ 'turbo-discover': {+ discover: {+ outputs: {+ run_legacy: 'false',+ matrix: '[{"group":"a"}]',+ mode: '',+ selection: '{"json_targets_files":"products/web_analytics/backend/hogql_queries"}',+ },+ },+ },+ },+ },+ { runs: ['turbo-tests', 'django', 'django_tests'] }+ ),+ backend(+ {+ name: 'product-only PR without events_json paths',+ steps: {+ changes: { filter: pathsFilter({ backend: true, legacy: false }) },+ 'turbo-discover': {+ discover: {+ outputs: { run_legacy: 'false', matrix: '[{"group":"a"}]', mode: '', selection: '{"json_targets_files":""}' },+ },+ },+ },+ },+ { runs: ['turbo-tests', 'django_tests'], skipped: ['django'] }+ ),backend({ name: 'draft PR labeled no-ci', github: pullRequest({ draft: true, labels: ['no-ci'] }) },{