: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): restore the test durations refresh and resize shards (#89958)
Julian Bezb1148567c83c
diff --git a/.depot/workflows/ci-backend-update-test-timing.yml b/.depot/workflows/ci-backend-update-test-timing.ymlindex 7544672342e6..df868de18ea1 100644--- a/.depot/workflows/ci-backend-update-test-timing.yml+++ b/.depot/workflows/ci-backend-update-test-timing.yml@@ -67,9 +67,14 @@ jobs:posthog-test-durations-- name: Set the previous map aside+ # .test_durations is not tracked, so there is nothing to restore it from+ # and a cache miss leaves no file at all.run: |- cp .test_durations /tmp/previous_durations- git checkout -- .test_durations+ if [ -f .test_durations ]; then+ mv .test_durations /tmp/previous_durations+ else+ echo "::warning::No cached map restored; a drifting Products slice has no stand-in"+ fi- name: Download timing artifactsenv:@@ -103,12 +108,21 @@ jobs:set -eif [ "$products_status" -ne 0 ]; thenecho "::warning::Products durations refresh exited $products_status; keeping the previous products slice. Drift or an incomplete JUnit set are the expected causes, see the log above."- # Only entries the fresh slices do not carry: the outlier merge would- # otherwise let a stale value here beat a fresh one for the same test.- jq -s 'add' $(ls /tmp/core_durations /tmp/temporal_durations 2>/dev/null) > /tmp/fresh_durations- jq --slurpfile fresh /tmp/fresh_durations \- 'with_entries(select((.key | startswith("products/")) and ($fresh[0][.key] == null)))' \- /tmp/previous_durations > /tmp/products_durations+ if [ -f /tmp/previous_durations ]; then+ # Only entries the fresh slices do not carry: the outlier merge would+ # otherwise let a stale value here beat a fresh one for the same test.+ jq -s 'add' $(ls /tmp/core_durations /tmp/temporal_durations 2>/dev/null) > /tmp/fresh_durations+ jq --slurpfile fresh /tmp/fresh_durations \+ 'with_entries(select((.key | startswith("products/")) and ($fresh[0][.key] == null)))' \+ /tmp/previous_durations > /tmp/products_durations+ else+ # No cached slice to stand in and no fresh one. A map with no product+ # entries would still become the newest cache and the latest successful+ # artifact, so every consumer would fall back to the file-count estimate+ # and under-shard the fixture-heavy products. Leave the older map newest.+ echo "::error::Products slice failed with no previous map to stand in; refusing to publish a map without product entries"+ exit 1+ fifiuv run .github/scripts/optimize_test_durations.py .test_durations \--merge-files /tmp/core_durations /tmp/temporal_durations /tmp/products_durations \diff --git a/.depot/workflows/ci-backend.yml b/.depot/workflows/ci-backend.ymlindex 03b1b47157b8..d8e502b19a08 100644--- a/.depot/workflows/ci-backend.yml+++ b/.depot/workflows/ci-backend.yml@@ -942,8 +942,15 @@ jobs:- name: Run product tests# --force: discover already decided this product needs testing, skip turbo cache# --log-order=stream: stream pytest output live instead of buffering until completion- # pytest_args: optional pytest-split flags for sharded products (e.g. "-- --splits 3 --group 1")+ # legs: one turbo invocation per entry, each with its own pytest-split flags+ # (e.g. "-- --splits 3 --group 1"). A job holds several legs when a split+ # product's last shard had budget left over for whole small products, and+ # pytest-split flags must not leak from that shard onto its job-mates.env:+ PRODUCT_LEGS: ${{ toJSON(matrix.legs) }}+ # Read only when an unrebased branch planned the pre-legs shape.+ LEGACY_FILTERS: ${{ matrix.filters }}+ LEGACY_PYTEST_ARGS: ${{ matrix.pytest_args }}CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA: ${{ matrix.new-events-schema && 'true' || 'false' }}# products/tasks/backend/temporal moved here from the Django Temporal# segment, and its conftest and workflows talk to Modal. Injected only@@ -965,17 +972,42 @@ jobs:# bin-packed buckets (each product writes its own file) and split products (unioned later).# sysmon: Python 3.12+'s low-overhead coverage backend, ~a few % vs ~20% for the C tracer.COVERAGE_CORE: sysmon+ shell: bashrun: |set +e- pnpm turbo run backend:test ${{ matrix.filters }} --concurrency=1 --output-logs=full --force --log-order=stream ${{ matrix.pytest_args }}- exit_code=$?- set -e- if [ $exit_code -eq 5 ]; then- echo "No tests collected for this shard, this is expected when splitting tests"- exit 0- else- exit $exit_code+ overall=0+ # A workflow edit reaches an open PR before the script edit does, so a+ # branch that has not rebased still plans the flat {filters, pytest_args}+ # shape. Normalize that into one leg rather than requiring the new key.+ if [ -z "$PRODUCT_LEGS" ] || [ "$PRODUCT_LEGS" = "null" ]; then+ PRODUCT_LEGS=$(jq -cn --arg f "$LEGACY_FILTERS" --arg a "$LEGACY_PYTEST_ARGS" \+ '[{filters: $f, pytest_args: $a}]')+ echo "Matrix entry carries no legs; running the legacy single invocation"+ fi+ leg_count=$(jq 'length' <<< "$PRODUCT_LEGS")+ # Neither shape present means the job would pass having run no tests, and+ # the rollup gate only reads this step's outcome. Fail loudly instead.+ if [ -z "$leg_count" ] || [ "$leg_count" -lt 1 ]; then+ echo "::error::No test legs in this matrix entry; refusing to pass without running tests"+ exit 1fi+ for ((leg_index = 0; leg_index < leg_count; leg_index++)); do+ leg_filters=$(jq -r ".[$leg_index].filters" <<< "$PRODUCT_LEGS")+ leg_args=$(jq -r ".[$leg_index].pytest_args" <<< "$PRODUCT_LEGS")+ echo "::group::turbo backend:test $leg_filters $leg_args"+ # Word splitting is intended here: both variables carry several flags.+ # shellcheck disable=SC2086+ pnpm turbo run backend:test $leg_filters --concurrency=1 --output-logs=full --force --log-order=stream $leg_args+ exit_code=$?+ echo "::endgroup::"+ if [ $exit_code -eq 5 ]; then+ echo "No tests collected for this leg, this is expected when splitting tests"+ elif [ $exit_code -ne 0 ]; then+ overall=$exit_code+ fi+ done+ set -e+ exit $overall# Lightweight repo-wide checks that only need Python + uv (no Docker/DB).# Consolidates checks that previously each spun up their own runner.repo-checks:diff --git a/.github/scripts/turbo-discover-sizing.test.js b/.github/scripts/turbo-discover-sizing.test.jsindex 557ee10e8cf8..6ba450e302be 100644--- a/.github/scripts/turbo-discover-sizing.test.js+++ b/.github/scripts/turbo-discover-sizing.test.js@@ -7,7 +7,7 @@const test = require('node:test')const assert = require('node:assert/strict')-const { pruneDeadDurations, getSegmentDuration, calculateShards, resolveProductSizing, buildMatrix, PRODUCT_JOB_OVERHEAD_SECONDS, PRODUCT_SAFETY_FACTOR, TARGET_WALL_SECONDS } = require('./turbo-discover.js')+const { pruneDeadDurations, getSegmentDuration, calculateShards, resolveProductSizing, buildMatrix, productSplitShards, PRODUCT_JOB_OVERHEAD_SECONDS, TARGET_WALL_SECONDS } = require('./turbo-discover.js')// A path that exists in every checkout, so the existence check is deterministic.const LIVE_FILE = '.github/scripts/turbo-discover.js'@@ -95,8 +95,8 @@ test('buildMatrix splits a product to the shared wall target', () => {const matrix = buildMatrix(['big-one'], union, true)- // 2000s of work, with the safety factor, over a (target - overhead) budget per shard.- assert.equal(matrix.length, Math.ceil((2000 * PRODUCT_SAFETY_FACTOR) / (TARGET_WALL_SECONDS - O)))+ // 2000s of work, with the imbalance margin, over a (target - overhead) budget.+ assert.equal(matrix.length, productSplitShards({ work: 2000, heavyCount: 0, lightWork: 2000, maxLight: 50, testCount: 40 }))assert.match(matrix[0].group, /^big-one \(1\/\d+\)$/)})@@ -107,5 +107,108 @@ test('buildMatrix leaves a small product packed', () => {assert.equal(matrix.length, 1)assert.equal(matrix[0].group, 'small-one')+ assert.deepEqual(matrix[0].legs, [{ filters: '--filter=@posthog/products-small-one', pytest_args: '' }])+})++test('a single-invocation entry keeps the pre-legs keys for unrebased branches', () => {+ // A workflow edit lands on an open PR before this script does, so an old+ // workflow reading matrix.filters must still find something to run.+ const union = { 'products/small_one/backend/test_c.py::test_c': 100 }++ const matrix = buildMatrix(['small-one'], union, true)++ assert.equal(matrix[0].filters, '--filter=@posthog/products-small-one')assert.equal(matrix[0].pytest_args, '')})++test('productSplitShards sizes the worst chunk, not the mean', () => {+ const budget = TARGET_WALL_SECONDS - PRODUCT_JOB_OVERHEAD_SECONDS+ const evenly = { work: 1000, heavyCount: 0, lightWork: 1000, maxLight: 10, testCount: 100 }+ const coarse = { work: 1000, heavyCount: 0, lightWork: 1000, maxLight: 150, testCount: 100 }++ // Same total work; the coarser grain cannot be cut as finely, so it needs more+ // shards to keep its worst chunk inside the budget.+ assert.ok(productSplitShards(coarse) > productSplitShards(evenly))+ assert.ok(evenly.lightWork / productSplitShards(evenly) + evenly.maxLight <= budget)+ assert.ok(coarse.lightWork / productSplitShards(coarse) + coarse.maxLight <= budget)+})++test('tests above half the budget each hold a shard of their own', () => {+ const budget = TARGET_WALL_SECONDS - PRODUCT_JOB_OVERHEAD_SECONDS+ const heavy = Math.ceil(budget * 0.8)++ // Ten tests this size cannot pair, so no count below ten holds the budget,+ // however the total work divides.+ assert.equal(productSplitShards({ work: heavy * 10, heavyCount: 10, lightWork: 0, maxLight: 0, testCount: 10 }), 10)+ // One heavy test and a sliver stays bounded rather than asking for a shard per+ // second of remainder. Two tests cannot fill three shards, so the count stops+ // there rather than planning one that collects nothing.+ assert.equal(+ productSplitShards({ work: budget + 1, heavyCount: 1, lightWork: 1, maxLight: 1, testCount: 2 }),+ 2+ )+})++test('the count never exceeds the tests there are to place', () => {+ // The fragmentation charge assumes a shape the suite may not have. Past the+ // test count a shard collects nothing and spends a runner for it.+ const many = { work: 10000, heavyCount: 3, lightWork: 100, maxLight: 10, testCount: 5 }++ assert.equal(productSplitShards(many), 5)+})++test('a product holding one test is never split', () => {+ const budget = TARGET_WALL_SECONDS - PRODUCT_JOB_OVERHEAD_SECONDS++ // One test over the budget still gets one job: a second would collect nothing,+ // and no split shortens the first.+ assert.equal(+ productSplitShards({ work: budget + 1, heavyCount: 1, lightWork: 0, maxLight: 0, testCount: 1 }),+ 1+ )+})++test('a heavy test between light ones splits the light run', () => {+ // Ordered [53, 301, 133] against a 320s budget: either contiguous cut leaves a+ // 354s or 434s chunk, so two shards cannot hold the budget however it is cut.+ assert.equal(productSplitShards({ work: 487, heavyCount: 1, lightWork: 186, maxLight: 133, testCount: 3 }), 3)+})++test('a product that fits one shard is packed, not split by its own margin', () => {+ // 300s of work sits under the (target - overhead) budget, so the margin must+ // not be what pushes it over into a two-way split.+ const union = {}+ for (let i = 0; i < 10; i++) {+ union[`products/mid_one/backend/test_${i}.py::test_${i}`] = 30+ }++ assert.ok(300 <= TARGET_WALL_SECONDS - PRODUCT_JOB_OVERHEAD_SECONDS)+ assert.equal(productSplitShards({ work: 300, heavyCount: 0, lightWork: 300, maxLight: 30, testCount: 10 }), 1)++ const matrix = buildMatrix(['mid-one'], union, true)++ assert.equal(matrix.length, 1)+ assert.equal(matrix[0].group, 'mid-one')+})++test("a split product's last shard absorbs a small product without leaking split flags", () => {+ const union = {}+ for (let i = 0; i < 11; i++) {+ union[`products/big_one/backend/test_${i}.py::test_${i}`] = 30+ }+ union['products/small_one/backend/test_s.py::test_s'] = 40++ assert.equal(productSplitShards({ work: 330, heavyCount: 0, lightWork: 330, maxLight: 30, testCount: 11 }), 2)++ const matrix = buildMatrix(['big-one', 'small-one'], union, true)++ // Two jobs, not three: small-one rides along in the lighter second shard.+ assert.equal(matrix.length, 2)+ const shared = matrix.find((entry) => entry.group.includes('small-one'))+ assert.equal(shared.group, 'big-one (2/2), small-one')+ assert.equal(shared.legs.length, 2)+ assert.match(shared.legs[0].pytest_args, /--splits 2 --group 2/)+ // The whole product runs in its own leg, so it never sees --splits/--group.+ assert.equal(shared.legs[1].filters, '--filter=@posthog/products-small-one')+ assert.equal(shared.legs[1].pytest_args, '')+})diff --git a/.github/scripts/turbo-discover.js b/.github/scripts/turbo-discover.jsindex 82acf41bbabd..b548f33a5019 100644--- a/.github/scripts/turbo-discover.js+++ b/.github/scripts/turbo-discover.js@@ -40,26 +40,32 @@ 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-// fungible across products — bin-pack products into target-sized shards, and-// multi-shard split any single product that overflows on its own.+// The test pool is not fungible across products, so a product is the unit of+// work: bin-pack products into target-sized jobs, and multi-shard split any+// single product that overflows on its own. A job runs what it holds+// sequentially, so its wall is the sum of its parts, not the max.// One flat wall-clock target for every test shard, Django and products alike.// Predictability is the point: a dev who kicks off CI knows what a shard costs// without knowing which segment it is. Sizing solves wall = overhead + work/n// for n, so the target is a promise about the PR lane (where the overheads below// are fitted); master pays extra overhead (full migration replay) on top.-// A full run's wall is discovery plus the slowest of its shards, and with many-// shards packed to one target the slowest lands a few minutes above it, so a-// 12-minute shard target puts a full PR run near 15 minutes end to end.+// A full run's wall is the pre-shard preamble plus the slowest of its shards.+// The preamble (discovery, matrix build, runner start) measures ~5.5 min, and+// sizing bounds the slowest shard at the target rather than the average, so a+// 12-minute shard target puts a full PR run near 18 minutes end to end.const TARGET_WALL_SECONDS = 12 * 60// Per-product cost within a runner: turbo dispatch, pytest collection, Django// init. First product pays ~45s, subsequent ~15s; use 60s as a conservative// average that also absorbs the amortized portion of runner startup.const PRODUCT_PER_PRODUCT_OVERHEAD_SECONDS = 60-// Headroom for run-to-run variance when deciding how much fits in a bucket. Was-// 2x originally because pytest-split data was noisy under Django Core's shared-// session; the outlier-based merge produces cleaner numbers now.-const PRODUCT_SAFETY_FACTOR = 1.3+// Headroom on a packed bucket, covering error in the recorded durations alone.+// A bucket runs its products sequentially, so its wall is the sum of its parts+// and it needs no allowance for an uneven split. That allowance belongs to the+// split path, which derives its own in productSplitShards.+const PRODUCT_BUCKET_SAFETY_FACTOR = 1.1+// No headroom constant for a split product: the gap between the mean shard that+// sizing solves for and the max shard that sets the wall is derived per product+// in productSplitShards below.// Fitted per-shard overhead for a split product job. Two measured parts, from// run 32717208712: the job base (docker stack, deps, turbo dispatch) is// mean(job wall - JUnit suite time), 247-413s across 12 bucket jobs (median@@ -96,10 +102,11 @@ const PRODUCTS_RUNNING_TEMPORAL_IN_JOB = new Set(['tasks','warehouse-sources',])-// Products that always get their own matrix entry instead of being packed with-// others — isolates a flaky/hang-prone product so it can't cancel bucket-mates-// at the job timeout. Trade-off: a dedicated runner.-const DEDICATED_BUCKET_PRODUCTS = new Set(['batch-exports'])+// Products that always get their own matrix entry instead of sharing one, so a+// hang cannot cancel job-mates when the job timeout fires. The cost is a+// dedicated runner, so a product belongs here only while its wall runs close+// enough to the job timeout that a hang is a realistic outcome.+const DEDICATED_BUCKET_PRODUCTS = new Set()// --- Staleness detection for .test_durations ---// When a product's test files on disk significantly outnumber what .test_durations@@ -696,6 +703,43 @@ function getProductDuration(product, durations) {return total}+// The longest single test in a product. pytest-split cuts between tests, never+// inside one, so this is the irreducible grain of any split and it bounds how+// far the worst chunk can run past the mean.+// Budget of test work one product shard can hold, mirroring calculateShards.+function productShardBudget() {+ return Math.max(TARGET_WALL_SECONDS - PRODUCT_JOB_OVERHEAD_SECONDS, PRODUCT_JOB_OVERHEAD_SECONDS / 2, 1)+}++// The parts of a product's duration distribution that sizing needs. Two tests+// longer than half a shard's budget can never share a shard, so those are counted+// rather than summed; the rest are summed, with their own longest, because a+// contiguous chunk of them runs at most one of them past the mean.+function getProductShape(product, durations) {+ const shape = { work: 0, maxTest: 0, heavyCount: 0, lightWork: 0, maxLight: 0, testCount: 0 }+ if (!durations) {+ return shape+ }+ const prefix = productPrefix(product)+ const excluded = PRODUCTS_RUNNING_TEMPORAL_IN_JOB.has(product) ? [] : EXCLUDED_PATH_SEGMENTS+ const heavyThreshold = productShardBudget() / 2+ for (const [test, dur] of Object.entries(durations)) {+ if (!test.startsWith(prefix) || excluded.some((seg) => test.includes(seg))) {+ continue+ }+ shape.work += dur+ shape.testCount += 1+ shape.maxTest = Math.max(shape.maxTest, dur)+ if (dur > heavyThreshold) {+ shape.heavyCount += 1+ } else {+ shape.lightWork += dur+ shape.maxLight = Math.max(shape.maxLight, dur)+ }+ }+ return shape+}+// One definition of a product's work estimate, shared by the split decision// (buildMatrix) and the bucket cost (packProducts), so they cannot disagree.//@@ -707,39 +751,56 @@ function getProductDuration(product, durations) {// under-sharding. `staleUnionWork` is non-null exactly when the guess replaced// the recorded sum, so the caller can log it once.function resolveProductSizing(product, durations, productsScaled = false) {- const unionWork = getProductDuration(product, durations)- if (productsScaled && unionWork > 0) {- return { work: unionWork, staleUnionWork: null, staleness: null }+ const shape = getProductShape(product, durations)+ if (productsScaled && shape.work > 0) {+ return { ...shape, staleUnionWork: null, staleness: null }}const staleness = checkProductStaleness(product, durations)if (staleness.stale && staleness.fileCount > 0) {const fallbackWork = staleness.fileCount * STALENESS_FALLBACK_SECONDS_PER_FILE- if (fallbackWork > unionWork) {- return { work: fallbackWork, staleUnionWork: unionWork, staleness }+ if (fallbackWork > shape.work) {+ // The tests the map does record are still measurements, and a heavy one+ // holds a shard whatever the coverage. Keep those and treat only the+ // guessed remainder as light, at one file's worth per test.+ const recordedHeavyWork = shape.work - shape.lightWork+ return {+ work: fallbackWork,+ maxTest: Math.max(shape.maxTest, STALENESS_FALLBACK_SECONDS_PER_FILE),+ heavyCount: shape.heavyCount,+ lightWork: Math.max(fallbackWork - recordedHeavyWork, 0),+ maxLight: Math.max(shape.maxLight, STALENESS_FALLBACK_SECONDS_PER_FILE),+ testCount: Math.max(shape.testCount, staleness.fileCount),+ staleUnionWork: shape.work,+ staleness,+ }}}- return { work: unionWork, staleUnionWork: null, staleness: null }+ return { ...shape, staleUnionWork: null, staleness: null }}function productEffectiveCost(product, durations, productsScaled = false) {const { work } = resolveProductSizing(product, durations, productsScaled)- return work * PRODUCT_SAFETY_FACTOR + PRODUCT_PER_PRODUCT_OVERHEAD_SECONDS+ return work * PRODUCT_BUCKET_SAFETY_FACTOR + PRODUCT_PER_PRODUCT_OVERHEAD_SECONDS}-// First-fit-decreasing bin packing into TARGET-sized shards. Sorts products by+// First-fit-decreasing bin packing into TARGET-sized jobs. Sorts products by// effective cost descending so the largest products land first and small ones-// fill the gaps. Each bucket caps at the wall target minus the base overhead the-// job pays once, so the effective costs only compete for the remaining budget.-function packProducts(products, durations, productsScaled = false) {+// fill the gaps. Each job caps at the wall target minus the base overhead it+// pays once, so the effective costs only compete for the remaining budget.+// `seedJobs` are jobs that already hold work — a split product's last shard —+// and they sit first so their leftover budget is used before a new runner is+// started. A seed carries its own base overhead, which is a large product's+// session cost rather than the packed-bucket base.+function packProducts(products, durations, productsScaled = false, seedJobs = []) {const items = products.map((product) => ({ product, cost: productEffectiveCost(product, durations, productsScaled) })).sort((a, b) => b.cost - a.cost)- const buckets = []+ const buckets = [...seedJobs]for (const { product, cost } of items) {let placed = falsefor (const bucket of buckets) {- if (bucket.cost + cost <= TARGET_WALL_SECONDS - PRODUCT_JOB_BASE_OVERHEAD_SECONDS) {+ if (bucket.cost + cost <= TARGET_WALL_SECONDS - bucket.baseOverhead) {bucket.products.push(product)bucket.cost += costplaced = true@@ -747,7 +808,13 @@ function packProducts(products, durations, productsScaled = false) {}}if (!placed) {- buckets.push({ products: [product], cost })+ buckets.push({+ label: null,+ legs: [],+ products: [product],+ cost,+ baseOverhead: PRODUCT_JOB_BASE_OVERHEAD_SECONDS,+ })}}return buckets@@ -833,6 +900,47 @@ function calculateShards(totalWorkSeconds, overheadSeconds, minShards = DJANGO_Mreturn Math.max(minShards, Math.min(DJANGO_MAX_SHARDS, shards))}+// Shards for one product. Sizing a split by work/n sizes the MEAN shard, but the+// run's wall is the MAX shard, and pytest-split cuts between tests rather than+// inside one, so size the worst chunk instead.+//+// Split the suite at half the budget. Two tests above that cannot share a shard+// at all, so each takes one and they set a floor no packing goes below. What is+// left is at most half a budget per test, so a contiguous chunk of it runs at+// most one such test past its mean, giving lightWork/n + maxLight <= budget and+// so n = ceil(lightWork / (budget - maxLight)). That denominator is at least+// half the budget, so it cannot collapse.+//+// The cuts are contiguous, so a heavy test sitting between light ones divides+// the light run rather than lifting out of it. H heavy tests leave at most H + 1+// light runs, and each run rounds up on its own, so the light side can cost H+// shards beyond its own bound. Charge that whenever any light work exists.+//+// That charge assumes a fragmentation the suite may not have, so cap the count+// at the number of tests. Past it a shard is guaranteed to collect nothing+// (pytest exit 5) and spends a runner without shortening the critical path.+//+// Reading the distribution rather than a fitted ratio ties the sizing to the+// map: a suite of heavy tests gets the shards they force, an evenly grained one+// gets none it does not need, and no constant carries a past map's error.+//+// A product whose whole suite fits one shard is not split, and the bound does+// not apply to it -- an unsplit chunk is the work itself, with nothing on top.+function productSplitShards(shape) {+ const budget = productShardBudget()+ const { work = 0, heavyCount = 0, lightWork = 0, maxLight = 0, testCount = Infinity } = shape ?? {}+ if (work <= budget) {+ return 1+ }+ const lightShards = lightWork > 0 ? Math.ceil(lightWork / (budget - maxLight)) : 0+ const fragmentation = lightWork > 0 ? heavyCount : 0+ const wanted = Math.min(heavyCount + lightShards + fragmentation, testCount)+ // The two-shard floor cannot outrank the test count: a product holding one+ // test that overruns the budget still gets one job, because the second would+ // collect nothing and splitting cannot shorten the first.+ return Math.max(Math.min(2, testCount), Math.min(DJANGO_MAX_SHARDS, wanted))+}+// Selector segment key -> Django matrix segment name.const MATRIX_NAME_BY_SEGMENT = { core: 'Core', poe: 'CorePOE', temporal: 'Temporal' }@@ -986,17 +1094,34 @@ function buildDjangoShards(durations, ranNodeIds = {}) {return result}+// A workflow edit reaches an open PR before this script does, so an entry a+// single turbo invocation can express keeps the pre-legs {filters, pytest_args}+// keys beside its leg. An entry with several legs has no such expression and+// carries legs alone, by which point the workflow reading it is the new one.+function matrixEntry(group, legs) {+ const entry = { group, legs }+ if (legs.length === 1) {+ entry.filters = legs[0].filters+ entry.pytest_args = legs[0].pytest_args+ }+ return entry+}+function buildMatrix(products, durations, productsScaled = false) {const matrix = []const packable = []+ const fillableJobs = []// Split a product across multiple shards with the same rule Django uses:- // enough shards that each lands at the shared wall target. The safety- // factor applies here as it does to packing: the products that split are- // the fixture-heavy suites whose recorded durations undercount the most,- // and a split sized on the bare sum lands its shards well past the target.+ // enough shards that each lands at the shared wall target. Unlike packing,+ // the split carries no safety factor -- productSplitShards derives its own+ // headroom from the product's longest test instead. That leaves it trusting+ // the recorded sum, which holds only while the map carries+ // PRODUCTS_SCALED_MARKER: call-only durations undercount a fixture-heavy+ // suite several-fold, and sizing an unscaled sum under-shards it.for (const product of products) {- const { work, staleUnionWork, staleness } = resolveProductSizing(product, durations, productsScaled)+ const sizing = resolveProductSizing(product, durations, productsScaled)+ const { work, maxTest, staleUnionWork, staleness } = sizingif (staleUnionWork !== null) {console.error(` ${product}: .test_durations stale, ${staleness.coveredCount}/${staleness.fileCount} test files covered ` +@@ -1008,7 +1133,7 @@ function buildMatrix(products, durations, productsScaled = false) {)}- const shards = calculateShards(work * PRODUCT_SAFETY_FACTOR, PRODUCT_JOB_OVERHEAD_SECONDS, 1)+ const shards = productSplitShards(sizing)if (shards > 1) {console.error(` ${product}: ${(work / 60).toFixed(1)} min work → split across ${shards} shards`)const filters = `--filter=@posthog/products-${product}`@@ -1017,34 +1142,47 @@ function buildMatrix(products, durations, productsScaled = false) {// optimally. The greedy rule in duration_based_chunks lets every shard// overrun the per-shard average, which on skewed suites starves trailing// shards down to zero tests (pytest exit 5, "no tests collected").+ const shardCost = work / shards + maxTestfor (let i = 1; i <= shards; i++) {- matrix.push({- group: `${product} (${i}/${shards})`,+ const leg = {filters,pytest_args: `-- --splits ${shards} --group ${i} --splitting-algorithm optimal_chunks`,- })+ }+ // work/shards + maxTest bounds every shard, whichever one+ // optimal_chunks leaves lightest, so one shard can be offered to the+ // packer without knowing which. Do not tighten this to work/shards:+ // the bound is what keeps a filled shard inside the job budget.+ if (i === shards && !DEDICATED_BUCKET_PRODUCTS.has(product)) {+ fillableJobs.push({+ label: `${product} (${i}/${shards})`,+ legs: [leg],+ products: [],+ cost: shardCost,+ baseOverhead: PRODUCT_JOB_OVERHEAD_SECONDS,+ })+ } else {+ matrix.push(matrixEntry(`${product} (${i}/${shards})`, [leg]))+ }}} else if (DEDICATED_BUCKET_PRODUCTS.has(product)) {- console.error(` ${product}: ${(work / 60).toFixed(1)} min work → dedicated bucket (never packed)`)- matrix.push({- group: product,- filters: `--filter=@posthog/products-${product}`,- pytest_args: '',- })+ console.error(` ${product}: ${(work / 60).toFixed(1)} min work → dedicated job (never shared)`)+ matrix.push(matrixEntry(product, [{ filters: `--filter=@posthog/products-${product}`, pytest_args: '' }]))} else {packable.push(product)}}- for (const bucket of packProducts(packable, durations, productsScaled)) {- console.error(- ` bucket (${(bucket.cost / 60).toFixed(1)} min effective): ${bucket.products.join(', ')}`- )- matrix.push({- group: bucket.products.join(', '),- filters: bucket.products.map((p) => `--filter=@posthog/products-${p}`).join(' '),- pytest_args: '',- })+ for (const bucket of packProducts(packable, durations, productsScaled, fillableJobs)) {+ const group = [bucket.label, ...bucket.products].filter(Boolean).join(', ')+ console.error(` job (${(bucket.cost / 60).toFixed(1)} min effective): ${group}`)+ const legs = [...bucket.legs]+ if (bucket.products.length > 0) {+ legs.push({+ filters: bucket.products.map((p) => `--filter=@posthog/products-${p}`).join(' '),+ pytest_args: '',+ })+ }+ matrix.push(matrixEntry(group, legs))}return matrix@@ -1062,7 +1200,9 @@ module.exports = {resolveProductSizing,buildMatrix,PRODUCT_JOB_OVERHEAD_SECONDS,- PRODUCT_SAFETY_FACTOR,+ PRODUCT_BUCKET_SAFETY_FACTOR,+ productSplitShards,+ getProductShape,PRODUCTS_SCALED_MARKER,TARGET_WALL_SECONDS,DJANGO_OVERHEAD_SECONDS_BY_SEGMENT,diff --git a/.github/workflows/ci-backend-update-test-timing.yml b/.github/workflows/ci-backend-update-test-timing.ymlindex fbde480bc553..ca341a4899aa 100644--- a/.github/workflows/ci-backend-update-test-timing.yml+++ b/.github/workflows/ci-backend-update-test-timing.yml@@ -155,7 +155,8 @@ jobs:# The merge below takes product entries only from the products file# (--replace-prefix), so a Products slice that fails the drift check# needs a stand-in or every product loses its durations. The last- # cached map is that stand-in. A miss leaves the checked-out file.+ # cached map is that stand-in. .test_durations is untracked, so a miss+ # leaves no file and the fallback below publishes no product entries.uses: actions/cache/restore@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3continue-on-error: truewith:@@ -166,11 +167,17 @@ jobs:posthog-test-durations-- name: Set the previous map aside- # The restore lands on the tracked file; keep the copy elsewhere and put- # the committed file back so the change check below diffs a clean tree.+ # Keep the restored map where the drift fallback below expects it, and+ # take it out of the tree so the fresh map is written rather than merged+ # onto the old one. .test_durations is not tracked (it left the repo when+ # the timing workflow started publishing it as an artifact), so there is+ # nothing to restore it from and a cache miss leaves no file at all.run: |- cp .test_durations /tmp/previous_durations- git checkout -- .test_durations+ if [ -f .test_durations ]; then+ mv .test_durations /tmp/previous_durations+ else+ echo "::warning::No cached map restored; a drifting Products slice has no stand-in"+ fi- name: Download timing artifactsenv:@@ -265,12 +272,21 @@ jobs:set -eif [ "$products_status" -ne 0 ]; thenecho "::warning::Products durations refresh exited $products_status; keeping the previous products slice. Drift or an incomplete JUnit set are the expected causes, see the log above."- # Only entries the fresh slices do not carry: the outlier merge would- # otherwise let a stale value here beat a fresh one for the same test.- jq -s 'add' $(ls /tmp/core_durations /tmp/temporal_durations /tmp/dagster_durations 2>/dev/null) > /tmp/fresh_durations- jq --slurpfile fresh /tmp/fresh_durations \- 'with_entries(select((.key | startswith("products/")) and ($fresh[0][.key] == null)))' \- /tmp/previous_durations > /tmp/products_durations+ if [ -f /tmp/previous_durations ]; then+ # Only entries the fresh slices do not carry: the outlier merge would+ # otherwise let a stale value here beat a fresh one for the same test.+ jq -s 'add' $(ls /tmp/core_durations /tmp/temporal_durations /tmp/dagster_durations 2>/dev/null) > /tmp/fresh_durations+ jq --slurpfile fresh /tmp/fresh_durations \+ 'with_entries(select((.key | startswith("products/")) and ($fresh[0][.key] == null)))' \+ /tmp/previous_durations > /tmp/products_durations+ else+ # No cached slice to stand in and no fresh one. A map with no product+ # entries would still become the newest cache and the latest successful+ # artifact, so every consumer would fall back to the file-count estimate+ # and under-shard the fixture-heavy products. Leave the older map newest.+ echo "::error::Products slice failed with no previous map to stand in; refusing to publish a map without product entries"+ exit 1+ fifi# Process Dagster segment if availablediff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.ymlindex 559638db70f4..38617b616a6a 100644--- a/.github/workflows/ci-backend.yml+++ b/.github/workflows/ci-backend.yml@@ -965,8 +965,15 @@ jobs:continue-on-error: true# --force: discover already decided this product needs testing, skip turbo cache# --log-order=stream: stream pytest output live instead of buffering until completion- # pytest_args: optional pytest-split flags for sharded products (e.g. "-- --splits 3 --group 1")+ # legs: one turbo invocation per entry, each with its own pytest-split flags+ # (e.g. "-- --splits 3 --group 1"). A job holds several legs when a split+ # product's last shard had budget left over for whole small products, and+ # pytest-split flags must not leak from that shard onto its job-mates.env:+ PRODUCT_LEGS: ${{ toJSON(matrix.legs) }}+ # Read only when an unrebased branch planned the pre-legs shape.+ LEGACY_FILTERS: ${{ matrix.filters }}+ LEGACY_PYTEST_ARGS: ${{ matrix.pytest_args }}CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA: ${{ matrix.new-events-schema && 'true' || 'false' }}# products/tasks/backend/temporal moved here from the Django Temporal# segment, and its conftest and workflows talk to Modal. Injected only@@ -993,17 +1000,42 @@ jobs:# bin-packed buckets (each product writes its own file) and split products (unioned later).# sysmon: Python 3.12+'s low-overhead coverage backend, ~a few % vs ~20% for the C tracer.COVERAGE_CORE: sysmon+ shell: bashrun: |set +e- pnpm turbo run backend:test ${{ matrix.filters }} --concurrency=1 --output-logs=full --force --log-order=stream ${{ matrix.pytest_args }}- exit_code=$?- set -e- if [ $exit_code -eq 5 ]; then- echo "No tests collected for this shard, this is expected when splitting tests"- exit 0- else- exit $exit_code+ overall=0+ # A workflow edit reaches an open PR before the script edit does, so a+ # branch that has not rebased still plans the flat {filters, pytest_args}+ # shape. Normalize that into one leg rather than requiring the new key.+ if [ -z "$PRODUCT_LEGS" ] || [ "$PRODUCT_LEGS" = "null" ]; then+ PRODUCT_LEGS=$(jq -cn --arg f "$LEGACY_FILTERS" --arg a "$LEGACY_PYTEST_ARGS" \+ '[{filters: $f, pytest_args: $a}]')+ echo "Matrix entry carries no legs; running the legacy single invocation"fi+ leg_count=$(jq 'length' <<< "$PRODUCT_LEGS")+ # Neither shape present means the job would pass having run no tests, and+ # the rollup gate only reads this step's outcome. Fail loudly instead.+ if [ -z "$leg_count" ] || [ "$leg_count" -lt 1 ]; then+ echo "::error::No test legs in this matrix entry; refusing to pass without running tests"+ exit 1+ fi+ for ((leg_index = 0; leg_index < leg_count; leg_index++)); do+ leg_filters=$(jq -r ".[$leg_index].filters" <<< "$PRODUCT_LEGS")+ leg_args=$(jq -r ".[$leg_index].pytest_args" <<< "$PRODUCT_LEGS")+ echo "::group::turbo backend:test $leg_filters $leg_args"+ # Word splitting is intended here: both variables carry several flags.+ # shellcheck disable=SC2086+ pnpm turbo run backend:test $leg_filters --concurrency=1 --output-logs=full --force --log-order=stream $leg_args+ exit_code=$?+ echo "::endgroup::"+ if [ $exit_code -eq 5 ]; then+ echo "No tests collected for this leg, this is expected when splitting tests"+ elif [ $exit_code -ne 0 ]; then+ overall=$exit_code+ fi+ done+ set -e+ exit $overall# Excluded reports bypass Trunk quarantine, so this step owns their verdict.- name: Prepare product JUnit for Trunk