: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
fix(ci): claim only the crates a Cargo.lock change affects (#86694)
posthog[bot]0162bf7c3c11
diff --git a/.github/scripts/trunk-impacted-targets.js b/.github/scripts/trunk-impacted-targets.jsindex 54322de73ba5..3e964cbd6703 100644--- a/.github/scripts/trunk-impacted-targets.js+++ b/.github/scripts/trunk-impacted-targets.js@@ -137,6 +137,11 @@ const PROTO = 'proto'// from its path, so it cannot be expressed as a static domain here.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.+const CARGO_LOCK = 'cargo-lock'+const TRIPWIRE_RULES = [// Markdown in these trees compiles into nothing and no suite reads it, so// it is prose like any other. Ahead of the trees themselves, which would@@ -249,11 +254,16 @@ const TRIPWIRE_RULES = [// pyproject.toml, so the python suites install a released wheel rather than// building either from this checkout. A resolution change reaches a python// lane only through the version bump, which is a pyproject.toml and uv.lock- // edit claiming those lanes above. ci-rust.yml already narrows a lockfile- // touch further, by diffing the resolved graph rather than rebuilding- // everything, which is a step this script cannot take without a cargo- // toolchain in the compute job.- ['rust/Cargo.lock', RUST],+ // edit claiming those lanes above.+ //+ // The lockfile narrows further than the manifest, because it states the+ // resolution rather than the request. CARGO_LOCK takes the crate list from+ // the same determinator ci-rust.yml runs, so a dependency added for one+ // crate stops claiming the whole workspace. rust/Cargo.toml stays on the+ // whole domain: a workspace-wide feature or version request can change how+ // a shared dependency compiles for every crate, and a manifest edit that+ // moves no resolution leaves no lockfile diff for the determinator to read.+ ['rust/Cargo.lock', CARGO_LOCK],['rust/Cargo.toml', RUST],['rust/.sqlx/**', RUST],['hogli.yaml', UNIVERSAL],@@ -1280,6 +1290,27 @@ function addRustLanes(targets, context) {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.+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))+ }+ return true+}+// The nodejs lane on its own. No tripwire resolves to it, because a file that// can break the ingestion suite can almost always break more than that. The// rust and proto rules still need to name it without dragging in the frontend.@@ -1351,6 +1382,7 @@ const DOMAIN_LANES = new Map([[PYTHON, addPythonLanes],[JAVASCRIPT, addJavaScriptLanes],[RUST, addRustLanes],+ [CARGO_LOCK, addCargoLockLanes],[NODE, addNodeLanes],[PRODUCT_SURFACE, addProductSurfaceLanes],[PROTO, addProtoLanes],@@ -1765,11 +1797,52 @@ 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.+//+// A name the crate graph 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) {+ return null+ }+ let crates+ try {+ crates = JSON.parse(raw)+ } catch (error) {+ console.error(`${CARGO_LOCK_CRATES_ENV} is not JSON (${error.message}); a lockfile 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`)+ return null+ }+ const unknown = crates.filter((crate) => !rustGraph.dependsOn.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'+ )+ return null+ }+ return crates+}+function buildContext(repoRoot) {const products = listProducts(repoRoot)const tachGraph = loadTachGraph(repoRoot)+ const rustGraph = loadRustGraph(repoRoot)return {products,+ cargoLockCrates: parseCargoLockCrates(process.env[CARGO_LOCK_CRATES_ENV], rustGraph),services: listServices(repoRoot),isolatedProducts: listIsolatedProducts(repoRoot, products),contractSurfaces: loadContractSurfaces(repoRoot, products),@@ -1777,7 +1850,7 @@ function buildContext(repoRoot) {backendDetachedProducts: loadBackendDetachedProducts(repoRoot, products, tachGraph),tachDeclaredProducts: listTachDeclaredProducts(products, tachGraph),semgrepDomains: loadSemgrepDomains(repoRoot),- rustGraph: loadRustGraph(repoRoot),+ rustGraph,tachGraph,}}@@ -1800,7 +1873,9 @@ module.exports = {semgrepDomain,stripJsonComments,tripwireDomain,+ parseCargoLockCrates,ALL,+ CARGO_LOCK,JAVASCRIPT,NATIVE_BINDING_CONSUMER_LANES,NODE,diff --git a/.github/scripts/trunk-impacted-targets.test.js b/.github/scripts/trunk-impacted-targets.test.jsindex 74fa5c4a9569..9cea5bfe7fd9 100644--- a/.github/scripts/trunk-impacted-targets.test.js+++ b/.github/scripts/trunk-impacted-targets.test.js@@ -15,6 +15,8 @@ const path = require('node:path')const {computeTargets,allKnownTargets,+ buildContext,+ parseCargoLockCrates,compileContractMatcher,compileWorkspaceMatcher,globToRegExp,@@ -727,7 +729,8 @@ test('a crate that builds an npm package claims the lanes importing it', () => {// The cargo lockfile, the manifest, and the sqlx offline data resolve nothing// outside the cargo workspace, so the lanes they can break are the rust ones// plus whatever reaches them through a native module, rather than every lane in-// the repo.+// the repo. rust/Cargo.lock is in the list on its fallback: this context carries+// no determinator answer, so it claims the same set. The narrowed case is below.test('the cargo workspace tripwires claim the rust lanes rather than every lane', () => {const bindingContext = {...CONTEXT,@@ -747,6 +750,67 @@ 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'] })+ assert.deepEqual(+ targets.filter((target) => target.startsWith('rust:crate:')),+ ['rust:crate:consumer', 'rust:crate:shared']+ )+ assert.equal(targets.includes('rust:crate:unrelated'), false, 'a crate the resolution did not move keeps its lane')+})++// An answer naming no crate falls back rather than claiming nothing, because a+// 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: [] })+ assert.deepEqual(+ targets.filter((target) => target.startsWith('rust:crate:')),+ ['rust:crate:consumer', 'rust:crate:shared', 'rust:crate:unrelated']+ )+ assert.equal(targets.includes('py:core'), false, 'the empty-set guard should not have fired')+})++// Each of these is a way for the answer to arrive unusable, and reading one as+// "no crate" would be narrower than reality, which is the direction that breaks+// master. All of them have to read as unknown so the caller widens.+test('an unusable determinator answer reads as unknown', () => {+ for (const [name, raw] of [+ ['a skipped or failed step', ''],+ ['an unset variable', undefined],+ ['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"]'],+ ]) {+ assert.equal(parseCargoLockCrates(raw, CONTEXT.rustGraph), 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'])+})++// 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)+ const members = fs+ .readFileSync(path.join(REPO_ROOT, 'rust/Cargo.toml'), 'utf8')+ .split(/^\s*\[/m)+ .find((section) => section.startsWith('workspace]'))+ .match(/members\s*=\s*\[([^\]]*)\]/)[1]+ .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 twodiff --git a/.github/workflows/trunk-impacted-targets.yml b/.github/workflows/trunk-impacted-targets.ymlindex a405834d985b..5803542689cd 100644--- a/.github/workflows/trunk-impacted-targets.yml+++ b/.github/workflows/trunk-impacted-targets.yml@@ -80,8 +80,10 @@ jobs:node-version-file: .nvmrctoken: ${{ github.token }}- - name: Compute impacted targets- id: targets+ # Split from the computation below so the cargo steps can be skipped+ # on the PRs that do not need them, which is nearly all of them.+ - name: Resolve the changed files+ id: changesenv:MERGE_TARGET: ${{ github.event.repository.default_branch }}run: |@@ -90,26 +92,71 @@ jobs:# A missing merge base (branch older than the fetched depth) or# any diff failure has to widen to ALL rather than upload a# partial file list, which Trunk cannot distinguish from a- # complete one.+ # complete one. The computation step reads `resolved` and+ # reports ALL when it is anything but true.if ! merge_base="$(git merge-base "refs/remotes/origin/$MERGE_TARGET" HEAD 2>/dev/null)"; thenecho "::warning::No merge base against $MERGE_TARGET within the fetched depth; reporting ALL."- echo 'targets={"impactedTargets":"ALL"}' >> "$GITHUB_OUTPUT"+ echo 'resolved=false' >> "$GITHUB_OUTPUT"exit 0fiif ! changed="$(git diff --name-only "$merge_base" HEAD)"; thenecho "::warning::Could not diff against the merge base; reporting ALL."- echo 'targets={"impactedTargets":"ALL"}' >> "$GITHUB_OUTPUT"+ echo 'resolved=false' >> "$GITHUB_OUTPUT"exit 0fiecho "$changed" | sed 's/^/ /'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"+ 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.+ - name: Install rust+ if: steps.changes.outputs.cargo_lock == 'true'+ uses: dtolnay/rust-toolchain@3c5f7ea28cd621ae0bf5283f0e981fb97b8a7af9+ with:+ toolchain: 1.91.1++ - name: Compute affected rust crates+ id: affected+ if: steps.changes.outputs.cargo_lock == '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+ uses: ./.github/actions/rust-compute-affected+ with:+ event-name: ${{ github.event_name }}+ pr-base-sha: ${{ github.event.pull_request.base.sha }}++ - name: Compute impacted targets+ id: targets+ env:+ RESOLVED: ${{ steps.changes.outputs.resolved }}+ # Empty when the determinator was skipped or failed, which the+ # 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 }}+ run: |+ set -uo pipefail++ if [ "$RESOLVED" != "true" ]; then+ echo 'targets={"impactedTargets":"ALL"}' >> "$GITHUB_OUTPUT"+ exit 0+ fi+# The script prints a JSON array on stdout, or the JSON string "ALL" when it# could not enumerate the targets, and never exits non-zero;# it degrades to "ALL" internally on any error.- computed="$(printf '%s\n' "$changed" | node .github/scripts/trunk-impacted-targets.js)"+ 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