Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(ci): add staleness guard to turbo-discover bin-packer (#69394)

mendral-app[bot]f18a872138a4
diff --git a/.github/scripts/turbo-discover-staleness.test.js b/.github/scripts/turbo-discover-staleness.test.js
new file mode 100644
index 000000000000..2612cf65d776
--- /dev/null
+++ b/.github/scripts/turbo-discover-staleness.test.js
@@ -0,0 +1,223 @@
+// Run with: node --test .github/scripts/turbo-discover-staleness.test.js
+//
+// Unit tests for the staleness detection logic in turbo-discover.js:
+// collectTestFiles, checkProductStaleness, productPrefix, productEffectiveCost.
+
+const test = require('node:test')
+const assert = require('node:assert/strict')
+const fs = require('fs')
+const os = require('os')
+const path = require('path')
+
+const {
+ collectTestFiles,
+ checkProductStaleness,
+ productPrefix,
+ productEffectiveCost,
+ STALENESS_COVERAGE_THRESHOLD,
+ STALENESS_FALLBACK_SECONDS_PER_FILE,
+} = require('./turbo-discover')
+
+test('productPrefix converts dashes to underscores', () => {
+ assert.equal(productPrefix('warehouse-sources'), 'products/warehouse_sources/')
+ assert.equal(productPrefix('batch-exports'), 'products/batch_exports/')
+ assert.equal(productPrefix('alerts'), 'products/alerts/')
+})
+
+test('collectTestFiles finds test_*.py and *_test.py recursively', () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'staleness-'))
+ try {
+ fs.mkdirSync(path.join(root, 'sub'), { recursive: true })
+ fs.writeFileSync(path.join(root, 'test_foo.py'), '')
+ fs.writeFileSync(path.join(root, 'bar_test.py'), '')
+ fs.writeFileSync(path.join(root, 'helper_utils.py'), '')
+ fs.writeFileSync(path.join(root, 'test_no_ext.txt'), '')
+ fs.writeFileSync(path.join(root, 'sub', 'test_nested.py'), '')
+
+ const files = collectTestFiles(root).sort()
+ assert.equal(files.length, 3)
+ assert.ok(files.some((f) => f.endsWith('test_foo.py')))
+ assert.ok(files.some((f) => f.endsWith('bar_test.py')))
+ assert.ok(files.some((f) => f.endsWith(path.join('sub', 'test_nested.py'))))
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+})
+
+test('collectTestFiles returns empty for non-existent directory', () => {
+ assert.deepEqual(collectTestFiles('/nonexistent/path/xyz'), [])
+})
+
+test('checkProductStaleness: exactly 70% coverage is NOT stale (threshold is <)', () => {
+ // Set up a temp product directory with 10 test files
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'staleness-threshold-'))
+ const origCwd = process.cwd()
+ try {
+ process.chdir(root)
+ const productDir = path.join(root, 'products', 'my_product', 'backend')
+ fs.mkdirSync(productDir, { recursive: true })
+ // Create 10 test files
+ for (let i = 0; i < 10; i++) {
+ fs.writeFileSync(path.join(productDir, `test_file${i}.py`), '')
+ }
+
+ // Build durations covering exactly 7/10 files (70%)
+ const durations = {}
+ for (let i = 0; i < 7; i++) {
+ durations[`products/my_product/backend/test_file${i}.py::TestClass::test_method`] = 1.0
+ }
+
+ const result = checkProductStaleness('my-product', durations)
+ assert.equal(result.stale, false, '70% coverage should NOT be stale (threshold is strict <)')
+ assert.equal(result.fileCount, 10)
+ assert.equal(result.coveredCount, 7)
+ assert.equal(result.coverage, 0.7)
+ } finally {
+ process.chdir(origCwd)
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+})
+
+test('checkProductStaleness: 69% coverage IS stale', () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'staleness-below-'))
+ const origCwd = process.cwd()
+ try {
+ process.chdir(root)
+ const productDir = path.join(root, 'products', 'my_product', 'backend')
+ fs.mkdirSync(productDir, { recursive: true })
+ // Create 100 test files for clean percentage
+ for (let i = 0; i < 100; i++) {
+ fs.writeFileSync(path.join(productDir, `test_file${i}.py`), '')
+ }
+
+ // Cover only 69 of 100 files
+ const durations = {}
+ for (let i = 0; i < 69; i++) {
+ durations[`products/my_product/backend/test_file${i}.py::TestClass::test_method`] = 1.0
+ }
+
+ const result = checkProductStaleness('my-product', durations)
+ assert.equal(result.stale, true, '69% coverage should be stale')
+ assert.equal(result.fileCount, 100)
+ assert.equal(result.coveredCount, 69)
+ } finally {
+ process.chdir(origCwd)
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+})
+
+test('checkProductStaleness: dash-to-underscore mapping works correctly', () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'staleness-dash-'))
+ const origCwd = process.cwd()
+ try {
+ process.chdir(root)
+ const productDir = path.join(root, 'products', 'warehouse_sources', 'backend')
+ fs.mkdirSync(productDir, { recursive: true })
+ fs.writeFileSync(path.join(productDir, 'test_source.py'), '')
+
+ // Duration key uses underscore (as stored in .test_durations)
+ const durations = {
+ 'products/warehouse_sources/backend/test_source.py::TestSource::test_connect': 2.0,
+ }
+
+ const result = checkProductStaleness('warehouse-sources', durations)
+ assert.equal(result.stale, false)
+ assert.equal(result.coveredCount, 1)
+ } finally {
+ process.chdir(origCwd)
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+})
+
+test('checkProductStaleness: durations with :: are correctly split to file path', () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'staleness-split-'))
+ const origCwd = process.cwd()
+ try {
+ process.chdir(root)
+ const productDir = path.join(root, 'products', 'alerts', 'backend')
+ fs.mkdirSync(productDir, { recursive: true })
+ fs.writeFileSync(path.join(productDir, 'test_alerts.py'), '')
+
+ // Multiple test entries from the same file
+ const durations = {
+ 'products/alerts/backend/test_alerts.py::TestAlerts::test_create': 0.5,
+ 'products/alerts/backend/test_alerts.py::TestAlerts::test_delete': 0.3,
+ 'products/alerts/backend/test_alerts.py::TestAlertsAPI::test_list': 1.0,
+ }
+
+ const result = checkProductStaleness('alerts', durations)
+ assert.equal(result.stale, false)
+ assert.equal(result.fileCount, 1)
+ assert.equal(result.coveredCount, 1)
+ } finally {
+ process.chdir(origCwd)
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+})
+
+test('checkProductStaleness: scans entire product dir including dags/', () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'staleness-dags-'))
+ const origCwd = process.cwd()
+ try {
+ process.chdir(root)
+ const backendDir = path.join(root, 'products', 'my_product', 'backend')
+ const dagsDir = path.join(root, 'products', 'my_product', 'dags')
+ fs.mkdirSync(backendDir, { recursive: true })
+ fs.mkdirSync(dagsDir, { recursive: true })
+ fs.writeFileSync(path.join(backendDir, 'test_main.py'), '')
+ fs.writeFileSync(path.join(dagsDir, 'test_dag.py'), '')
+
+ // Only cover the backend file
+ const durations = {
+ 'products/my_product/backend/test_main.py::Test::test_it': 1.0,
+ }
+
+ const result = checkProductStaleness('my-product', durations)
+ // 1/2 files covered = 50% < 70% → stale
+ assert.equal(result.stale, true)
+ assert.equal(result.fileCount, 2)
+ assert.equal(result.coveredCount, 1)
+ } finally {
+ process.chdir(origCwd)
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+})
+
+test('checkProductStaleness: early returns include coverage field', () => {
+ const noDurations = checkProductStaleness('any-product', null)
+ assert.equal(noDurations.coverage, 0)
+ assert.equal(noDurations.stale, true)
+
+ // Product with no test files (nonexistent dir)
+ const noFiles = checkProductStaleness('nonexistent-product', { 'some/path.py::test': 1.0 })
+ assert.equal(noFiles.coverage, 0)
+ assert.equal(noFiles.stale, false)
+})
+
+test('productEffectiveCost uses staleness fallback when coverage is poor', () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'staleness-cost-'))
+ const origCwd = process.cwd()
+ try {
+ process.chdir(root)
+ const productDir = path.join(root, 'products', 'big_product', 'backend')
+ fs.mkdirSync(productDir, { recursive: true })
+ // Create 50 test files
+ for (let i = 0; i < 50; i++) {
+ fs.writeFileSync(path.join(productDir, `test_file${i}.py`), '')
+ }
+
+ // Cover only 10/50 = 20% (stale)
+ const durations = {}
+ for (let i = 0; i < 10; i++) {
+ durations[`products/big_product/backend/test_file${i}.py::Test::test`] = 0.5
+ }
+
+ const cost = productEffectiveCost('big-product', durations)
+ // Fallback: max(5.0 duration, 50 * 5) = 250s → 250 * 1.3 + 60 = 385
+ const expectedBase = 50 * STALENESS_FALLBACK_SECONDS_PER_FILE
+ assert.ok(cost > expectedBase, `cost ${cost} should exceed fallback base ${expectedBase}`)
+ } finally {
+ process.chdir(origCwd)
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+})
diff --git a/.github/scripts/turbo-discover.js b/.github/scripts/turbo-discover.js
index 8568ab2a7ea5..038f1bee18b0 100644
--- a/.github/scripts/turbo-discover.js
+++ b/.github/scripts/turbo-discover.js
@@ -23,6 +23,7 @@
const { execFileSync } = require('child_process')
const fs = require('fs')
+const path = require('path')
const { analyzeSchemaImpact, readBaseSchema } = require('./schema-impact')
// --- Product shard sizing (same Amdahl shape as Django below) ---
@@ -58,6 +59,17 @@ const PRODUCTS_RUNNING_TEMPORAL_IN_JOB = new Set(['warehouse-sources'])
// at the job timeout. Trade-off: a dedicated runner.
const DEDICATED_BUCKET_PRODUCTS = new Set(['batch-exports'])
+// --- Staleness detection for .test_durations ---
+// When a product's test files on disk significantly outnumber what .test_durations
+// covers, the duration data is stale and cost estimates are unreliable. In that
+// case, fall back to a file-count-based estimate to prevent under-sharding.
+// Threshold: if fewer than 70% of on-disk test files appear in .test_durations,
+// treat the product's duration data as stale.
+const STALENESS_COVERAGE_THRESHOLD = 0.7
+// Conservative per-file fallback duration (seconds) when stale. Accounts for
+// parametrized tests that expand a single file into many test cases.
+const STALENESS_FALLBACK_SECONDS_PER_FILE = 5
+
// --- Django shard auto-sizing (Amdahl's law) ---
// wall_clock = overhead + (total_from_durations_file / shards)
//
@@ -236,12 +248,68 @@ function loadTestDurations() {
return parsed
}
+// Recursively collect test files (test_*.py / *_test.py) under a directory.
+function collectTestFiles(dir) {
+ const files = []
+ let entries
+ try {
+ entries = fs.readdirSync(dir, { withFileTypes: true })
+ } catch {
+ return files
+ }
+ for (const entry of entries) {
+ const full = path.join(dir, entry.name)
+ if (entry.isDirectory()) {
+ files.push(...collectTestFiles(full))
+ } else if (
+ entry.isFile() &&
+ entry.name.endsWith('.py') &&
+ (entry.name.startsWith('test_') || entry.name.endsWith('_test.py'))
+ ) {
+ files.push(full)
+ }
+ }
+ return files
+}
+
+function productPrefix(product) {
+ return `products/${product.replace(/-/g, '_')}/`
+}
+
+// Check if .test_durations is stale for a product by comparing on-disk test
+// file coverage vs recorded entries. Returns { stale, fileCount, coveredCount, coverage }.
+function checkProductStaleness(product, durations) {
+ if (!durations) return { stale: true, fileCount: 0, coveredCount: 0, coverage: 0 }
+ const dirName = product.replace(/-/g, '_')
+ const productDir = path.join('products', dirName)
+ const testFiles = collectTestFiles(productDir)
+ if (testFiles.length === 0) return { stale: false, fileCount: 0, coveredCount: 0, coverage: 0 }
+
+ const prefix = productPrefix(product)
+ // Build set of file paths that have at least one entry in durations
+ const coveredFiles = new Set()
+ for (const testPath of Object.keys(durations)) {
+ if (testPath.startsWith(prefix)) {
+ // Extract file path (everything before ::)
+ const filePart = testPath.split('::')[0]
+ coveredFiles.add(filePart)
+ }
+ }
+
+ let coveredCount = 0
+ for (const file of testFiles) {
+ if (coveredFiles.has(file)) coveredCount++
+ }
+
+ const coverage = coveredCount / testFiles.length
+ return { stale: coverage < STALENESS_COVERAGE_THRESHOLD, fileCount: testFiles.length, coveredCount, coverage }
+}
+
function getProductDuration(product, durations) {
if (!durations) {
return 0
}
- const dirName = product.replace(/-/g, '_')
- const prefix = `products/${dirName}/`
+ const prefix = productPrefix(product)
// Temporal tests are normally excluded (they run in the Django Temporal segment), but a product
// that runs its own temporal suite in the product job must count them toward its size.
const excluded = PRODUCTS_RUNNING_TEMPORAL_IN_JOB.has(product) ? [] : EXCLUDED_PATH_SEGMENTS
@@ -255,7 +323,12 @@ function getProductDuration(product, durations) {
}
function productEffectiveCost(product, durations) {
- return getProductDuration(product, durations) * PRODUCT_SAFETY_FACTOR + PRODUCT_PER_PRODUCT_OVERHEAD_SECONDS
+ let base = getProductDuration(product, durations)
+ const staleness = checkProductStaleness(product, durations)
+ if (staleness.stale && staleness.fileCount > 0) {
+ base = Math.max(base, staleness.fileCount * STALENESS_FALLBACK_SECONDS_PER_FILE)
+ }
+ return base * PRODUCT_SAFETY_FACTOR + PRODUCT_PER_PRODUCT_OVERHEAD_SECONDS
}
// First-fit-decreasing bin packing into TARGET-sized shards. Sorts products by
@@ -365,8 +438,27 @@ function buildMatrix(products, durations) {
// can't balance well when many tests have flat-default 0.01s values),
// paying duplicate Docker setup for little parallel work gained.
for (const product of products) {
- const raw = getProductDuration(product, durations) + PRODUCT_PER_PRODUCT_OVERHEAD_SECONDS
+ const staleness = checkProductStaleness(product, durations)
+ let raw = getProductDuration(product, durations) + PRODUCT_PER_PRODUCT_OVERHEAD_SECONDS
const targetWall = PRODUCT_TARGET_WALL_OVERRIDE[product] ?? PRODUCT_TARGET_WALL_SECONDS
+
+ // Staleness guard: if .test_durations has poor coverage for this product,
+ // use a file-count-based fallback to avoid under-sharding.
+ if (staleness.stale && staleness.fileCount > 0) {
+ const fallbackRaw = staleness.fileCount * STALENESS_FALLBACK_SECONDS_PER_FILE + PRODUCT_PER_PRODUCT_OVERHEAD_SECONDS
+ if (fallbackRaw > raw) {
+ console.error(
+ ` ${product}: .test_durations stale — ${staleness.coveredCount}/${staleness.fileCount} test files covered ` +
+ `(${(staleness.coverage * 100).toFixed(0)}%). Using fallback estimate: ${(fallbackRaw / 60).toFixed(1)} min (was ${(raw / 60).toFixed(1)} min)`
+ )
+ console.error(
+ `::warning title=Stale .test_durations::Product '${product}' has only ${staleness.coveredCount}/${staleness.fileCount} ` +
+ `test files covered in .test_durations. Duration estimates are unreliable — using fallback sharding.`
+ )
+ raw = fallbackRaw
+ }
+ }
+
if (raw > targetWall) {
const shards = Math.ceil(raw / targetWall)
console.error(` ${product}: ${(raw / 60).toFixed(1)} min raw → split across ${shards} shards`)
@@ -404,7 +496,11 @@ function buildMatrix(products, durations) {
return matrix
}
+// Exported for unit tests only — not part of the public API.
+module.exports = { collectTestFiles, checkProductStaleness, productPrefix, productEffectiveCost, STALENESS_COVERAGE_THRESHOLD, STALENESS_FALLBACK_SECONDS_PER_FILE }
+
// --- Main ---
+if (require.main === module) {
const legacyChanged = process.env.LEGACY_CHANGED === 'true'
const schemaChanged = process.env.SCHEMA_CHANGED === 'true'
@@ -543,3 +639,5 @@ const result = {
}
// eslint-disable-next-line no-console
process.stdout.write(JSON.stringify(result) + '\n')
+
+} // end if (require.main === module)