: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): compute trunk merge-queue lanes from impacted targets (#74266)
Georges-Antoine Assia80cdefa4a9e
diff --git a/.github/scripts/trunk-impacted-targets.js b/.github/scripts/trunk-impacted-targets.jsnew file mode 100644index 000000000000..91bc9951d6fc--- /dev/null+++ b/.github/scripts/trunk-impacted-targets.js@@ -0,0 +1,601 @@+#!/usr/bin/env node++// Maps a PR's changed files to the target names Trunk's parallel merge queue+// uses to assign lanes.+//+// THE SAFETY INVARIANT: Trunk runs two PRs in parallel lanes if and only if+// their target sets are disjoint, which means those PRs merge into master+// without ever having been tested together. Reporting extra targets only costs+// parallelism; reporting too few lets conflicting PRs land side by side and+// breaks master. Every rule here is therefore biased toward over-reporting,+// and anything unrecognized falls through to "ALL" (overlaps everything, which+// is the single-lane behavior we had before this script existed).+//+// 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+// a safe source for lane assignment: ci-frontend.yml's `frontend` filter+// matches '**/*.md' and '**/*.yaml', so nearly every PR in the repo matches it.+//+// Core targets expand to include every leaf target in their domain, because+// Trunk only has set intersection to express "core overlaps everything+// downstream". A change to posthog/ can break any product, so it reports+// py:core plus every py:product:*, which serializes it against all backend+// work while still running parallel to rust, nodejs, and services.+//+// ACCEPTED RISK: fe:core and py:core are disjoint, so a frontend PR and a+// backend PR can merge in parallel. The E2E suite exercises both together and+// runs on either kind of change, which means a combination neither PR's own run+// covered can still break master. That residual risk is inherent to parallel+// queues rather than specific to these rules. If it shows up in practice, the+// knob is an `e2e` target emitted for every change matching the E2E trigger+// 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+// Diagnostics on stderr++const fs = require('fs')+const path = require('path')++const ALL = 'ALL'++const REPO_ROOT = path.resolve(__dirname, '..', '..')++// Files whose effect crosses every lane boundary: lockfiles and workspace+// manifests (a dependency bump changes what every tree compiles against),+// cross-language contracts (a schema or proto change lands in generated code+// on both sides), the module graphs that this script and turbo-discover read,+// and the CI definitions that decide what runs for everyone.+const TRIPWIRES = [+ 'pnpm-lock.yaml',+ 'pnpm-workspace.yaml',+ 'package.json',+ 'uv.lock',+ 'pyproject.toml',+ 'requirements.txt',+ 'requirements-dev.txt',+ 'rust/Cargo.lock',+ 'rust/Cargo.toml',+ 'rust/.sqlx/**',+ 'tach.toml',+ 'turbo.json',+ 'hogli.yaml',+ '.nvmrc',+ '.github/**',+ 'docker-compose*.yml',+ 'Dockerfile*',+ 'proto/**',+ // schema.json generates posthog/schema.py, and both sides are committed.+ 'frontend/src/queries/schema.json',+ 'posthog/schema.py',+ // products.json is loaded at runtime by posthog/products.py and generated+ // from every product's manifest.+ 'frontend/src/products.json',+ 'products/*/manifest.tsx',+ // Generates the frontend API types from the backend serializers, so a+ // change lands on both sides of the fe/py split at once.+ 'tools/openapi-codegen/**',+ // Ownership data read by the backend, frontend, and script suites alike.+ 'tools/owners/**',+ 'conftest.py',+ 'pytest.ini',+ 'mypy.ini',+ '.test_durations',+ '.test_quarantine.json',+ // bin/ appears in the backend, frontend, and E2E path filters alike.+ 'bin/**',+ 'patches/**',+ 'tsconfig.json',+ 'tsconfig.*.json',+ 'babel.config.js',+ 'webpack.config.js',+ '.oxlintrc.json',+ '.oxfmtrc*',+]++// Subdirectories of common/ that belong to a single domain. Anything else+// under common/ is deliberately absent so it falls through to ALL rather than+// being guessed at.+const COMMON_PYTHON = ['hogql_parser', 'hogvm', 'ingestion', 'migration_utils', 'plugin_transpiler', 'alerting']+const COMMON_FRONTEND = ['esbuilder', 'storybook', 'tailwind', 'replay-shared', 'replay-headless']++// Tools that own their whole test story and that no suite imports, so they can+// hold a lane of their own. Everything else under tools/ falls through to the+// backend lanes, which keeps a newly added tool over-reporting until someone+// establishes it belongs here.+//+// hogli and hogli-commands are deliberately absent: ci-backend.yml drives the+// suite through hogli, and posthog/conftest.py imports+// hogli_commands.quarantine.pytest_support on every pytest run.+const TOOLS_INDEPENDENT = [+ 'phrocs',+ 'hogbox-preview',+ 'traffic-sim',+ 'hedgebox-dummy',+ 'pr-approval-agent',+ 'query-performance-ai',+ 'infra-scripts',+]++// Supports the three forms used in TRIPWIRES: `**` spanning directories, `*`+// within a single path segment, and literal names. The two star forms are+// parked on placeholders first so neither rewrites the other's output.+const GLOBSTAR_SLASH = '\u0000'+const GLOBSTAR = '\u0001'++function globToRegExp(glob) {+ const body = glob+ .replace(/[.+^${}()|[\]\\]/g, '\\$&')+ .replace(/\*\*\//g, GLOBSTAR_SLASH)+ .replace(/\*\*/g, GLOBSTAR)+ .replace(/\*/g, '[^/]*')+ .split(GLOBSTAR_SLASH)+ .join('(?:.*/)?')+ .split(GLOBSTAR)+ .join('.*')+ return new RegExp(`^${body}$`)+}++const TRIPWIRE_MATCHERS = TRIPWIRES.map(globToRegExp)++function isTripwire(file) {+ return TRIPWIRE_MATCHERS.some((re) => re.test(file))+}++function listProducts(repoRoot) {+ return fs+ .readdirSync(path.join(repoRoot, 'products'), { withFileTypes: true })+ .filter((entry) => entry.isDirectory())+ .map((entry) => entry.name)+ .sort()+}++// A product is isolated when it declares a backend:contract-check script, the+// same signal turbo-discover uses to decide a product can be tested alone.+// Non-isolated products have no narrowed contract, so a change in one is+// treated as a core change.+function listIsolatedProducts(repoRoot, products) {+ const isolated = new Set()+ for (const product of products) {+ const manifest = path.join(repoRoot, 'products', product, 'package.json')+ if (!fs.existsSync(manifest)) {+ continue+ }+ const parsed = JSON.parse(fs.readFileSync(manifest, 'utf8'))+ if (parsed.scripts && parsed.scripts['backend:contract-check']) {+ isolated.add(product)+ }+ }+ return isolated+}++// --- Rust crate graph ---++// Discovers workspace crates as (directory, crate name) pairs. Crate names can+// differ from directory names, and file paths only carry the directory, so both+// are needed to translate a changed path into a graph node.+function discoverRustCrates(repoRoot) {+ const crates = []+ const walk = (dir, depth) => {+ if (depth > 3) {+ return+ }+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {+ if (entry.name === 'target' || entry.name === '.git' || entry.name.startsWith('.')) {+ continue+ }+ const full = path.join(dir, entry.name)+ if (entry.isDirectory()) {+ walk(full, depth + 1)+ } else if (entry.name === 'Cargo.toml') {+ const relative = path.relative(path.join(repoRoot, 'rust'), dir)+ if (!relative) {+ continue+ }+ const text = fs.readFileSync(full, 'utf8')+ const name = parseCrateName(text)+ if (name) {+ crates.push({ dir: relative, name, text })+ }+ }+ }+ }+ walk(path.join(repoRoot, 'rust'), 0)+ return crates+}++function parseCrateName(tomlText) {+ const packageSection = tomlText.split(/^\s*\[/m).find((section) => section.startsWith('package]'))+ if (!packageSection) {+ return null+ }+ const match = packageSection.match(/^\s*name\s*=\s*"([^"]+)"/m)+ return match ? match[1] : null+}++// Collects the intra-workspace crates a Cargo.toml depends on. Dependencies+// declared as `foo.workspace = true` resolve through the workspace table to the+// same crate name, so matching on the dependency key covers both that form and+// a direct path dependency.+//+// A `package = "..."` key renames the dependency, so the real crate is that+// value rather than the key. Most uses point at an external crate under a+// version-suffixed alias (prost14 = { package = "prost" }), which contributes+// no intra-workspace edge, but resolving through it is what keeps a renamed+// workspace crate from being dropped.+// Classifies a section header, returning null when it carries no dependencies.+// Cargo spells dependency sections four ways, and the ones where the dependency+// name lives in the header rather than in a body key are easy to miss:+//+// [dependencies] -> body keys are the names+// [dev-dependencies] / [build-dependencies] -> body keys are the names+// [target.'cfg(...)'.dependencies] -> body keys are the names+// [dependencies.<name>] -> the header carries the name+//+// `[workspace.dependencies]` is excluded: it declares versions for the whole+// workspace rather than this crate's own edges.+function dependencySectionName(header) {+ if (header.startsWith('workspace.')) {+ return null+ }+ const match = header.match(/(?:^|\.)(?:dev-|build-)?dependencies(?:\.(.+))?$/)+ if (!match) {+ return null+ }+ return { named: match[1] ? match[1].replace(/^["']|["']$/g, '') : null }+}++function parseCrateDependencies(tomlText, crateNames) {+ const deps = new Set()+ const sections = tomlText.split(/^\s*\[/m)+ for (const section of sections) {+ const header = section.split(']')[0]+ const dependencySection = dependencySectionName(header)+ if (!dependencySection) {+ continue+ }+ const body = section.slice(section.indexOf(']') + 1)++ // In a [dependencies.<name>] table the body holds attributes (path,+ // version, features), not dependency names, so scanning its keys would+ // both miss the real edge and risk matching an attribute that happens+ // to share a crate name.+ if (dependencySection.named) {+ const renamed = body.match(/^\s*package\s*=\s*"([^"]+)"/m)+ const name = renamed ? renamed[1] : dependencySection.named+ if (crateNames.has(name)) {+ deps.add(name)+ }+ continue+ }++ for (const line of body.split('\n')) {+ const stripped = line.replace(/#.*$/, '').trim()+ if (!stripped) {+ continue+ }+ const renamed = stripped.match(/\bpackage\s*=\s*"([^"]+)"/)+ if (renamed) {+ if (crateNames.has(renamed[1])) {+ deps.add(renamed[1])+ }+ continue+ }+ const match = stripped.match(/^([A-Za-z0-9_-]+)\s*(?:\.[A-Za-z-]+)?\s*=/)+ if (match && crateNames.has(match[1])) {+ deps.add(match[1])+ }+ }+ }+ return [...deps]+}++// Returns null when the crate graph can't be built. Callers must treat null as+// "unknown dependents" and report every rust target, never as "no dependents".+function loadRustGraph(repoRoot) {+ try {+ const crates = discoverRustCrates(repoRoot)+ if (crates.length === 0) {+ return null+ }+ const crateNames = new Set(crates.map((crate) => crate.name))+ const dependsOn = new Map()+ for (const crate of crates) {+ dependsOn.set(crate.name, parseCrateDependencies(crate.text, crateNames))+ }+ // Longest directory first so rust/common/hogvm resolves to its own crate+ // rather than to rust/common.+ const byDir = crates+ .map((crate) => ({ dir: crate.dir, name: crate.name }))+ .sort((a, b) => b.dir.length - a.dir.length)+ return { dependsOn, byDir }+ } catch (error) {+ console.error(`Rust crate graph unavailable (${error.message}); reporting every rust target`)+ return null+ }+}++function reverseClosure(seeds, dependsOn) {+ const reverse = new Map()+ for (const [node, deps] of dependsOn) {+ for (const dep of deps) {+ if (!reverse.has(dep)) {+ reverse.set(dep, [])+ }+ reverse.get(dep).push(node)+ }+ }+ const reached = new Set(seeds)+ const queue = [...seeds]+ while (queue.length > 0) {+ const current = queue.shift()+ for (const dependent of reverse.get(current) || []) {+ if (reached.has(dependent)) {+ continue+ }+ reached.add(dependent)+ queue.push(dependent)+ }+ }+ return [...reached]+}++// --- Target computation ---++const pyProduct = (product) => `py:product:${product}`+const feProduct = (product) => `fe:product:${product}`+const rustCrate = (crate) => `rust:crate:${crate}`++function computeTargets(changedFiles, context) {+ const { products, isolatedProducts, rustGraph, tachGraph } = context+ const targets = new Set()++ const allPyProducts = () => {+ targets.add('py:core')+ for (const product of products) {+ targets.add(pyProduct(product))+ }+ }+ const allFeProducts = () => {+ targets.add('fe:core')+ for (const product of products) {+ targets.add(feProduct(product))+ }+ }++ const changedIsolatedProducts = new Set()++ for (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]++ if (top === 'posthog' || (top === 'ee' && segments[1] !== 'frontend')) {+ allPyProducts()+ continue+ }+ if (top === 'frontend' || (top === 'ee' && segments[1] === 'frontend') || top === 'packages') {+ allFeProducts()+ continue+ }+ // A spec change cannot break app code, but it runs against whatever+ // frontend lands beside it, so it shares the frontend lanes.+ if (top === 'playwright') {+ allFeProducts()+ continue+ }+ if (top === 'nodejs') {+ targets.add('node:ingestion')+ continue+ }+ if (top === 'services' && segments.length > 1) {+ targets.add(`svc:${segments[1]}`)+ continue+ }+ if (top === 'docs') {+ targets.add('docs')+ continue+ }+ if (top === '.agents') {+ targets.add('agents')+ continue+ }+ if (top === 'tools') {+ // A file sitting directly under tools/ rather than inside a tool's+ // own directory is one of the CI-steering scripts (backend test+ // selection, playwright spec selection, the selection verdict).+ // Those decide what runs across every suite, so they widen fully.+ if (segments.length < 3) {+ return ALL+ }+ if (TOOLS_INDEPENDENT.includes(segments[1])) {+ targets.add(`tools:${segments[1]}`)+ continue+ }+ allPyProducts()+ continue+ }+ if (top === 'common' && segments.length > 1) {+ if (COMMON_PYTHON.includes(segments[1])) {+ allPyProducts()+ continue+ }+ if (COMMON_FRONTEND.includes(segments[1])) {+ allFeProducts()+ continue+ }+ return ALL+ }+ if (top === 'rust') {+ if (!rustGraph) {+ targets.add('rust:unresolved')+ continue+ }+ const crate = rustGraph.byDir.find(+ (entry) => file.startsWith(`rust/${entry.dir}/`) || file === `rust/${entry.dir}`+ )+ if (!crate) {+ return ALL+ }+ targets.add(rustCrate(crate.name))+ continue+ }+ if (top === 'products' && segments.length > 2) {+ const product = segments[1]+ if (!products.includes(product)) {+ return ALL+ }+ const isBackend = segments[2] === 'backend' || file.endsWith('.py')+ const isFrontend = segments[2] === 'frontend' || /\.tsx?$/.test(file)++ if (isFrontend || (!isBackend && !isFrontend)) {+ targets.add(feProduct(product))+ }+ if (isBackend || (!isBackend && !isFrontend)) {+ if (isolatedProducts.has(product)) {+ targets.add(pyProduct(product))+ changedIsolatedProducts.add(product)+ } else {+ allPyProducts()+ }+ }+ continue+ }++ // Nothing claimed this path. Defaulting to an empty target set would+ // read as "parallel with everything", which is the one failure mode+ // that silently breaks master, so widen to ALL instead.+ return ALL+ }++ // Naming a dependent's target is all a lane needs: it puts the two PRs in+ // the same lane so they are tested together. Isolation governs whether a+ // product's own change can be tested alone, which is a different question,+ // 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.+ if (changedIsolatedProducts.size > 0) {+ const dependents = tachDependentProducts([...changedIsolatedProducts], tachGraph)+ if (dependents === null) {+ allPyProducts()+ } else {+ for (const dependent of dependents) {+ targets.add(pyProduct(dependent))+ }+ }+ }++ if (rustGraph && [...targets].some((target) => target.startsWith('rust:crate:'))) {+ const seeds = [...targets]+ .filter((target) => target.startsWith('rust:crate:'))+ .map((target) => target.slice('rust:crate:'.length))+ for (const crate of reverseClosure(seeds, rustGraph.dependsOn)) {+ targets.add(rustCrate(crate))+ }+ }++ if (targets.has('rust:unresolved')) {+ targets.delete('rust:unresolved')+ if (rustGraph) {+ for (const crate of rustGraph.dependsOn.keys()) {+ targets.add(rustCrate(crate))+ }+ } else {+ return ALL+ }+ }++ if (targets.size === 0) {+ return ALL+ }+ 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.+function tachDependentProducts(changedProducts, tachGraph) {+ if (!tachGraph) {+ return null+ }+ try {+ const { tachDependents } = tachGraph+ return tachDependents(+ changedProducts.map((product) => product.replace(/_/g, '-')),+ tachGraph.graph+ ).map((product) => product.replace(/-/g, '_'))+ } catch (error) {+ console.error(`Dependent cascade failed (${error.message}); widening to all backend targets`)+ return null+ }+}++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+ }+}++function buildContext(repoRoot) {+ const products = listProducts(repoRoot)+ return {+ products,+ isolatedProducts: listIsolatedProducts(repoRoot, products),+ rustGraph: loadRustGraph(repoRoot),+ tachGraph: loadTachGraph(repoRoot),+ }+}++module.exports = {+ computeTargets,+ buildContext,+ globToRegExp,+ isTripwire,+ parseCrateDependencies,+ parseCrateName,+ reverseClosure,+ ALL,+}++if (require.main === module) {+ let result+ try {+ const changedFiles = fs+ .readFileSync(0, 'utf8')+ .split('\n')+ .map((line) => line.trim())+ .filter(Boolean)+ if (changedFiles.length === 0) {+ console.error('No changed files on stdin; reporting ALL')+ result = ALL+ } else {+ result = computeTargets(changedFiles, buildContext(REPO_ROOT))+ }+ } catch (error) {+ // Any unexpected failure has to widen rather than narrow, because a+ // partial target list is indistinguishable to Trunk from a correct one.+ console.error(`Target computation failed (${error.stack}); reporting ALL`)+ result = ALL+ }+ if (Array.isArray(result)) {+ console.error(`Computed ${result.length} target(s): ${JSON.stringify(result)}`)+ }+ process.stdout.write(JSON.stringify(result))+}diff --git a/.github/scripts/trunk-impacted-targets.test.js b/.github/scripts/trunk-impacted-targets.test.jsnew file mode 100644index 000000000000..796907f57131--- /dev/null+++ b/.github/scripts/trunk-impacted-targets.test.js@@ -0,0 +1,283 @@+// Run with: node --test .github/scripts/trunk-impacted-targets.test.js+//+// Unit tests for the Trunk merge-queue target computation. Every case here+// guards the same class of bug: a target set that is narrower than reality,+// which makes Trunk merge two conflicting PRs in parallel lanes and breaks+// master. Uses synthetic products/crates/graphs throughout rather than the+// real repo layout, which would turn these into change-detector tests that+// break whenever a product or crate is added.++const test = require('node:test')+const assert = require('node:assert/strict')++const {+ computeTargets,+ globToRegExp,+ isTripwire,+ parseCrateDependencies,+ reverseClosure,+ ALL,+} = require('./trunk-impacted-targets')++const CONTEXT = {+ products: ['alpha', 'beta', 'gamma'],+ isolatedProducts: new Set(['alpha', 'beta']),+ rustGraph: {+ dependsOn: new Map([+ ['shared', []],+ ['consumer', ['shared']],+ ['unrelated', []],+ ]),+ byDir: [+ { dir: 'consumer', name: 'consumer' },+ { dir: 'unrelated', name: 'unrelated' },+ { dir: 'shared', name: 'shared' },+ ],+ },+ tachGraph: {+ graph: new Map(),+ // Mirrors turbo-discover's dashed-name contract at the boundary.+ tachDependents: (changed) => (changed.includes('alpha') ? ['beta', 'gamma'] : []),+ },+}++test('every tripwire forces ALL', () => {+ const tripwireFiles = [+ 'pnpm-lock.yaml',+ 'uv.lock',+ 'rust/Cargo.lock',+ 'tach.toml',+ '.github/workflows/ci-backend.yml',+ 'proto/events.proto',+ 'frontend/src/queries/schema.json',+ 'posthog/schema.py',+ 'products/alpha/manifest.tsx',+ 'bin/start',+ '.test_durations',+ ]+ for (const file of tripwireFiles) {+ assert.equal(isTripwire(file), true, `${file} should be a tripwire`)+ assert.equal(computeTargets([file], CONTEXT), ALL, `${file} should force ALL`)+ }+})++test('a tripwire anywhere in the change set forces ALL even alongside narrow files', () => {+ assert.equal(computeTargets(['products/alpha/backend/api.py', 'pnpm-lock.yaml'], CONTEXT), ALL)+})++// The single most dangerous failure mode: an unclaimed path yielding an empty+// target set reads to Trunk as "overlaps nothing", so the PR merges in parallel+// with everything. A new top-level directory must widen, never narrow.+test('an unmapped path forces ALL rather than an empty target set', () => {+ for (const file of ['terraform/main.tf', 'some-new-toplevel/thing.go', 'common/unrecognized/x.ts']) {+ assert.equal(computeTargets([file], CONTEXT), ALL, `${file} should force ALL`)+ }+})++test('globs match across directories only through **', () => {+ assert.equal(globToRegExp('.github/**').test('.github/workflows/ci.yml'), true)+ assert.equal(globToRegExp('products/*/manifest.tsx').test('products/alpha/manifest.tsx'), true)+ // A single star must not span a separator, or products/*/manifest.tsx would+ // swallow unrelated nested paths and quietly widen every product change.+ assert.equal(globToRegExp('products/*/manifest.tsx').test('products/alpha/nested/manifest.tsx'), false)+ assert.equal(globToRegExp('Dockerfile*').test('Dockerfile.sqlx-migrate'), true)+ assert.equal(globToRegExp('pnpm-lock.yaml').test('nested/pnpm-lock.yaml'), false)+})++test('a changed rust crate pulls in the crates that depend on it', () => {+ assert.deepEqual(computeTargets(['rust/shared/src/lib.rs'], CONTEXT), ['rust:crate:consumer', 'rust:crate:shared'])+ // A leaf crate must not drag in its own dependencies, only its dependents.+ assert.deepEqual(computeTargets(['rust/consumer/src/main.rs'], CONTEXT), ['rust:crate:consumer'])+ assert.deepEqual(computeTargets(['rust/unrelated/src/main.rs'], CONTEXT), ['rust:crate:unrelated'])+})++test('an unresolvable rust crate graph reports every crate instead of narrowing', () => {+ const noGraph = { ...CONTEXT, rustGraph: null }+ assert.equal(computeTargets(['rust/shared/src/lib.rs'], noGraph), ALL)+})++test('a rust path outside every known crate forces ALL', () => {+ assert.equal(computeTargets(['rust/not-a-crate/file.rs'], CONTEXT), ALL)+})++test('reverseClosure walks transitively and excludes unrelated nodes', () => {+ const graph = new Map([+ ['base', []],+ ['mid', ['base']],+ ['top', ['mid']],+ ['island', []],+ ])+ assert.deepEqual(reverseClosure(['base'], graph).sort(), ['base', 'mid', 'top'])+ assert.deepEqual(reverseClosure(['island'], graph), ['island'])+})++// Guards the prost14 = { package = "prost" } shape: treating any renamed+// dependency as unparseable knocked out the whole rust graph, collapsing every+// rust PR into ALL.+test('renamed dependencies resolve to the real crate without failing the graph', () => {+ const crateNames = new Set(['shared', 'consumer'])+ const toml = `+[package]+name = "consumer"++[dependencies]+prost14 = { package = "prost", version = "0.14" }+aliased = { package = "shared", path = "../shared" }+shared.workspace = true+serde = "1"+`+ assert.deepEqual(parseCrateDependencies(toml, crateNames).sort(), ['shared'])+})++// Cargo spells dependency sections four ways. The [dependencies.<name>] form+// carries the name in the header, and reading only body keys silently dropped+// the edge (rust/personhog-stateright depends on personhog-coordination this+// way), which let a shared crate and its dependent get disjoint targets and+// merge in parallel.+test('dependency sections are parsed in every header form Cargo allows', () => {+ const crateNames = new Set(['shared', 'other', 'renamed-crate'])+ const cases = [+ ['plain table', '[dependencies]\nshared = { path = "../shared" }\n', ['shared']],+ ['dev table', '[dev-dependencies]\nshared.workspace = true\n', ['shared']],+ ['build table', '[build-dependencies]\nshared = "1"\n', ['shared']],+ ['dependency-per-table', '[dependencies.shared]\npath = "../shared"\nversion = "0.1"\n', ['shared']],+ ['dev dependency-per-table', '[dev-dependencies.other]\npath = "../other"\n', ['other']],+ [+ 'target-scoped table',+ '[target.\'cfg(not(target_env = "msvc"))\'.dependencies]\nshared = { version = "1" }\n',+ ['shared'],+ ],+ [+ 'dependency-per-table with a rename',+ '[dependencies.alias]\npackage = "renamed-crate"\npath = "../renamed-crate"\n',+ ['renamed-crate'],+ ],+ // The workspace table declares versions for every member, not this+ // crate's own edges.+ ['workspace table excluded', '[workspace.dependencies]\nshared = { path = "shared" }\n', []],+ ]+ for (const [label, toml, expected] of cases) {+ assert.deepEqual(parseCrateDependencies(toml, crateNames).sort(), expected, label)+ }+})++// Attribute keys inside a [dependencies.<name>] table would be read as+// dependency names if the body were scanned, inventing an edge to any crate+// that happens to share a name with a Cargo attribute.+test('attributes inside a dependency-per-table are not read as crate names', () => {+ const crateNames = new Set(['shared', 'path', 'features'])+ const toml = '[dependencies.shared]\npath = "../shared"\nfeatures = ["a"]\n'+ assert.deepEqual(parseCrateDependencies(toml, crateNames), ['shared'])+})++test('an isolated product change stays narrow and names its tach dependents', () => {+ assert.deepEqual(computeTargets(['products/alpha/backend/api.py'], CONTEXT), [+ 'py:product:alpha',+ 'py:product:beta',+ 'py:product:gamma',+ ])+ // beta has no dependents in the synthetic graph, so it must not widen.+ assert.deepEqual(computeTargets(['products/beta/backend/api.py'], CONTEXT), ['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)+ for (const product of CONTEXT.products) {+ assert.equal(targets.includes(`py:product:${product}`), true, `expected py:product:${product}`)+ }+})++test('an unavailable tach graph widens backend changes instead of narrowing', () => {+ const noTach = { ...CONTEXT, tachGraph: null }+ const targets = computeTargets(['products/alpha/backend/api.py'], noTach)+ assert.equal(targets.includes('py:core'), true)+ assert.equal(targets.includes('py:product:gamma'), true)+})++// Core changes have to overlap every leaf in their domain, because set+// intersection is the only way Trunk can express "this can break anything+// downstream".+test('core changes expand to every leaf target in their own domain', () => {+ const backend = computeTargets(['posthog/models/team.py'], CONTEXT)+ assert.deepEqual(backend, ['py:core', 'py:product:alpha', 'py:product:beta', 'py:product:gamma'])++ const frontend = computeTargets(['frontend/src/lib/components/Foo.tsx'], CONTEXT)+ assert.deepEqual(frontend, ['fe:core', 'fe:product:alpha', 'fe:product:beta', 'fe:product:gamma'])+})++test('product frontend and backend changes land in separate domains', () => {+ assert.deepEqual(computeTargets(['products/alpha/frontend/Scene.tsx'], CONTEXT), ['fe:product:alpha'])+ assert.deepEqual(computeTargets(['products/beta/backend/api.py'], CONTEXT), ['py:product:beta'])+})++test('a product file that is neither backend nor frontend claims both domains', () => {+ const targets = computeTargets(['products/beta/mcp/tools.yaml'], CONTEXT)+ assert.equal(targets.includes('py:product:beta'), true)+ assert.equal(targets.includes('fe:product:beta'), true)+})++// tools/ is not one bucket. phrocs is Go with its own CI and nothing imports+// it, while hogli-commands is loaded by posthog/conftest.py on every pytest+// run, so lumping them together either serializes phrocs needlessly or hands+// hogli a lane it must not have.+test('independently testable tools get their own lane', () => {+ assert.deepEqual(computeTargets(['tools/phrocs/internal/tui/app.go'], CONTEXT), ['tools:phrocs'])+ assert.deepEqual(computeTargets(['tools/traffic-sim/main.go'], CONTEXT), ['tools:traffic-sim'])+})++test('backend-coupled and unrecognized tools stay in the backend lanes', () => {+ for (const file of [+ 'tools/hogli/cli.py',+ 'tools/hogli-commands/hogli_commands/quarantine/core.py',+ // A tool nobody has classified yet must over-report rather than be+ // handed a lane it has not earned.+ 'tools/some-new-tool/main.py',+ ]) {+ const targets = computeTargets([file], CONTEXT)+ assert.equal(targets.includes('py:core'), true, `${file} should widen to the backend lanes`)+ }+})++// These steer what every suite runs, so they cannot sit in one domain's lane.+test('CI-steering scripts directly under tools/ force ALL', () => {+ assert.equal(computeTargets(['tools/playwright_spec_selection.py'], CONTEXT), ALL)+ assert.equal(computeTargets(['tools/snob_backend_test_selection_shadow.py'], CONTEXT), ALL)+})++// Both sit on the fe/py boundary: openapi-codegen generates the frontend types+// from backend serializers, and owners is read by both suites.+test('cross-domain tools are tripwires rather than backend-only', () => {+ assert.equal(computeTargets(['tools/openapi-codegen/config.ts'], CONTEXT), ALL)+ 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'])+})++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 sets = [rust, node, service, docs]+ 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))+ assert.deepEqual(overlap, [], `${sets[i]} and ${sets[j]} must not overlap`)+ }+ }+})++// Playwright specs run against whatever frontend lands beside them, so they+// have to share the frontend lanes rather than forming an island.+test('playwright changes overlap the frontend domain', () => {+ const specs = computeTargets(['playwright/e2e/login.spec.ts'], CONTEXT)+ const frontend = computeTargets(['frontend/src/lib/components/Foo.tsx'], CONTEXT)+ assert.equal(+ specs.some((target) => frontend.includes(target)),+ true+ )+})diff --git a/.github/workflows/ci-scripts.yml b/.github/workflows/ci-scripts.ymlindex c60751270b74..dcb4a9abc032 100644--- a/.github/workflows/ci-scripts.yml+++ b/.github/workflows/ci-scripts.yml@@ -71,3 +71,6 @@ jobs:- name: Turbo-discover dependent-cascade tests (Node)run: node --test .github/scripts/turbo-discover-cascade.test.js++ - name: Trunk impacted-targets tests (Node)+ run: node --test .github/scripts/trunk-impacted-targets.test.jsdiff --git a/.github/workflows/trunk-impacted-targets.yml b/.github/workflows/trunk-impacted-targets.ymlindex 6b454444857c..b0465376a192 100644--- a/.github/workflows/trunk-impacted-targets.yml+++ b/.github/workflows/trunk-impacted-targets.yml@@ -4,6 +4,12 @@ name: Trunk impacted targets# schedule it. Trunk needs an impacted-targets upload to place a PR into a lane;# without one, fork PRs never enter the queue and have to be merged by hand.#+# Targets are computed by .github/scripts/trunk-impacted-targets.js, which maps+# changed paths onto lane names. Trunk runs two PRs in parallel only when their+# target sets are disjoint, so that script is biased toward over-reporting and+# falls back to "ALL" (overlaps everything, the old single-lane behavior)+# whenever it cannot classify a change with confidence.+## The upload authenticates with the org API token (x-api-token) on internal PRs.# Fork PR workflow runs do NOT receive repo secrets — GitHub withholds them from# `pull_request` runs originating in a fork — so for forks we authenticate with@@ -15,6 +21,18 @@ name: Trunk impacted targets# trigger, never `pull_request_target`. `pull_request_target` would hand repo# secrets to code from untrusted forks ("pwn request"). The fork path# deliberately needs no secret, so `pull_request` is sufficient and safe.+#+# SECURITY: the two jobs below MUST stay separate, and `upload` MUST NOT check+# out or run anything from the PR. `compute` executes PR-controlled code (the+# target script, and whatever the PR did to it), so it is kept free of secrets.+# Splitting on a step boundary instead of a job boundary would not be enough:+# steps in one job share a runner, and a script can prepend a directory to+# GITHUB_PATH (or export through GITHUB_ENV) so that a later step's `jq` and+# `curl` resolve to attacker-supplied executables, which would then run with+# TRUNK_API_TOKEN in their environment. Separate jobs get separate runners, so+# the only thing crossing the boundary is the JSON string in the job output.+# That string is consumed through `env:` and `jq --argjson`, never interpolated+# into a shell command.on:workflow_call:@@ -26,14 +44,73 @@ permissions:contents: readjobs:+ compute:+ name: Compute impacted targets+ runs-on: ubuntu-24.04+ timeout-minutes: 10+ # Runs PR-controlled code, so it gets read access to the repo and+ # nothing else. No secret is available to this job.+ permissions:+ contents: read+ outputs:+ targets: ${{ steps.targets.outputs.targets }}+ steps:+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ with:+ fetch-depth: 1000+ filter: blob:none++ - name: Fetch PR base for the changed-file diff+ env:+ BASE_REF: ${{ github.event.pull_request.base.ref }}+ run: git fetch --no-tags --depth=1000 --filter=blob:none origin "$BASE_REF:refs/remotes/origin/$BASE_REF"++ - uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v6.2.0+ with:+ node-version-file: .nvmrc+ token: ${{ github.token }}++ - name: Compute impacted targets+ id: targets+ env:+ BASE_REF: ${{ github.event.pull_request.base.ref }}+ run: |+ set -uo pipefail++ # A missing merge base (branch older than the fetched depth) or+ # any diff failure has to widen to ALL rather than upload a+ # partial file list, which Trunk cannot distinguish from a+ # complete one.+ if ! merge_base="$(git merge-base "refs/remotes/origin/$BASE_REF" HEAD 2>/dev/null)"; then+ echo "::warning::No merge base against $BASE_REF within the fetched depth; reporting ALL."+ echo 'targets={"impactedTargets":"ALL"}' >> "$GITHUB_OUTPUT"+ exit 0+ fi++ if ! changed="$(git diff --name-only "$merge_base" HEAD)"; then+ echo "::warning::Could not diff against the merge base; reporting ALL."+ echo 'targets={"impactedTargets":"ALL"}' >> "$GITHUB_OUTPUT"+ exit 0+ fi++ echo "$changed" | sed 's/^/ /'++ # The script prints "ALL" or a JSON array on stdout and never+ # exits non-zero; it degrades to "ALL" internally on any error.+ computed="$(printf '%s\n' "$changed" | node .github/scripts/trunk-impacted-targets.js)"+ printf 'targets=%s\n' "$(jq -cn --argjson t "$computed" '{impactedTargets: $t}')" >> "$GITHUB_OUTPUT"+upload:name: Upload impacted targets to Trunk+ needs: compute+ # Runs even when the computation failed, because a PR with no upload+ # never enters the queue at all. A missing result degrades to ALL below.+ if: ${{ !cancelled() }}runs-on: ubuntu-24.04timeout-minutes: 5- # Reads only the event payload and talks out to Trunk — no repo write or- # PR API access needed.- permissions:- contents: read+ # Talks only to Trunk. It never checks out the repo, so it needs no+ # GitHub permissions whatsoever.+ permissions: {}env:IS_FORK: ${{ github.event.pull_request.head.repo.full_name != github.repository }}RUN_ID: ${{ github.run_id }}@@ -44,27 +121,30 @@ jobs:# run's head_sha, which is what Trunk checks on a fork upload.PR_SHA: ${{ github.event.pull_request.head.sha }}TARGET_BRANCH: ${{ github.event.pull_request.base.ref }}- TRUNK_API_TOKEN: ${{ secrets.TRUNK_API_TOKEN }}steps:- name: Upload impacted targets to Trunk# Not continue-on-error: a silent failure here is exactly what keeps# fork PRs out of the queue, so surface upload problems loudly.# --retry rides out transient Trunk/network blips.+ env:+ TRUNK_API_TOKEN: ${{ secrets.TRUNK_API_TOKEN }}+ IMPACTED_TARGETS: ${{ needs.compute.outputs.targets }}run: |set -euo pipefail+ # An empty result means the compute job failed or was skipped.+ # ALL overlaps every lane, so it is the safe degradation: the+ # PR still enters the queue, just without any parallelism.+ if [ -z "$IMPACTED_TARGETS" ]; then+ echo "::warning::No computed targets available; falling back to ALL."+ IMPACTED_TARGETS='{"impactedTargets":"ALL"}'+ fi+if [ "$IS_FORK" != "true" ] && [ -z "$TRUNK_API_TOKEN" ]; thenecho "::warning::TRUNK_API_TOKEN is not set — skipping the impacted-targets upload."exit 0fi- # We report "ALL" — every target — which is always correct: it- # can never under-report and let the queue merge conflicting- # PRs in parallel. It yields no parallelism benefit, but it- # gets every PR (forks included) into the queue. To actually- # parallelise, replace "ALL" with a computed target-name list- # (e.g. derived from the ci-paths-filter.yml outputs) once the- # queue's target names are defined.payload="$(jq -n \--arg host "github.com" \--arg owner "$REPO_OWNER" \@@ -72,7 +152,8 @@ jobs:--argjson number "$PR_NUMBER" \--arg sha "$PR_SHA" \--arg targetBranch "$TARGET_BRANCH" \- '{repo: {host: $host, owner: $owner, name: $name}, pr: {number: $number, sha: $sha}, targetBranch: $targetBranch, impactedTargets: "ALL"}')"+ --argjson impacted "$IMPACTED_TARGETS" \+ '{repo: {host: $host, owner: $owner, name: $name}, pr: {number: $number, sha: $sha}, targetBranch: $targetBranch} + $impacted')"if [ "$IS_FORK" = "true" ]; thenecho "Fork PR — authenticating with x-forked-workflow-run-id ($RUN_ID)"