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.

feat(ci): resolve impacted targets from the github api, not local history (#117151)

Georges-Antoine Assi0a6ef0b19470
diff --git a/.agents/skills/authoring-ci-workflows/SKILL.md b/.agents/skills/authoring-ci-workflows/SKILL.md
index db9d71b225e8..38a5f119c21a 100644
--- a/.agents/skills/authoring-ci-workflows/SKILL.md
+++ b/.agents/skills/authoring-ci-workflows/SKILL.md
@@ -240,6 +240,14 @@ Measured checkout-step durations, from the GitHub API on real runs:
- **Default:** plain `actions/checkout` (depth 1). Add nothing.
+- **Asking for changed files or a merge base:** ask the GitHub API, not local history.
+ On `pull_request` the checkout's HEAD is the merge commit, so `repos/{repo}/compare/{default_branch}...{merge_sha}?per_page=1` returns the merge base and the change set in one call.
+ It lists at most 300 files, so a list at the cap is truncated. Past it, fetch the merge base without blobs and `git diff --name-only --no-renames <sha> HEAD`, which reads only trees.
+ `repos/{repo}/pulls/{n}/files` is no substitute: it diffs the PR head against its own base, not the merge commit, and reads whatever head the PR has when the call runs.
+ List a rename's `previous_filename` too, since the old path counts as deleted.
+ To read one file at the merge base, `git fetch --no-tags --depth=1 --filter=blob:none origin <sha>` and `git show <sha>:<path>` it, or use the contents API.
+ `trunk-impacted-targets.yml` is the reference.
+
- **Diffing against the PR base:** you need real history, so bound the depth, filter blobs, **and** sparse-checkout the files the job reads:
```yaml
diff --git a/.github/actions/rust-compute-affected/action.yml b/.github/actions/rust-compute-affected/action.yml
index c0f1e9beadea..cb5563d78b9e 100644
--- a/.github/actions/rust-compute-affected/action.yml
+++ b/.github/actions/rust-compute-affected/action.yml
@@ -15,18 +15,30 @@ inputs:
description: 'Previous HEAD for push events (github.event.before)'
required: false
default: ''
- base-branch:
+ base-ref:
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.
+ A merge base the caller already resolved. When set, the action diffs
+ against it and makes no compare call, so the package graph and a
+ `changed-files` list from the caller share one base. A value that is
+ not a full commit SHA rebuilds all.
required: false
default: ''
rebuild-all:
description: 'Force a full rebuild (skip diff analysis)'
required: false
default: 'false'
+ changed-files:
+ description: |
+ Path to a newline-separated list of changed files. When set, the
+ binary reads the change set from it instead of running git diff,
+ so the caller's checkout needs no history. The base commit is then
+ fetched on its own, at depth 1, for the old package graph.
+ required: false
+ default: ''
+ token:
+ description: Token for the compare API call that resolves the merge base.
+ required: false
+ default: ${{ github.token }}
outputs:
crates:
@@ -72,32 +84,44 @@ 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 }}
+ BASE_REF: ${{ inputs.base-ref }}
FORCE_REBUILD: ${{ inputs.rebuild-all }}
+ CHANGED_FILES: ${{ inputs.changed-files }}
+ REPOSITORY: ${{ github.repository }}
+ GH_TOKEN: ${{ inputs.token }}
working-directory: rust
run: |
if [ "$FORCE_REBUILD" = "true" ]; then
echo "rebuild-all requested"
result=$(./target/release/affected-services --files rust/Cargo.lock)
else
- if [ "$EVENT_NAME" = "push" ]; then
+ if [ -n "$BASE_REF" ]; then
+ if [[ "$BASE_REF" =~ ^[0-9a-f]{40}$ ]]; then
+ base_ref="$BASE_REF"
+ else
+ echo "base-ref is not a commit SHA: $BASE_REF"
+ base_ref=""
+ fi
+ elif [ "$EVENT_NAME" = "push" ]; then
base_ref="$PUSH_BEFORE_SHA"
else
- # 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="$BASE_BRANCH"
- if [ -z "$base_branch" ] && [ -f "$GITHUB_EVENT_PATH" ]; then
+ # Try to resolve the base branch name from 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=$(jq -r '.pull_request.base.ref // empty' "$GITHUB_EVENT_PATH" 2>/dev/null || true)
fi
if [ -n "$base_branch" ]; then
- git fetch --no-tags origin "$base_branch"
- base_ref=$(git merge-base FETCH_HEAD HEAD || true)
- if [ -n "$base_ref" ]; then
- echo "Using merge-base of origin/$base_branch and HEAD: $base_ref"
+ head_sha=$(git rev-parse HEAD)
+ # On an API error gh writes the error body to stdout, so
+ # only a full SHA counts as a merge base.
+ base_ref=$(gh api "repos/$REPOSITORY/compare/$base_branch...$head_sha?per_page=1" --jq '.merge_base_commit.sha' 2>/dev/null || true)
+ if [[ "$base_ref" =~ ^[0-9a-f]{40}$ ]]; then
+ echo "Using the merge base of $base_branch and HEAD from the compare API: $base_ref"
else
- echo "merge-base empty; falling back to PR base SHA"
+ echo "The compare API gave no merge base; falling back to PR base SHA"
base_ref="$PR_BASE_SHA"
fi
else
@@ -109,7 +133,14 @@ runs:
echo "No valid base ref — rebuilding all"
result=$(./target/release/affected-services --files rust/Cargo.lock)
else
- result=$(./target/release/affected-services --base-ref "$base_ref")
+ if ! git cat-file -e "$base_ref^{commit}" 2>/dev/null; then
+ git fetch --no-tags --depth=1 --filter=blob:none origin "$base_ref" || true
+ fi
+ if [ -n "$CHANGED_FILES" ]; then
+ result=$(./target/release/affected-services --stdin --base-ref "$base_ref" < "$CHANGED_FILES")
+ else
+ result=$(./target/release/affected-services --base-ref "$base_ref")
+ fi
fi
fi
diff --git a/.github/workflows/trunk-impacted-targets.yml b/.github/workflows/trunk-impacted-targets.yml
index da1aaf6424c4..dd41fe8aca74 100644
--- a/.github/workflows/trunk-impacted-targets.yml
+++ b/.github/workflows/trunk-impacted-targets.yml
@@ -58,22 +58,9 @@ jobs:
targets: ${{ steps.targets.outputs.targets }}
telemetry: ${{ steps.telemetry.outputs.properties }}
steps:
+ # Depth 1: the change set and the merge base come from the GitHub API
+ # below, not from local history.
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- with:
- fetch-depth: 1000
- filter: blob:none
-
- # The default branch, not `base.ref`. A stacked PR's base is the layer
- # below it, but the queue tests the whole stack merged into master, so
- # master is the radius Trunk schedules against. Diffing against a stack
- # parent that has fallen behind master counts every commit the head
- # picked up in between as this PR's own, and a change set that wide
- # claims every lane — which serializes the queue behind a PR that
- # touched none of them.
- - name: Fetch the merge target for the changed-file diff
- env:
- MERGE_TARGET: ${{ github.event.repository.default_branch }}
- run: git fetch --no-tags --depth=1000 --filter=blob:none origin "$MERGE_TARGET:refs/remotes/origin/$MERGE_TARGET"
- uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v6.2.0
with:
@@ -91,41 +78,105 @@ jobs:
# 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.
+ #
+ # The default branch, not `base.ref`. A stacked PR's base is the layer
+ # below it, but the queue tests the whole stack merged into master, so
+ # master is the radius Trunk schedules against. Diffing against a stack
+ # parent that has fallen behind master counts every commit the head
+ # picked up in between as this PR's own, and a change set that wide
+ # claims every lane — which serializes the queue behind a PR that
+ # touched none of them.
+ #
+ # HEAD is the PR merge commit, so comparing the default branch with
+ # it gives the merge base and the files the PR changes relative to it
+ # in one call.
- name: Resolve the changed files
id: changes
env:
+ GH_TOKEN: ${{ github.token }}
+ REPOSITORY: ${{ github.repository }}
MERGE_TARGET: ${{ github.event.repository.default_branch }}
run: |
set -uo pipefail
- # A missing merge base (branch older than the fetched depth) or
- # any diff failure has to widen to ALL rather than upload a
- # partial file list, which Trunk cannot distinguish from a
- # complete one. 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)"; then
- echo "::warning::No merge base against $MERGE_TARGET within the fetched depth; reporting ALL."
- echo 'resolved=false' >> "$GITHUB_OUTPUT"
- exit 0
- fi
-
- # --no-renames lists a renamed file as its old path and its new
- # one. The old path is what the target script reads as deleted,
- # and it widens on that: the tach map has no importer edge for it.
- if ! changed="$(git diff --name-only --no-renames "$merge_base" HEAD)"; then
- echo "::warning::Could not diff against the merge base; reporting ALL."
+ # An API failure or a truncated file list has to widen to ALL
+ # rather than upload a partial file list, which Trunk cannot
+ # distinguish from a complete one. The computation step reads
+ # `resolved` and reports ALL when it is anything but true.
+ unresolved() {
+ echo "::warning::$1; reporting ALL."
echo 'resolved=false' >> "$GITHUB_OUTPUT"
exit 0
+ }
+
+ # Each attempt overwrites the output file, so a failed attempt
+ # leaves no partial page behind for the next one to append to.
+ # A 4xx, rate limits included, would fail again on the same
+ # token bucket, so only network errors and 5xx are retried.
+ gh_api_to() {
+ local out="$1" err="$RUNNER_TEMP/gh-api-error.txt" attempt
+ shift
+ for attempt in 1 2 3; do
+ if gh api "$@" > "$out" 2> "$err"; then
+ return 0
+ fi
+ cat "$err" >&2
+ grep -qE '\(HTTP 4[0-9]{2}\)' "$err" && return 1
+ [ "$attempt" -lt 3 ] && sleep $((attempt * 5))
+ done
+ return 1
+ }
+
+ # A renamed file is listed as its old path and its new one. The
+ # old path is what the target script reads as deleted, and it
+ # widens on that: the tach map has no importer edge for it.
+ file_paths='.filename, (select(.previous_filename) | .previous_filename)'
+
+ head_sha="$(git rev-parse HEAD)"
+ compare="$RUNNER_TEMP/compare.json"
+ gh_api_to "$compare" "repos/$REPOSITORY/compare/$MERGE_TARGET...$head_sha?per_page=1" \
+ || unresolved "The compare API failed for $MERGE_TARGET...$head_sha"
+
+ merge_base="$(jq -r '.merge_base_commit.sha // empty' "$compare")"
+ [[ "$merge_base" =~ ^[0-9a-f]{40}$ ]] || unresolved "The compare API returned no merge base"
+ jq -e '.files | type == "array"' "$compare" > /dev/null || unresolved "The compare API returned no file list"
+
+ # The compare API lists at most 300 files. Past that, the merge
+ # base commit is fetched without blobs and diffed against the
+ # checked-out merge commit, which needs only their trees. The pull
+ # request files API is no substitute: it describes the PR head
+ # against its own base, and reads whatever head the PR has now.
+ if [ "$(jq '.files | length' "$compare")" -lt 300 ]; then
+ jq -r ".files[] | $file_paths" "$compare" > "$RUNNER_TEMP/listed-files.txt"
+ else
+ git fetch --no-tags --depth=1 --filter=blob:none origin "$merge_base" \
+ || unresolved "Could not fetch the merge base $merge_base"
+ git diff --name-only --no-renames "$merge_base" HEAD > "$RUNNER_TEMP/listed-files.txt" \
+ || unresolved "Could not diff against the merge base"
fi
- echo "$changed" | sed 's/^/ /'
- printf '%s\n' "$changed" > "$RUNNER_TEMP/changed-files.txt"
+ sort -u "$RUNNER_TEMP/listed-files.txt" > "$RUNNER_TEMP/changed-files.txt"
+ sed 's/^/ /' "$RUNNER_TEMP/changed-files.txt"
+ changed="$(cat "$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
+ if printf '%s\n' "$changed" | grep -qxF 'pnpm-lock.yaml'; then
+ echo 'js_lockfile_changed=true' >> "$GITHUB_OUTPUT"
+ fi
+
+ # The target script reads the base lockfile with `git show` at the
+ # merge base, so that one commit is fetched without its blobs and the
+ # read fetches the two files it needs.
+ - name: Fetch the merge base commit
+ if: steps.changes.outputs.js_lockfile_changed == 'true'
+ continue-on-error: true
+ env:
+ MERGE_BASE: ${{ steps.changes.outputs.merge_base }}
+ run: git fetch --no-tags --depth=1 --filter=blob:none origin "$MERGE_BASE"
# The determinator that ci-rust.yml selects tests with is the sole
# authority on which crates a change set affects, because the lane
@@ -151,13 +202,13 @@ jobs:
uses: ./.github/actions/rust-compute-affected
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 }}
+ # Reuse the master merge base the file list came from. A
+ # stacked PR's base is the layer below it, and a graph diffed
+ # against another base would drop crates the file list implies.
+ base-ref: ${{ steps.changes.outputs.merge_base }}
+ # The checkout is shallow, so the action takes the file list
+ # resolved above instead of diffing against the merge base.
+ changed-files: ${{ runner.temp }}/changed-files.txt
- name: Compute impacted targets
id: targets
diff --git a/rust/affected-services/src/main.rs b/rust/affected-services/src/main.rs
index 3b97daed0963..49561ab2b250 100644
--- a/rust/affected-services/src/main.rs
+++ b/rust/affected-services/src/main.rs
@@ -14,13 +14,13 @@ use affected_services::images::parse_images_yaml;
#[derive(Parser)]
#[command(about = "Compute affected Rust services from changed files")]
struct Cli {
- #[arg(long, conflicts_with_all = ["files", "stdin", "dump_graph"])]
+ #[arg(long, conflicts_with_all = ["files", "dump_graph"])]
base_ref: Option<String>,
#[arg(long, num_args = 1.., conflicts_with_all = ["base_ref", "stdin", "dump_graph"])]
files: Option<Vec<String>>,
- #[arg(long, conflicts_with_all = ["base_ref", "files", "dump_graph"])]
+ #[arg(long, conflicts_with_all = ["files", "dump_graph"])]
stdin: bool,
#[arg(long, conflicts_with_all = ["base_ref", "files", "stdin"])]
@@ -62,25 +62,28 @@ fn main() -> Result<()> {
let (changed_files, old_graph) = if let Some(files) = cli.files {
(files, None)
- } else if cli.stdin {
- let files = std::io::stdin()
- .lock()
- .lines()
- .map_while(Result::ok)
- .filter(|l| !l.is_empty())
- .collect();
- (files, None)
- } else if let Some(base_ref) = &cli.base_ref {
- let files = get_changed_files(base_ref)?;
- let workspace_subdir = workspace_dir
- .strip_prefix(&repo_root)
- .unwrap_or(Path::new("rust"))
- .to_string_lossy()
- .to_string();
- let old = build_old_package_graph(base_ref, &workspace_subdir);
- (files, old)
} else {
- anyhow::bail!("one of --base-ref, --files, --stdin, or --dump-graph is required");
+ let files = if cli.stdin {
+ std::io::stdin()
+ .lock()
+ .lines()
+ .map_while(Result::ok)
+ .filter(|l| !l.is_empty())
+ .collect()
+ } else if let Some(base_ref) = &cli.base_ref {
+ get_changed_files(base_ref)?
+ } else {
+ anyhow::bail!("one of --base-ref, --files, --stdin, or --dump-graph is required");
+ };
+ let old = cli.base_ref.as_deref().and_then(|base_ref| {
+ let workspace_subdir = workspace_dir
+ .strip_prefix(&repo_root)
+ .unwrap_or(Path::new("rust"))
+ .to_string_lossy()
+ .to_string();
+ build_old_package_graph(base_ref, &workspace_subdir)
+ });
+ (files, old)
};
let result = compute_affected(&changed_files, old_graph.as_ref(), &new_graph, &images)?;