:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(devex): read the dependent cascade from tach map (#89839)
Julian Bezc16d909d6ac1
diff --git a/.depot/workflows/ci-backend.yml b/.depot/workflows/ci-backend.ymlindex e89e5c17f591..ccae87d5db07 100644--- a/.depot/workflows/ci-backend.yml+++ b/.depot/workflows/ci-backend.yml@@ -630,6 +630,14 @@ jobs:uses: ./.depot/actions/pnpm-installwith:install-command: pnpm install --frozen-lockfile --filter=@posthog/root+ # turbo-discover.js runs .github/scripts/tach_map.py under `uv run+ # --no-project` for the dependent cascade; the script pins tach, so no+ # Python project sync is needed. A missing uv widens the cascade to+ # every product rather than failing the job.+ - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0+ continue-on-error: true+ with:+ version: '0.11.28' # pinned: unpinned setup-uv calls GH API on every job, exhausts rate limit- name: Restore test durations from cache# Restore fresh timings so shard counts match GitHub Actions; miss falls back to committed.uses: actions/cache/restore@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3diff --git a/.github/scripts/tach_map.py b/.github/scripts/tach_map.pynew file mode 100644index 000000000000..a6cfbe7371e7--- /dev/null+++ b/.github/scripts/tach_map.py@@ -0,0 +1,17 @@+# /// script+# requires-python = ">=3.11"+# dependencies = ["tach==0.34.1"]+# ///+"""Print tach's file-level import map ({file: [files that import it]}) as JSON on stdout.++turbo-discover.js and trunk-impacted-targets.js run this with `uv run --no-project` from the+repo root, so they need uv and nothing from the Python project. The tach pin above is the one+uv.lock carries, so the map comes from the same tach that `tach check` runs in ci-backend.+"""++import sys++from tach.start import start++sys.argv = ["tach", "map", "--direction", "dependents", "--output", "-"]+start()diff --git a/.github/scripts/test_tach_map.py b/.github/scripts/test_tach_map.pynew file mode 100644index 000000000000..a92a719364e4--- /dev/null+++ b/.github/scripts/test_tach_map.py@@ -0,0 +1,26 @@+import re+import tomllib+from pathlib import Path++SCRIPTS_DIR = Path(__file__).parent+REPO_ROOT = SCRIPTS_DIR.parent.parent+++def pep723_tach_pin(script_text: str) -> str:+ match = re.search(r'^# dependencies = \[\s*"tach==([^"]+)"\s*\]', script_text, re.MULTILINE)+ assert match is not None, "tach_map.py must pin exactly one dependency, tach==<version>"+ return match.group(1)+++def locked_tach_version(lock_text: str) -> str:+ packages = tomllib.loads(lock_text)["package"]+ return next(package["version"] for package in packages if package["name"] == "tach")+++def test_tach_map_pins_the_locked_tach_version() -> None:+ pinned = pep723_tach_pin((SCRIPTS_DIR / "tach_map.py").read_text())+ locked = locked_tach_version((REPO_ROOT / "uv.lock").read_text())+ assert pinned == locked, (+ f"tach_map.py pins tach=={pinned} but uv.lock resolves tach=={locked}; "+ "bump the PEP 723 pin so the import map comes from the tach that `tach check` runs"+ )diff --git a/.github/scripts/trunk-impacted-targets.js b/.github/scripts/trunk-impacted-targets.jsindex 89fd60d13baa..4073c6fe2939 100644--- a/.github/scripts/trunk-impacted-targets.js+++ b/.github/scripts/trunk-impacted-targets.js@@ -26,10 +26,20 @@// call to the old name, and master breaks on a combination neither run held.//// 1. A product change claims its own lane plus its direct importers, rather-// than every backend lane. tach.toml is the enforced Python module graph-// (`tach check` runs in CI), so for a product it declares, the modules-// that may import it are exactly the ones listing it in `depends_on`. A-// product absent from that graph is unconstrained and still widens.+// than every backend lane. The tach map is the real Python import graph+// (`tach map` reads the imports that `tach check` enforces in CI), so for+// a product it walked, the products that import it are known from the+// files. A product absent from that map has no known importer set and+// still widens.+//+// ACCEPTED RISK: the map is read from each PR's own tree, so an importer+// that does not exist yet is not in it. PR A renames a symbol in X, PR B+// adds the first call from Y to X, and neither lane names the other's+// product; master holds the combination untested. The declared graph in+// tach.toml covered only the slice of this where Y had listed X in+// `depends_on` before importing it, and closing it fully would make every+// PR claim what its products import as well, which lands nearly every+// product PR in the hub products' lanes.//// This does NOT require the product to be isolated. Isolation is the// stronger claim that a change inside the product can only break the@@ -59,7 +69,7 @@// product_analytics, which depends on warehouse_sources) is no longer// serialized, and master's post-merge run is the only net for it. The// transitive closure was not a usable alternative: a 31-product cycle in-// tach.toml means every member reaches every other, so any seed inside it+// the product graph means every member reaches every other, so any seed inside it// expanded to the whole backend and the cascade could not distinguish// products at all.//@@ -223,9 +233,10 @@ const TRIPWIRE_RULES = [['.github/workflows/trunk-impacted-targets.yml', UNIVERSAL],['turbo.json', UNIVERSAL],- // tach.toml is one of those graphs, so it carries the same self-gating- // hazard, but every edge it can move lands on a python lane: `tach check`- // runs in ci-backend.yml, and the two readers of the graph, this script and+ // tach.toml shapes one of those graphs (its exclude list decides what+ // `tach map` walks), so it carries the same self-gating hazard, but every+ // edge it can move lands on a python lane: `tach check` runs in+ // ci-backend.yml, and the two readers of the map, this script and// turbo-discover, use it only to cascade python product lanes. `python`// claims all of them, so a PR editing the graph still overlaps every PR// whose lanes were computed against the old one.@@ -1215,8 +1226,8 @@ function isInProductWorkspace(product, file, productWorkspaces) {// filter, but a filter tuned to over-run is not a safe source for lane// assignment, while an --ignore is a statement that the suite does not// cover the path at all.-// 2. The product is absent from tach.toml, the enforced Python module graph,-// so no declared module may import it.+// 2. The product is absent from the tach map, the real Python import graph,+// so no Python file under a source root imports it.//// A product satisfying both cannot fail another product's backend suite, so// its files claim its own lanes instead of all of them. Either condition@@ -1251,15 +1262,14 @@ function loadBackendDetachedProducts(repoRoot, products, tachGraph) {return detached}-// tach spells its modules both ways across the file, so a product counts as-// declared under either spelling. A product absent from the graph, or a graph-// that could not be read at all, is not constrained by `tach check` and so has-// no bounded importer set.+// A product the tach map walked has a known importer set. One absent from the+// map (no Python with an import edge under a source root, or excluded by+// tach.toml), or a map that could not be read at all, has none.function isTachDeclared(product, tachGraph) {if (!tachGraph) {return false}- return tachGraph.graph.has(product) || tachGraph.graph.has(product.replace(/_/g, '-'))+ return tachGraph.graph.has(product)}function listTachDeclaredProducts(products, tachGraph) {@@ -1884,6 +1894,7 @@ function computeTargets(changedFiles, context) {productWorkspaces = new Map(),backendDetachedProducts = new Set(),tachDeclaredProducts = listTachDeclaredProducts(products, tachGraph),+ deletedFiles = new Set(),} = contextconst targets = new Set()@@ -2075,7 +2086,13 @@ function computeTargets(changedFiles, context) {targets.add(feProduct(product))}if (isBackend || (!isBackend && !isFrontend && !isWorkspaceOnly)) {- if (isolatedProducts.has(product)) {+ if (isBackend && deletedFiles.has(file)) {+ // The tach map is read from the head tree, so a deleted or+ // renamed-away file is not in it and its importers are+ // unknown. The PR that removes a facade module beside a+ // caller it missed is the exact conflict lanes exist for.+ allPyProducts()+ } else if (isolatedProducts.has(product)) {targets.add(pyProduct(product))if (touchesContractSurface(product, file, contractSurfaces)) {cascadeSeeds.add(product)@@ -2105,9 +2122,9 @@ function computeTargets(changedFiles, context) {// product can be too unsealed to skip the suite and still// have a bounded importer set.//- // The bound only holds for a product tach declares. One- // absent from the graph is unconstrained by `tach check`,- // so anything may import it and it still widens below.+ // The bound only holds for a product the tach map walked.+ // One absent from the map has no known importer set, so+ // it still widens below.targets.add(pyProduct(product))cascadeSeeds.add(product)} else {@@ -2212,9 +2229,10 @@ function computeTargets(changedFiles, context) {return [...targets].sort()}-// tach.toml is the enforced Python module graph (`tach check` runs in CI, so it-// cannot drift from what is importable). Turbo-style dashed names cross the-// boundary in both directions; product directories are underscored.+// The tach map is the real Python import graph (`tach map` reads the imports+// that `tach check` enforces in CI, so it cannot drift from what is+// importable). Turbo-style dashed names cross the boundary in both directions;+// product directories are underscored.function tachDependentProducts(changedProducts, tachGraph) {if (!tachGraph) {return null@@ -2233,14 +2251,9 @@ function tachDependentProducts(changedProducts, tachGraph) {}function loadTachGraph(repoRoot) {- try {- const { parseTachModules, tachDependents } = require('./turbo-discover')- const text = fs.readFileSync(path.join(repoRoot, 'tach.toml'), 'utf8')- return { graph: parseTachModules(text), tachDependents }- } catch (error) {- console.error(`tach.toml graph unavailable (${error.message}); backend changes widen to all products`)- return null- }+ const { loadTachModuleGraph, tachDependents } = require('./turbo-discover')+ const graph = loadTachModuleGraph(repoRoot)+ return graph === null ? null : { graph, tachDependents }}// Every directory under services/ holds a lane, so the list has to be read@@ -2369,7 +2382,9 @@ if (require.main === module) {console.error('No changed files on stdin; reporting ALL')result = ALL} else {- result = computeTargets(changedFiles, buildContext(REPO_ROOT))+ // The change list carries deleted paths too; the tree no longer does.+ const deletedFiles = new Set(changedFiles.filter((file) => !fs.existsSync(path.join(REPO_ROOT, file))))+ result = computeTargets(changedFiles, { ...buildContext(REPO_ROOT), deletedFiles })}} catch (error) {// Any unexpected failure has to widen rather than narrow, because adiff --git a/.github/scripts/trunk-impacted-targets.test.js b/.github/scripts/trunk-impacted-targets.test.jsindex 3fe92cce8c57..6903fd7d87d6 100644--- a/.github/scripts/trunk-impacted-targets.test.js+++ b/.github/scripts/trunk-impacted-targets.test.js@@ -42,7 +42,7 @@ const {RUST,UNIVERSAL,} = require('./trunk-impacted-targets')-const { parseTachModules, tachDependents } = require('./turbo-discover')+const { tachDependents } = require('./turbo-discover')const CONTEXT = {products: ['alpha', 'beta', 'gamma'],@@ -71,28 +71,18 @@ const CONTEXT = {// What a widening decision now uploads in place of the "ALL" sentinel.const EVERYTHING = allKnownTargets(CONTEXT)-// A graph that declares all three products, so their importer sets are bounded.-// The base CONTEXT deliberately declares none, which covers the case where a-// product sits outside `tach check` and has to keep widening.+// A graph the tach map walked all three products into, so their importer sets+// are known. The base CONTEXT deliberately holds none, which covers the case+// where a product sits outside the map and has to keep widening. Keys and+// values are product directory names, the shape productGraphFromTachMap emits.const TACH_DECLARED_CONTEXT = {...CONTEXT,tachGraph: {- graph: parseTachModules(`-[[modules]]-path = "products.alpha"-depends_on = []-layer = "modules"--[[modules]]-path = "products.beta"-depends_on = ["products.gamma"]-layer = "modules"--[[modules]]-path = "products.gamma"-depends_on = []-layer = "modules"-`),+ graph: new Map([+ ['alpha', []],+ ['beta', ['gamma']],+ ['gamma', []],+ ]),tachDependents,},}@@ -1502,18 +1492,11 @@ test('a contract with no product-relative inputs yields no matcher', () => {// targets, and in the real graph a 31-product cycle makes the transitive// closure the whole backend.test('the cascade names direct importers and stops before the next hop', () => {- const toml = `-[[modules]]-path = "products.beta"-depends_on = ["products.alpha"]-layer = "modules"--[[modules]]-path = "products.gamma"-depends_on = ["products.beta"]-layer = "modules"-`- const context = { ...CONTEXT, tachGraph: { graph: parseTachModules(toml), tachDependents } }+ const graph = new Map([+ ['beta', ['alpha']],+ ['gamma', ['beta']],+ ])+ const context = { ...CONTEXT, tachGraph: { graph, tachDependents } }assert.deepEqual(computeTargets(['products/alpha/backend/api.py'], context), ['py:product:alpha','py:product:beta',@@ -1523,6 +1506,15 @@ layer = "modules"// The base CONTEXT keeps an empty tach graph, so no product is declared in it.// A product `tach check` does not constrain has no bounded importer set: any// module may import it, so its change still has to reach every backend lane.+// The tach map is read from the head tree, so a file the PR deleted has no+// importer edge left; alpha's known importers are not enough to bound its lane.+test('a deleted product python file widens to every backend target', () => {+ const file = 'products/alpha/backend/facade/api.py'+ const context = { ...TACH_DECLARED_CONTEXT, deletedFiles: new Set([file]) }+ assert.equal(computeTargets([file], context).includes('py:core'), true)+ assert.equal(computeTargets([file], TACH_DECLARED_CONTEXT).includes('py:core'), false)+})+test('a product absent from the tach graph widens to every backend target', () => {const targets = computeTargets(['products/gamma/backend/api.py'], CONTEXT)assert.equal(targets.includes('py:core'), true)@@ -1532,7 +1524,7 @@ test('a product absent from the tach graph widens to every backend target', () =})// The lane only has to answer whether another PR can reference the symbols this-// one changed, and tach.toml answers exactly that. Isolation is the stronger,+// one changed, and the tach map answers exactly that. Isolation is the stronger,// separate claim that the product's own suite is sufficient, which lets CI// skip the full Django suite, and which products/architecture.md says tach// cannot prove. A product can be too unsealed for that and still be bounded@@ -1725,7 +1717,7 @@ test('the vendored workspace files claim only the product lane', () => {})// delta stands in for products/desktop: an app imported from another-// repository that pytest.ini ignores and tach.toml never declares. Its+// repository that pytest.ini ignores and the tach map never walks. Its// vendored .py files read as backend to the layout rules, so without the// detachment check they claim every backend lane for suites that never run on// them.diff --git a/.github/scripts/turbo-discover-cascade.test.js b/.github/scripts/turbo-discover-cascade.test.jsindex 70d9bab0864a..cfc7d9fed6af 100644--- a/.github/scripts/turbo-discover-cascade.test.js+++ b/.github/scripts/turbo-discover-cascade.test.js@@ -1,98 +1,55 @@// 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.+// productGraphFromTachMap, tachDependents, loadTachModuleGraph. Uses a+// synthetic graph throughout — never asserts against the real tach map, which+// would turn into a change-detector test that breaks on every unrelated import.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"+const { productGraphFromTachMap, tachDependents, loadTachModuleGraph } = require('./turbo-discover')++// Graph literals use the shape productGraphFromTachMap emits: product directory+// name -> sorted product directory names it imports.+const graph = (edges) => new Map(Object.entries(edges))++test('the file map collapses to a product graph: importers outside products/ and loose files under it are dropped, self-imports vanish, test importers count', () => {+ const fileMap = {+ 'products/data_warehouse/backend/facade/api.py': [+ 'products/data_modeling/backend/logic/models.py',+ 'products/data_modeling/backend/test/test_models.py',+ 'products/data_warehouse/backend/routes.py',+ 'posthog/settings/web.py',+ 'products/conftest.py',+ ],+ 'products/lonely/backend/api.py': ['ee/api/wrapper.py'],+ 'posthog/models/team.py': ['products/data_modeling/backend/logic/models.py'],+ 'products/__init__.py': ['products/data_modeling/backend/apps.py'],+ }+ assert.deepEqual(+ productGraphFromTachMap(fileMap),+ graph({+ data_warehouse: [],+ data_modeling: ['data_warehouse'],+ lonely: [],+ })+ )+})-[[modules]]-path = "products.data_modeling"-depends_on = [- "posthog",- "products.data_warehouse",-]-layer = "modules"-`- const graph = parseTachModules(toml)- const dependents = tachDependents(['data-warehouse'], graph)+test('normalization round-trip: dashed input resolves against underscored directory names and returns dashed output', () => {+ const dependents = tachDependents(+ ['data-warehouse'],+ graph({ data_warehouse: [], data_modeling: ['data_warehouse'] })+ )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 cyclic = graph({ a: ['b'], b: ['a'], x: ['y'], y: ['z'], z: ['x'], downstream: ['z'] })- 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'])+ assert.deepEqual(tachDependents(['a'], cyclic).sort(), ['b'])+ assert.deepEqual(tachDependents(['x'], cyclic).sort(), ['downstream', 'y', 'z'])})// Test selection must stay transitive by default: a change in c can break a's@@ -100,167 +57,33 @@ layer = "modules"// assignment asks for one hop, so a flipped default here would silently// under-test every contract change.test('direct stops at the first hop while the default stays transitive', () => {- 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)- assert.deepEqual(tachDependents(['c'], graph, { direct: true }), ['b'])- assert.deepEqual(tachDependents(['c'], graph).sort(), ['a', 'b'])+ const chain = graph({ a: ['b'], b: ['c'], c: [] })+ assert.deepEqual(tachDependents(['c'], chain, { direct: true }), ['b'])+ assert.deepEqual(tachDependents(['c'], chain).sort(), ['a', 'b'])})test('direct dependents terminate on a cycle rather than walking it', () => {- 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.downstream"-depends_on = ["products.a"]-layer = "modules"-`- const graph = parseTachModules(toml)- assert.deepEqual(tachDependents(['b'], graph, { direct: true }), ['a'])+ assert.deepEqual(tachDependents(['b'], graph({ a: ['b'], b: ['a'], downstream: ['a'] }), { direct: true }), ['a'])})-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'))+test("core is never a node: two products that only meet through posthog are not each other's dependents", () => {+ const fileMap = {+ 'products/x/backend/api.py': ['posthog/api/router.py'],+ 'posthog/api/router.py': ['products/y/backend/routes.py'],}-- // 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), [])+ const collapsed = productGraphFromTachMap(fileMap)+ assert.deepEqual(collapsed, graph({ x: [], y: [] }))+ assert.deepEqual(tachDependents(['x'], collapsed), [])+ assert.deepEqual(tachDependents(['y'], collapsed), [])})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, [])+ assert.deepEqual(tachDependents(['a', 'b'], graph({ a: ['b'], b: [] })), [])})-// tach.toml annotates facade-only edges with prose that names the tach block-// enforcing them, so a depends_on list can carry a `]` inside a comment. The-// scan for the list's closing bracket used to stop there and drop every entry-// below it, and the fail-closed check could not see it because that check-// discarded comments too.-test('a comment inside depends_on does not truncate the list', () => {- const toml = `-[[modules]]-path = "products.a"-depends_on = [- "products.b",- # Facade-only (enforced by c's [[interfaces]] block): a queues c's work.- "products.c",- "products.d", # direct import-]-layer = "modules"-`- assert.deepEqual(parseTachModules(toml).get('a'), ['b', 'c', 'd'])-})--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)+// The callers widen on null and would crash on a throw, so a run that cannot+// start has to come back as "unknown", not as an exception. A repo root that+// does not exist fails the spawn before any real uv or tach is involved.+test('fail closed: a run that cannot start yields null instead of throwing', () => {+ assert.equal(loadTachModuleGraph('/nonexistent/repo-root'), null)})diff --git a/.github/scripts/turbo-discover.js b/.github/scripts/turbo-discover.jsindex b548f33a5019..eccb45c81a65 100644--- a/.github/scripts/turbo-discover.js+++ b/.github/scripts/turbo-discover.js@@ -300,110 +300,81 @@ function dropProducts(products, allProducts, names, label) {return remaining}-// --- Dependent cascade (tach.toml) ---+// --- Dependent cascade (tach map) ---// 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+// dependents never get retested — see #70556. `tach map` is the graph we+// actually have: it walks the real imports of every Python file under+// tach.toml's source roots, the same imports `tach check --dependencies`+// enforces in CI, so it can't drift from what's importable. It reads the files+// rather than the declared depends_on lists, so an import the declaration+// misses (a module path in a string, a test that imports another product's+// facade) still cascades. 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.+//+// tach_map.py pins tach in its PEP 723 block and runs under `uv run+// --no-project`, so the callers need uv and nothing from the Python project.+const TACH_MAP_SCRIPT = path.join(__dirname, 'tach_map.py')+const PRODUCTS_DIR = 'products/'++// Turbo package names are dashed; 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.-// TOML comments run to the end of the line, and a `#` inside a double-quoted-// string does not start one. Comments have to go before the block scan below,-// because a comment inside a depends_on list can carry a `]`: tach.toml-// documents a facade-only edge as "enforced by stamphog's [[interfaces]]-// block", and that bracket ends the non-greedy scan early, dropping every-// entry after it.-function stripTomlComments(tomlText) {- let out = ''- let inString = false- for (let index = 0; index < tomlText.length; index++) {- const char = tomlText[index]- if (char === '"' && tomlText[index - 1] !== '\\') {- inString = !inString- }- if (!inString && char === '#') {- while (index < tomlText.length && tomlText[index] !== '\n') {- index++- }- out += '\n'- continue- }- out += char+// The product that owns a file path from the map, or null for a file outside+// products/ (posthog, ee, common, tools) and for the loose files directly under+// products/ (conftest.py, __init__.py).+function productOfFile(file) {+ if (!file.startsWith(PRODUCTS_DIR)) {+ return null}- return out+ const [product, rest] = file.slice(PRODUCTS_DIR.length).split('/', 2)+ return rest === undefined ? null : product}-function parseTachModules(tomlText) {+// Collapse tach's file map ({ file: [files that import it] }) into+// product -> [products it imports]. Keys and values are product directory+// names (underscores); callers normalize to/from Turbo's dashed names. Every+// product that owns a file in the map is a key, with or without cross-product+// imports, so a reader can tell "no importers" from "not walked".+//+// Files outside products/ (posthog, ee, common) are dropped on both sides+// deliberately. See tachDependents for why routing through them would be+// wrong, not just inconvenient. Test files stay in: a test that imports+// another product's facade depends on that product as much as production+// code does.+function productGraphFromTachMap(fileMap) {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. With comments stripped, 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 = stripTomlComments(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 node = (product) => {+ if (!graph.has(product)) {+ graph.set(product, new Set())}- 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+ return graph.get(product)+ }+ for (const [imported, importers] of Object.entries(fileMap)) {+ const importedProduct = productOfFile(imported)+ if (importedProduct !== null) {+ node(importedProduct)}- // Comments are already gone, so anything left beside the quoted entries- // is an entry shape these regexes cannot represent.- const leftover = dependsMatch[1].replace(/"[^"]*"/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)}`- )+ for (const importer of importers) {+ const importerProduct = productOfFile(importer)+ if (importerProduct === null) {+ continue+ }+ const deps = node(importerProduct)+ if (importedProduct !== null && importedProduct !== importerProduct) {+ deps.add(importedProduct)+ }}- 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+ }+ return new Map([...graph].map(([product, deps]) => [product, [...deps].sort()]))}// 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+// (dashes); moduleGraph keys/values are directory names (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).@@ -448,28 +419,82 @@ function tachDependents(changedProducts, moduleGraph, { direct = false } = {}) {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+// Runs tach_map.py in repoRoot and returns the product graph, or null when uv+// is missing, the run fails, or it prints something that is not the map. 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.+//+// tach map exits 0 and drops a file it cannot parse, so a syntax error hides+// that file's imports. That cannot under-test here: a file broken on master+// fails ruff and every import of it, and a file the PR broke sits in a product+// Turbo already selects.+//+// The run walks every Python file and takes seconds, so the result is kept per+// process; a second caller gets the same graph, a failure included.+const tachModuleGraphByRoot = new Map()++function loadTachModuleGraph(repoRoot = process.cwd()) {+ if (!tachModuleGraphByRoot.has(repoRoot)) {+ tachModuleGraphByRoot.set(repoRoot, runTachMap(repoRoot))+ }+ return tachModuleGraphByRoot.get(repoRoot)+}++function runTachMap(repoRoot) {+ let rawtry {- text = fs.readFileSync(TACH_TOML_FILE, 'utf-8')+ raw = execFileSync('uv', ['run', '--no-project', TACH_MAP_SCRIPT], { ...TURBO_EXEC_OPTS, cwd: repoRoot })} catch (e) {- console.error(`::warning::Could not read ${TACH_TOML_FILE} (${e.message}) — falling back to testing all products`)+ console.error(`::warning::tach map failed (${e.message}) — the dependent cascade widens to every product`)return null}try {- return parseTachModules(text)+ return productGraphFromTachMap(JSON.parse(raw))} catch (e) {- console.error(`::warning::Could not parse ${TACH_TOML_FILE} (${e.message}) — falling back to testing all products`)+ console.error(`::warning::Could not parse the tach map (${e.message}) — the dependent cascade widens to every product`)return null}}-// Products that transitively depend on `products` per tach.toml, or null when the-// graph cannot be read. Callers treat null as "unknown dependents" and widen.+// Python files under products/ that the diff deleted, or null when the diff+// cannot be read. Renames count as deletions of the old path. Empty without a+// base ref: a push run tests everything regardless.+//+// The map is read from the head tree, so a deleted file is not a key in it and+// an importer of that file has no edge left; the importer's suite would be the+// one that fails on the missing module. Any such file makes the cascade+// unknown, so callers widen on it as they do on an unreadable map.+function deletedProductPythonFiles() {+ const base = process.env.TURBO_SCM_BASE+ if (!base) {+ return []+ }+ try {+ return execFileSync(+ 'git',+ ['diff', '--name-only', '--no-renames', '--diff-filter=D', `${base}...HEAD`, '--', 'products/'],+ TURBO_EXEC_OPTS+ )+ .split('\n')+ .filter((file) => file.endsWith('.py') && productOfFile(file) !== null)+ } catch (e) {+ console.error(`::warning::Could not list deleted files against ${base} (${e.message}) — the dependent cascade widens to every product`)+ return null+ }+}++// Products that transitively depend on `products` per the tach map, or null when+// the map cannot be read. Callers treat null as "unknown dependents" and widen.function tachDependentProducts(products, allProductSet) {+ const deleted = deletedProductPythonFiles()+ if (deleted === null) {+ return null+ }+ if (deleted.length > 0) {+ console.error(`Deleted product files have no importer edges in the tach map: ${JSON.stringify(deleted)} — the dependent cascade widens to every product`)+ return null+ }const tachGraph = loadTachModuleGraph()if (tachGraph === null) {return null@@ -1214,7 +1239,8 @@ module.exports = {productEffectiveCost,STALENESS_COVERAGE_THRESHOLD,STALENESS_FALLBACK_SECONDS_PER_FILE,- parseTachModules,+ productGraphFromTachMap,+ loadTachModuleGraph,tachDependents,}@@ -1311,7 +1337,7 @@ if (legacyChanged) {} else {if (dependents.length > 0) {console.error(- `Dependent products cascaded in via tach.toml: ${JSON.stringify(dependents)} (transitively depend on ${JSON.stringify(affectedContracts)})`+ `Dependent products cascaded in via tach map: ${JSON.stringify(dependents)} (transitively depend on ${JSON.stringify(affectedContracts)})`)}products = [...new Set([...affectedProducts, ...dependents])].sort()diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.ymlindex abdb10d7d4d6..029515215dcd 100644--- a/.github/workflows/ci-backend.yml+++ b/.github/workflows/ci-backend.yml@@ -194,9 +194,9 @@ jobs:- pytest.ini- conftest.py # Root conftest loads for every pytest run- .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's exclude list shapes the import map turbo-discover+ # reads for the dependent cascade, and `tach check` validates+ # the declarations — a graph-only PR must still dispatch both.- tach.toml# generates posthog/schema.py- frontend/src/queries/schema.json@@ -526,6 +526,15 @@ jobs:install-command: pnpm install --frozen-lockfile --filter=@posthog/roottoken: ${{ steps.setup-gh-token.outputs.token || github.token }}+ # turbo-discover.js runs .github/scripts/tach_map.py under `uv run+ # --no-project` for the dependent cascade; the script pins tach, so no+ # Python project sync is needed. A missing uv widens the cascade to+ # every product rather than failing the job.+ - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0+ continue-on-error: true+ with:+ version: '0.11.28' # pinned: unpinned setup-uv calls GH API on every job, exhausts rate limit+- name: Restore test durations from cache# Shard counts are derived from .test_durations (Amdahl). Restore the newest# cache (refreshed by ci-backend-update-test-timing.yml several times a day);diff --git a/.github/workflows/ci-scripts.yml b/.github/workflows/ci-scripts.ymlindex 9bd136b97a39..744b0348d6db 100644--- a/.github/workflows/ci-scripts.yml+++ b/.github/workflows/ci-scripts.yml@@ -20,6 +20,9 @@ on:- tools/test_snob_backend_test_selection_shadow.py- tools/test_selection_verdict.py- tools/test_test_selection_verdict.py+ # test_tach_map.py holds tach_map.py's pin to the locked tach version,+ # and a routine dependency bump is what moves it.+ - uv.lockconcurrency:group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}diff --git a/.github/workflows/trunk-impacted-targets.yml b/.github/workflows/trunk-impacted-targets.ymlindex 54095db8e8a6..4c68873f0029 100644--- a/.github/workflows/trunk-impacted-targets.yml+++ b/.github/workflows/trunk-impacted-targets.yml@@ -80,6 +80,15 @@ jobs:node-version-file: .nvmrctoken: ${{ github.token }}+ # The target script runs .github/scripts/tach_map.py under `uv run+ # --no-project` to find a changed product's importers; the script pins+ # tach, so no Python project sync is needed. A missing uv widens those+ # products to every backend lane rather than failing the job.+ - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0+ continue-on-error: true+ with:+ version: '0.11.28' # pinned: unpinned setup-uv calls GH API on every job, exhausts rate limit+# Split from the computation below so the cargo steps can be skipped# on the PRs that do not need them, which is nearly all of them.- name: Resolve the changed files@@ -100,7 +109,10 @@ jobs:exit 0fi- if ! changed="$(git diff --name-only "$merge_base" HEAD)"; then+ # --no-renames lists a renamed file as its old path and its new+ # one. The old path is what the target script reads as deleted,+ # and it widens on that: the tach map has no importer edge for it.+ if ! changed="$(git diff --name-only --no-renames "$merge_base" HEAD)"; thenecho "::warning::Could not diff against the merge base; reporting ALL."echo 'resolved=false' >> "$GITHUB_OUTPUT"exit 0@@ -269,8 +281,14 @@ jobs:# The key is the write-only token from hogli.yaml's telemetry block:# it cannot read data, which is why it is committed rather than a# secret, and why this works on fork PRs too.+ #+ # Only human PRs against this repository are recorded. The queue's+ # trunk-merge/** batch PRs run this workflow too and nearly all of+ # them widen, so counting them doubles every widening figure on the+ # lane dashboard. A fork running the workflow on its own repository+ # has no diff to compute and would report a degraded lane here.- name: Record lane telemetry- if: ${{ !cancelled() }}+ if: ${{ !cancelled() && github.repository == 'PostHog/posthog' && !startsWith(github.head_ref, 'trunk-merge/') }}continue-on-error: trueenv:POSTHOG_TELEMETRY_HOST: https://us.i.posthog.com