: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
fix(devex): realign the Django segment partition and the isolated-product readers (#87081)
Julian Beza23805ebb819
diff --git a/.depot/workflows/ci-backend.yml b/.depot/workflows/ci-backend.ymlindex 71660b2b91ad..d4a6009f5320 100644--- a/.depot/workflows/ci-backend.yml+++ b/.depot/workflows/ci-backend.yml@@ -649,11 +649,15 @@ jobs:# 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.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.@@ -826,9 +830,10 @@ jobs:# Partition selected files by the Django segment that owns them.# Mirrors the positional path arguments in the Run Core / Run Temporal pytest invocations:# Core (POE off): posthog ee/ (minus posthog/temporal, posthog/dags,- # posthog/test/repo_invariants)- # Core POE on: posthog/clickhouse, posthog/queries, posthog/api/test/test_insight*,- # posthog/api/test/dashboards/test_dashboard.py, ee/clickhouse/+ # common/hogvm/python/test, posthog/test/repo_invariants)+ # Core POE on: posthog/clickhouse, posthog/queries, ee/clickhouse/,+ # products/product_analytics/backend/tests/api,+ # posthog/api/test/dashboards/test_dashboard.py# Temporal: posthog/temporal, products/{batch_exports,tasks}/backend/temporal,# products/signals/backend/emission# Compat: CLICKHOUSE_COMPAT_PYTEST_TARGETS (posthog/clickhouse, ee/clickhouse)@@ -855,7 +860,7 @@ jobs:posthog/temporal/*|products/batch_exports/backend/tests/temporal/*|products/tasks/backend/temporal/*|products/signals/backend/emission/*)temporal+=("$f");;- posthog/clickhouse/*|posthog/queries/*|ee/clickhouse/*|products/product_analytics/backend/tests/api/*|posthog/api/test/test_insight*|posthog/api/test/dashboards/test_dashboard.py)+ posthog/clickhouse/*|posthog/queries/*|ee/clickhouse/*|products/product_analytics/backend/tests/api/*|posthog/api/test/dashboards/test_dashboard.py)poe+=("$f")core+=("$f");;diff --git a/.github/scripts/trunk-impacted-targets.js b/.github/scripts/trunk-impacted-targets.jsindex 02061922c6e5..cc7129c67bad 100644--- a/.github/scripts/trunk-impacted-targets.js+++ b/.github/scripts/trunk-impacted-targets.js@@ -601,15 +601,17 @@ function listProducts(repoRoot) {.sort()}-// A product is isolated when it declares a backend:contract-check script, the-// same signal turbo-discover uses to decide a product can be tested alone.-// Non-isolated products have no narrowed contract, so a change in one is-// treated as a core change.-function listIsolatedProducts(repoRoot, products) {+// A product is isolated when it declares a backend:contract-check script *and*+// narrows that task's inputs in its own turbo.json, the same pair turbo-discover+// uses to decide a product can be tested alone. The script alone leaves the task+// on the root definition, whose inputs are the product's whole backend, so the+// product claims a contract surface it never narrowed. Non-isolated products+// have no narrowed contract, so a change in one is treated as a core change.+function listIsolatedProducts(repoRoot, products, contractSurfaces) {const isolated = new Set()for (const product of products) {const manifest = path.join(repoRoot, 'products', product, 'package.json')- if (!fs.existsSync(manifest)) {+ if (!fs.existsSync(manifest) || !contractSurfaces.has(product)) {continue}const parsed = JSON.parse(fs.readFileSync(manifest, 'utf8'))@@ -1845,12 +1847,13 @@ function buildContext(repoRoot) {const products = listProducts(repoRoot)const tachGraph = loadTachGraph(repoRoot)const rustGraph = loadRustGraph(repoRoot)+ const contractSurfaces = loadContractSurfaces(repoRoot, products)return {products,cargoLockCrates: parseCargoLockCrates(process.env[CARGO_LOCK_CRATES_ENV], rustGraph),services: listServices(repoRoot),- isolatedProducts: listIsolatedProducts(repoRoot, products),- contractSurfaces: loadContractSurfaces(repoRoot, products),+ isolatedProducts: listIsolatedProducts(repoRoot, products, contractSurfaces),+ contractSurfaces,productWorkspaces: loadProductWorkspaces(repoRoot, products),backendDetachedProducts: loadBackendDetachedProducts(repoRoot, products, tachGraph),tachDeclaredProducts: listTachDeclaredProducts(products, tachGraph),@@ -1869,6 +1872,8 @@ module.exports = {globToRegExp,isProductDirectory,isTripwire,+ listIsolatedProducts,+ loadContractSurfaces,parseCrateDependencies,parseCrateName,parsePytestIgnores,diff --git a/.github/scripts/trunk-impacted-targets.test.js b/.github/scripts/trunk-impacted-targets.test.jsindex 585b2e2895a9..25d9be3a5155 100644--- a/.github/scripts/trunk-impacted-targets.test.js+++ b/.github/scripts/trunk-impacted-targets.test.js@@ -10,6 +10,7 @@const test = require('node:test')const assert = require('node:assert/strict')const fs = require('node:fs')+const os = require('node:os')const path = require('node:path')const {@@ -22,6 +23,8 @@ const {globToRegExp,isProductDirectory,isTripwire,+ listIsolatedProducts,+ loadContractSurfaces,parseCrateDependencies,parseCrateName,parsePytestIgnores,@@ -1104,6 +1107,32 @@ test('editing the declarations that define the gate always cascades', () => {}})+// Isolation is the claim that a product's change can be tested alone, and the+// contract-check script alone does not back it: without a turbo.json the task+// keeps the root inputs, which are the product's whole backend. turbo-discover+// reads the same pair, so a reader that accepted the script alone would call a+// product isolated in one place and not the other.+test('isolation needs both the contract-check script and a narrowed turbo.json', () => {+ const repoRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'isolation-'))+ const write = (product, files) => {+ fs.mkdirSync(path.join(repoRoot, 'products', product), { recursive: true })+ for (const [name, body] of Object.entries(files)) {+ fs.writeFileSync(path.join(repoRoot, 'products', product, name), JSON.stringify(body))+ }+ }+ const contractScript = { scripts: { 'backend:contract-check': 'true' } }+ const narrowed = { tasks: { 'backend:contract-check': { inputs: ['backend/facade/**'] } } }+ write('declared', { 'package.json': contractScript, 'turbo.json': narrowed })+ write('script-only', { 'package.json': contractScript })+ write('inputs-only', { 'turbo.json': narrowed })+ write('neither', { 'package.json': {} })++ const products = ['declared', 'inputs-only', 'neither', 'script-only']+ const isolated = listIsolatedProducts(repoRoot, products, loadContractSurfaces(repoRoot, products))++ assert.deepEqual([...isolated], ['declared'])+})+test('contract inputs honor negation and drop inputs outside the product', () => {const matcher = compileContractMatcher(['backend/**/*.py', '!backend/**/__pycache__/**', '../../uv.lock'])assert.equal(matcher('backend/api.py'), true)diff --git a/.github/scripts/turbo-discover.js b/.github/scripts/turbo-discover.jsindex d9d7450b4804..b264dfd4284f 100644--- a/.github/scripts/turbo-discover.js+++ b/.github/scripts/turbo-discover.js@@ -25,6 +25,7 @@ const { execFileSync } = require('child_process')const fs = require('fs')const path = require('path')const { analyzeSchemaImpact, readBaseSchema } = require('./schema-impact')+const { loadContractSurfaces } = require('./trunk-impacted-targets')// --- Product shard sizing (same Amdahl shape as Django below) ---// Each product is atomic for packing, but unlike Django the test pool isn't@@ -127,8 +128,19 @@ function packageToProduct(pkg) {return pkg.replace('@posthog/products-', '')}-function getIsolatedProducts(contractTasks) {- return new Set(contractTasks.map((t) => packageToProduct(t.package)))+// A product that ships the contract-check script but no turbo.json of its own+// inherits the root task, whose inputs are the product's whole backend. Every+// backend edit then reads as a contract change, so the isolation it claims can+// never pay out. Requiring the narrowed declaration keeps "isolated" meaning+// what turbo-discover uses it for, and reading it through loadContractSurfaces+// keeps this reader and the Trunk lane reader on one definition.+function getIsolatedProducts(contractTasks, repoRoot = process.cwd()) {+ const products = contractTasks.map((t) => packageToProduct(t.package))+ // Package names use dashes, product directories use underscores; the surface+ // reader resolves products/<dir>/turbo.json, so look up the directory form.+ const toDir = (product) => product.replace(/-/g, '_')+ const surfaces = loadContractSurfaces(repoRoot, products.map(toDir))+ return new Set(products.filter((product) => surfaces.has(toDir(product))))}function getAffectedTaskProducts(tasks) {@@ -524,14 +536,16 @@ function packProducts(products, durations) {return buckets}-// Path filters matching the Django workflow pytest invocations.-// Core: posthog/ + ee/ minus temporal, dags, hogvm+// Path filters matching the Django workflow pytest invocations. A segment that+// drifts from its pytest targets sizes shards for a run that never happens, so+// turbo-discover.test.js asserts these against ci-backend.yml itself.+// Core: posthog/ + ee/ minus the paths the Core invocation --ignore's// Core POE: subset of Core (ignores hogql, hogql_queries) — same pool, fewer tests-// Temporal: posthog/temporal + products/batch_exports/backend/tests/temporal + products/tasks/backend/temporal+// Temporal: posthog/temporal + the product temporal/emission suites it runs alongsideconst DJANGO_SEGMENTS = {Core: {include: ['posthog/', 'ee/'],- exclude: ['posthog/temporal/', 'posthog/dags/', 'common/hogvm/'],+ exclude: ['posthog/temporal/', 'posthog/dags/', 'common/hogvm/python/test/', 'posthog/test/repo_invariants/'],},CorePOE: {// Keep in sync with the person-on-events pytest targets in@@ -543,10 +557,22 @@ const DJANGO_SEGMENTS = {'posthog/api/test/dashboards/test_dashboard.py','ee/clickhouse/',],- exclude: ['posthog/temporal/', 'posthog/dags/', 'common/hogvm/', 'posthog/hogql_queries/', 'posthog/hogql/'],+ exclude: [+ 'posthog/temporal/',+ 'posthog/dags/',+ 'common/hogvm/python/test/',+ 'posthog/test/repo_invariants/',+ 'posthog/hogql_queries/',+ 'posthog/hogql/',+ ],},Temporal: {- include: ['posthog/temporal/', 'products/batch_exports/backend/tests/temporal/', 'products/tasks/backend/temporal/'],+ include: [+ 'posthog/temporal/',+ 'products/batch_exports/backend/tests/temporal/',+ 'products/tasks/backend/temporal/',+ 'products/signals/backend/emission/',+ ],exclude: [],},}@@ -674,6 +700,8 @@ function buildMatrix(products, durations) {module.exports = {calculateShards,DJANGO_OVERHEAD_SECONDS_BY_SEGMENT,+ DJANGO_SEGMENTS,+ getIsolatedProducts,collectTestFiles,checkProductStaleness,productPrefix,diff --git a/.github/scripts/turbo-discover.test.js b/.github/scripts/turbo-discover.test.jsnew file mode 100644index 000000000000..301d982be569--- /dev/null+++ b/.github/scripts/turbo-discover.test.js@@ -0,0 +1,198 @@+// Run with: node --test .github/scripts/turbo-discover.test.js+//+// 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.+//+// 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.++const test = require('node:test')+const assert = require('node:assert/strict')+const fs = require('node:fs')+const os = require('node:os')+const path = require('node:path')++const { DJANGO_SEGMENTS, getIsolatedProducts } = require('./turbo-discover')++const REPO_ROOT = path.join(__dirname, '..', '..')+const WORKFLOWS = ['.github/workflows/ci-backend.yml', '.depot/workflows/ci-backend.yml']++// pytest takes `./posthog/queries/` and `posthog` for the same directory, and+// --ignore drops the trailing slash. DJANGO_SEGMENTS stores prefixes, so every+// spelling has to land on the same one. File targets keep their extension.+function toPrefix(target) {+ const cleaned = target.replace(/^\.\//, '').replace(/\/$/, '')+ return cleaned.endsWith('.py') ? cleaned : `${cleaned}/`+}++function sorted(prefixes) {+ return [...new Set(prefixes)].sort()+}++function section(text, startMarker, endMarker) {+ const start = text.indexOf(startMarker)+ assert.notEqual(start, -1, `missing ${startMarker}`)+ const end = text.indexOf(endMarker, start)+ assert.notEqual(end, -1, `missing ${endMarker}`)+ return text.slice(start, end)+}++function matchAll(text, pattern) {+ return [...text.matchAll(pattern)].map((match) => match[1])+}++// The Core step runs both matrix legs: `full_targets` is reassigned per leg and+// the person-on-events leg adds its own ignores on top of the shared ones. The+// compat leg reads its targets from an env var, so it has no literal to pick up.+function parseCoreStep(text) {+ const step = section(text, 'full_targets="posthog ee/"', '--junitxml=junit-core.xml')+ const targets = matchAll(step, /full_targets="([^"]*)"/g).filter((value) => !value.startsWith('$'))+ assert.equal(targets.length, 2, 'expected a Core and a person-on-events full_targets assignment')+ const [core, poe] = targets.map((value) => value.trim().split(/\s+/))+ const poeIgnoreLine = step.match(/full_ignores\+=\(([^)]*)\)/)+ return {+ core,+ poe,+ ignores: matchAll(step.replace(/full_ignores\+=\([^)]*\)/g, ''), /--ignore=(\S+)/g),+ poeIgnores: poeIgnoreLine ? matchAll(poeIgnoreLine[1], /--ignore=(\S+)/g) : [],+ }+}++function parseTemporalTargets(text) {+ const invocation = text.match(/pytest [^\n]*junit_duration_report=call (posthog\/temporal[^\n]*?) -m /)+ assert.notEqual(invocation, null, 'missing the full Temporal pytest invocation')+ 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)+ const expected = {+ Core: { include: core.core, exclude: core.ignores },+ CorePOE: { include: core.poe, exclude: [...core.ignores, ...core.poeIgnores] },+ Temporal: { include: parseTemporalTargets(text), exclude: [] },+ }++ for (const [segment, paths] of Object.entries(expected)) {+ test(`${segment} segment matches the pytest targets in ${workflow}`, () => {+ assert.deepEqual(sorted(DJANGO_SEGMENTS[segment].include), sorted(paths.include.map(toPrefix)))+ 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.+const SELECTOR = 'tools/snob_backend_test_selection_shadow.py'++function pythonTuple(text, name) {+ const match = text.match(new RegExp(`${name} = \\(([^)]*)\\)`))+ assert.notEqual(match, null, `missing ${name} in ${SELECTOR}`)+ return matchAll(match[1], /"([^"]+)"/g)+}++test('the backend test selector routes files with the same partition', () => {+ const text = fs.readFileSync(path.join(REPO_ROOT, SELECTOR), 'utf8')+ const temporal = pythonTuple(text, '_TEMPORAL_PREFIXES')+ const poe = [...pythonTuple(text, '_POE_PREFIXES'), ...matchAll(text, /path == "([^"]+)"/g)]+ const ignored = pythonTuple(text, '_CORE_IGNORED_PREFIXES')++ assert.deepEqual(sorted(temporal), sorted(DJANGO_SEGMENTS.Temporal.include))+ assert.deepEqual(sorted(poe), sorted(DJANGO_SEGMENTS.CorePOE.include))+ // The selector checks the temporal prefixes first, so Core's exclusion of+ // them is implicit there and explicit in the table.+ const claimedFromCore = temporal.filter((prefix) =>+ DJANGO_SEGMENTS.Core.include.some((include) => prefix.startsWith(include))+ )+ assert.deepEqual(sorted([...ignored, ...claimedFromCore]), sorted(DJANGO_SEGMENTS.Core.exclude))+})++// Isolation is the claim that a product can be tested without the Django suite.+// A product that ships the contract-check script but no turbo.json of its own+// leaves the task on the root definition, whose inputs are its whole backend,+// so every backend edit reads as a contract change and cascades anyway.+test('isolation needs both the contract-check script and narrowed contract inputs', () => {+ const repoRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'isolated-products-'))+ const declare = (product, turboJson) => {+ fs.mkdirSync(path.join(repoRoot, 'products', product), { recursive: true })+ if (turboJson) {+ fs.writeFileSync(path.join(repoRoot, 'products', product, 'turbo.json'), JSON.stringify(turboJson))+ }+ }+ declare('declared', { tasks: { 'backend:contract-check': { inputs: ['backend/facade/**'] } } })+ declare('empty-inputs', { tasks: { 'backend:contract-check': { inputs: [] } } })+ declare('other-task', { tasks: { 'backend:test': { inputs: ['backend/**'] } } })+ declare('no-turbo-json', null)+ // Directory uses underscores while the package name uses dashes — the lookup+ // must bridge the two or every multiword product reads as non-isolated.+ declare('multi_word', { tasks: { 'backend:contract-check': { inputs: ['backend/facade/**'] } } })++ // Every task here comes from `turbo run backend:contract-check`, so each of+ // these products already declares the script.+ const tasks = ['declared', 'empty-inputs', 'other-task', 'no-turbo-json', 'multi-word'].map((product) => ({+ package: `@posthog/products-${product}`,+ }))++ assert.deepEqual([...getIsolatedProducts(tasks, repoRoot)].sort(), ['declared', 'multi-word'])+})diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.ymlindex 81a28ded22a6..f1e65080843c 100644--- a/.github/workflows/ci-backend.yml+++ b/.github/workflows/ci-backend.yml@@ -579,11 +579,15 @@ jobs:# 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.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@@ -757,9 +761,10 @@ jobs:# Partition selected files by the Django segment that owns them.# Mirrors the positional path arguments in the Run Core / Run Temporal pytest invocations:# Core (POE off): posthog ee/ (minus posthog/temporal, posthog/dags,- # posthog/test/repo_invariants)- # Core POE on: posthog/clickhouse, posthog/queries, posthog/api/test/test_insight*,- # posthog/api/test/dashboards/test_dashboard.py, ee/clickhouse/+ # common/hogvm/python/test, posthog/test/repo_invariants)+ # Core POE on: posthog/clickhouse, posthog/queries, ee/clickhouse/,+ # products/product_analytics/backend/tests/api,+ # posthog/api/test/dashboards/test_dashboard.py# Temporal: posthog/temporal, products/{batch_exports,tasks}/backend/temporal,# products/signals/backend/emission# Compat: CLICKHOUSE_COMPAT_PYTEST_TARGETS (posthog/clickhouse, ee/clickhouse)@@ -786,7 +791,7 @@ jobs:posthog/temporal/*|products/batch_exports/backend/tests/temporal/*|products/tasks/backend/temporal/*|products/signals/backend/emission/*)temporal+=("$f");;- posthog/clickhouse/*|posthog/queries/*|ee/clickhouse/*|products/product_analytics/backend/tests/api/*|posthog/api/test/test_insight*|posthog/api/test/dashboards/test_dashboard.py)+ posthog/clickhouse/*|posthog/queries/*|ee/clickhouse/*|products/product_analytics/backend/tests/api/*|posthog/api/test/dashboards/test_dashboard.py)poe+=("$f")core+=("$f");;diff --git a/.github/workflows/ci-scripts.yml b/.github/workflows/ci-scripts.ymlindex 15ccf460fbc8..5b961ebeea76 100644--- a/.github/workflows/ci-scripts.yml+++ b/.github/workflows/ci-scripts.yml@@ -9,6 +9,14 @@ on:- .github/scripts/**- .github/auto-assign-labels.json- .github/workflows/ci-scripts.yml+ # turbo-discover.test.js pins the Django segment table to these.+ - .github/workflows/ci-backend.yml+ - .depot/workflows/ci-backend.yml+ # 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.py+ - tools/test_selection_verdict.py+ - tools/test_test_selection_verdict.pyconcurrency:group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}@@ -37,7 +45,7 @@ jobs:# defusedxml + opentelemetry + tools/owners are report_test_timings.py's script deps.- name: Install pytest- run: python -m pip install --quiet pytest defusedxml==0.7.1 opentelemetry-sdk==1.33.1 opentelemetry-exporter-otlp-proto-http==1.33.1 ./tools/owners+ run: python -m pip install --quiet pytest parameterized defusedxml==0.7.1 opentelemetry-sdk==1.33.1 opentelemetry-exporter-otlp-proto-http==1.33.1 ./tools/owners# `-c /dev/null` skips the repo pytest.ini (its --reuse-db addopt needs# pytest-django, which we don't install here). `--noconftest` skips the@@ -55,6 +63,13 @@ jobs:if: ${{ hashFiles('.github/scripts/test_report_workflow_run_traces.py') != '' }}run: python -m pytest .github/scripts/test_report_workflow_run_traces.py -v -c /dev/null -p no:cacheprovider --noconftest+ # The Django test selector decides what ci-backend runs, and a wrong+ # subset is silent: it reports green having skipped the test that would+ # have failed. hashFiles guard for PRs that predate the selector tests.+ - name: Backend test-selection tests (Python)+ if: ${{ hashFiles('tools/test_snob_backend_test_selection_shadow.py') != '' }}+ run: python -m pytest tools/test_snob_backend_test_selection_shadow.py tools/test_test_selection_verdict.py -v -c /dev/null -p no:cacheprovider --noconftest+# Shells out to schema_usage_scan.py via python3 (preinstalled on ubuntu).- name: Schema-impact tests (Node)run: node --test .github/scripts/schema-impact.test.js@@ -89,6 +104,11 @@ jobs:- name: Turbo-discover dependent-cascade tests (Node)run: node --test .github/scripts/turbo-discover-cascade.test.js+ # hashFiles guard so an unrebased PR predating these files doesn't fail here.+ - name: Turbo-discover segment and staleness tests (Node)+ if: ${{ hashFiles('.github/scripts/turbo-discover.test.js') != '' }}+ run: node --test .github/scripts/turbo-discover.test.js .github/scripts/turbo-discover-staleness.test.js+- name: Selected Django shards tests (Node)run: node --test .github/scripts/selected-django-shards.test.jsdiff --git a/tools/snob_backend_test_selection_shadow.py b/tools/snob_backend_test_selection_shadow.pyindex a40691f8a5d5..ee13b3967be6 100755--- a/tools/snob_backend_test_selection_shadow.py+++ b/tools/snob_backend_test_selection_shadow.py@@ -612,7 +612,7 @@ _POE_PREFIXES = ("ee/clickhouse/","products/product_analytics/backend/tests/api/",)-_CORE_IGNORED_PREFIXES = ("posthog/dags/", "common/hogvm/python/test/")+_CORE_IGNORED_PREFIXES = ("posthog/dags/", "common/hogvm/python/test/", "posthog/test/repo_invariants/")def segments_for_test_file(path: str) -> frozenset[str]:@@ -626,12 +626,7 @@ def segments_for_test_file(path: str) -> frozenset[str]:return frozenset({"temporal"})if path.startswith(_CORE_IGNORED_PREFIXES):return frozenset()- is_poe = (- path.startswith(_POE_PREFIXES)- or path.startswith("posthog/api/test/test_insight")- or path == "posthog/api/test/dashboards/test_dashboard.py"- )- if is_poe:+ if path.startswith(_POE_PREFIXES) or path == "posthog/api/test/dashboards/test_dashboard.py":return frozenset({"core", "poe"})if path.startswith(("posthog/", "ee/")):return frozenset({"core"})diff --git a/tools/test_snob_backend_test_selection_shadow.py b/tools/test_snob_backend_test_selection_shadow.pyindex 91ba9c3b2bf7..d92148397029 100644--- a/tools/test_snob_backend_test_selection_shadow.py+++ b/tools/test_snob_backend_test_selection_shadow.py@@ -281,17 +281,25 @@ class TestSnobBackendTestSelectionShadow(unittest.TestCase):self.assertTrue(result.full_run_reasons, f"{path} selected nothing and forced no full run")- def test_segments_for_test_file_mirrors_matrix_partition(self) -> None:+ @parameterized.expand(+ [+ ("core", "posthog/models/test_a.py", {"core"}),+ # POE patterns run in both the Core matrix and the person-on-events matrix.+ ("poe_runs_in_core_too", "posthog/clickhouse/test_b.py", {"core", "poe"}),+ ("temporal", "posthog/temporal/tests/test_c.py", {"temporal"}),+ # The Temporal invocation runs the product suites alongside posthog/temporal.+ ("temporal_signals_emission", "products/signals/backend/emission/test_c.py", {"temporal"}),+ # Explicitly ignored by the Core invocation, and not a draft-narrowable matrix.+ ("core_ignored_dags", "posthog/dags/test_e.py", set()),+ ("core_ignored_repo_invariants", "posthog/test/repo_invariants/test_f.py", set()),+ # Product/turbo tests are not part of any draft-narrowable Django matrix.+ ("turbo_product", "products/warehouse_sources/backend/test_d.py", set()),+ ]+ )+ def test_segments_for_test_file_mirrors_matrix_partition(self, _name: str, path: str, expected: set[str]) -> None:selection = _load_selection_module()- self.assertEqual(selection.segments_for_test_file("posthog/models/test_a.py"), frozenset({"core"}))- # POE patterns run in both the Core matrix and the person-on-events matrix.- self.assertEqual(selection.segments_for_test_file("posthog/clickhouse/test_b.py"), frozenset({"core", "poe"}))- self.assertEqual(selection.segments_for_test_file("posthog/temporal/tests/test_c.py"), frozenset({"temporal"}))- # Explicitly ignored by the Core invocation, and not a draft-narrowable matrix.- self.assertEqual(selection.segments_for_test_file("posthog/dags/test_e.py"), frozenset())- # Product/turbo tests are not part of any draft-narrowable Django matrix.- self.assertEqual(selection.segments_for_test_file("products/warehouse_sources/backend/test_d.py"), frozenset())+ self.assertEqual(selection.segments_for_test_file(path), frozenset(expected))def test_narrowable_baseline_excludes_turbo_product_tests(self) -> None:selection = _load_selection_module()