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.

feat(devex): cascade product tests to dependents on contract changes (#70702)

Julian Bez41dc3dc5aa0e
diff --git a/.depot/workflows/ci-backend.yml b/.depot/workflows/ci-backend.yml
index f1b4398f561f..82f9775219d6 100644
--- a/.depot/workflows/ci-backend.yml
+++ b/.depot/workflows/ci-backend.yml
@@ -246,6 +246,10 @@ jobs:
- conftest.py # Root conftest loads for every pytest run
- .test_durations # Used for pytest-split sharding
- .test_quarantine.json # Un-quarantining must re-run the affected tests
+ # turbo-discover reads the module graph for the dependent
+ # cascade, and `tach check` validates it — a graph-only PR
+ # must still dispatch both.
+ - tach.toml
# generates posthog/schema.py
- frontend/src/queries/schema.json
# Operator parity check
diff --git a/.github/scripts/turbo-discover-cascade.test.js b/.github/scripts/turbo-discover-cascade.test.js
new file mode 100644
index 000000000000..4690adee5706
--- /dev/null
+++ b/.github/scripts/turbo-discover-cascade.test.js
@@ -0,0 +1,199 @@
+// Run with: node --test .github/scripts/turbo-discover-cascade.test.js
+//
+// Unit tests for the dependent-cascade logic in turbo-discover.js:
+// parseTachModules, tachDependents. Uses a synthetic graph throughout —
+// never asserts against the real tach.toml, which would turn into a
+// change-detector test that breaks on every unrelated dependency edit.
+
+const test = require('node:test')
+const assert = require('node:assert/strict')
+
+const { parseTachModules, tachDependents } = require('./turbo-discover')
+
+test('normalization round-trip: dashed input resolves against underscored tach names and returns dashed output', () => {
+ const toml = `
+[[modules]]
+path = "products.data_warehouse"
+depends_on = [
+ "posthog",
+]
+layer = "modules"
+
+[[modules]]
+path = "products.data_modeling"
+depends_on = [
+ "posthog",
+ "products.data_warehouse",
+]
+layer = "modules"
+`
+ const graph = parseTachModules(toml)
+ const dependents = tachDependents(['data-warehouse'], graph)
+ assert.deepEqual(dependents.sort(), ['data-modeling'])
+})
+
+test('cycle safety: terminates and returns correct dependents with a 2-cycle and a 3-cycle present', () => {
+ const toml = `
+[[modules]]
+path = "products.a"
+depends_on = ["products.b"]
+layer = "modules"
+
+[[modules]]
+path = "products.b"
+depends_on = ["products.a"]
+layer = "modules"
+
+[[modules]]
+path = "products.x"
+depends_on = ["products.y"]
+layer = "modules"
+
+[[modules]]
+path = "products.y"
+depends_on = ["products.z"]
+layer = "modules"
+
+[[modules]]
+path = "products.z"
+depends_on = ["products.x"]
+layer = "modules"
+
+[[modules]]
+path = "products.downstream"
+depends_on = ["products.z"]
+layer = "modules"
+`
+ const graph = parseTachModules(toml)
+
+ const abResult = tachDependents(['a'], graph)
+ assert.deepEqual(abResult.sort(), ['b'])
+
+ const xyzResult = tachDependents(['x'], graph)
+ assert.deepEqual(xyzResult.sort(), ['downstream', 'y', 'z'])
+})
+
+test('transitive: a multi-hop change reaches dependents beyond the first hop', () => {
+ const toml = `
+[[modules]]
+path = "products.a"
+depends_on = ["products.b"]
+layer = "modules"
+
+[[modules]]
+path = "products.b"
+depends_on = ["products.c"]
+layer = "modules"
+
+[[modules]]
+path = "products.c"
+depends_on = ["posthog"]
+layer = "modules"
+`
+ const graph = parseTachModules(toml)
+ const dependents = tachDependents(['c'], graph)
+ assert.deepEqual(dependents.sort(), ['a', 'b'])
+})
+
+test('core is never a node: posthog/ee/<root> are excluded as keys and values, and closures never traverse through them', () => {
+ const toml = `
+[[modules]]
+path = "<root>"
+depends_on = []
+layer = "modules"
+
+[[modules]]
+path = "ee"
+depends_on = [
+ "products.x",
+]
+layer = "modules"
+
+[[modules]]
+path = "posthog"
+depends_on = [
+ "ee",
+ "products.x",
+ "products.y",
+]
+layer = "modules"
+
+[[modules]]
+path = "products.x"
+depends_on = ["posthog"]
+layer = "modules"
+
+[[modules]]
+path = "products.y"
+depends_on = ["posthog"]
+layer = "modules"
+`
+ const graph = parseTachModules(toml)
+ assert.equal(graph.has('posthog'), false)
+ assert.equal(graph.has('ee'), false)
+ assert.equal(graph.has('<root>'), false)
+ for (const deps of graph.values()) {
+ assert.ok(!deps.includes('posthog'))
+ assert.ok(!deps.includes('ee'))
+ }
+
+ // x and y both only reach each other via posthog — not a real edge in the
+ // product graph, so neither should show up as the other's dependent.
+ assert.deepEqual(tachDependents(['x'], graph), [])
+ assert.deepEqual(tachDependents(['y'], graph), [])
+})
+
+test('changed products are excluded from their own dependent set', () => {
+ const toml = `
+[[modules]]
+path = "products.a"
+depends_on = ["products.b"]
+layer = "modules"
+
+[[modules]]
+path = "products.b"
+depends_on = ["posthog"]
+layer = "modules"
+`
+ const graph = parseTachModules(toml)
+ const dependents = tachDependents(['a', 'b'], graph)
+ assert.deepEqual(dependents, [])
+})
+
+test('fail closed: a depends_on entry that is not a double-quoted string throws instead of silently dropping the edge', () => {
+ const toml = `
+[[modules]]
+path = "products.a"
+depends_on = ['products.b']
+layer = "modules"
+`
+ assert.throws(() => parseTachModules(toml), /depends_on/)
+})
+
+test('fail closed: a path that is not a double-quoted string throws instead of silently dropping the module', () => {
+ const toml = `
+[[modules]]
+path = 'products.a'
+depends_on = ["products.b"]
+layer = "modules"
+`
+ assert.throws(() => parseTachModules(toml), /path/)
+})
+
+test('comments inside a depends_on list are tolerated, and a block without depends_on is skipped without error', () => {
+ const toml = `
+[[modules]]
+path = "products.a"
+depends_on = [
+ "products.b", # transitional edge
+]
+layer = "modules"
+
+[[modules]]
+path = "products.no_deps"
+layer = "modules"
+`
+ const graph = parseTachModules(toml)
+ assert.deepEqual(graph.get('a'), ['b'])
+ assert.equal(graph.has('no_deps'), false)
+})
diff --git a/.github/scripts/turbo-discover.js b/.github/scripts/turbo-discover.js
index 5530414d99d3..f9c3f658bbaa 100644
--- a/.github/scripts/turbo-discover.js
+++ b/.github/scripts/turbo-discover.js
@@ -219,6 +219,138 @@ function dropProducts(products, allProducts, names, label) {
return remaining
}
+// --- Dependent cascade (tach.toml) ---
+// When a product's contract changes, Turbo's graph has no edges to the
+// products that depend on it (no workspace deps, no `dependsOn`), so those
+// dependents never get retested — see #70556. tach.toml is the graph we
+// actually have: `tach check --dependencies` runs in CI, so it can't drift
+// from what's importable. Reuse it to compute who transitively depends on a
+// changed product's contract.
+const TACH_TOML_FILE = 'tach.toml'
+const TACH_MODULE_PREFIX = 'products.'
+
+// Turbo package names are dashed; tach module paths and product directories are
+// underscored. Every boundary crossing goes through these, so the convention is
+// stated once rather than re-derived at each call site.
+const productToModule = (product) => product.replace(/-/g, '_')
+const moduleToProduct = (module) => module.replace(/_/g, '-')
+
+// Parse tach.toml's [[modules]] blocks into product -> [products it depends
+// on]. Keys/values are tach names with the "products." prefix stripped
+// (underscores preserved) — callers normalize to/from Turbo's dashed names.
+//
+// Only products.* modules become nodes or edges. posthog/ee (and the
+// common.* utility modules) are dropped on both sides deliberately: they
+// aren't products.* so they fall out of the startsWith filter for free. See
+// tachDependents for why routing through them would be wrong, not just
+// inconvenient.
+function parseTachModules(tomlText) {
+ const graph = new Map()
+ // Each `[[modules]]` block holds exactly one `path` and one `depends_on`
+ // before the next block starts — split on the marker and take the first
+ // match of each within a block. depends_on entries are plain quoted
+ // strings with no nested brackets, so a non-greedy scan to the first `]`
+ // is safe even across multi-line lists or lists split across shared lines.
+ //
+ // Only double-quoted strings are supported. Other valid TOML (single-quoted
+ // literals, inline tables) would be dropped by the regexes without error,
+ // silently shrinking the cascade — so any entry the regexes can't represent
+ // throws instead, which loadTachModuleGraph turns into "test all products".
+ // A false trip over-tests; a silent drop under-tests, so err on throwing.
+ const blocks = tomlText.split('[[modules]]').slice(1)
+ for (const block of blocks) {
+ const pathMatch = block.match(/path\s*=\s*"([^"]+)"/)
+ if (!pathMatch) {
+ if (/^\s*path\s*=/m.test(block)) {
+ throw new Error('unsupported `path` syntax in a tach.toml module block (expected a double-quoted string)')
+ }
+ continue
+ }
+ const dependsMatch = block.match(/depends_on\s*=\s*\[([\s\S]*?)\]/)
+ if (!dependsMatch) {
+ if (/^\s*depends_on\s*=/m.test(block)) {
+ throw new Error(`unsupported \`depends_on\` syntax for ${pathMatch[1]} in tach.toml (expected a list)`)
+ }
+ continue
+ }
+ const leftover = dependsMatch[1].replace(/"[^"]*"/g, '').replace(/#[^\n]*/g, '')
+ if (/[^\s,]/.test(leftover)) {
+ throw new Error(
+ `unsupported \`depends_on\` entry for ${pathMatch[1]} in tach.toml (expected double-quoted strings): ${leftover.trim().slice(0, 80)}`
+ )
+ }
+ const modulePath = pathMatch[1]
+ if (!modulePath.startsWith(TACH_MODULE_PREFIX)) {continue}
+ const product = modulePath.slice(TACH_MODULE_PREFIX.length)
+ const deps = [...dependsMatch[1].matchAll(/"([^"]+)"/g)]
+ .map((m) => m[1])
+ .filter((d) => d.startsWith(TACH_MODULE_PREFIX))
+ .map((d) => d.slice(TACH_MODULE_PREFIX.length))
+ graph.set(product, deps)
+ }
+ return graph
+}
+
+// Reverse transitive closure over the product graph: who (transitively)
+// depends on any of `changedProducts`? Input/output are Turbo-style names
+// (dashes); moduleGraph keys/values are tach-style (underscores) — convert
+// at the boundary in both directions, since a mismatch here doesn't error,
+// it just silently returns nothing (a false negative — exactly the bug this
+// is fixing).
+//
+// Deliberately never traverses through posthog/ee (moduleGraph has already
+// dropped them as nodes): routing through core degenerates the cascade to
+// "every product" — most products depend on core and core depends on most
+// products, so any path through it reaches the whole graph. Core's own tests
+// aren't at risk either way — a contract change already forces runLegacy so
+// the full Django suite runs. The accepted gap is the mediated path (product
+// A -> a core wrapper -> product X's facade); measurement showed it's mostly
+// either unreachable (no product imports the file) or funnels through a few
+// composition-root hubs where "imports Team" doesn't mean "depends on a
+// product's behavior" — the residual after excluding those is a handful of
+// narrow wrappers reaching at most a few products each.
+function tachDependents(changedProducts, moduleGraph) {
+ const reverse = new Map()
+ for (const [product, deps] of moduleGraph) {
+ for (const dep of deps) {
+ if (!reverse.has(dep)) {reverse.set(dep, [])}
+ reverse.get(dep).push(product)
+ }
+ }
+
+ const changedSet = new Set(changedProducts.map(productToModule))
+ const visited = new Set()
+ const queue = [...changedSet]
+ while (queue.length > 0) {
+ const current = queue.shift()
+ for (const dependent of reverse.get(current) || []) {
+ if (visited.has(dependent) || changedSet.has(dependent)) {continue}
+ visited.add(dependent)
+ queue.push(dependent)
+ }
+ }
+ return [...visited].map(moduleToProduct)
+}
+
+// Returns null when the graph can't be read or parsed. Callers must treat null as
+// "unknown dependents" and widen the matrix — never as "no dependents", which would
+// silently under-test exactly the contract changes this cascade guards.
+function loadTachModuleGraph() {
+ let text
+ try {
+ text = fs.readFileSync(TACH_TOML_FILE, 'utf-8')
+ } catch (e) {
+ console.error(`::warning::Could not read ${TACH_TOML_FILE} (${e.message}) — falling back to testing all products`)
+ return null
+ }
+ try {
+ return parseTachModules(text)
+ } catch (e) {
+ console.error(`::warning::Could not parse ${TACH_TOML_FILE} (${e.message}) — falling back to testing all products`)
+ return null
+ }
+}
+
function loadTestDurations() {
let parsed
try {
@@ -272,14 +404,14 @@ function collectTestFiles(dir) {
}
function productPrefix(product) {
- return `products/${product.replace(/-/g, '_')}/`
+ return `products/${productToModule(product)}/`
}
// 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 dirName = productToModule(product)
const productDir = path.join('products', dirName)
const testFiles = collectTestFiles(productDir)
if (testFiles.length === 0) {return { stale: false, fileCount: 0, coveredCount: 0, coverage: 0 }}
@@ -500,7 +632,16 @@ function buildMatrix(products, durations) {
}
// 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 }
+module.exports = {
+ collectTestFiles,
+ checkProductStaleness,
+ productPrefix,
+ productEffectiveCost,
+ STALENESS_COVERAGE_THRESHOLD,
+ STALENESS_FALLBACK_SECONDS_PER_FILE,
+ parseTachModules,
+ tachDependents,
+}
// --- Main ---
if (require.main === module) {
@@ -526,6 +667,7 @@ try {
process.exit(1)
}
const allProducts = getAllProducts(allTestTasks)
+const allProductSet = new Set(allProducts)
let products
let runLegacy
@@ -559,11 +701,27 @@ if (legacyChanged) {
if (affectedContracts.length > 0) {
console.error(`Isolated product contracts changed: ${JSON.stringify(affectedContracts)} — Django will run`)
runLegacy = true
+ const tachGraph = loadTachModuleGraph()
+ if (tachGraph === null) {
+ // Fail toward over-testing, like the quarantine loaders above: without the
+ // graph we cannot know which products depend on the changed contract, and
+ // guessing "none" silently recreates the gap this cascade exists to close.
+ console.error('Dependent cascade unavailable — testing all products rather than risk skipping a dependent')
+ products = allProducts
+ } else {
+ const dependents = tachDependents(affectedContracts, tachGraph).filter((p) => allProductSet.has(p))
+ if (dependents.length > 0) {
+ console.error(
+ `Dependent products cascaded in via tach.toml: ${JSON.stringify(dependents)} (transitively depend on ${JSON.stringify(affectedContracts)})`
+ )
+ }
+ products = [...new Set([...affectedProducts, ...dependents])].sort()
+ }
} else {
console.error('Only isolated product internals changed — Django can be skipped')
runLegacy = false
+ products = affectedProducts
}
- products = affectedProducts
} else {
console.error('No product changes detected')
products = []
diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.yml
index c9bc3c828cfd..23f12b11a960 100644
--- a/.github/workflows/ci-backend.yml
+++ b/.github/workflows/ci-backend.yml
@@ -157,6 +157,10 @@ jobs:
- conftest.py # Root conftest loads for every pytest run
- .test_durations # Used for pytest-split sharding
- .test_quarantine.json # Un-quarantining must re-run the affected tests
+ # turbo-discover reads the module graph for the dependent
+ # cascade, and `tach check` validates it — a graph-only PR
+ # must still dispatch both.
+ - tach.toml
# generates posthog/schema.py
- frontend/src/queries/schema.json
# Operator parity check
diff --git a/.github/workflows/ci-scripts.yml b/.github/workflows/ci-scripts.yml
index 492ee10abc13..8916dd8d7984 100644
--- a/.github/workflows/ci-scripts.yml
+++ b/.github/workflows/ci-scripts.yml
@@ -65,3 +65,6 @@ jobs:
- name: CI report section tests (Node)
run: node --test .github/scripts/post-ci-sections.test.mjs
+
+ - name: Turbo-discover dependent-cascade tests (Node)
+ run: node --test .github/scripts/turbo-discover-cascade.test.js