: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): source rust merge-queue lanes from the cargo determinator (#90078)
Georges-Antoine Assi8c7c8174e4cd
diff --git a/.github/actions/rust-compute-affected/action.yml b/.github/actions/rust-compute-affected/action.ymlindex a072c645144e..c0f1e9beadea 100644--- a/.github/actions/rust-compute-affected/action.yml+++ b/.github/actions/rust-compute-affected/action.yml@@ -15,6 +15,14 @@ inputs:description: 'Previous HEAD for push events (github.event.before)'required: falsedefault: ''+ base-branch:+ description: |+ Branch to resolve the merge base against, overriding the PR base ref+ from the event payload. Pass the default branch when the caller's+ change radius is measured against it rather than against the PR+ base, which for a stacked PR is the layer below it.+ required: false+ default: ''rebuild-all:description: 'Force a full rebuild (skip diff analysis)'required: false@@ -64,6 +72,7 @@ runs:EVENT_NAME: ${{ inputs.event-name }}PR_BASE_SHA: ${{ inputs.pr-base-sha }}PUSH_BEFORE_SHA: ${{ inputs.push-before-sha }}+ BASE_BRANCH: ${{ inputs.base-branch }}FORCE_REBUILD: ${{ inputs.rebuild-all }}working-directory: rustrun: |@@ -77,8 +86,8 @@ runs:# Try to resolve the base branch name from the input or# the GitHub event payload so we diff against the current# tip rather than the potentially stale PR base SHA.- base_branch=""- if [ -f "$GITHUB_EVENT_PATH" ]; then+ base_branch="$BASE_BRANCH"+ if [ -z "$base_branch" ] && [ -f "$GITHUB_EVENT_PATH" ]; thenbase_branch=$(jq -r '.pull_request.base.ref // empty' "$GITHUB_EVENT_PATH" 2>/dev/null || true)fidiff --git a/.github/scripts/trunk-impacted-targets.js b/.github/scripts/trunk-impacted-targets.jsindex 7813308fc534..052c90a3afd0 100644--- a/.github/scripts/trunk-impacted-targets.js+++ b/.github/scripts/trunk-impacted-targets.js@@ -15,7 +15,7 @@// The intersection Trunk computes is identical, but the uploaded list says// which lanes the PR claimed, so the telemetry can compare it against the lanes// the PR should have claimed. "ALL" is kept for the cases where the set cannot-// be built at all — an unreadable crate graph or services/ listing here, and a+// be built at all — an unreadable crate inventory or services/ listing here, and a// failed diff in the workflow, which never reaches this script. That is a// different statement from "everything": it means "unknown".//@@ -150,8 +150,9 @@ const PROTO = 'proto'const SEMGREP = 'semgrep'// rust/Cargo.lock, answered by the cargo determinator rather than by the path.-// Its own domain because the answer is a crate list rather than a fixed set of-// lanes, and it degrades to RUST when that list is absent.+// Its own domain because the file names no crate directory to seed from, so+// its radius is whatever the determinator's answer says the resolution change+// moved, degrading to every crate when that answer is absent.const CARGO_LOCK = 'cargo-lock'const TRIPWIRE_RULES = [@@ -1089,11 +1090,11 @@ function touchesContractSurface(product, file, contractSurfaces) {return matcher(relativePath)}-// --- Rust crate graph ---+// --- Rust crate inventory ---// 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.+// are needed to translate a changed path into a crate.function discoverRustCrates(repoRoot) {const crates = []const walk = (dir, depth) => {@@ -1112,13 +1113,12 @@ function discoverRustCrates(repoRoot) {if (!relative) {continue}- const text = fs.readFileSync(full, 'utf8')- const name = parseCrateName(text)+ const name = parseCrateName(fs.readFileSync(full, 'utf8'))if (name) {// A package.json beside the Cargo.toml means the crate also// builds an npm package, so its lane extends past rust/.const publishesNpmPackage = fs.existsSync(path.join(dir, 'package.json'))- crates.push({ dir: relative, name, text, publishesNpmPackage })+ crates.push({ dir: relative, name, publishesNpmPackage })}}}@@ -1136,174 +1136,51 @@ function parseCrateName(tomlText) {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.+// The dependency edges between crates deliberately live elsewhere:+// rust/affected-services, the determinator ci-rust.yml selects tests with,+// is the sole authority on which crates a change set affects, and its answer+// reaches this script through RUST_AFFECTED_CRATES. The inventory only names+// the crates: it maps a changed path to the crate holding it, enumerates the+// full set a widening claims, and flags the crates that also publish npm+// packages.//-// 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]-}--// Dependencies no Cargo.toml declares, because they are not compile-time edges:-// the key crate spawns the listed ones as binaries at run time. The cargo graph-// cannot see that, so the reverse closure would stop short of the spawner and-// leave it free to merge in parallel with a change to a service it executes.-//-// Mirrors the [[package-rule]] on-affected block in-// rust/affected-services/determinator-rules.toml, which exists for this same-// blind spot on the CI side. The two lists have to be changed together, which a-// test asserts, and loadRustGraph gives up the whole graph rather than dropping-// an edge if a crate named here stops existing.-const RUNTIME_SPAWN_EDGES = new Map([- [- 'personhog-test-harness',- ['personhog-replica', 'personhog-router', 'personhog-leader', 'personhog-writer', 'personhog-identity'],- ],-])--// Returns null when the crate graph can't be built. Callers must treat null as-// "unknown dependents" and widen to every target, never as "no dependents".-// Widening past the rust lanes is deliberate: without the graph the script-// cannot tell which crate a rust path belongs to either, so the rust targets-// alone would not be a superset of what the change can break.-function loadRustGraph(repoRoot) {+// Returns null when the inventory can't be built. Callers must treat null as+// "unknown crates" and widen to every target, never as "no crates". Widening+// past the rust lanes is deliberate: without the inventory the script cannot+// tell which crate a rust path belongs to either, so the rust targets alone+// would not be a superset of what the change can break.+function loadRustInventory(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))- }- // A crate renamed out from under the runtime map would otherwise drop- // its edge silently, which is the under-reporting direction, so an- // unresolvable entry gives up the whole graph instead.- for (const [spawner, spawned] of RUNTIME_SPAWN_EDGES) {- const unknown = [spawner, ...spawned].filter((crate) => !crateNames.has(crate))- if (unknown.length > 0) {- console.error(- `Runtime spawn edges name crates that no longer exist (${unknown.join(', ')}); ` +- 'widening to every target until RUNTIME_SPAWN_EDGES is updated'- )- return null- }- dependsOn.set(spawner, [...new Set([...dependsOn.get(spawner), ...spawned])])- }const nativeBindings = new Set(crates.filter((crate) => crate.publishesNpmPackage).map((crate) => crate.name))// 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, nativeBindings }+ return { crateNames, byDir, nativeBindings }} catch (error) {- console.error(`Rust crate graph unavailable (${error.message}); widening to every target`)+ console.error(`Rust crate inventory unavailable (${error.message}); widening to every 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}`+// Internal sentinel for a file whose crate radius only the determinator's+// answer can state, because the path names no crate directory to seed from+// (rust/Cargo.lock). Consumed by the determinator resolution at the end of+// computeTargets and never uploaded.+const RUST_DETERMINATOR = 'rust:determinator'+// The lanes that import a native module built from the cargo workspace.// nodejs/package.json is the only dependent of the two binding packages// (@posthog/hogvm-node, @posthog/replay-anonymizer) today,@@ -1325,8 +1202,8 @@ const NATIVE_BINDING_CONSUMER_LANES = ['node:ingestion']// dynamic parts (products, services, crates) are read rather than listed for// that reason, and a missing one returns null so the caller falls back to ALL.function allKnownTargets(context) {- const { products, services, rustGraph } = context- if (!rustGraph || !services) {+ const { products, services, rustInventory } = context+ if (!rustInventory || !services) {return null}const targets = new Set(['py:core', 'fe:core', 'node:ingestion', 'agents'])@@ -1345,7 +1222,7 @@ function allKnownTargets(context) {targets.add(target)}}- for (const crate of rustGraph.dependsOn.keys()) {+ for (const crate of rustInventory.crateNames) {targets.add(rustCrate(crate))}// "ALL" overlapped the prose lane too, so a docs PR serialized behind a@@ -1441,33 +1318,24 @@ function addDesktopLanes(targets, context) {}function addRustLanes(targets, context) {- if (!context.rustGraph) {+ if (!context.rustInventory) {return false}- for (const crate of context.rustGraph.dependsOn.keys()) {+ for (const crate of context.rustInventory.crateNames) {targets.add(rustCrate(crate))}return true}-// The crates the determinator says the change set moved, or every crate when it-// could not say. computeTargets runs its reverse closure over whatever lands-// here, so these are seeds rather than a finished answer.-//-// An answer naming no crate is a real verdict on a lockfile edit that moved no-// resolution, but claiming nothing for it costs more than it saves. A change set-// of only rust/Cargo.lock would then reach computeTargets' empty-set guard,-// which reads a target-less set as a path no rule claimed and widens to every-// lane in the repo — worse than the every-crate fallback, for a case rare enough-// not to be worth the lanes.+// rust/Cargo.lock sits in no crate directory, so its radius is whatever the+// determinator's answer says the resolution change moved. The sentinel defers+// to that answer, which the resolution at the end of computeTargets reads,+// falling back to every crate when it is missing, empty, or in disagreement.function addCargoLockLanes(targets, context) {- const crates = context.cargoLockCrates- if (!crates || crates.length === 0) {- return addRustLanes(targets, context)- }- for (const crate of crates) {- targets.add(rustCrate(crate))+ if (!context.rustInventory) {+ return false}+ targets.add(RUST_DETERMINATOR)return true}@@ -1514,14 +1382,14 @@ function addProtoLanes(targets, context, file) {const segments = file.split('/')const trees =segments.length === 2 ? [...PROTO_TREES.keys()] : [segments[1]].filter((tree) => PROTO_TREES.has(tree))- if (trees.length === 0 || !context.rustGraph) {+ if (trees.length === 0 || !context.rustInventory) {return false}for (const tree of trees) {const { crates, domains } = PROTO_TREES.get(tree)// A crate renamed out from under the table would drop the rust half// silently, which is the under-reporting direction.- if (crates.some((crate) => !context.rustGraph.dependsOn.has(crate))) {+ if (crates.some((crate) => !context.rustInventory.crateNames.has(crate))) {console.error(`No crate named for proto tree ${tree}; widening to every target until PROTO_TREES is updated`)@@ -1630,7 +1498,7 @@ function computeTargets(changedFiles, context) {const {products,isolatedProducts,- rustGraph,+ rustInventory,tachGraph,contractSurfaces = new Map(),productWorkspaces = new Map(),@@ -1779,11 +1647,11 @@ function computeTargets(changedFiles, context) {return everything(context)}if (top === 'rust') {- if (!rustGraph) {+ if (!rustInventory) {targets.add('rust:unresolved')continue}- const crate = rustGraph.byDir.find(+ const crate = rustInventory.byDir.find((entry) => file.startsWith(`rust/${entry.dir}/`) || file === `rust/${entry.dir}`)if (crate) {@@ -1897,19 +1765,38 @@ function computeTargets(changedFiles, context) {}}- 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))- const affectedCrates = reverseClosure(seeds, rustGraph.dependsOn)+ // The rust:crate: targets accumulated above are seeds: the crates the+ // changed paths sit in, plus the ones the proto and workspace rules named.+ // The dependency closure over them is the determinator's answer, the same+ // rust/affected-services run ci-rust.yml selects tests with, delivered+ // through RUST_AFFECTED_CRATES. This script holds no crate dependency+ // edges of its own, so a missing answer widens to every crate, and so does+ // an answer that omits a seed, which means the determinator and this+ // script disagree about the workspace. An answer naming no crate widens+ // too: it is a real verdict on a lockfile edit that moved no resolution,+ // but claiming nothing for it would reach the empty-set guard below and+ // widen past the rust lanes entirely.+ const needsDeterminator = targets.delete(RUST_DETERMINATOR)+ const rustSeeds = [...targets]+ .filter((target) => target.startsWith('rust:crate:'))+ .map((target) => target.slice('rust:crate:'.length))+ if (needsDeterminator || rustSeeds.length > 0) {+ if (!rustInventory) {+ return everything(context)+ }+ const answer = context.rustAffectedCrates+ const affectedCrates =+ answer && answer.length > 0 && rustSeeds.every((seed) => answer.includes(seed))+ ? answer+ : [...rustInventory.crateNames]for (const crate of affectedCrates) {targets.add(rustCrate(crate))}// A crate that also builds an npm package compiles into a native module- // the JS workspace imports, so the closure does not end at rust/. The+ // the JS workspace imports, so the radius does not end at rust/. The// dependents are found through package.json rather than Cargo.toml,- // which is why the crate graph alone stops one edge short.- const bindings = rustGraph.nativeBindings || new Set()+ // which is why the determinator's answer alone stops one edge short.+ const bindings = rustInventory.nativeBindings || new Set()if (affectedCrates.some((crate) => bindings.has(crate))) {for (const target of NATIVE_BINDING_CONSUMER_LANES) {targets.add(target)@@ -1919,8 +1806,8 @@ function computeTargets(changedFiles, context) {if (targets.has('rust:unresolved')) {targets.delete('rust:unresolved')- if (rustGraph) {- for (const crate of rustGraph.dependsOn.keys()) {+ if (rustInventory) {+ for (const crate of rustInventory.crateNames) {targets.add(rustCrate(crate))}} else {@@ -1992,39 +1879,41 @@ function listServices(repoRoot) {}}-// The crate list rust-compute-affected produced for this diff, as a JSON array.-// The workflow only runs the determinator when the change set holds-// rust/Cargo.lock, so on every other PR this is unset and never read.-const CARGO_LOCK_CRATES_ENV = 'CARGO_LOCK_CRATES'--// Returns null for unknown, which the caller widens on. The determinator answers-// for the whole diff rather than for the lockfile alone, so this is a superset-// of the lockfile's own contribution — the safe direction, and the union with-// the path rules is what lands either way.+// The crate list rust-compute-affected produced for this diff, as a JSON+// array. It is the determinator's affected set (the changed crates plus the+// closure of their dependents, with the runtime spawn edges its rules+// declare), so it arrives as a finished answer rather than as seeds to close+// over. The workflow only runs the determinator when the change set touches+// rust/ or proto/, so on every other PR this is unset and never read.+const RUST_AFFECTED_CRATES_ENV = 'RUST_AFFECTED_CRATES'++// Returns null for unknown, which the caller widens on. The determinator+// answers for the whole diff rather than for the rust paths alone, so this is+// a superset of their own contribution, which is the safe direction.//-// A name the crate graph does not know means the two disagree about the+// A name the crate inventory does not know means the two disagree about the// workspace, and a disagreement resolves to unknown rather than to a lane list// built from half of it.-function parseCargoLockCrates(raw, rustGraph) {- if (!rustGraph || !raw) {+function parseRustAffectedCrates(raw, rustInventory) {+ if (!rustInventory || !raw) {return null}let cratestry {crates = JSON.parse(raw)} catch (error) {- console.error(`${CARGO_LOCK_CRATES_ENV} is not JSON (${error.message}); a lockfile change claims every crate`)+ console.error(`${RUST_AFFECTED_CRATES_ENV} is not JSON (${error.message}); a rust change claims every crate`)return null}if (!Array.isArray(crates) || crates.some((crate) => typeof crate !== 'string')) {- console.error(`${CARGO_LOCK_CRATES_ENV} is not a list of crate names; a lockfile change claims every crate`)+ console.error(`${RUST_AFFECTED_CRATES_ENV} is not a list of crate names; a rust change claims every crate`)return null}- const unknown = crates.filter((crate) => !rustGraph.dependsOn.has(crate))+ const unknown = crates.filter((crate) => !rustInventory.crateNames.has(crate))if (unknown.length > 0) {console.error(- `The determinator named crates the graph does not hold (${unknown.join(', ')}); ` +- 'a lockfile change claims every crate'+ `The determinator named crates the inventory does not hold (${unknown.join(', ')}); ` ++ 'a rust change claims every crate')return null}@@ -2034,11 +1923,11 @@ function parseCargoLockCrates(raw, rustGraph) {function buildContext(repoRoot) {const products = listProducts(repoRoot)const tachGraph = loadTachGraph(repoRoot)- const rustGraph = loadRustGraph(repoRoot)+ const rustInventory = loadRustInventory(repoRoot)const contractSurfaces = loadContractSurfaces(repoRoot, products)return {products,- cargoLockCrates: parseCargoLockCrates(process.env[CARGO_LOCK_CRATES_ENV], rustGraph),+ rustAffectedCrates: parseRustAffectedCrates(process.env[RUST_AFFECTED_CRATES_ENV], rustInventory),services: listServices(repoRoot),isolatedProducts: listIsolatedProducts(repoRoot, products, contractSurfaces),contractSurfaces,@@ -2046,7 +1935,7 @@ function buildContext(repoRoot) {backendDetachedProducts: loadBackendDetachedProducts(repoRoot, products, tachGraph),tachDeclaredProducts: listTachDeclaredProducts(products, tachGraph),semgrepDomains: loadSemgrepDomains(repoRoot),- rustGraph,+ rustInventory,tachGraph,}}@@ -2062,16 +1951,14 @@ module.exports = {isTripwire,listIsolatedProducts,loadContractSurfaces,- parseCrateDependencies,parseCrateName,parsePytestIgnores,parseSemgrepLanguages,parseWorkspacePackageGlobs,- reverseClosure,semgrepDomain,stripJsonComments,tripwireDomain,- parseCargoLockCrates,+ parseRustAffectedCrates,ALL,CARGO_LOCK,JAVASCRIPT,@@ -2080,7 +1967,6 @@ module.exports = {PROTO_TREES,PYTHON,REPO_ROOT,- RUNTIME_SPAWN_EDGES,RUST,UNIVERSAL,}diff --git a/.github/scripts/trunk-impacted-targets.test.js b/.github/scripts/trunk-impacted-targets.test.jsindex 45cbc4ef36d5..30ee027e3bb7 100644--- a/.github/scripts/trunk-impacted-targets.test.js+++ b/.github/scripts/trunk-impacted-targets.test.js@@ -18,7 +18,7 @@ const {computeTargets,allKnownTargets,buildContext,- parseCargoLockCrates,+ parseRustAffectedCrates,compileContractMatcher,compileWorkspaceMatcher,globToRegExp,@@ -26,12 +26,10 @@ const {isTripwire,listIsolatedProducts,loadContractSurfaces,- parseCrateDependencies,parseCrateName,parsePytestIgnores,parseSemgrepLanguages,parseWorkspacePackageGlobs,- reverseClosure,semgrepDomain,tripwireDomain,ALL,@@ -41,7 +39,6 @@ const {PROTO_TREES,PYTHON,REPO_ROOT,- RUNTIME_SPAWN_EDGES,RUST,UNIVERSAL,} = require('./trunk-impacted-targets')@@ -56,12 +53,8 @@ const CONTEXT = {['.semgrep/rules/devex/ts-rule.yaml', JAVASCRIPT],['.semgrep/rules/devex/generic-rule.yaml', UNIVERSAL],]),- rustGraph: {- dependsOn: new Map([- ['shared', []],- ['consumer', ['shared']],- ['unrelated', []],- ]),+ rustInventory: {+ crateNames: new Set(['shared', 'consumer', 'unrelated']),byDir: [{ dir: 'consumer', name: 'consumer' },{ dir: 'unrelated', name: 'unrelated' },@@ -105,32 +98,24 @@ layer = "modules"}// PROTO_TREES names the crates that compile each tree, so the crate half of-// this graph has to carry their real names. The dependent and the bystander are-// synthetic, which is what keeps the closure assertions off the real crate-// graph.+// this inventory has to carry their real names. The dependent and the+// bystander are synthetic, which is what keeps the assertions off the real+// crate workspace.+const PROTO_CRATES = [+ 'cymbal-proto',+ 'ingestion-worker-proto',+ 'kafka-assigner-proto',+ 'personhog-proto',+ 'personhog-consumer',+ 'prometheus-rw-proto',+ 'usage-ingestion-proto',+ 'unrelated',+]const PROTO_CONTEXT = {...CONTEXT,- rustGraph: {- dependsOn: new Map([- ['cymbal-proto', []],- ['ingestion-worker-proto', []],- ['kafka-assigner-proto', []],- ['personhog-proto', []],- ['personhog-consumer', ['personhog-proto']],- ['prometheus-rw-proto', []],- ['usage-ingestion-proto', []],- ['unrelated', []],- ]),- byDir: [- { dir: 'cymbal-proto', name: 'cymbal-proto' },- { dir: 'ingestion-worker-proto', name: 'ingestion-worker-proto' },- { dir: 'kafka-assigner-proto', name: 'kafka-assigner-proto' },- { dir: 'personhog-proto', name: 'personhog-proto' },- { dir: 'personhog-consumer', name: 'personhog-consumer' },- { dir: 'prometheus-rw-proto', name: 'prometheus-rw-proto' },- { dir: 'usage-ingestion-proto', name: 'usage-ingestion-proto' },- { dir: 'unrelated', name: 'unrelated' },- ],+ rustInventory: {+ crateNames: new Set(PROTO_CRATES),+ byDir: PROTO_CRATES.map((name) => ({ dir: name, name })),},}@@ -212,10 +197,14 @@ test('a lockfile claims its own toolchain rather than every lane', () => {// Every consumer of a proto commits the stubs generated from it, so the set is// enumerable rather than open-ended: tonic for the crate, and checked-in-// personhog stubs for python and nodejs. The rust half is the crate that-// compiles the tree plus the dependents the closure adds, not every crate.+// personhog stubs for python and nodejs. The rust half is the determinator's+// answer for the diff (the crate that compiles the tree plus its dependents),+// not every crate.test('a proto claims the consumers that generate from it rather than every lane', () => {- const targets = computeTargets(['proto/personhog/types/v1/person.proto'], PROTO_CONTEXT)+ const targets = computeTargets(['proto/personhog/types/v1/person.proto'], {+ ...PROTO_CONTEXT,+ rustAffectedCrates: ['personhog-proto', 'personhog-consumer'],+ })for (const target of ['py:core','py:product:alpha',@@ -242,12 +231,20 @@ test('a proto claims the consumers that generate from it rather than every lane'// The narrowing the per-tree table buys: a tree nothing outside rust/ generates// from used to serialize against every python lane in the repo.test('a proto tree with no stubs outside rust claims neither python nor nodejs', () => {- assert.deepEqual(computeTargets(['proto/cymbal/resolution/v1/resolution.proto'], PROTO_CONTEXT), [- 'rust:crate:cymbal-proto',- ])- assert.deepEqual(computeTargets(['proto/kafka_assigner/v1/service.proto'], PROTO_CONTEXT), [- 'rust:crate:kafka-assigner-proto',- ])+ assert.deepEqual(+ computeTargets(['proto/cymbal/resolution/v1/resolution.proto'], {+ ...PROTO_CONTEXT,+ rustAffectedCrates: ['cymbal-proto'],+ }),+ ['rust:crate:cymbal-proto']+ )+ assert.deepEqual(+ computeTargets(['proto/kafka_assigner/v1/service.proto'], {+ ...PROTO_CONTEXT,+ rustAffectedCrates: ['kafka-assigner-proto'],+ }),+ ['rust:crate:kafka-assigner-proto']+ )})// buf's lint and breaking-change settings sit at the root and govern every@@ -277,9 +274,9 @@ test('an undeclared proto tree or a renamed proto crate widens', () => {const renamed = {...PROTO_CONTEXT,- rustGraph: {- ...PROTO_CONTEXT.rustGraph,- dependsOn: new Map([...PROTO_CONTEXT.rustGraph.dependsOn].filter(([crate]) => crate !== 'personhog-proto')),+ rustInventory: {+ ...PROTO_CONTEXT.rustInventory,+ crateNames: new Set([...PROTO_CONTEXT.rustInventory.crateNames].filter((c) => c !== 'personhog-proto')),},}assert.deepEqual(computeTargets(['proto/personhog/types/v1/person.proto'], renamed), allKnownTargets(renamed))@@ -744,7 +741,7 @@ test('every target the rules can emit appears in the enumerated universe', () =>// every crate or service has to fall back to the sentinel rather than upload a// set that is missing lanes.test('an incomplete context falls back to the ALL sentinel', () => {- assert.equal(allKnownTargets({ ...CONTEXT, rustGraph: null }), null)+ assert.equal(allKnownTargets({ ...CONTEXT, rustInventory: null }), null)assert.equal(allKnownTargets({ ...CONTEXT, services: null }), null)assert.equal(computeTargets(['some-new-toplevel/thing.go'], { ...CONTEXT, services: null }), ALL)// An explicit-lanes rule cannot validate its names without the full@@ -845,16 +842,44 @@ test('globs match across directories only through **', () => {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'])+// The determinator's answer is the affected set (the changed crates plus+// their dependents), so it is used as it stands rather than closed over again.+// The script holds no crate dependency edges of its own.+test('a rust change takes its crate set from the determinator answer', () => {+ assert.deepEqual(+ computeTargets(['rust/shared/src/lib.rs'], { ...CONTEXT, rustAffectedCrates: ['consumer', 'shared'] }),+ ['rust:crate:consumer', 'rust:crate:shared']+ )+ assert.deepEqual(+ computeTargets(['rust/unrelated/src/main.rs'], { ...CONTEXT, rustAffectedCrates: ['unrelated'] }),+ ['rust:crate:unrelated']+ )+})++// Without the answer the script cannot name the dependents of the changed+// crate, and a set missing a dependent is the direction that breaks master.+test('a rust change without a determinator answer claims every crate', () => {+ assert.deepEqual(computeTargets(['rust/shared/src/lib.rs'], CONTEXT), [+ 'rust:crate:consumer',+ 'rust:crate:shared',+ 'rust:crate:unrelated',+ ])+})++// An answer that omits a crate the changed paths sit in means the determinator+// and this script disagree about the workspace, and a lane list built from+// half of that disagreement could be the narrow half.+test('an answer that omits a seeded crate widens to every crate', () => {+ assert.deepEqual(computeTargets(['rust/consumer/src/main.rs'], { ...CONTEXT, rustAffectedCrates: ['shared'] }), [+ 'rust:crate:consumer',+ 'rust:crate:shared',+ '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('an unresolvable rust crate inventory reports every crate instead of narrowing', () => {+ const noInventory = { ...CONTEXT, rustInventory: null }+ assert.equal(computeTargets(['rust/shared/src/lib.rs'], noInventory), ALL)})test('a rust path outside every known crate widens', () => {@@ -867,19 +892,33 @@ test('a rust path outside every known crate widens', () => {test('a crate that builds an npm package claims the lanes importing it', () => {const bindingContext = {...CONTEXT,- rustGraph: { ...CONTEXT.rustGraph, nativeBindings: new Set(['consumer']) },+ rustInventory: { ...CONTEXT.rustInventory, nativeBindings: new Set(['consumer']) },}- // Reached through the closure rather than directly: `shared` is not itself a- // binding, but what it compiles into ships inside one.- const viaDependency = computeTargets(['rust/shared/src/lib.rs'], bindingContext)+ // Reached through the answer's closure rather than directly: `shared` is+ // not itself a binding, but what it compiles into ships inside one.+ const viaDependency = computeTargets(['rust/shared/src/lib.rs'], {+ ...bindingContext,+ rustAffectedCrates: ['consumer', 'shared'],+ })assert.equal(viaDependency.includes('node:ingestion'), true)- const direct = computeTargets(['rust/consumer/src/lib.rs'], bindingContext)+ const direct = computeTargets(['rust/consumer/src/lib.rs'], {+ ...bindingContext,+ rustAffectedCrates: ['consumer'],+ })assert.equal(direct.includes('node:ingestion'), true)// A crate no binding depends on keeps its own lane.- const unrelated = computeTargets(['rust/unrelated/src/main.rs'], bindingContext)+ const unrelated = computeTargets(['rust/unrelated/src/main.rs'], {+ ...bindingContext,+ rustAffectedCrates: ['unrelated'],+ })assert.deepEqual(unrelated, ['rust:crate:unrelated'])++ // The every-crate fallback covers the bindings, so it reaches their+ // consumers too.+ const widened = computeTargets(['rust/shared/src/lib.rs'], bindingContext)+ assert.equal(widened.includes('node:ingestion'), true)})// The cargo lockfile, the manifest, and the sqlx offline data resolve nothing@@ -890,7 +929,7 @@ test('a crate that builds an npm package claims the lanes importing it', () => {test('the cargo workspace tripwires claim the rust lanes rather than every lane', () => {const bindingContext = {...CONTEXT,- rustGraph: { ...CONTEXT.rustGraph, nativeBindings: new Set(['consumer']) },+ rustInventory: { ...CONTEXT.rustInventory, nativeBindings: new Set(['consumer']) },}for (const file of ['rust/Cargo.lock', 'rust/Cargo.toml', 'rust/.sqlx/query-0a1b.json']) {const targets = computeTargets([file], bindingContext)@@ -906,11 +945,11 @@ test('the cargo workspace tripwires claim the rust lanes rather than every lane'}})-// The seeds are the crates the determinator named; computeTargets owns the-// closure over them. Without it, a resolution change in a crate every other-// crate depends on would claim one lane.-test('a narrowed lockfile change still claims the dependents of the crates it named', () => {- const targets = computeTargets(['rust/Cargo.lock'], { ...CONTEXT, cargoLockCrates: ['shared'] })+// The determinator's answer already holds the dependents of the crates the+// resolution moved, so the lockfile takes it as it stands. Without it, a+// lockfile touch claims every crate (the case above this one pins).+test('a narrowed lockfile change claims the crates the determinator named', () => {+ const targets = computeTargets(['rust/Cargo.lock'], { ...CONTEXT, rustAffectedCrates: ['consumer', 'shared'] })assert.deepEqual(targets.filter((target) => target.startsWith('rust:crate:')),['rust:crate:consumer', 'rust:crate:shared']@@ -922,7 +961,7 @@ test('a narrowed lockfile change still claims the dependents of the crates it na// lockfile-only change set would otherwise reach the empty-set guard and widen// past the rust lanes entirely. This pins the fallback against that.test('a determinator answer naming no crate claims every crate, not every lane', () => {- const targets = computeTargets(['rust/Cargo.lock'], { ...CONTEXT, cargoLockCrates: [] })+ const targets = computeTargets(['rust/Cargo.lock'], { ...CONTEXT, rustAffectedCrates: [] })assert.deepEqual(targets.filter((target) => target.startsWith('rust:crate:')),['rust:crate:consumer', 'rust:crate:shared', 'rust:crate:unrelated']@@ -940,21 +979,21 @@ test('an unusable determinator answer reads as unknown', () => {['output that is not JSON', 'shared,consumer'],['JSON that is not a list', '{"crates":["shared"]}'],['a list holding something other than a name', '["shared", 7]'],- ['a crate the graph does not hold', '["shared", "ghost"]'],+ ['a crate the inventory does not hold', '["shared", "ghost"]'],]) {- assert.equal(parseCargoLockCrates(raw, CONTEXT.rustGraph), null, `${name} should read as unknown`)+ assert.equal(parseRustAffectedCrates(raw, CONTEXT.rustInventory), null, `${name} should read as unknown`)}})-test('a determinator answer the graph agrees with is used as it stands', () => {- assert.deepEqual(parseCargoLockCrates('["shared"]', CONTEXT.rustGraph), ['shared'])+test('a determinator answer the inventory agrees with is used as it stands', () => {+ assert.deepEqual(parseRustAffectedCrates('["shared"]', CONTEXT.rustInventory), ['shared'])})-// The determinator's workspace and this script's crate graph are built from the-// same manifests by different code, so a name in one and not the other means one-// of them is wrong. Reads the real graph, which is the only place that can drift.-test('the crate graph holds every crate the determinator can name', () => {- const { rustGraph } = buildContext(REPO_ROOT)+// The determinator's workspace and this script's crate inventory are built from+// the same manifests by different code, so a name in one and not the other means+// one of them is wrong. Reads the real repo, which is the only place that can drift.+test('the crate inventory holds every crate the determinator can name', () => {+ const { rustInventory } = buildContext(REPO_ROOT)const members = fs.readFileSync(path.join(REPO_ROOT, 'rust/Cargo.toml'), 'utf8').split(/^\s*\[/m)@@ -963,31 +1002,8 @@ test('the crate graph holds every crate the determinator can name', () => {.split(',').map((entry) => entry.trim().replace(/^"|"$/g, '')).filter(Boolean)- const missing = members.filter((dir) => !rustGraph.byDir.some((crate) => crate.dir === dir))- assert.deepEqual(missing, [], 'these workspace members are absent from the crate graph')-})--// The two lists below are the same rule written twice, once for the merge queue-// and once for CI's selective builds. Nothing but this test stops them drifting,-// and the failure is silent in both directions: an edge the queue drops lets two-// conflicting PRs merge in parallel.-test('the runtime spawn edges match the determinator package rules', () => {- const rulesToml = fs.readFileSync(path.join(REPO_ROOT, 'rust/affected-services/determinator-rules.toml'), 'utf8')- const names = (block, key) => {- const match = block.match(new RegExp(`${key}\\s*=\\s*\\[([^\\]]*)\\]`))- return match ? [...match[1].matchAll(/"([^"]+)"/g)].map((m) => m[1]).sort() : []- }- const packageRules = rulesToml- .split(/^\s*\[\[package-rule\]\]\s*$/m)- .slice(1)- .map((block) => ({ onAffected: names(block, 'on-affected'), markChanged: names(block, 'mark-changed') }))-- const fromScript = [...RUNTIME_SPAWN_EDGES]- .map(([spawner, spawned]) => ({ onAffected: [...spawned].sort(), markChanged: [spawner] }))- .sort((a, b) => a.markChanged[0].localeCompare(b.markChanged[0]))- const fromRules = packageRules.sort((a, b) => a.markChanged[0].localeCompare(b.markChanged[0]))-- assert.deepEqual(fromScript, fromRules)+ const missing = members.filter((dir) => !rustInventory.byDir.some((crate) => crate.dir === dir))+ assert.deepEqual(missing, [], 'these workspace members are absent from the crate inventory')})// The consumer lanes are declared rather than derived, so a second dependent@@ -1147,76 +1163,6 @@ test('rust migration sets claim the suites that read their schema', () => {])})-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',@@ -1655,7 +1601,10 @@ test('a change set of nothing but markdown reports the prose lane', () => {// touched a markdown file, even with their code in unrelated trees. The prose// lane must not reintroduce that by riding along with real lanes.test('markdown alongside code contributes no lane of its own', () => {- assert.deepEqual(computeTargets(['rust/unrelated/src/main.rs', 'README.md'], CONTEXT), ['rust:crate:unrelated'])+ assert.deepEqual(+ computeTargets(['rust/unrelated/src/main.rs', 'README.md'], { ...CONTEXT, rustAffectedCrates: ['unrelated'] }),+ ['rust:crate:unrelated']+ )})// hogli build:skills zips products/*/skills/*, and ci-agent-skills.yml gates ondiff --git a/.github/workflows/trunk-impacted-targets.yml b/.github/workflows/trunk-impacted-targets.ymlindex 5803542689cd..54095db8e8a6 100644--- a/.github/workflows/trunk-impacted-targets.yml+++ b/.github/workflows/trunk-impacted-targets.yml@@ -110,24 +110,28 @@ jobs:printf '%s\n' "$changed" > "$RUNNER_TEMP/changed-files.txt"echo 'resolved=true' >> "$GITHUB_OUTPUT"- if printf '%s\n' "$changed" | grep -qx 'rust/Cargo.lock'; then- echo 'cargo_lock=true' >> "$GITHUB_OUTPUT"+ if printf '%s\n' "$changed" | grep -qE '^(rust|proto)/'; then+ echo 'rust_affected=true' >> "$GITHUB_OUTPUT"fi- # A lockfile touch would otherwise claim all 66 crates, so the two- # steps below buy the narrow answer from the determinator that- # ci-rust.yml already runs. Measured at ~50s on a cache miss, which a- # lockfile change always is, since the binary's cache key holds it.- # Skipped entirely on a PR that leaves rust/Cargo.lock alone.+ # The determinator that ci-rust.yml selects tests with is the sole+ # authority on which crates a change set affects, because the lane+ # script holds no crate dependency edges of its own, so the two+ # steps below buy its answer for every diff that touches rust/ or+ # proto/. Measured at ~50s on a cache miss (a lockfile change+ # always misses, since the binary's cache key holds+ # rust/Cargo.lock); a cache hit runs the restored binary in a few+ # seconds. Skipped entirely on the PRs that touch neither tree,+ # which is nearly all of them.- name: Install rust- if: steps.changes.outputs.cargo_lock == 'true'+ if: steps.changes.outputs.rust_affected == 'true'uses: dtolnay/rust-toolchain@3c5f7ea28cd621ae0bf5283f0e981fb97b8a7af9with:toolchain: 1.91.1- name: Compute affected rust cratesid: affected- if: steps.changes.outputs.cargo_lock == 'true'+ if: steps.changes.outputs.rust_affected == 'true'# A failure here must not keep the PR out of the queue. The crate# list goes missing, and the script falls back to every crate.continue-on-error: true@@ -135,6 +139,12 @@ jobs:with:event-name: ${{ github.event_name }}pr-base-sha: ${{ github.event.pull_request.base.sha }}+ # Diff against master rather than the PR base, for the same+ # reason the changed-file diff above does: a stacked PR's+ # base is the layer below it, and an answer computed against+ # a different radius than the file list would read as a+ # disagreement and widen to every crate.+ base-branch: ${{ github.event.repository.default_branch }}- name: Compute impacted targetsid: targets@@ -144,7 +154,7 @@ jobs:# script reads as every crate. Its own rebuild-all verdict# needs no special case: it fills `crates` with the whole# workspace, which lands on the same target set.- CARGO_LOCK_CRATES: ${{ steps.affected.outputs.crates }}+ RUST_AFFECTED_CRATES: ${{ steps.affected.outputs.crates }}run: |set -uo pipefaildiff --git a/rust/affected-services/determinator-rules.toml b/rust/affected-services/determinator-rules.tomlindex d1d52f2b562e..8397866671c3 100644--- a/rust/affected-services/determinator-rules.toml+++ b/rust/affected-services/determinator-rules.toml@@ -104,8 +104,9 @@ mark-changed = []# runs against those changes.## The merge queue needs the same edge to keep a harness change out of a lane-# parallel to one of these services, so it is mirrored in RUNTIME_SPAWN_EDGES in-# .github/scripts/trunk-impacted-targets.js. Change both; a test compares them.+# parallel to one of these services. It gets it from here: the lane script+# (.github/scripts/trunk-impacted-targets.js) takes this binary's affected set+# as its rust:crate: answer, so this rule is the edge's only home.[[package-rule]]on-affected = ["personhog-replica",