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.

fix(ci): split nodejs into import-derived merge queue lanes (#110140)

Georges-Antoine Assif73c38df2338
diff --git a/.github/scripts/trunk-impacted-targets.js b/.github/scripts/trunk-impacted-targets.js
index 2dd1c0a7af92..76eac4399e4a 100644
--- a/.github/scripts/trunk-impacted-targets.js
+++ b/.github/scripts/trunk-impacted-targets.js
@@ -100,6 +100,7 @@
// prose-only PRs.
// Diagnostics on stderr
+const { execFileSync } = require('child_process')
const fs = require('fs')
const path = require('path')
@@ -153,11 +154,12 @@ const SEMGREP = 'semgrep'
// moved, degrading to every crate when that answer is absent.
const CARGO_LOCK = 'cargo-lock'
-// The nodejs lane on its own, for files whose only reader is the ingestion
-// suite or an image built from nodejs/ sources and native bindings that claim
-// this lane already. The rust and proto rules also use it to name that lane
+// The nodejs lanes on their own, for files whose only readers are the nodejs
+// suites or an image built from nodejs/ sources and native bindings that claim
+// these lanes already. The rust and proto rules also use it to name those lanes
// without dragging in the frontend.
const NODE = 'node'
+const JS_LOCKFILE = 'js-lockfile'
// Suites that run the backend and the frontend together: E2E, Hog, and the
// builds of the images those suites run inside. Both language families in
@@ -560,8 +562,8 @@ const TRIPWIRE_RULES = [
// PR, and the shape that reaches a python lane is lockfile drift against a
// workspace package.json, which needs both PRs to edit pnpm-lock.yaml and
// so surfaces as a textual conflict git forces a rebase for.
- ['pnpm-lock.yaml', JAVASCRIPT],
- ['pnpm-workspace.yaml', JAVASCRIPT],
+ ['pnpm-lock.yaml', JS_LOCKFILE],
+ ['pnpm-workspace.yaml', JS_LOCKFILE],
['package.json', JAVASCRIPT],
// The python lockfile and manifests, on the same reasoning. Every section
// of pyproject.toml configures a python tool, and nothing in the pnpm
@@ -598,7 +600,7 @@ const TRIPWIRE_RULES = [
// workflow or suite, whose rule above already carries the radius.
// Dockerfile.llm-analytics is built only by its master-push CD workflow,
// Dockerfile.ml-mirror-image-scrub only from nodejs/ sources and the
- // replay-anonymizer addon, whose changes already claim the node lane, and the
+ // replay-anonymizer addon, whose changes already claim the node lanes, and the
// playwright and sandbox images host suites that run both language
// families. Everything else at the root, the unified app image included,
// backs E2E, hobby, and production, which is the app-image radius; no
@@ -1514,9 +1516,15 @@ const RUST_DETERMINATOR = 'rust:determinator'
// and the test suite re-derives that from pnpm-workspace.yaml so a second
// dependent fails there rather than silently going unclaimed here. The
// image-scrub sidecar under nodejs/src/ingestion loads the replay-anonymizer
-// addon too, built from the crate rather than installed from the package, and
-// it sits in this same lane.
-const NATIVE_BINDING_CONSUMER_LANES = ['node:ingestion']
+// addon too, built from the crate rather than installed from the package.
+// A binding change claims every node lane.
+const NODE_INGESTION = 'node:ingestion'
+const NODE_SUB_LANES = [
+ ['node:recording-rasterizer', 'nodejs/src/session-replay/recording-rasterizer'],
+ ['node:cdp', 'nodejs/src/cdp'],
+]
+const NODE_LANES = [NODE_INGESTION, ...NODE_SUB_LANES.map(([lane]) => lane)]
+const NATIVE_BINDING_CONSUMER_LANES = NODE_LANES
// Every target this script can emit. A widening decision names this set instead
// of the "ALL" sentinel, so the set intersection Trunk computes is unchanged
@@ -1539,7 +1547,6 @@ function allKnownTargets(context) {
const targets = new Set([
'py:core',
'fe:core',
- 'node:ingestion',
'agents',
'deploy',
'hobby',
@@ -1548,6 +1555,9 @@ function allKnownTargets(context) {
'ownership',
'ci-tooling',
])
+ for (const lane of NODE_LANES) {
+ targets.add(lane)
+ }
for (const product of products) {
targets.add(pyProduct(product))
targets.add(feProduct(product))
@@ -1605,7 +1615,9 @@ function addJavaScriptLanes(targets, context) {
}
// The pnpm workspace spans frontend, nodejs, services, tools, and products,
// and ci-cli.yml builds the CLI from services/mcp sources.
- targets.add('node:ingestion')
+ for (const lane of NODE_LANES) {
+ targets.add(lane)
+ }
for (const service of context.services) {
targets.add(`svc:${service}`)
}
@@ -1669,7 +1681,28 @@ function addCargoLockLanes(targets, context) {
}
function addNodeLanes(targets) {
- targets.add('node:ingestion')
+ for (const lane of NODE_LANES) {
+ targets.add(lane)
+ }
+ return true
+}
+
+function addJsLockfileLanes(targets, context) {
+ const lanes = new Set()
+ if (!addJavaScriptLanes(lanes, context)) {
+ return false
+ }
+ const reached = context.jsLockfileNodeLanes ? context.jsLockfileNodeLanes() : null
+ if (reached) {
+ for (const lane of NODE_LANES) {
+ if (!reached.has(lane)) {
+ lanes.delete(lane)
+ }
+ }
+ }
+ for (const lane of lanes) {
+ targets.add(lane)
+ }
return true
}
@@ -1816,6 +1849,7 @@ function addProtoLanes(targets, context, file) {
const DOMAIN_LANES = new Map([
[PYTHON, addPythonLanes],
[JAVASCRIPT, addJavaScriptLanes],
+ [JS_LOCKFILE, addJsLockfileLanes],
[RUST, addRustLanes],
[CARGO_LOCK, addCargoLockLanes],
[NODE, addNodeLanes],
@@ -1970,6 +2004,10 @@ function computeTargets(changedFiles, context) {
continue
}
+ for (const lane of nodeLanesForWorkspaceFile(file, context)) {
+ targets.add(lane)
+ }
+
if (top === 'posthog' || (top === 'ee' && segments[1] !== 'frontend')) {
allPyProducts()
continue
@@ -1990,7 +2028,9 @@ function computeTargets(changedFiles, context) {
continue
}
if (top === 'nodejs') {
- targets.add('node:ingestion')
+ for (const lane of nodeLanesForSource(file, context)) {
+ targets.add(lane)
+ }
continue
}
if (top === 'services' && segments.length > 1) {
@@ -2327,13 +2367,571 @@ function parseRustAffectedCrates(raw, rustInventory) {
return crates
}
+const NODE_SOURCE_ROOT = 'nodejs/src'
+const NODE_TESTS_ROOT = 'nodejs/tests'
+const NODE_IMPORT_ROOTS = [NODE_SOURCE_ROOT, NODE_TESTS_ROOT]
+const NODE_IMPORTER = 'nodejs'
+const ROOT_IMPORTER = '.'
+const NODE_SPECIFIER = String.raw`([^'"\s\x60$]+)`
+const NODE_IMPORT_PATTERNS = [
+ new RegExp(String.raw`\bfrom\s*['"]${NODE_SPECIFIER}['"]`, 'g'),
+ new RegExp(String.raw`\bimport\s*['"]${NODE_SPECIFIER}['"]`, 'g'),
+ new RegExp(String.raw`\bimport\(\s*['"]${NODE_SPECIFIER}['"]\s*\)`, 'g'),
+ new RegExp(String.raw`\brequire\(\s*['"]${NODE_SPECIFIER}['"]\s*\)`, 'g'),
+ new RegExp(String.raw`\bjest\.(?:mock|requireActual)\(\s*['"]${NODE_SPECIFIER}['"]`, 'g'),
+]
+const NODE_RESOLVE_SUFFIXES = ['', '.ts', '.tsx', '.js', '.json', '.d.ts', '/index.ts', '/index.tsx', '/index.js']
+const NODE_SOURCE_EXTENSIONS = /\.(ts|tsx|js|mjs|cjs)$/
+const NODE_BUILTINS = new Set(require('module').builtinModules)
+const NODE_WORKSPACE_FALLBACK_DIRS = ['common/hogvm', 'common/replay-headless', 'common/replay-shared']
+
+function nodeSubLaneOf(file) {
+ const match = NODE_SUB_LANES.find(([, dir]) => file.startsWith(`${dir}/`))
+ return match ? match[0] : null
+}
+
+function isNodeEntryPoint(file) {
+ if (!file.startsWith(`${NODE_SOURCE_ROOT}/`)) {
+ return true
+ }
+ const rest = file.slice(NODE_SOURCE_ROOT.length + 1)
+ return !rest.includes('/') || rest.startsWith('servers/')
+}
+
+function nodeOwnerLane(file) {
+ return nodeSubLaneOf(file) || (isNodeEntryPoint(file) ? null : NODE_INGESTION)
+}
+
+function nodeImportSpecifiers(text) {
+ const specifiers = []
+ for (const pattern of NODE_IMPORT_PATTERNS) {
+ for (const match of text.matchAll(pattern)) {
+ specifiers.push(match[1])
+ }
+ }
+ return specifiers
+}
+
+function nodeImportBase(fromFile, specifier) {
+ if (specifier.startsWith('~/tests/')) {
+ return `${NODE_TESTS_ROOT}/${specifier.slice('~/tests/'.length)}`
+ }
+ if (specifier.startsWith('~/')) {
+ return `${NODE_SOURCE_ROOT}/${specifier.slice(2)}`
+ }
+ if (specifier.startsWith('.')) {
+ return path.posix.normalize(path.posix.join(path.posix.dirname(fromFile), specifier))
+ }
+ return undefined
+}
+
+function resolveNodeImport(repoRoot, fromFile, specifier) {
+ const base = nodeImportBase(fromFile, specifier)
+ if (base === undefined) {
+ return undefined
+ }
+ const stems = base.endsWith('.js') ? [base, base.slice(0, -3)] : [base]
+ for (const stem of stems) {
+ for (const suffix of NODE_RESOLVE_SUFFIXES) {
+ const candidate = `${stem}${suffix}`
+ const absolute = path.join(repoRoot, candidate)
+ if (fs.existsSync(absolute) && fs.statSync(absolute).isFile()) {
+ return candidate
+ }
+ }
+ }
+ return null
+}
+
+function nodePackageName(specifier) {
+ if (specifier.startsWith('node:') || NODE_BUILTINS.has(specifier.split('/')[0])) {
+ return null
+ }
+ const segments = specifier.split('/')
+ return specifier.startsWith('@') ? segments.slice(0, 2).join('/') : segments[0]
+}
+
+function listFilesUnder(repoRoot, relativeDir) {
+ const files = []
+ const walk = (dir) => {
+ for (const entry of fs.readdirSync(path.join(repoRoot, dir), { withFileTypes: true })) {
+ const child = `${dir}/${entry.name}`
+ if (entry.isDirectory()) {
+ if (entry.name !== 'node_modules') {
+ walk(child)
+ }
+ } else if (NODE_SOURCE_EXTENSIONS.test(entry.name)) {
+ files.push(child)
+ }
+ }
+ }
+ walk(relativeDir)
+ return files
+}
+
+function readNodeImports(repoRoot) {
+ const edges = new Map()
+ const roots = NODE_IMPORT_ROOTS.filter((dir) => fs.existsSync(path.join(repoRoot, dir)))
+ for (const file of roots.flatMap((dir) => listFilesUnder(repoRoot, dir))) {
+ const imports = { files: [], packages: new Set() }
+ for (const specifier of nodeImportSpecifiers(fs.readFileSync(path.join(repoRoot, file), 'utf8'))) {
+ const resolved = resolveNodeImport(repoRoot, file, specifier)
+ if (resolved === undefined) {
+ const name = nodePackageName(specifier)
+ if (name) {
+ imports.packages.add(name)
+ }
+ continue
+ }
+ if (resolved === null) {
+ const subLane = nodeSubLaneOf(file)
+ if (subLane && nodeSubLaneOf(nodeImportBase(file, specifier)) === subLane) {
+ continue
+ }
+ console.error(`Could not resolve ${specifier} from ${file}; every nodejs file claims every node lane`)
+ return null
+ }
+ imports.files.push(resolved)
+ }
+ edges.set(file, imports)
+ }
+ return edges
+}
+
+function loadNodeLaneMap(repoRoot) {
+ if (!fs.existsSync(path.join(repoRoot, NODE_SOURCE_ROOT))) {
+ return null
+ }
+ let edges
+ try {
+ edges = readNodeImports(repoRoot)
+ } catch (error) {
+ console.error(`Could not map the nodejs imports (${error.message}); every nodejs file claims every node lane`)
+ return null
+ }
+ if (!edges) {
+ return null
+ }
+ const fileLanes = new Map()
+ const packageLanes = new Map()
+ const claim = (map, key, lane) => {
+ if (!map.has(key)) {
+ map.set(key, new Set())
+ }
+ map.get(key).add(lane)
+ }
+ for (const lane of NODE_LANES) {
+ const queue = [...edges.keys()].filter((file) => nodeOwnerLane(file) === lane)
+ const seen = new Set()
+ while (queue.length > 0) {
+ const file = queue.pop()
+ if (seen.has(file)) {
+ continue
+ }
+ seen.add(file)
+ claim(fileLanes, file, lane)
+ const imports = edges.get(file)
+ if (!imports) {
+ continue
+ }
+ for (const name of imports.packages) {
+ claim(packageLanes, name, lane)
+ }
+ queue.push(...imports.files)
+ }
+ }
+ for (const [file, imports] of edges) {
+ if (nodeOwnerLane(file) === null) {
+ for (const name of imports.packages) {
+ for (const lane of NODE_LANES) {
+ claim(packageLanes, name, lane)
+ }
+ }
+ }
+ }
+ return { fileLanes, packageLanes }
+}
+
+function nodeLanesForSource(file, context) {
+ const map = context.nodeLaneMap
+ const deleted = context.deletedFiles && context.deletedFiles.has(file)
+ if (!map || !file.startsWith(`${NODE_SOURCE_ROOT}/`) || file.endsWith('.d.ts') || deleted) {
+ return NODE_LANES
+ }
+ const owner = nodeOwnerLane(file)
+ if (owner === null) {
+ return NODE_LANES
+ }
+ const lanes = map.fileLanes.get(file)
+ return lanes ? [...lanes] : [owner]
+}
+
+function nodeLanesForPackage(name, context) {
+ const lanes = context.nodeLaneMap && context.nodeLaneMap.packageLanes.get(name)
+ return lanes ? [...lanes] : NODE_LANES
+}
+
+function unquoteYamlKey(key) {
+ return key.replace(/^(['"])(.*)\1$/, '$2')
+}
+
+function parsePnpmLockfile(text) {
+ const sections = new Map()
+ let section = null
+ let entry = null
+ for (const line of text.split('\n')) {
+ if (!line.trim()) {
+ continue
+ }
+ const top = line.match(/^([^\s#][^:]*):\s*(.*)$/)
+ if (top) {
+ section = { scalar: top[2], entries: new Map() }
+ sections.set(top[1], section)
+ entry = null
+ continue
+ }
+ if (!section) {
+ return null
+ }
+ const key = line.match(/^ {2}('[^']*'|"[^"]*"|[^\s'"].*?):(?:\s+(.*))?$/)
+ if (key) {
+ entry = { lines: key[2] ? [key[2].trim()] : [] }
+ section.entries.set(unquoteYamlKey(key[1]), entry)
+ continue
+ }
+ if (entry) {
+ entry.lines.push(line)
+ } else {
+ section.entries.set(line, { lines: [] })
+ }
+ }
+ return sections
+}
+
+function importerDependencies(entry) {
+ const dependencies = []
+ let current = null
+ for (const line of entry.lines) {
+ const dependency = line.match(/^ {6}(\S.*?):\s*$/)
+ if (dependency) {
+ current = { name: unquoteYamlKey(dependency[1]), lines: [line] }
+ continue
+ }
+ if (current && /^ {8}/.test(line)) {
+ current.lines.push(line)
+ const version = line.match(/^ {8}version:\s*(.+)$/)
+ if (version) {
+ dependencies.push({ ...current, version: unquoteYamlKey(version[1].trim()) })
+ current = null
+ }
+ }
+ }
+ return dependencies
+}
+
+function snapshotDependencies(entry) {
+ const dependencies = []
+ let group = null
+ for (const line of entry.lines) {
+ const header = line.match(/^ {4}(\S+):\s*$/)
+ if (header) {
+ group = header[1]
+ continue
+ }
+ const dependency = line.match(/^ {6}(\S.*?):\s*(.+)$/)
+ if (dependency && (group === 'dependencies' || group === 'optionalDependencies')) {
+ dependencies.push({ name: unquoteYamlKey(dependency[1]), version: unquoteYamlKey(dependency[2].trim()) })
+ }
+ }
+ return dependencies
+}
+
+function snapshotKey(name, version) {
+ const atIndex = version.indexOf('@', 1)
+ const parenIndex = version.indexOf('(')
+ const isAlias = atIndex > 0 && (parenIndex === -1 || atIndex < parenIndex)
+ return isAlias ? version : `${name}@${version}`
+}
+
+function linkTarget(importer, version) {
+ return path.posix.normalize(path.posix.join(importer, version.slice('link:'.length)))
+}
+
+const PNPM_LOCK_RESOLUTION_SECTIONS = new Set(['importers', 'packages', 'snapshots', 'catalogs'])
+
+class LockfileWalkError extends Error {}
+
+function dependencyFingerprint(lockfile, dependency, fromImporter, isWorkspaceMember) {
+ const importers = lockfile.get('importers')
+ const snapshots = lockfile.get('snapshots')
+ const packages = lockfile.get('packages')
+ const parts = [dependency.lines.join('\n')]
+ const pendingImporters = []
+ const pendingSnapshots = []
+ if (dependency.version.startsWith('link:')) {
+ pendingImporters.push(linkTarget(fromImporter, dependency.version))
+ } else {
+ pendingSnapshots.push(snapshotKey(dependency.name, dependency.version))
+ }
+ const seenImporters = new Set()
+ const seenSnapshots = new Set()
+ while (pendingImporters.length > 0 || pendingSnapshots.length > 0) {
+ if (pendingImporters.length > 0) {
+ const importer = pendingImporters.pop()
+ if (seenImporters.has(importer)) {
+ continue
+ }
+ seenImporters.add(importer)
+ const entry = importers.entries.get(importer)
+ if (!entry) {
+ if (!isWorkspaceMember(importer)) {
+ throw new LockfileWalkError(`the lockfile links ${importer}, which no workspace glob names`)
+ }
+ parts.push(`importer:${importer}:`)
+ continue
+ }
+ parts.push(`importer:${importer}:${entry.lines.join('\n')}`)
+ for (const next of importerDependencies(entry)) {
+ if (next.version.startsWith('link:')) {
+ pendingImporters.push(linkTarget(importer, next.version))
+ } else {
+ pendingSnapshots.push(snapshotKey(next.name, next.version))
+ }
+ }
+ continue
+ }
+ const key = pendingSnapshots.pop()
+ if (seenSnapshots.has(key)) {
+ continue
+ }
+ seenSnapshots.add(key)
+ const snapshot = snapshots.entries.get(key)
+ const packageKey = key.includes('(', 1) ? key.slice(0, key.indexOf('(', 1)) : key
+ const packageEntry = packages.entries.get(packageKey)
+ if (!snapshot || !packageEntry) {
+ throw new LockfileWalkError(`the lockfile has no entry for ${key}`)
+ }
+ parts.push(`snapshot:${key}:${snapshot.lines.join('\n')}\n${packageEntry.lines.join('\n')}`)
+ for (const next of snapshotDependencies(snapshot)) {
+ if (!next.version.startsWith('link:')) {
+ pendingSnapshots.push(snapshotKey(next.name, next.version))
+ }
+ }
+ }
+ return parts.sort().join('\n\n')
+}
+
+function nodeDependencyFingerprints(lockfile, isWorkspaceMember) {
+ const importers = lockfile.get('importers')
+ if (!importers || !lockfile.get('snapshots') || !lockfile.get('packages')) {
+ throw new LockfileWalkError('the lockfile has no importers, packages or snapshots section')
+ }
+ const entry = importers.entries.get(NODE_IMPORTER)
+ if (!entry) {
+ throw new LockfileWalkError(`the lockfile has no importer ${NODE_IMPORTER}`)
+ }
+ const fingerprints = { node: new Map(), root: new Map() }
+ for (const dependency of importerDependencies(entry)) {
+ fingerprints.node.set(
+ dependency.name,
+ dependencyFingerprint(lockfile, dependency, NODE_IMPORTER, isWorkspaceMember)
+ )
+ }
+ const root = importers.entries.get(ROOT_IMPORTER)
+ for (const dependency of root ? importerDependencies(root) : []) {
+ fingerprints.root.set(
+ dependency.name,
+ dependencyFingerprint(lockfile, dependency, ROOT_IMPORTER, isWorkspaceMember)
+ )
+ }
+ return fingerprints
+}
+
+function changedDependencies(base, head) {
+ return [...new Set([...base.keys(), ...head.keys()])].filter((name) => base.get(name) !== head.get(name))
+}
+
+function nonResolutionSections(lockfile) {
+ return JSON.stringify(
+ [...lockfile.entries()]
+ .filter(([name]) => !PNPM_LOCK_RESOLUTION_SECTIONS.has(name))
+ .map(([name, section]) => [
+ name,
+ section.scalar,
+ [...section.entries.entries()].map(([key, entry]) => [key, entry.lines]),
+ ])
+ )
+}
+
+function workspaceWithoutCatalogs(text) {
+ const kept = []
+ let inCatalog = false
+ for (const line of text.split('\n')) {
+ if (/^\S/.test(line)) {
+ inCatalog = /^catalogs?:/.test(line)
+ }
+ if (!inCatalog && line.trim() && !line.trim().startsWith('#')) {
+ kept.push(line.trimEnd())
+ }
+ }
+ return kept.join('\n')
+}
+
+function workspaceMembership(workspace) {
+ const matcher = compileWorkspaceMatcher(parseWorkspacePackageGlobs(workspace))
+ return (importer) => Boolean(matcher) && matcher(`${importer}/package.json`)
+}
+
+function jsLockfileNodeLanes({ baseLockfile, headLockfile, baseWorkspace, headWorkspace, nodeLaneMap }) {
+ if (baseLockfile == null || headLockfile == null || baseWorkspace == null || headWorkspace == null) {
+ return null
+ }
+ const allLanes = new Set(NODE_LANES)
+ if (workspaceWithoutCatalogs(baseWorkspace) !== workspaceWithoutCatalogs(headWorkspace)) {
+ return allLanes
+ }
+ const base = parsePnpmLockfile(baseLockfile)
+ const head = parsePnpmLockfile(headLockfile)
+ if (!base || !head) {
+ return null
+ }
+ if (nonResolutionSections(base) !== nonResolutionSections(head)) {
+ return allLanes
+ }
+ let baseFingerprints
+ let headFingerprints
+ try {
+ baseFingerprints = nodeDependencyFingerprints(base, workspaceMembership(baseWorkspace))
+ headFingerprints = nodeDependencyFingerprints(head, workspaceMembership(headWorkspace))
+ } catch (error) {
+ if (error instanceof LockfileWalkError) {
+ console.error(`${error.message}; a JS lockfile change claims every node lane`)
+ return null
+ }
+ throw error
+ }
+ const changed = [
+ ...changedDependencies(baseFingerprints.node, headFingerprints.node),
+ ...changedDependencies(baseFingerprints.root, headFingerprints.root).filter(
+ (name) => !baseFingerprints.node.has(name) && !headFingerprints.node.has(name)
+ ),
+ ]
+ return new Set(changed.flatMap((name) => nodeLanesForPackage(name, { nodeLaneMap })))
+}
+
+function nodeWorkspaceDependencies(headLockfile) {
+ const lockfile = headLockfile && parsePnpmLockfile(headLockfile)
+ const importers = lockfile && lockfile.get('importers')
+ const entry = importers && importers.entries.get(NODE_IMPORTER)
+ if (!entry) {
+ return null
+ }
+ const dirs = new Map()
+ for (const dependency of importerDependencies(entry)) {
+ if (!dependency.version.startsWith('link:')) {
+ continue
+ }
+ const pending = [linkTarget(NODE_IMPORTER, dependency.version)]
+ while (pending.length > 0) {
+ const dir = pending.pop()
+ if (!dirs.has(dir)) {
+ dirs.set(dir, new Set())
+ }
+ if (dirs.get(dir).has(dependency.name)) {
+ continue
+ }
+ dirs.get(dir).add(dependency.name)
+ const linked = importers.entries.get(dir)
+ for (const next of linked ? importerDependencies(linked) : []) {
+ if (next.version.startsWith('link:')) {
+ pending.push(linkTarget(dir, next.version))
+ }
+ }
+ }
+ }
+ return dirs
+}
+
+function nodeLanesForWorkspaceFile(file, context) {
+ const dirs = context.nodeWorkspaceDependencies
+ if (!dirs) {
+ return NODE_WORKSPACE_FALLBACK_DIRS.some((dir) => file.startsWith(`${dir}/`)) ? NODE_LANES : []
+ }
+ const lanes = new Set()
+ for (const [dir, dependencies] of dirs) {
+ if (file.startsWith(`${dir}/`)) {
+ for (const name of dependencies) {
+ for (const lane of nodeLanesForPackage(name, context)) {
+ lanes.add(lane)
+ }
+ }
+ }
+ }
+ return [...lanes]
+}
+
+const LANE_MERGE_BASE_ENV = 'LANE_MERGE_BASE'
+
+function readOptional(file) {
+ try {
+ return fs.readFileSync(file, 'utf8')
+ } catch (error) {
+ console.error(`Could not read ${file} (${error.message}); a JS lockfile change claims every node lane`)
+ return null
+ }
+}
+
+function readAtRevision(repoRoot, revision, file) {
+ try {
+ return execFileSync('git', ['show', `${revision}:${file}`], {
+ cwd: repoRoot,
+ encoding: 'utf8',
+ maxBuffer: 256 * 1024 * 1024,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ })
+ } catch (error) {
+ console.error(
+ `Could not read ${file} at ${revision} (${error.message}); a JS lockfile change claims every node lane`
+ )
+ return null
+ }
+}
+
+function jsLockfileNodeLanesLoader(repoRoot, nodeLaneMap, headLockfile) {
+ let answer
+ return () => {
+ if (answer !== undefined) {
+ return answer
+ }
+ const mergeBase = process.env[LANE_MERGE_BASE_ENV] || ''
+ if (!/^[0-9a-f]{40}$/.test(mergeBase)) {
+ console.error(`${LANE_MERGE_BASE_ENV} is not a commit id; a JS lockfile change claims every node lane`)
+ answer = null
+ return answer
+ }
+ answer = jsLockfileNodeLanes({
+ baseLockfile: readAtRevision(repoRoot, mergeBase, 'pnpm-lock.yaml'),
+ baseWorkspace: readAtRevision(repoRoot, mergeBase, 'pnpm-workspace.yaml'),
+ headLockfile,
+ headWorkspace: readOptional(path.join(repoRoot, 'pnpm-workspace.yaml')),
+ nodeLaneMap,
+ })
+ return answer
+ }
+}
+
function buildContext(repoRoot) {
const products = listProducts(repoRoot)
const tachGraph = loadTachGraph(repoRoot)
const rustInventory = loadRustInventory(repoRoot)
const contractSurfaces = loadContractSurfaces(repoRoot, products)
+ const nodeLaneMap = loadNodeLaneMap(repoRoot)
+ const headLockfile = readOptional(path.join(repoRoot, 'pnpm-lock.yaml'))
return {
products,
+ nodeLaneMap,
+ nodeWorkspaceDependencies: nodeWorkspaceDependencies(headLockfile),
+ jsLockfileNodeLanes: jsLockfileNodeLanesLoader(repoRoot, nodeLaneMap, headLockfile),
rustAffectedCrates: parseRustAffectedCrates(process.env[RUST_AFFECTED_CRATES_ENV], rustInventory),
services: listServices(repoRoot),
isolatedProducts: listIsolatedProducts(repoRoot, products, contractSurfaces),
@@ -2349,6 +2947,10 @@ function buildContext(repoRoot) {
module.exports = {
computeTargets,
+ jsLockfileNodeLanes,
+ loadNodeLaneMap,
+ NODE_LANES,
+ NODE_SUB_LANES,
allKnownTargets,
buildContext,
compileContractMatcher,
diff --git a/.github/scripts/trunk-impacted-targets.test.js b/.github/scripts/trunk-impacted-targets.test.js
index d73c93d5aa1c..f6bc1dc4c2c2 100644
--- a/.github/scripts/trunk-impacted-targets.test.js
+++ b/.github/scripts/trunk-impacted-targets.test.js
@@ -16,6 +16,10 @@ const path = require('node:path')
const {
computeTargets,
+ jsLockfileNodeLanes,
+ loadNodeLaneMap,
+ NODE_LANES,
+ NODE_SUB_LANES,
allKnownTargets,
buildContext,
parseRustAffectedCrates,
@@ -819,15 +823,375 @@ test('the agent-skills workflow claims both language families', () => {
assert.deepEqual(targets, computeTargets(['mypy.ini', '.oxlintrc.json'], CONTEXT))
})
-test('the ml-mirror sidecar image and its workflow stay on the node lane', () => {
+test('the ml-mirror sidecar image and its workflow stay on the node lanes', () => {
for (const file of [
'.github/workflows/ci-ml-mirror-image-scrub-container.yml',
'Dockerfile.ml-mirror-image-scrub',
]) {
- assert.deepEqual(computeTargets([file], CONTEXT), ['node:ingestion'], file)
+ assert.deepEqual(computeTargets([file], CONTEXT), [...NODE_LANES].sort(), file)
}
})
+const [RASTERIZER_LANE, RASTERIZER_DIR] = NODE_SUB_LANES.find(([lane]) => lane === 'node:recording-rasterizer')
+const [CDP_LANE] = NODE_SUB_LANES.find(([lane]) => lane === 'node:cdp')
+const ALL_NODE_LANES = [...NODE_LANES].sort()
+
+const NODE_CONTEXT = {
+ ...CONTEXT,
+ nodeLaneMap: {
+ fileLanes: new Map([
+ ['nodejs/src/cdp/hog-executor.ts', new Set([CDP_LANE])],
+ ['nodejs/src/cdp/types.ts', new Set([CDP_LANE, 'node:ingestion'])],
+ ['nodejs/src/ingestion/pipelines/step.ts', new Set(['node:ingestion'])],
+ [`${RASTERIZER_DIR}/capture/player.ts`, new Set([RASTERIZER_LANE])],
+ ]),
+ packageLanes: new Map([
+ ['@posthog/replay-headless', new Set([RASTERIZER_LANE])],
+ ['@posthog/hogvm', new Set([CDP_LANE, 'node:ingestion'])],
+ ]),
+ },
+ nodeWorkspaceDependencies: new Map([
+ ['common/hogvm/typescript', new Set(['@posthog/hogvm'])],
+ ['common/replay-headless', new Set(['@posthog/replay-headless'])],
+ ['common/replay-shared', new Set(['@posthog/replay-headless'])],
+ ]),
+}
+
+test('a nodejs file claims every node lane whose imports reach it', () => {
+ const cases = [
+ ['nodejs/src/cdp/hog-executor.ts', NODE_CONTEXT, [CDP_LANE]],
+ ['nodejs/src/cdp/types.ts', NODE_CONTEXT, [CDP_LANE, 'node:ingestion'].sort()],
+ ['nodejs/src/ingestion/pipelines/step.ts', NODE_CONTEXT, ['node:ingestion']],
+ [`${RASTERIZER_DIR}/capture/player.ts`, NODE_CONTEXT, [RASTERIZER_LANE]],
+ ['nodejs/src/cdp/not-imported-yet.json', NODE_CONTEXT, [CDP_LANE]],
+ ['nodejs/src/servers/cdp-api-server.ts', NODE_CONTEXT, ALL_NODE_LANES],
+ ['nodejs/src/index.ts', NODE_CONTEXT, ALL_NODE_LANES],
+ ['nodejs/src/types/ambient.d.ts', NODE_CONTEXT, ALL_NODE_LANES],
+ ['nodejs/package.json', NODE_CONTEXT, ALL_NODE_LANES],
+ ['nodejs/tests/helpers/kafka.ts', NODE_CONTEXT, ALL_NODE_LANES],
+ ['nodejs/src/cdp/hog-executor.ts', CONTEXT, ALL_NODE_LANES],
+ ]
+ for (const [file, context, expected] of cases) {
+ assert.deepEqual(computeTargets([file], context), expected, file)
+ }
+ const deleted = 'nodejs/src/cdp/gone.ts'
+ assert.deepEqual(computeTargets([deleted], { ...NODE_CONTEXT, deletedFiles: new Set([deleted]) }), ALL_NODE_LANES)
+})
+
+test('a workspace package nodejs links claims the node lanes that import it', () => {
+ const nodeLanesOf = (file, context) =>
+ computeTargets([file], context).filter((target) => target.startsWith('node:'))
+ assert.deepEqual(
+ nodeLanesOf('common/hogvm/typescript/src/execute.ts', NODE_CONTEXT),
+ [CDP_LANE, 'node:ingestion'].sort()
+ )
+ assert.equal(computeTargets(['common/hogvm/typescript/src/execute.ts'], NODE_CONTEXT).includes('py:core'), true)
+ assert.deepEqual(nodeLanesOf('common/replay-shared/src/index.ts', NODE_CONTEXT), [RASTERIZER_LANE])
+ assert.deepEqual(nodeLanesOf('common/replay-headless/src/player.ts', NODE_CONTEXT), [RASTERIZER_LANE])
+ assert.deepEqual(nodeLanesOf('common/hogvm/typescript/src/execute.ts', CONTEXT), ALL_NODE_LANES)
+ assert.deepEqual(nodeLanesOf('common/hogvm/typescript/README.md', NODE_CONTEXT), [])
+})
+
+function writeTree(files) {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'node-lanes-'))
+ for (const [file, text] of Object.entries(files)) {
+ fs.mkdirSync(path.join(root, path.dirname(file)), { recursive: true })
+ fs.writeFileSync(path.join(root, file), text)
+ }
+ return root
+}
+
+test('the node lane map follows imports in both directions and fails closed', () => {
+ const tree = {
+ 'nodejs/src/common/config.ts': "import { Kafka } from 'kafka-client'\nimport { brokers } from './kafka'\n",
+ 'nodejs/src/common/kafka.ts': 'export const brokers = []\n',
+ 'nodejs/src/common/types.ts': "import type { HogFunction } from '../cdp/types'\nexport type T = HogFunction\n",
+ 'nodejs/src/cdp/types.ts': 'export type HogFunction = {}\n',
+ 'nodejs/src/cdp/executor.ts':
+ "import { config } from '~/common/config'\nimport { exec } from '@posthog/hogvm'\n",
+ 'nodejs/src/ingestion/step.ts': "import type { T } from '~/common/types'\nimport fs from 'node:fs'\n",
+ 'nodejs/src/cdp/executor.test.ts': "import { seed } from '~/tests/helpers/seed'\n",
+ 'nodejs/tests/helpers/seed.ts': "import { rows } from '~/ingestion/rows'\n",
+ 'nodejs/src/ingestion/rows.ts': 'export const rows = []\n',
+ [`${RASTERIZER_DIR}/player.ts`]: "import { Player } from '@posthog/replay-headless/protocol'\n",
+ [`${RASTERIZER_DIR}/__tests__/guard.test.ts`]: "const script = `require('./missing-in-child-process')`\n",
+ 'nodejs/src/servers/cdp-server.ts':
+ "import { run } from '../cdp/executor'\nimport express from 'ultimate-express'\n",
+ 'nodejs/src/ingestion/errors.ts': [
+ "throw new Error(`could not load from '${lib}'`)",
+ "logger.warn('Imported from \\'Cymbal is down.\\'')",
+ "const query = `SELECT * from '${trigger.table_name}'`",
+ ].join('\n'),
+ }
+ const map = loadNodeLaneMap(writeTree(tree))
+ const lanesOf = (file) => [...(map.fileLanes.get(file) || [])].sort()
+ assert.deepEqual(lanesOf('nodejs/src/cdp/executor.ts'), [CDP_LANE])
+ assert.deepEqual(lanesOf('nodejs/src/cdp/types.ts'), [CDP_LANE, 'node:ingestion'].sort())
+ assert.deepEqual(lanesOf('nodejs/src/common/config.ts'), [CDP_LANE, 'node:ingestion'].sort())
+ assert.deepEqual(lanesOf('nodejs/src/common/kafka.ts'), [CDP_LANE, 'node:ingestion'].sort())
+ assert.deepEqual(lanesOf('nodejs/src/ingestion/step.ts'), ['node:ingestion'])
+ assert.deepEqual(lanesOf('nodejs/src/ingestion/rows.ts'), [CDP_LANE, 'node:ingestion'].sort())
+ assert.deepEqual(lanesOf(`${RASTERIZER_DIR}/player.ts`), [RASTERIZER_LANE])
+ assert.deepEqual(lanesOf('nodejs/src/servers/cdp-server.ts'), [])
+ assert.deepEqual([...map.packageLanes.get('@posthog/replay-headless')], [RASTERIZER_LANE])
+ assert.deepEqual([...map.packageLanes.get('@posthog/hogvm')], [CDP_LANE])
+ assert.deepEqual([...map.packageLanes.get('kafka-client')].sort(), [CDP_LANE, 'node:ingestion'].sort())
+ assert.deepEqual([...map.packageLanes.get('ultimate-express')].sort(), ALL_NODE_LANES)
+ assert.deepEqual([...map.packageLanes.keys()].sort(), [
+ '@posthog/hogvm',
+ '@posthog/replay-headless',
+ 'kafka-client',
+ 'ultimate-express',
+ ])
+
+ assert.equal(
+ loadNodeLaneMap(writeTree({ ...tree, 'nodejs/src/ingestion/broken.ts': "import { x } from './nowhere'\n" })),
+ null
+ )
+})
+
+function lockfile({ rootDeps, nodeDeps, headlessDeps, snapshots, packages, overrides = '' }) {
+ return [
+ "lockfileVersion: '9.0'",
+ '',
+ 'settings:',
+ ' autoInstallPeers: true',
+ '',
+ overrides,
+ 'importers:',
+ '',
+ ' .:',
+ ' devDependencies:',
+ rootDeps,
+ '',
+ ' nodejs:',
+ ' dependencies:',
+ " '@posthog/replay-headless':",
+ ' specifier: workspace:*',
+ ' version: link:../common/replay-headless',
+ ' tiny-lib:',
+ ' specifier: link:../packages/tiny-lib',
+ ' version: link:../packages/tiny-lib',
+ nodeDeps,
+ '',
+ ' common/replay-headless:',
+ ' dependencies:',
+ headlessDeps,
+ '',
+ 'packages:',
+ '',
+ packages,
+ '',
+ 'snapshots:',
+ '',
+ snapshots,
+ '',
+ ].join('\n')
+}
+
+function lockfileWith({
+ sdk = '1.0.0',
+ shim = '1.0.0',
+ runner = '1.0.0',
+ pad = '1.0.0',
+ tool = '1.0.0',
+ rootKafka = '3.0.0',
+ overrides,
+} = {}) {
+ const entry = (name, version) => [
+ ` ${name}@${version}:`,
+ ` resolution: {integrity: sha512-${name}${version}}`,
+ '',
+ ]
+ return lockfile({
+ overrides,
+ rootDeps: [
+ ['left-pad', pad],
+ ['build-tool', tool],
+ ['kafka-client', rootKafka],
+ ]
+ .flatMap(([name, version]) => [
+ ` ${name}:`,
+ ` specifier: ^${version}`,
+ ` version: ${version}`,
+ ])
+ .join('\n'),
+ nodeDeps: [
+ ' kafka-client:',
+ ' specifier: ^2.0.0',
+ ' version: 2.0.0',
+ ' devDependencies:',
+ ' test-runner:',
+ ' specifier: ^1.0.0',
+ ` version: ${runner}`,
+ ].join('\n'),
+ headlessDeps: [' browser-sdk:', ' specifier: catalog:', ` version: ${sdk}`].join('\n'),
+ packages: [
+ ...entry('browser-sdk', sdk),
+ ...entry('kafka-client', '2.0.0'),
+ ...entry('kafka-client', rootKafka),
+ ...entry('shim', shim),
+ ...entry('test-runner', runner),
+ ...entry('left-pad', pad),
+ ...entry('build-tool', tool),
+ ].join('\n'),
+ snapshots: [
+ ` browser-sdk@${sdk}: {}`,
+ '',
+ ' dependencies:',
+ ` shim: ${shim}`,
+ '',
+ ` kafka-client@${rootKafka}: {}`,
+ '',
+ ` shim@${shim}: {}`,
+ '',
+ ` test-runner@${runner}: {}`,
+ '',
+ ` left-pad@${pad}: {}`,
+ '',
+ ` build-tool@${tool}: {}`,
+ ].join('\n'),
+ })
+}
+
+const WORKSPACE = [
+ 'packages:',
+ ' - nodejs',
+ ' - common/*',
+ ' - packages/*',
+ 'catalog:',
+ ' browser-sdk: ^1.0.0',
+].join('\n')
+
+test('a JS lockfile change claims the node lanes whose dependencies it moved', () => {
+ const base = lockfileWith()
+ const nodeLaneMap = {
+ fileLanes: new Map(),
+ packageLanes: new Map([
+ ['@posthog/replay-headless', new Set([RASTERIZER_LANE])],
+ ['kafka-client', new Set([CDP_LANE, 'node:ingestion'])],
+ ['left-pad', new Set([CDP_LANE])],
+ ]),
+ }
+ const cases = [
+ [
+ 'a root dependency a lane imports without declaring it',
+ lockfileWith({ pad: '1.0.1' }),
+ WORKSPACE,
+ nodeLaneMap,
+ [CDP_LANE],
+ ],
+ ['a root dependency no lane imports', lockfileWith({ tool: '1.0.1' }), WORKSPACE, nodeLaneMap, ALL_NODE_LANES],
+ ['a root copy of a package nodejs declares', lockfileWith({ rootKafka: '3.0.1' }), WORKSPACE, nodeLaneMap, []],
+ ['a root dependency with no node lane map', lockfileWith({ pad: '1.0.1' }), WORKSPACE, null, ALL_NODE_LANES],
+ ['an unchanged lockfile', base, WORKSPACE, nodeLaneMap, []],
+ [
+ 'a bump only replay-headless resolves',
+ lockfileWith({ sdk: '1.0.1' }),
+ WORKSPACE,
+ nodeLaneMap,
+ [RASTERIZER_LANE],
+ ],
+ [
+ 'a transitive dependency of a package two lanes import',
+ lockfileWith({ shim: '1.0.1' }),
+ WORKSPACE,
+ nodeLaneMap,
+ [CDP_LANE, 'node:ingestion'],
+ ],
+ ['a dependency no lane imports', lockfileWith({ runner: '1.0.1' }), WORKSPACE, nodeLaneMap, ALL_NODE_LANES],
+ ['a bump with no node lane map', lockfileWith({ sdk: '1.0.1' }), WORKSPACE, null, ALL_NODE_LANES],
+ [
+ 'a new override',
+ lockfileWith({ overrides: 'overrides:\n shim: 1.0.0\n' }),
+ WORKSPACE,
+ nodeLaneMap,
+ ALL_NODE_LANES,
+ ],
+ [
+ 'a workspace change outside the catalog',
+ base,
+ WORKSPACE.replace(' - packages/*', ' - packages/*\n - tools/*'),
+ nodeLaneMap,
+ ALL_NODE_LANES,
+ ],
+ ['a catalog-only workspace change', base, WORKSPACE.replace('^1.0.0', '^1.0.1'), nodeLaneMap, []],
+ ['a snapshot the walk cannot find', base.replace(' [email protected]: {}', ''), WORKSPACE, nodeLaneMap, null],
+ ]
+ for (const [label, headLockfile, headWorkspace, map, expected] of cases) {
+ const reached = jsLockfileNodeLanes({
+ baseLockfile: base,
+ headLockfile,
+ baseWorkspace: WORKSPACE,
+ headWorkspace,
+ nodeLaneMap: map,
+ })
+ assert.deepEqual(reached && [...reached].sort(), expected && [...expected].sort(), label)
+ }
+ assert.equal(
+ jsLockfileNodeLanes({
+ baseLockfile: null,
+ headLockfile: base,
+ baseWorkspace: WORKSPACE,
+ headWorkspace: WORKSPACE,
+ nodeLaneMap,
+ }),
+ null
+ )
+})
+
+test('a JS lockfile lane keeps only the node lanes the lockfile reached', () => {
+ const nodeLanesOf = (files, context) =>
+ computeTargets(files, context).filter((target) => target.startsWith('node:'))
+ for (const file of ['pnpm-lock.yaml', 'pnpm-workspace.yaml']) {
+ const narrowed = computeTargets([file], {
+ ...NODE_CONTEXT,
+ jsLockfileNodeLanes: () => new Set([RASTERIZER_LANE]),
+ })
+ assert.deepEqual(
+ narrowed.filter((target) => target.startsWith('node:')),
+ [RASTERIZER_LANE],
+ file
+ )
+ assert.equal(narrowed.includes('fe:core'), true, file)
+ for (const [label, answer] of [
+ ['null', () => null],
+ ['absent', undefined],
+ ]) {
+ assert.deepEqual(
+ nodeLanesOf([file], { ...NODE_CONTEXT, jsLockfileNodeLanes: answer }),
+ ALL_NODE_LANES,
+ `${file} ${label}`
+ )
+ }
+ }
+ assert.deepEqual(
+ nodeLanesOf(['nodejs/src/ingestion/pipelines/step.ts', 'pnpm-lock.yaml'], {
+ ...NODE_CONTEXT,
+ jsLockfileNodeLanes: () => new Set(),
+ }),
+ ['node:ingestion']
+ )
+ assert.deepEqual(
+ nodeLanesOf(['package.json'], { ...NODE_CONTEXT, jsLockfileNodeLanes: () => new Set() }),
+ ALL_NODE_LANES
+ )
+
+ let reads = 0
+ const lazy = {
+ ...NODE_CONTEXT,
+ jsLockfileNodeLanes: () => {
+ reads++
+ return new Set([RASTERIZER_LANE])
+ },
+ }
+ computeTargets(['nodejs/src/ingestion/pipelines/step.ts', 'frontend/src/scenes/App.tsx'], lazy)
+ assert.equal(reads, 0)
+ assert.deepEqual(nodeLanesOf(['pnpm-lock.yaml', 'pnpm-workspace.yaml'], lazy), [RASTERIZER_LANE])
+ assert.equal(reads, 2)
+})
+
// Semgrep enforces the languages: declaration on every rule, so it is a sound
// source for the radius. The IDOR allowlist every new team-scoped model has to
// touch is a python rule, and used to serialize those PRs against the frontend.
diff --git a/.github/workflows/trunk-impacted-targets.yml b/.github/workflows/trunk-impacted-targets.yml
index 0ee86f30ee0a..45c4228293fa 100644
--- a/.github/workflows/trunk-impacted-targets.yml
+++ b/.github/workflows/trunk-impacted-targets.yml
@@ -122,6 +122,7 @@ jobs:
printf '%s\n' "$changed" > "$RUNNER_TEMP/changed-files.txt"
echo 'resolved=true' >> "$GITHUB_OUTPUT"
+ echo "merge_base=$merge_base" >> "$GITHUB_OUTPUT"
if printf '%s\n' "$changed" | grep -qE '^(rust|proto)/'; then
echo 'rust_affected=true' >> "$GITHUB_OUTPUT"
fi
@@ -167,6 +168,7 @@ jobs:
# needs no special case: it fills `crates` with the whole
# workspace, which lands on the same target set.
RUST_AFFECTED_CRATES: ${{ steps.affected.outputs.crates }}
+ LANE_MERGE_BASE: ${{ steps.changes.outputs.merge_base }}
run: |
set -uo pipefail