: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(ci): narrow merge-queue lanes for isolated product changes (#75140)
Georges-Antoine Assi46f44ad148dd
diff --git a/.github/scripts/trunk-impacted-targets.js b/.github/scripts/trunk-impacted-targets.jsindex 91bc9951d6fc..4f4bf9de3cac 100644--- a/.github/scripts/trunk-impacted-targets.js+++ b/.github/scripts/trunk-impacted-targets.js@@ -11,6 +11,35 @@// and anything unrecognized falls through to "ALL" (overlaps everything, which// is the single-lane behavior we had before this script existed).//+// The bias is relaxed in exactly two places, both bounded by what one PR can+// name in another. The conflict that lanes exist to prevent is semantic rather+// than textual, because a textual one would force a rebase and a retest: PR A+// renames a facade function and updates every current caller, PR B adds a new+// call to the old name, and master breaks on a combination neither run held.+//+// 1. Only a change to a product's declared contract surface seeds the+// dependent cascade. A file that no module outside the product can import+// cannot be the shared symbol two PRs disagree about, so a change confined+// to internals keeps its own product's lane. The surface is the product's+// own `backend:contract-check` inputs in products/<name>/turbo.json, the+// same declaration turbo-discover reads to decide whether dependent test+// suites run, so the two mechanisms cannot drift apart. A product that+// declares no narrowed inputs cascades on every backend file as before.+// This makes the declaration load-bearing for correctness: an input list+// that omits a file other products import puts those products in a+// parallel lane.+//+// 2. The cascade names direct importers rather than the transitive closure.+// Only a direct importer can reference the changed product's symbols.+// ACCEPTED RISK: a conflict mediated through an intermediate product (A+// changes warehouse_sources, B changes code whose behavior depends on+// 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+// expanded to the whole backend and the cascade could not distinguish+// products at all.+//// That bias is the opposite of the one in ci-*.yml path filters. Those filters// decide which tests to run, where an over-broad match wastes runner minutes// and an under-broad match skips tests. They are tuned to over-run and are NOT@@ -32,7 +61,9 @@// paths in ci-e2e-playwright.yml, which puts all such PRs back in one lane.//// Input: changed file paths, one per line, on stdin-// Output: JSON on stdout, either the string "ALL" or an array of target names+// Output: JSON on stdout, either the string "ALL" or an array of target names.+// A change set of nothing but prose reports the single "prose" lane,+// which overlaps only other prose-only PRs.// Diagnostics on stderrconst fs = require('fs')@@ -170,6 +201,138 @@ function listIsolatedProducts(repoRoot, products) {return isolated}+// --- Contract surfaces ---++const CONTRACT_TASK = 'backend:contract-check'++// turbo.json permits comments, which JSON.parse rejects. Strip them outside+// string literals so a `//` inside a glob survives.+function stripJsonComments(text) {+ let out = ''+ let inString = false+ let escaped = false+ for (let i = 0; i < text.length; i++) {+ const char = text[i]+ const next = text[i + 1]+ if (inString) {+ out += char+ if (escaped) {+ escaped = false+ } else if (char === '\\') {+ escaped = true+ } else if (char === '"') {+ inString = false+ }+ continue+ }+ if (char === '"') {+ inString = true+ out += char+ continue+ }+ if (char === '/' && next === '/') {+ while (i < text.length && text[i] !== '\n') {+ i+++ }+ out += '\n'+ continue+ }+ if (char === '/' && next === '*') {+ i += 2+ while (i < text.length && !(text[i] === '*' && text[i + 1] === '/')) {+ i+++ }+ i+++ continue+ }+ out += char+ }+ return out+}++// Compiles a task's `inputs` into a predicate over product-relative paths. A+// path is contract when at least one positive glob matches it and no negated+// one does, matching how Turbo reads the same list.+function compileContractMatcher(inputs) {+ const include = []+ const exclude = []+ for (const input of inputs) {+ const negated = input.startsWith('!')+ const glob = negated ? input.slice(1) : input+ // An input reaching outside the product (../../uv.lock and the like)+ // cannot be expressed as a product-relative path. Dropping it is safe+ // because every such file in use today is already a tripwire or lands+ // in py:core, both of which overlap this product's lane anyway.+ if (glob.startsWith('../')) {+ continue+ }+ if (negated) {+ exclude.push(globToRegExp(glob))+ } else {+ include.push(globToRegExp(glob))+ }+ }+ if (include.length === 0) {+ return null+ }+ return (relativePath) =>+ include.some((re) => re.test(relativePath)) && !exclude.some((re) => re.test(relativePath))+}++// Only products that narrow `backend:contract-check` in their own turbo.json get+// an entry. Absence means "every backend file is contract", so a product that+// has not declared a surface, or whose turbo.json cannot be read, keeps+// cascading on every backend change.+function loadContractSurfaces(repoRoot, products) {+ const surfaces = new Map()+ for (const product of products) {+ const manifest = path.join(repoRoot, 'products', product, 'turbo.json')+ if (!fs.existsSync(manifest)) {+ continue+ }+ let inputs+ try {+ const parsed = JSON.parse(stripJsonComments(fs.readFileSync(manifest, 'utf8')))+ const tasks = parsed.tasks || parsed.pipeline || {}+ inputs = (tasks[CONTRACT_TASK] || {}).inputs+ } catch (error) {+ console.error(+ `Could not read products/${product}/turbo.json (${error.message}); every backend file counts as its contract`+ )+ continue+ }+ if (!Array.isArray(inputs)) {+ continue+ }+ const matcher = compileContractMatcher(inputs)+ if (matcher) {+ surfaces.set(product, matcher)+ }+ }+ return surfaces+}++// The files that define the gate for their own product: turbo.json holds the+// contract inputs, package.json decides whether the product is isolated at all.+// Neither is importable, so the surface test would call them internal, and both+// are read from the PR's own tree. A change that drops a path from the contract+// and edits a file under that path in the same commit would then be gated+// against its own new, narrower contract and keep the lane to itself, which is+// exactly when the dependents most need to be tested alongside it.+const CONTRACT_DECLARATIONS = ['turbo.json', 'package.json']++function touchesContractSurface(product, file, contractSurfaces) {+ const relativePath = file.slice(`products/${product}/`.length)+ if (CONTRACT_DECLARATIONS.includes(relativePath)) {+ return true+ }+ const matcher = contractSurfaces.get(product)+ if (!matcher) {+ return true+ }+ return matcher(relativePath)+}+// --- Rust crate graph ---// Discovers workspace crates as (directory, crate name) pairs. Crate names can@@ -348,7 +511,7 @@ const feProduct = (product) => `fe:product:${product}`const rustCrate = (crate) => `rust:crate:${crate}`function computeTargets(changedFiles, context) {- const { products, isolatedProducts, rustGraph, tachGraph } = context+ const { products, isolatedProducts, rustGraph, tachGraph, contractSurfaces = new Map() } = contextconst targets = new Set()const allPyProducts = () => {@@ -365,23 +528,31 @@ function computeTargets(changedFiles, context) {}const changedIsolatedProducts = new Set()+ let inertFiles = 0for (const file of changedFiles) {if (isTripwire(file)) {return ALL}- // Markdown never compiles into any tree, so it is classified before the- // directory rules that would otherwise pull a README under posthog/- // into the backend lane.- if (/\.mdx?$/.test(file)) {- targets.add('docs')- continue- }-const segments = file.split('/')const top = segments[0]+ // Prose compiles into nothing and no PR can disagree with another about+ // it, so it claims no lane at all rather than the shared one it used to+ // get, which serialized any two PRs that happened to touch a markdown+ // file. Classified before the directory rules that would otherwise pull+ // a README under posthog/ into the backend lane.+ //+ // The exception is markdown that is a build input: `hogli build:skills`+ // zips products/*/skills/*, and ci-agent-skills.yml gates on those paths+ // and on .agents/. Both fall through to their directory rules below.+ const isSkillSource = top === '.agents' || (top === 'products' && segments[2] === 'skills')+ if (/\.mdx?$/.test(file) && !isSkillSource) {+ inertFiles+++ continue+ }+if (top === 'posthog' || (top === 'ee' && segments[1] !== 'frontend')) {allPyProducts()continue@@ -404,8 +575,13 @@ function computeTargets(changedFiles, context) {targets.add(`svc:${segments[1]}`)continue}- if (top === 'docs') {- targets.add('docs')+ // docs/ is prose, which the markdown rule above has already taken, with+ // one exception: docs/onboarding is the @posthog/docs-onboarding+ // workspace package that frontend/package.json depends on, so its+ // sources compile into the app. Anything else non-prose under docs/ is+ // unclassified and falls through to ALL at the end of the loop.+ if (top === 'docs' && segments[1] === 'onboarding') {+ allFeProducts()continue}if (top === '.agents') {@@ -466,7 +642,9 @@ function computeTargets(changedFiles, context) {if (isBackend || (!isBackend && !isFrontend)) {if (isolatedProducts.has(product)) {targets.add(pyProduct(product))- changedIsolatedProducts.add(product)+ if (touchesContractSurface(product, file, contractSurfaces)) {+ changedIsolatedProducts.add(product)+ }} else {allPyProducts()}@@ -486,6 +664,10 @@ function computeTargets(changedFiles, context) {// so a non-isolated dependent is named here rather than widening to every// backend target. Only 14 of the products declare a contract check, so// widening on each of them would collapse every cascade to the full set.+ //+ // The seeds are the products whose contract surface changed, and the+ // dependents are one hop deep. See the two numbered narrowings at the top+ // of this file for what that gives up.if (changedIsolatedProducts.size > 0) {const dependents = tachDependentProducts([...changedIsolatedProducts], tachGraph)if (dependents === null) {@@ -518,7 +700,18 @@ function computeTargets(changedFiles, context) {}if (targets.size === 0) {- return ALL+ // A change set of nothing but prose overlaps only other prose. Trunk+ // does not document what it does with an empty target list, and the one+ // documented rule is that a PR is not processed until its targets are+ // uploaded, so a lane of its own avoids betting a docs PR's ability to+ // enter the queue on undocumented behavior. This is deliberately not+ // added per file: emitting it alongside real lanes is what made the old+ // docs target serialize two PRs whose only overlap was a README.+ //+ // Anything else that reaches an empty set contains a path no rule+ // claimed, which is the failure mode that silently breaks master, so it+ // still widens to ALL.+ return inertFiles === changedFiles.length ? ['prose'] : ALL}return [...targets].sort()}@@ -534,7 +727,8 @@ function tachDependentProducts(changedProducts, tachGraph) {const { tachDependents } = tachGraphreturn tachDependents(changedProducts.map((product) => product.replace(/_/g, '-')),- tachGraph.graph+ tachGraph.graph,+ { direct: true }).map((product) => product.replace(/-/g, '_'))} catch (error) {console.error(`Dependent cascade failed (${error.message}); widening to all backend targets`)@@ -558,6 +752,7 @@ function buildContext(repoRoot) {return {products,isolatedProducts: listIsolatedProducts(repoRoot, products),+ contractSurfaces: loadContractSurfaces(repoRoot, products),rustGraph: loadRustGraph(repoRoot),tachGraph: loadTachGraph(repoRoot),}@@ -566,11 +761,13 @@ function buildContext(repoRoot) {module.exports = {computeTargets,buildContext,+ compileContractMatcher,globToRegExp,isTripwire,parseCrateDependencies,parseCrateName,reverseClosure,+ stripJsonComments,ALL,}diff --git a/.github/scripts/trunk-impacted-targets.test.js b/.github/scripts/trunk-impacted-targets.test.jsindex 796907f57131..c366416e291d 100644--- a/.github/scripts/trunk-impacted-targets.test.js+++ b/.github/scripts/trunk-impacted-targets.test.js@@ -12,12 +12,14 @@ const assert = require('node:assert/strict')const {computeTargets,+ compileContractMatcher,globToRegExp,isTripwire,parseCrateDependencies,reverseClosure,ALL,} = require('./trunk-impacted-targets')+const { parseTachModules, tachDependents } = require('./turbo-discover')const CONTEXT = {products: ['alpha', 'beta', 'gamma'],@@ -180,6 +182,94 @@ test('an isolated product change stays narrow and names its tach dependents', ()assert.deepEqual(computeTargets(['products/beta/backend/api.py'], CONTEXT), ['py:product:beta'])})+const withContractSurface = (product, inputs) => ({+ ...CONTEXT,+ contractSurfaces: new Map([[product, compileContractMatcher(inputs)]]),+})++// Nothing outside the product can import a file the product never exposes, so+// no other PR can add a call to it and there is no combination to serialize.+test('a change outside a declared contract surface keeps its own lane', () => {+ const context = withContractSurface('alpha', ['backend/facade/**'])+ assert.deepEqual(computeTargets(['products/alpha/backend/connectors/mongo.py'], context), ['py:product:alpha'])+})++test('a change inside a declared contract surface still cascades to dependents', () => {+ const context = withContractSurface('alpha', ['backend/facade/**'])+ assert.deepEqual(computeTargets(['products/alpha/backend/facade/models.py'], context), [+ 'py:product:alpha',+ 'py:product:beta',+ 'py:product:gamma',+ ])+})++// The gate applies to the change set, not to each file: a PR that touches the+// contract has to cascade no matter how much internal code sits beside it.+test('one contract file among internals still cascades', () => {+ const context = withContractSurface('alpha', ['backend/facade/**'])+ const targets = computeTargets(+ ['products/alpha/backend/connectors/mongo.py', 'products/alpha/backend/facade/models.py'],+ context+ )+ assert.equal(targets.includes('py:product:gamma'), true)+})++// The absence of a declaration has to mean "all of it is contract". Reading it+// as "none of it" would hand every isolated product a lane it has not earned.+test('a product that declares no contract surface cascades on any backend file', () => {+ const targets = computeTargets(['products/alpha/backend/connectors/mongo.py'], CONTEXT)+ assert.equal(targets.includes('py:product:gamma'), true)+})++// Both declarations are read from the PR's own tree, so a change that narrows+// the contract and edits a file it just removed would otherwise be gated+// against the narrower version and never reach its dependents.+test('editing the declarations that define the gate always cascades', () => {+ const context = withContractSurface('alpha', ['backend/facade/**'])+ for (const file of ['products/alpha/turbo.json', 'products/alpha/package.json']) {+ const targets = computeTargets([file], context)+ assert.equal(targets.includes('py:product:gamma'), true, file)+ }+})++test('contract inputs honor negation and drop inputs outside the product', () => {+ const matcher = compileContractMatcher(['backend/**/*.py', '!backend/**/__pycache__/**', '../../uv.lock'])+ assert.equal(matcher('backend/api.py'), true)+ assert.equal(matcher('backend/facade/models.py'), true)+ assert.equal(matcher('backend/__pycache__/api.py'), false)+ assert.equal(matcher('frontend/Scene.tsx'), false)+})++// A matcher that matched nothing would classify every file as internal, which+// is the same silent under-report as a missing cascade.+test('a contract with no product-relative inputs yields no matcher', () => {+ assert.equal(compileContractMatcher(['../../uv.lock']), null)+ assert.equal(compileContractMatcher([]), null)+})++// Only a direct importer can name the changed product's symbols. The hop beyond+// reaches the changed code through an intermediate whose own PR carries its own+// 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 } }+ assert.deepEqual(computeTargets(['products/alpha/backend/api.py'], context), [+ 'py:product:alpha',+ 'py:product:beta',+ ])+})+test('a non-isolated product change widens to every backend target', () => {const targets = computeTargets(['products/gamma/backend/api.py'], CONTEXT)assert.equal(targets.includes('py:core'), true)@@ -252,17 +342,51 @@ test('cross-domain tools are tripwires rather than backend-only', () => {assert.equal(computeTargets(['tools/owners/owners/__init__.py'], CONTEXT), ALL)})-test('markdown is classified as docs regardless of which tree it sits in', () => {- assert.deepEqual(computeTargets(['posthog/README.md', 'docs/guide.mdx'], CONTEXT), ['docs'])+// Prose overlaps only other prose, and has to reach that lane through the+// size-0 guard rather than being widened to ALL with the unclassified paths.+test('a change set of nothing but markdown reports the prose lane', () => {+ assert.deepEqual(computeTargets(['posthog/README.md', 'docs/guide.mdx', 'CHANGELOG.md'], CONTEXT), ['prose'])+})++// The old shared docs lane serialized two PRs whose only overlap was having+// touched a markdown file, even with their code in unrelated trees. The prose+// lane must not reintroduce that by riding along with real lanes.+test('markdown alongside code contributes no lane of its own', () => {+ assert.deepEqual(computeTargets(['rust/unrelated/src/main.rs', 'README.md'], CONTEXT), ['rust:crate:unrelated'])+})++// hogli build:skills zips products/*/skills/*, and ci-agent-skills.yml gates on+// those paths and on .agents/, so this markdown is a build input, not prose.+test('skill markdown keeps the lane of the tree that builds it', () => {+ assert.deepEqual(computeTargets(['.agents/skills/merging-prs/SKILL.md'], CONTEXT), ['agents'])+ const productSkill = computeTargets(['products/beta/skills/creating-experiments/SKILL.md'], CONTEXT)+ assert.equal(productSkill.includes('py:product:beta'), true)+ assert.equal(productSkill.includes('fe:product:beta'), true)+})++// docs/onboarding is the @posthog/docs-onboarding workspace package that+// frontend/package.json depends on, so its sources compile into the app. On the+// old docs lane it was disjoint from fe:core and could merge in parallel with+// the frontend PR that consumes it.+test('docs/onboarding sources claim the frontend domain', () => {+ const onboarding = computeTargets(['docs/onboarding/experiments/nextjs.tsx'], CONTEXT)+ const frontend = computeTargets(['frontend/src/lib/components/Foo.tsx'], CONTEXT)+ assert.deepEqual(onboarding, frontend)+})++// Everything under docs/ is prose today apart from that package, so a new+// non-prose tree there must widen rather than inherit the inert classification.+test('an unrecognized non-prose file under docs forces ALL', () => {+ assert.equal(computeTargets(['docs/tooling/generate.py'], CONTEXT), ALL)})test('independent trees stay disjoint so they can share no lane', () => {const rust = computeTargets(['rust/unrelated/src/main.rs'], CONTEXT)const node = computeTargets(['nodejs/src/worker.ts'], CONTEXT)const service = computeTargets(['services/mcp/src/index.ts'], CONTEXT)- const docs = computeTargets(['docs/guide.md'], CONTEXT)+ const agents = computeTargets(['.agents/skills/merging-prs/SKILL.md'], CONTEXT)- const sets = [rust, node, service, docs]+ const sets = [rust, node, service, agents]for (let i = 0; i < sets.length; i++) {for (let j = i + 1; j < sets.length; j++) {const overlap = sets[i].filter((target) => sets[j].includes(target))diff --git a/.github/scripts/turbo-discover-cascade.test.js b/.github/scripts/turbo-discover-cascade.test.jsindex 4690adee5706..25f0511ef1a1 100644--- a/.github/scripts/turbo-discover-cascade.test.js+++ b/.github/scripts/turbo-discover-cascade.test.js@@ -95,6 +95,53 @@ layer = "modules"assert.deepEqual(dependents.sort(), ['a', 'b'])})+// Test selection must stay transitive by default: a change in c can break a's+// tests through b even though a never imports c. Only merge-queue lane+// 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'])+})++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'])+})+test('core is never a node: posthog/ee/<root> are excluded as keys and values, and closures never traverse through them', () => {const toml = `[[modules]]diff --git a/.github/scripts/turbo-discover.js b/.github/scripts/turbo-discover.jsindex f9c3f658bbaa..2f90a84492d8 100644--- a/.github/scripts/turbo-discover.js+++ b/.github/scripts/turbo-discover.js@@ -309,7 +309,13 @@ function parseTachModules(tomlText) {// 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) {+//+// `direct` stops the walk after the first hop. Test selection must stay+// transitive, because a change in A can break C's tests through B without C+// ever importing A. Merge-queue lane assignment asks a narrower question and+// passes direct: true; see trunk-impacted-targets.js for why one hop is the+// boundary there.+function tachDependents(changedProducts, moduleGraph, { direct = false } = {}) {const reverse = new Map()for (const [product, deps] of moduleGraph) {for (const dep of deps) {@@ -326,7 +332,7 @@ function tachDependents(changedProducts, moduleGraph) {for (const dependent of reverse.get(current) || []) {if (visited.has(dependent) || changedSet.has(dependent)) {continue}visited.add(dependent)- queue.push(dependent)+ if (!direct) {queue.push(dependent)}}}return [...visited].map(moduleToProduct)diff --git a/products/customer_analytics/turbo.json b/products/customer_analytics/turbo.jsonindex bb57633e21e2..119ef0b546d0 100644--- a/products/customer_analytics/turbo.json+++ b/products/customer_analytics/turbo.json@@ -8,7 +8,8 @@"backend/routes.py","backend/hogql_queries/**","backend/max_tools.py",- "backend/models/team_customer_analytics_config.py",+ "backend/models/**",+ "backend/test/factories.py","backend/tasks/**"],"outputs": [],diff --git a/products/error_tracking/turbo.json b/products/error_tracking/turbo.jsonindex 9792401d39d4..d5d0219c4a1f 100644--- a/products/error_tracking/turbo.json+++ b/products/error_tracking/turbo.json@@ -6,6 +6,7 @@"backend/facade/**","backend/presentation/**","backend/routes.py",+ "backend/models.py","backend/sql.py","backend/embedding.py","backend/indexed_embedding.py",