Skip to content

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

chore(ci): fail prs that mix python or frontend lanes with node or rust (#112261)

Zach Brown548a13311ea8
diff --git a/.github/scripts/post-ci-sections.test.mjs b/.github/scripts/post-ci-sections.test.mjs
index 4203b521dd8c..21b62c3a1fc1 100644
--- a/.github/scripts/post-ci-sections.test.mjs
+++ b/.github/scripts/post-ci-sections.test.mjs
@@ -4,7 +4,7 @@ import { describe, it } from 'node:test'
import { buildDocsPreviewSection } from './post-docs-preview-section.mjs'
import { buildHobbySection } from './post-hobby-section.mjs'
import { buildHogboxPreviewSection } from './post-hogbox-preview-section.mjs'
-import { buildTrunkLaneSection, postTrunkLaneSection } from './post-trunk-lane-section.mjs'
+import { buildTrunkLaneSection, parseCrossLane, postTrunkLaneSection } from './post-trunk-lane-section.mjs'
const commonHobby = {
previewMode: true,
@@ -102,6 +102,36 @@ describe('CI report section builders', () => {
})
}
+ it('warns and names both sides when a PR mixes lanes', () => {
+ const section = buildTrunkLaneSection({
+ impactedTargets: ['node:ingestion', 'py:core'],
+ isUniversal: false,
+ crossLane: { mixed: true, heavyFiles: ['posthog/api/x.py'], lightFiles: ['nodejs/src/y.ts'] },
+ })
+ assert.equal(section.status, 'warn')
+ assert.match(section.summary, /mixes lanes/)
+ assert.match(section.body, /<code>posthog\/api\/x\.py<\/code>/)
+ assert.match(section.body, /<code>nodejs\/src\/y\.ts<\/code>/)
+ })
+
+ it('counts the files the telemetry cut from a capped list', () => {
+ const crossLane = parseCrossLane({
+ cross_lane: true,
+ cross_lane_heavy_files: ['a.py', 'b.py', 'c.py', 'd.py'],
+ cross_lane_heavy_file_count: 150,
+ cross_lane_light_files: ['nodejs/src/y.ts'],
+ })
+ const section = buildTrunkLaneSection({ impactedTargets: ['node:ingestion', 'py:core'], crossLane })
+ assert.match(section.body, /<code>c\.py<\/code> and 147 more/)
+ })
+
+ it('gives no cross-lane warning when the file lists have the wrong shape', () => {
+ assert.equal(
+ parseCrossLane({ cross_lane: true, cross_lane_heavy_files: 'a.py', cross_lane_light_files: [1] }),
+ null
+ )
+ })
+
it('renders a docs preview link after a successful trigger', () => {
const section = buildDocsPreviewSection({
triggerStatus: 'success',
diff --git a/.github/scripts/post-trunk-lane-section.mjs b/.github/scripts/post-trunk-lane-section.mjs
index 6f5351a848d3..f90474d19265 100644
--- a/.github/scripts/post-trunk-lane-section.mjs
+++ b/.github/scripts/post-trunk-lane-section.mjs
@@ -18,7 +18,7 @@ function formatTarget(target) {
return `<code>${escapedTarget}</code>`
}
-export function buildTrunkLaneSection({ impactedTargets, isUniversal }) {
+export function buildTrunkLaneSection({ impactedTargets, isUniversal, crossLane = null }) {
if (
isUniversal ||
!Array.isArray(impactedTargets) ||
@@ -37,16 +37,58 @@ export function buildTrunkLaneSection({ impactedTargets, isUniversal }) {
// shared family name rather than listing them all.
const summary = impactedTargets.length === 1 ? `${laneName} (${formatTarget(impactedTargets[0])})` : laneName
+ const base = `This PR is assigned to the ${summary}. It ${runsBackendPythonTests ? 'runs' : 'does not run'} backend Python tests and may merge in parallel with PRs in other lanes.`
+ if (crossLane?.mixed) {
+ return {
+ status: 'warn',
+ summary: `${summary}, mixes lanes`,
+ body: `${base}\n\n${crossLaneParagraph(crossLane)}`,
+ }
+ }
return {
status: runsBackendPythonTests ? 'warn' : 'ok',
summary,
- body: `This PR is assigned to the ${summary}. It ${runsBackendPythonTests ? 'runs' : 'does not run'} backend Python tests and may merge in parallel with PRs in other lanes.`,
+ body: base,
+ }
+}
+
+// The telemetry caps each list, so the total arrives beside it.
+function fileList(files, total = files.length) {
+ const shown = files.slice(0, 3).map(formatTarget).join(', ')
+ const count = Math.max(total, files.length)
+ return count > 3 ? `${shown} and ${count - 3} more` : shown
+}
+
+function crossLaneParagraph({ heavyFiles, lightFiles, heavyCount, lightCount }) {
+ return (
+ `This PR changes Python or frontend code (${fileList(heavyFiles, heavyCount)}) and Node or Rust code (${fileList(lightFiles, lightCount)}) together. ` +
+ 'In the merge queue, every Node or Rust PR behind it in the same lane then runs the Django and frontend suites too, ' +
+ 'so the cross-lane check fails. Split it, or add the `cross-lane-change` label if the halves must land together.'
+ )
+}
+
+// PR-controlled scripts produce these properties, so a wrong shape must not fail the section.
+export function parseCrossLane(laneProperties) {
+ const strings = (value) => (Array.isArray(value) ? value.filter((item) => typeof item === 'string') : [])
+ const heavyFiles = strings(laneProperties.cross_lane_heavy_files)
+ const lightFiles = strings(laneProperties.cross_lane_light_files)
+ if (laneProperties.cross_lane !== true || heavyFiles.length === 0 || lightFiles.length === 0) {
+ return null
+ }
+ const count = (value, files) => (Number.isInteger(value) ? value : files.length)
+ return {
+ mixed: true,
+ heavyFiles,
+ lightFiles,
+ heavyCount: count(laneProperties.cross_lane_heavy_file_count, heavyFiles),
+ lightCount: count(laneProperties.cross_lane_light_file_count, lightFiles),
}
}
export async function postTrunkLaneSection({
impactedTargets,
isUniversal,
+ crossLane = null,
expectedHeadSha,
getCurrentHeadSha,
post = postSection,
@@ -64,7 +106,7 @@ export async function postTrunkLaneSection({
return false
}
- const section = buildTrunkLaneSection({ impactedTargets, isUniversal })
+ const section = buildTrunkLaneSection({ impactedTargets, isUniversal, crossLane })
await post({ id: 'trunk-lane', ...section })
return true
}
@@ -91,10 +133,12 @@ async function main() {
const impactedTargets = parseJson(process.env.IMPACTED_TARGETS).impactedTargets
const laneProperties = parseJson(process.env.LANE_PROPERTIES)
const isUniversal = typeof laneProperties.is_all === 'boolean' ? laneProperties.is_all : true
+ const crossLane = parseCrossLane(laneProperties)
await postTrunkLaneSection({
impactedTargets,
isUniversal,
+ crossLane,
expectedHeadSha: process.env.EXPECTED_HEAD_SHA,
getCurrentHeadSha,
})
diff --git a/.github/scripts/trunk-cross-lane.js b/.github/scripts/trunk-cross-lane.js
new file mode 100644
index 000000000000..d6864e57512d
--- /dev/null
+++ b/.github/scripts/trunk-cross-lane.js
@@ -0,0 +1,81 @@
+// Flags a PR mixing Python or frontend lanes with Node or Rust lanes, which makes
+// queued Node and Rust PRs behind it run the slow suites. Files whose own rule
+// spans both sides (protos) and all tripwires are ignored.
+
+const { allKnownTargets, computeTargets, isTripwire } = require('./trunk-impacted-targets')
+
+const HEAVY_PREFIXES = ['py:', 'fe:']
+const LIGHT_PREFIXES = ['node:', 'rust:']
+
+// Beyond this a PR is a mass move, where a verdict is noise.
+const MAX_FILES = 1000
+
+function sideOf(targets) {
+ const heavy = targets.some((target) => HEAVY_PREFIXES.some((prefix) => target.startsWith(prefix)))
+ const light = targets.some((target) => LIGHT_PREFIXES.some((prefix) => target.startsWith(prefix)))
+ return heavy && light ? 'both' : heavy ? 'heavy' : light ? 'light' : 'neither'
+}
+
+/** Null when no verdict can be given. */
+function crossLaneFiles(changedFiles, context) {
+ if (changedFiles.length === 0 || changedFiles.length > MAX_FILES) {
+ return null
+ }
+ let universe
+ try {
+ universe = allKnownTargets(context)
+ } catch (error) {
+ console.error(`Could not enumerate the lanes (${error.message}); cross_lane reports unknown`)
+ return null
+ }
+ const heavyFiles = []
+ const lightFiles = []
+ let unclassified = false
+ for (const file of changedFiles) {
+ // Tripwires are workflows and tool settings, and the warning is about code.
+ if (isTripwire(file)) {
+ continue
+ }
+ const targets = laneTargets(file, context, universe)
+ if (!targets) {
+ unclassified = true
+ continue
+ }
+ const side = sideOf(targets)
+ if (side === 'heavy') {
+ heavyFiles.push(file)
+ } else if (side === 'light') {
+ lightFiles.push(file)
+ }
+ }
+ const mixed = heavyFiles.length > 0 && lightFiles.length > 0
+ // An unclassified file can add a side but not remove one, so a proven mix holds.
+ if (unclassified && !mixed) {
+ return null
+ }
+ return { mixed, heavyFiles, lightFiles }
+}
+
+/** Null when the lane rules name no side for the file. */
+function laneTargets(file, context, universe) {
+ let targets
+ try {
+ targets = computeTargets([file], context)
+ } catch (error) {
+ console.error(`Could not classify ${file} by lane side (${error.message}); it counts on neither side`)
+ return null
+ }
+ // ALL means the rules could not enumerate the lanes of this file.
+ if (!Array.isArray(targets)) {
+ console.error(`Could not enumerate the lanes of ${file}; it counts on neither side`)
+ return null
+ }
+ // Every lane is the unknown-path fallback or a deliberate widening. Neither names a side.
+ if (universe && targets.length >= universe.length) {
+ console.error(`${file} claims every lane; it counts on neither side`)
+ return null
+ }
+ return targets
+}
+
+module.exports = { crossLaneFiles, sideOf, MAX_FILES }
diff --git a/.github/scripts/trunk-cross-lane.test.js b/.github/scripts/trunk-cross-lane.test.js
new file mode 100644
index 000000000000..7ecb5f780215
--- /dev/null
+++ b/.github/scripts/trunk-cross-lane.test.js
@@ -0,0 +1,92 @@
+// Run with: node --test .github/scripts/trunk-cross-lane.test.js
+
+const test = require('node:test')
+const assert = require('node:assert/strict')
+
+const { crossLaneFiles, MAX_FILES } = require('./trunk-cross-lane')
+
+const CONTEXT = {
+ products: ['alpha', 'beta'],
+ services: ['mcp'],
+ isolatedProducts: new Set(['alpha', 'beta']),
+ semgrepDomains: new Map(),
+ rustInventory: {
+ crateNames: new Set(['capture', 'shared']),
+ byDir: [
+ { dir: 'capture', name: 'capture' },
+ { dir: 'shared', name: 'shared' },
+ ],
+ },
+ rustAffectedCrates: ['capture'],
+ tachGraph: {
+ graph: new Map([
+ ['alpha', []],
+ ['beta', []],
+ ]),
+ tachDependents: () => [],
+ },
+}
+
+for (const [name, files, mixed] of [
+ ['Django beside Node', ['posthog/api/event_tracker.py', 'nodejs/src/ingestion/ingestion-consumer.ts'], true],
+ ['frontend beside Node', ['frontend/src/scenes/urls.ts', 'nodejs/src/cdp/consumers/cdp-api.ts'], true],
+ ['a product backend beside Rust', ['products/alpha/backend/models.py', 'rust/capture/src/router.rs'], true],
+ ['Node and Rust together', ['nodejs/src/ingestion/ingestion-consumer.ts', 'rust/capture/src/router.rs'], false],
+ ['Django and frontend together', ['posthog/api/event_tracker.py', 'frontend/src/scenes/urls.ts'], false],
+ ['Node alone', ['nodejs/src/ingestion/ingestion-consumer.ts'], false],
+ // Markdown claims no lane, so a README beside Node code is not a mix.
+ ['prose beside Node', ['README.md', 'nodejs/src/ingestion/ingestion-consumer.ts'], false],
+ [
+ 'a Python workflow beside a Rust workflow',
+ ['.github/workflows/ci-backend.yml', '.github/workflows/ci-rust.yml'],
+ false,
+ ],
+]) {
+ test(`${name} is ${mixed ? '' : 'not '}a cross-lane change`, () => {
+ assert.equal(crossLaneFiles(files, CONTEXT).mixed, mixed)
+ })
+}
+
+test('names the files on each side so the author knows what to split', () => {
+ const verdict = crossLaneFiles(
+ ['posthog/api/event_tracker.py', 'nodejs/src/ingestion/ingestion-consumer.ts', 'README.md'],
+ CONTEXT
+ )
+ assert.deepEqual(verdict.heavyFiles, ['posthog/api/event_tracker.py'])
+ assert.deepEqual(verdict.lightFiles, ['nodejs/src/ingestion/ingestion-consumer.ts'])
+})
+
+test('a file that claims both sides by rule is not counted on either', () => {
+ const verdict = crossLaneFiles(['hogli.yaml', 'nodejs/src/ingestion/ingestion-consumer.ts'], CONTEXT)
+ assert.equal(verdict.mixed, false)
+ assert.deepEqual(verdict.heavyFiles, [])
+})
+
+test('gives no verdict for an empty or oversized change set', () => {
+ assert.equal(crossLaneFiles([], CONTEXT), null)
+ const huge = Array.from({ length: MAX_FILES + 1 }, (_, i) => `posthog/file_${i}.py`)
+ assert.equal(crossLaneFiles(huge, CONTEXT), null)
+})
+
+test('logs the file that could not be classified rather than failing silently', (t) => {
+ const errors = t.mock.method(console, 'error', () => {})
+ const broken = { ...CONTEXT, isolatedProducts: undefined }
+ assert.equal(crossLaneFiles(['products/alpha/backend/models.py'], broken), null)
+ assert.match(errors.mock.calls[0].arguments[0], /products\/alpha\/backend\/models\.py/)
+})
+
+test('gives no verdict when any file cannot be enumerated', (t) => {
+ t.mock.method(console, 'error', () => {})
+ const noCrates = { ...CONTEXT, rustInventory: null }
+ assert.equal(crossLaneFiles(['posthog/api/event_tracker.py', 'rust/capture/src/router.rs'], noCrates), null)
+})
+
+test('a file that falls through every lane rule gives no verdict, unless the other files already prove a mix', (t) => {
+ t.mock.method(console, 'error', () => {})
+ assert.equal(crossLaneFiles(['posthog/api/event_tracker.py', 'some-new-toplevel/thing.go'], CONTEXT), null)
+ const proven = crossLaneFiles(
+ ['posthog/api/event_tracker.py', 'nodejs/src/ingestion/ingestion-consumer.ts', 'some-new-toplevel/thing.go'],
+ CONTEXT
+ )
+ assert.equal(proven.mixed, true)
+})
diff --git a/.github/scripts/trunk-impacted-targets.js b/.github/scripts/trunk-impacted-targets.js
index c2c3eacbb32f..9304d264cec7 100644
--- a/.github/scripts/trunk-impacted-targets.js
+++ b/.github/scripts/trunk-impacted-targets.js
@@ -531,8 +531,9 @@ const TRIPWIRE_RULES = [
['tsconfig.*.json', JAVASCRIPT],
['babel.config.js', JAVASCRIPT],
['webpack.config.js', JAVASCRIPT],
- ['.oxlintrc.json', JAVASCRIPT],
- ['.oxfmtrc*', JAVASCRIPT],
+ // Both ignore nodejs/, which has its own toolchain; a lane test guards that.
+ ['.oxlintrc.json', FRONTEND_SUITE],
+ ['.oxfmtrc*', FRONTEND_SUITE],
// Prettier still formats the nodejs tree (ci-nodejs runs its check), so
// its ignore file is a JS toolchain setting like the two above.
['.prettierignore', JAVASCRIPT],
@@ -2934,6 +2935,11 @@ function jsLockfileNodeLanesLoader(repoRoot, nodeLaneMap, headLockfile) {
}
}
+// The change list carries deleted paths too; the tree no longer does.
+function findDeletedFiles(changedFiles) {
+ return new Set(changedFiles.filter((file) => !fs.existsSync(path.join(REPO_ROOT, file))))
+}
+
function buildContext(repoRoot) {
const products = listProducts(repoRoot)
const tachGraph = loadTachGraph(repoRoot)
@@ -2969,6 +2975,7 @@ module.exports = {
buildContext,
compileContractMatcher,
compileWorkspaceMatcher,
+ findDeletedFiles,
globToRegExp,
isProductDirectory,
isTripwire,
@@ -3012,9 +3019,10 @@ if (require.main === module) {
console.error('No changed files on stdin; reporting ALL')
result = ALL
} else {
- // 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 })
+ result = computeTargets(changedFiles, {
+ ...buildContext(REPO_ROOT),
+ deletedFiles: findDeletedFiles(changedFiles),
+ })
}
} catch (error) {
// Any unexpected failure has to widen rather than narrow, because a
diff --git a/.github/scripts/trunk-impacted-targets.test.js b/.github/scripts/trunk-impacted-targets.test.js
index c1031172d4f8..6532081df8ce 100644
--- a/.github/scripts/trunk-impacted-targets.test.js
+++ b/.github/scripts/trunk-impacted-targets.test.js
@@ -43,6 +43,7 @@ const {
PROTO_TREES,
PYTHON,
REPO_ROOT,
+ stripJsonComments,
RUST,
UNIVERSAL,
} = require('./trunk-impacted-targets')
@@ -183,7 +184,7 @@ test('the tach graph claims the python lanes rather than every lane', () => {
// Only the root files narrow: a product's own manifests keep the product's lanes.
test('a lockfile claims its own toolchain rather than every lane', () => {
for (const file of ['pnpm-lock.yaml', 'pnpm-workspace.yaml', 'package.json']) {
- assert.deepEqual(computeTargets([file], CONTEXT), computeTargets(['.oxlintrc.json'], CONTEXT), file)
+ assert.deepEqual(computeTargets([file], CONTEXT), computeTargets(['tsconfig.json'], CONTEXT), file)
}
for (const file of ['uv.lock', 'pyproject.toml']) {
assert.deepEqual(computeTargets([file], CONTEXT), computeTargets(['mypy.ini'], CONTEXT), file)
@@ -383,7 +384,7 @@ test('every proto tree declaring a stub consumer has stubs there, and no other t
// serializes against Rust, and a backend one no longer serializes against the
// frontend.
test('a language-scoped tripwire claims only that language', () => {
- const javascript = computeTargets(['.oxlintrc.json'], CONTEXT)
+ const javascript = computeTargets(['tsconfig.json'], CONTEXT)
assert.equal(javascript.includes('fe:core'), true)
assert.equal(javascript.includes('fe:product:alpha'), true)
assert.equal(javascript.includes('node:ingestion'), true)
@@ -451,7 +452,7 @@ test('the generated frontend product artifacts claim only the frontend lanes', (
// story the workflows tell: a tool's own settings can only fail the code that
// tool reads, so they no longer serialize a PR against the whole repo.
test('single-language root configuration claims that language', () => {
- const javascript = computeTargets(['.oxlintrc.json'], CONTEXT)
+ const javascript = computeTargets(['tsconfig.json'], CONTEXT)
for (const file of ['postcss.config.js', '.stylelintrc.js', '.stylelintignore', '.kearc', 'posthog.json']) {
assert.deepEqual(computeTargets([file], CONTEXT), javascript, file)
}
@@ -461,6 +462,25 @@ test('single-language root configuration claims that language', () => {
}
})
+test('the root oxc configs claim the JS lanes except node', () => {
+ const javascript = computeTargets(['tsconfig.json'], CONTEXT)
+ for (const file of ['.oxlintrc.json', '.oxfmtrc.json']) {
+ assert.deepEqual(
+ computeTargets([file], CONTEXT),
+ javascript.filter((target) => !target.startsWith('node:')),
+ file
+ )
+ }
+})
+
+test('the root oxc configs keep ignoring nodejs', () => {
+ for (const file of ['.oxlintrc.json', '.oxfmtrc.json']) {
+ const config = JSON.parse(stripJsonComments(fs.readFileSync(path.join(REPO_ROOT, file), 'utf8')))
+ const ignored = (config.ignorePatterns || []).map((pattern) => pattern.replace(/\/(\*\*)?$/, ''))
+ assert.equal(ignored.includes('nodejs'), true, `${file} must ignore nodejs/`)
+ }
+})
+
// Root files whose reader is the stack, the image, or the ownership data every
// suite runs on. The narrowing above stops here: these keep the full set, but
// by decision rather than for want of a rule.
@@ -523,7 +543,7 @@ test('the paths-filter action and its CI share the ci-tooling lane', () => {
test('pnpm patches take the JS lanes and depot.json the repo-config lane', () => {
assert.deepEqual(
computeTargets(['patches/[email protected]'], CONTEXT),
- computeTargets(['.oxlintrc.json'], CONTEXT)
+ computeTargets(['tsconfig.json'], CONTEXT)
)
assert.deepEqual(computeTargets(['depot.json'], CONTEXT), ['repo-config'])
})
@@ -559,7 +579,7 @@ test('the cargo-dist manifest shares the cli lane', () => {
})
test('a single-language workflow claims that language rather than everything', () => {
- const javascript = computeTargets(['.oxlintrc.json'], CONTEXT)
+ const javascript = computeTargets(['tsconfig.json'], CONTEXT)
for (const file of [
'.github/workflows/ci-frontend.yml',
'.github/workflows/ci-storybook.yml',
@@ -836,7 +856,7 @@ test('the agent-skills workflow claims both language families', () => {
assert.equal(targets.includes('agents'), false)
assert.equal(targets.includes('py:core'), true)
assert.equal(targets.includes('fe:core'), true)
- assert.deepEqual(targets, computeTargets(['mypy.ini', '.oxlintrc.json'], CONTEXT))
+ assert.deepEqual(targets, computeTargets(['mypy.ini', 'tsconfig.json'], CONTEXT))
})
test('the ml-mirror sidecar image and its workflow stay on the node lanes', () => {
@@ -1218,7 +1238,7 @@ test('a semgrep rule claims the lanes of the languages it declares', () => {
)
assert.deepEqual(
computeTargets(['.semgrep/rules/devex/ts-rule.yaml'], CONTEXT),
- computeTargets(['.oxlintrc.json'], CONTEXT)
+ computeTargets(['tsconfig.json'], CONTEXT)
)
// A rule spanning languages with no single lane mapping, and a rule file
// the context never resolved, both keep the old radius.
@@ -1374,7 +1394,7 @@ test('an incomplete context falls back to the ALL sentinel', () => {
test('tripwire domains are reported for telemetry', () => {
assert.equal(tripwireDomain('hogli.yaml'), UNIVERSAL)
- assert.equal(tripwireDomain('.oxlintrc.json'), JAVASCRIPT)
+ assert.equal(tripwireDomain('tsconfig.json'), JAVASCRIPT)
assert.equal(tripwireDomain('mypy.ini'), PYTHON)
assert.equal(tripwireDomain('.github/workflows/ci-rust.yml'), RUST)
assert.equal(tripwireDomain('.github/pull_request_template.md'), null)
diff --git a/.github/scripts/trunk-lane-telemetry.js b/.github/scripts/trunk-lane-telemetry.js
index 03c1b905ee1c..b3606684e558 100644
--- a/.github/scripts/trunk-lane-telemetry.js
+++ b/.github/scripts/trunk-lane-telemetry.js
@@ -13,9 +13,11 @@
//
// Raw paths are deliberately not sent. A PR can touch thousands of them, they
// blow past property limits, and in aggregate the directory histogram answers
-// the same questions. The exception is tripwire_files, which names the handful
-// of paths that widened the PR, because that is the field that says which rule
-// to go tune, alongside tripwire_domains for how far each one reached.
+// the same questions. The first exception is tripwire_files, which names the
+// handful of paths that widened the PR, because that is the field that says
+// which rule to go tune, alongside tripwire_domains for how far each one reached.
+// The second is the two cross_lane file lists, capped the same way, because the
+// CI report names those files to the author.
//
// Input: changed file paths, one per line, on stdin
// IMPACTED_TARGETS — the JSON uploaded to Trunk, {"impactedTargets": ...}
@@ -26,10 +28,12 @@ const {
ALL,
allKnownTargets,
buildContext,
+ findDeletedFiles,
isTripwire,
tripwireDomain,
REPO_ROOT,
} = require('./trunk-impacted-targets')
+const { crossLaneFiles } = require('./trunk-cross-lane')
// Enough to name the culprit without turning a wide PR into a huge payload.
const MAX_LISTED = 20
@@ -44,7 +48,7 @@ function domainOf(target) {
// universe tells them apart. Without it the dashboard would read every widening
// as a PR that legitimately claimed every lane, which is the distinction this
// event exists to make.
-function buildProperties(changedFiles, impactedTargets, universe) {
+function buildProperties(changedFiles, impactedTargets, universe, crossLane = null) {
const targets = Array.isArray(impactedTargets) ? impactedTargets : []
const isAll = impactedTargets === ALL || (Boolean(universe) && targets.length === universe.length)
const isProse = targets.length === 1 && targets[0] === 'prose'
@@ -106,6 +110,12 @@ function buildProperties(changedFiles, impactedTargets, universe) {
target_domains: targetDomains,
tripwire_files: tripwireFiles.slice(0, MAX_LISTED),
tripwire_domains: tripwireDomains,
+ // Null when no verdict could be given.
+ cross_lane: crossLane ? crossLane.mixed : null,
+ cross_lane_heavy_files: crossLane ? crossLane.heavyFiles.slice(0, MAX_LISTED) : [],
+ cross_lane_light_files: crossLane ? crossLane.lightFiles.slice(0, MAX_LISTED) : [],
+ cross_lane_heavy_file_count: crossLane ? crossLane.heavyFiles.length : 0,
+ cross_lane_light_file_count: crossLane ? crossLane.lightFiles.length : 0,
// Separates the three ways a PR ends up in one lane: a rule that
// deliberately widened it, a path no rule claimed (the early warning
// that the script needs a rule for a directory someone just added), and
@@ -135,11 +145,23 @@ if (require.main === module) {
} catch (error) {
console.error(`Could not read IMPACTED_TARGETS (${error.message}); reporting the file side only`)
}
+ let context = null
let universe = null
try {
- universe = allKnownTargets(buildContext(REPO_ROOT))
+ context = buildContext(REPO_ROOT)
+ universe = allKnownTargets(context)
} catch (error) {
console.error(`Could not enumerate the target universe (${error.message}); is_all reports the sentinel only`)
}
- process.stdout.write(JSON.stringify(buildProperties(changedFiles, impactedTargets, universe)))
+ let crossLane = null
+ if (context) {
+ try {
+ crossLane = crossLaneFiles(changedFiles, { ...context, deletedFiles: findDeletedFiles(changedFiles) })
+ } catch (error) {
+ console.error(
+ `Could not classify the change set by lane side (${error.message}); cross_lane reports unknown`
+ )
+ }
+ }
+ process.stdout.write(JSON.stringify(buildProperties(changedFiles, impactedTargets, universe, crossLane)))
}
diff --git a/.github/scripts/trunk-lane-telemetry.test.js b/.github/scripts/trunk-lane-telemetry.test.js
index c41ff9a0a242..310fd5b17a09 100644
--- a/.github/scripts/trunk-lane-telemetry.test.js
+++ b/.github/scripts/trunk-lane-telemetry.test.js
@@ -55,7 +55,7 @@ test('the ALL sentinel still reports no targets but is flagged', () => {
// its weight, and it is not recoverable from the paths alone once the split
// exists.
test('tripwire domains are counted alongside the files', () => {
- const props = buildProperties(['.oxlintrc.json', 'mypy.ini', 'hogli.yaml'], UNIVERSE, UNIVERSE)
+ const props = buildProperties(['tsconfig.json', 'mypy.ini', 'hogli.yaml'], UNIVERSE, UNIVERSE)
assert.deepEqual(props.tripwire_domains, { javascript: 1, python: 1, universal: 1 })
})
@@ -67,3 +67,24 @@ test('file paths are summarized rather than sent', () => {
assert.equal(props.changed_file_count, 3)
assert.deepEqual(props.target_domains, { py: 1, fe: 1 })
})
+
+test('the cross-lane verdict and its files ride along, or report unknown', () => {
+ const mixed = buildProperties(['posthog/api/x.py', 'nodejs/src/y.ts'], ['node:ingestion', 'py:core'], UNIVERSE, {
+ mixed: true,
+ heavyFiles: ['posthog/api/x.py'],
+ lightFiles: ['nodejs/src/y.ts'],
+ })
+ assert.equal(mixed.cross_lane, true)
+ assert.deepEqual(mixed.cross_lane_heavy_files, ['posthog/api/x.py'])
+ assert.deepEqual(mixed.cross_lane_light_files, ['nodejs/src/y.ts'])
+
+ const wide = buildProperties([], ['node:ingestion', 'py:core'], UNIVERSE, {
+ mixed: true,
+ heavyFiles: Array.from({ length: 150 }, (_, i) => `posthog/file_${i}.py`),
+ lightFiles: ['nodejs/src/y.ts'],
+ })
+ assert.equal(wide.cross_lane_heavy_files.length, 20)
+ assert.equal(wide.cross_lane_heavy_file_count, 150)
+
+ assert.equal(buildProperties(['nodejs/src/y.ts'], ['node:ingestion'], UNIVERSE).cross_lane, null)
+})
diff --git a/.github/workflows/ci-scripts.yml b/.github/workflows/ci-scripts.yml
index 3ab34056d9ea..c212856a8277 100644
--- a/.github/workflows/ci-scripts.yml
+++ b/.github/workflows/ci-scripts.yml
@@ -16,6 +16,9 @@ on:
# trunk-impacted-targets.test.js reads proto/ and fails on a tree the
# table does not declare, so adding one has to run these tests.
- proto/**
+ # The lane tests guard that both root oxc configs keep ignoring nodejs/.
+ - .oxlintrc.json
+ - .oxfmtrc*
# turbo-discover.test.js pins the Django segment table to these, and checks
# that every path in the events_json list exists.
- .github/workflows/ci-backend.yml
@@ -70,6 +73,8 @@ jobs:
/products/README.md
/services/README.md
/.nvmrc
+ /.oxlintrc.json
+ /.oxfmtrc.json
/owners.yaml
/pnpm-workspace.yaml
/uv.lock
diff --git a/.github/workflows/trunk-impacted-targets.yml b/.github/workflows/trunk-impacted-targets.yml
index 45c4228293fa..da1aaf6424c4 100644
--- a/.github/workflows/trunk-impacted-targets.yml
+++ b/.github/workflows/trunk-impacted-targets.yml
@@ -183,17 +183,17 @@ jobs:
computed="$(node .github/scripts/trunk-impacted-targets.js < "$RUNNER_TEMP/changed-files.txt")"
printf 'targets=%s\n' "$(jq -cn --argjson t "$computed" '{impactedTargets: $t}')" >> "$GITHUB_OUTPUT"
- # Summarizes the change set and the targets for the lane-cost
- # dashboard. Never gates: a telemetry problem must not keep a PR out
- # of the queue. The early exits above leave no file behind, which
- # the script reports as the degraded case rather than as a PR that
- # touched nothing.
+ # Lane-cost telemetry. The cross-lane job gates on its output and
+ # passes if this step fails.
- name: Summarize lane assignment
id: telemetry
if: ${{ !cancelled() }}
continue-on-error: true
env:
IMPACTED_TARGETS: ${{ steps.targets.outputs.targets }}
+ # Same inputs as the upload, for the cross-lane verdict.
+ RUST_AFFECTED_CRATES: ${{ steps.affected.outputs.crates }}
+ LANE_MERGE_BASE: ${{ steps.changes.outputs.merge_base }}
run: |
set -uo pipefail
touch "$RUNNER_TEMP/changed-files.txt"
@@ -337,6 +337,55 @@ jobs:
-H "Content-Type: application/json" \
--data "$event" > /dev/null
+ cross-lane:
+ name: Check the PR does not mix lanes
+ needs: compute
+ # The queue's batch PR is the union of PRs that each passed this check.
+ if: >-
+ ${{
+ !(github.event.pull_request.head.repo.full_name == github.repository &&
+ startsWith(github.head_ref, 'trunk-merge/'))
+ }}
+ runs-on: ubuntu-24.04
+ timeout-minutes: 5
+ permissions: {}
+ steps:
+ - name: Fail when Python or frontend changes ride with Node or Rust changes
+ env:
+ LANE_PROPERTIES: ${{ needs.compute.outputs.telemetry }}
+ OVERRIDDEN: ${{ contains(github.event.pull_request.labels.*.name, 'cross-lane-change') }}
+ run: |
+ set -uo pipefail
+ props="${LANE_PROPERTIES:-}"
+ [ -n "$props" ] || props='{}'
+ verdict="$(printf '%s' "$props" | jq -r 'if .cross_lane == true then "mixed" elif .cross_lane == false then "clean" else "unknown" end' 2>/dev/null || echo unknown)"
+
+ if [ "$verdict" = "clean" ]; then
+ echo "This PR stays on one side of the merge queue lanes."
+ exit 0
+ fi
+ # No verdict means the lane rules could not classify the diff; blocking on that would block on a CI fault.
+ if [ "$verdict" = "unknown" ]; then
+ echo "::notice::Could not classify this PR by lane side; not blocking."
+ exit 0
+ fi
+
+ echo "Python or frontend files:"
+ printf '%s' "$props" | jq -r '.cross_lane_heavy_files[]? | " " + .'
+ echo "Node or Rust files:"
+ printf '%s' "$props" | jq -r '.cross_lane_light_files[]? | " " + .'
+ echo ""
+ echo "The merge queue tests each PR on top of the PRs ahead of it in its lane, so every"
+ echo "Node or Rust PR queued behind this one would run the Django and frontend suites."
+ echo "Split it into separate PRs. hogli ci:preflight reports this before you push."
+
+ if [ "$OVERRIDDEN" = "true" ]; then
+ echo "::warning::This PR mixes lanes and carries the 'cross-lane-change' label, so the check passes."
+ exit 0
+ fi
+ echo "::error::This PR mixes Python or frontend changes with Node or Rust changes. Split it, or, if the halves must land together, add the 'cross-lane-change' label and push again."
+ exit 1
+
comment:
name: Update Trunk lane in CI report
needs: [compute, upload]
diff --git a/tools/hogli-commands/hogli_commands/ci_preflight.py b/tools/hogli-commands/hogli_commands/ci_preflight.py
index 505d6c90d1b4..148c811211bf 100644
--- a/tools/hogli-commands/hogli_commands/ci_preflight.py
+++ b/tools/hogli-commands/hogli_commands/ci_preflight.py
@@ -57,6 +57,7 @@ from hogli_commands.preflight_checks import (
Outcome,
Scope,
Status,
+ check_cross_lane,
check_merge_queue_lane,
check_semgrep_devex,
check_snapshot_baselines,
@@ -357,6 +358,14 @@ DIFF_CHECKS: list[DiffCheck] = [
verify=None,
run=check_semgrep_devex,
),
+ DiffCheck(
+ key="cross-lane",
+ label="Python or frontend changes mixed with Node or Rust changes (fails CI without a label)",
+ triggers=["*"],
+ verify=None,
+ run=check_cross_lane,
+ soft=True,
+ ),
DiffCheck(
key="merge-queue-lane",
label="merge queue lane this diff claims",
diff --git a/tools/hogli-commands/hogli_commands/preflight_checks.py b/tools/hogli-commands/hogli_commands/preflight_checks.py
index 5848f8de1974..6993edc81557 100644
--- a/tools/hogli-commands/hogli_commands/preflight_checks.py
+++ b/tools/hogli-commands/hogli_commands/preflight_checks.py
@@ -8,6 +8,7 @@ import json
import time
import shutil
import tempfile
+import functools
import subprocess
from dataclasses import dataclass
from pathlib import Path
@@ -401,14 +402,37 @@ def _node(script: str, files: list[str], env: dict[str, str]) -> object:
return json.loads(result.stdout)
+@dataclass(frozen=True, kw_only=True, slots=True)
+class Lane:
+ """The diff's lane as CI computes it, shared by both lane checks. Unchecked script output."""
+
+ changed: list[str]
+ targets: object
+ summary: object
+
+
+def _lane(scope: Scope) -> Lane:
+ # CI lists a rename as its old path and its new one, and the old path can widen the lane.
+ changed = tuple(sorted({*scope.changed, *_renamed_from(scope).values()}))
+ return _lane_for(changed, scope.merge_base)
+
+
+def _lane_for(changed: tuple[str, ...], merge_base: str) -> Lane:
+ env = {**os.environ, "LANE_MERGE_BASE": merge_base}
+ targets = _node(LANE_TARGETS_SCRIPT, list(changed), env)
+ summary = _node(
+ LANE_SUMMARY_SCRIPT, list(changed), {**env, "IMPACTED_TARGETS": json.dumps({"impactedTargets": targets})}
+ )
+ return Lane(changed=list(changed), targets=targets, summary=summary)
+
+
def check_merge_queue_lane(scope: Scope) -> Outcome:
if shutil.which("node") is None:
return "skipped", "node not found"
- # CI lists a rename as its old path and its new one, and the old path can widen the lane.
- changed = sorted({*scope.changed, *_renamed_from(scope).values()})
+ computed = _lane(scope)
+ changed, targets, lane = computed.changed, computed.targets, computed.summary
env = {**os.environ, "LANE_MERGE_BASE": scope.merge_base}
- targets = _node(LANE_TARGETS_SCRIPT, changed, env)
- lane = _node(LANE_SUMMARY_SCRIPT, changed, {**env, "IMPACTED_TARGETS": json.dumps({"impactedTargets": targets})})
if not isinstance(lane, dict) or not isinstance(targets, list):
return "skipped", "could not compute the merge queue lane"
if not lane.get("is_all"):
@@ -433,3 +457,34 @@ def check_merge_queue_lane(scope: Scope) -> Outcome:
f"Without these {len(suspects)} file(s) the other changes claim {len(narrowed)} of {len(targets)} "
f"lane targets: {', '.join(suspects[:3])}{more}",
)
+
+
+CROSS_LANE_LABEL = "cross-lane-change"
+
+
+def _first(files: list[str], total: int) -> str:
+ count = max(total, len(files))
+ more = f" (+{count - 2} more)" if count > 2 else ""
+ return ", ".join(files[:2]) + more
+
+
+def check_cross_lane(scope: Scope) -> Outcome:
+ if shutil.which("node") is None:
+ return "skipped", "node not found"
+ lane = _lane(scope).summary
+ verdict = lane.get("cross_lane") if isinstance(lane, dict) else None
+ if verdict is False:
+ return "pass", "stays on one side of the merge queue lanes"
+ if verdict is not True:
+ return "skipped", "could not classify the diff by lane side"
+ assert isinstance(lane, dict)
+ mixed = (
+ f"mixes Python or frontend files "
+ f"({_first(lane.get('cross_lane_heavy_files') or [], lane.get('cross_lane_heavy_file_count') or 0)}) "
+ f"with Node or Rust files "
+ f"({_first(lane.get('cross_lane_light_files') or [], lane.get('cross_lane_light_file_count') or 0)})"
+ )
+ return (
+ "warning",
+ f"{mixed}, which fails CI. Split the PR, or add the {CROSS_LANE_LABEL} label if the halves must land together",
+ )
diff --git a/tools/hogli-commands/hogli_commands/tests/test_preflight_checks.py b/tools/hogli-commands/hogli_commands/tests/test_preflight_checks.py
index 4769cfac7c77..597bc9849271 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_preflight_checks.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_preflight_checks.py
@@ -10,10 +10,12 @@ import pytest
from unittest.mock import MagicMock, patch
from hogli.telemetry import _CI_ENV_VARS
+from hogli_commands import preflight_checks
from hogli_commands.preflight_checks import (
Finding,
Scope,
SemgrepUnavailable,
+ check_cross_lane,
check_merge_queue_lane,
check_semgrep_devex,
check_snapshot_baselines,
@@ -307,6 +309,11 @@ def _node_output(payload: object) -> subprocess.CompletedProcess[str]:
return subprocess.CompletedProcess(args=[], returncode=0, stdout=json.dumps(payload), stderr="")
[email protected](autouse=True)
+def fresh_lane_cache() -> None:
+ preflight_checks._lane_for.cache_clear()
+
+
def _widened(listed: int, total: int) -> dict[str, object]:
files = [WORKFLOW, *(f".github/workflows/{n}.yml" for n in range(listed - 1))]
return {"is_all": True, "tripwire_files": files, "tripwire_domains": {"universal": total}}
@@ -341,3 +348,45 @@ class TestMergeQueueLane:
assert status == expected_status
if expected_status == "warning":
assert WORKFLOW in detail
+
+
+MIXED = {"cross_lane": True, "cross_lane_heavy_files": [PRODUCT_FILE], "cross_lane_light_files": ["nodejs/a.ts"]}
+
+
+class TestCrossLane:
+ @pytest.mark.parametrize(
+ "summary,expected_status",
+ [
+ ({"cross_lane": False}, "pass"),
+ ({"cross_lane": None}, "skipped"),
+ (MIXED, "warning"),
+ ],
+ )
+ @patch("hogli_commands.preflight_checks._renamed_from", return_value={})
+ @patch("hogli_commands.preflight_checks.shutil.which", return_value="/usr/bin/node")
+ def test_warns_on_a_mixed_diff(
+ self,
+ mock_which: MagicMock,
+ mock_renames: MagicMock,
+ summary: dict[str, object],
+ expected_status: str,
+ ) -> None:
+ runs = [_node_output(EVERY_LANE), _node_output(summary)]
+ with patch("hogli_commands.preflight_checks.subprocess.run", side_effect=runs):
+ status, detail = check_cross_lane(_scope([PRODUCT_FILE, "nodejs/a.ts"]))
+
+ assert status == expected_status
+ if expected_status == "warning":
+ assert PRODUCT_FILE in detail and "nodejs/a.ts" in detail
+
+ @patch("hogli_commands.preflight_checks._renamed_from", return_value={})
+ @patch("hogli_commands.preflight_checks.shutil.which", return_value="/usr/bin/node")
+ def test_shares_one_lane_computation_with_the_lane_check(
+ self, mock_which: MagicMock, mock_renames: MagicMock
+ ) -> None:
+ runs = [_node_output(["py:core"]), _node_output({**MIXED, "is_all": False})]
+ with patch("hogli_commands.preflight_checks.subprocess.run", side_effect=runs) as run:
+ check_cross_lane(_scope([PRODUCT_FILE, "nodejs/a.ts"]))
+ check_merge_queue_lane(_scope([PRODUCT_FILE, "nodejs/a.ts"]))
+
+ assert run.call_count == 2