diff --git a/.github/workflows/build-failure-analysis-command.lock.yml b/.github/workflows/build-failure-analysis-command.lock.yml
index bbe4028033..11a07f2388 100644
--- a/.github/workflows/build-failure-analysis-command.lock.yml
+++ b/.github/workflows/build-failure-analysis-command.lock.yml
@@ -1,4 +1,4 @@
-# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"2892f1fff729423daffcbc94c32d1e9d71bf2b6fb5d3c51138c455980e7e7efd","body_hash":"dbeeacd9172428fc1f34b1146573d24a669de1f5b9a539f390da3d041b37dc1e","compiler_version":"v0.83.1","strict":true,"agent_id":"copilot","engine_versions":{"copilot":"1.0.73"}}
+# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"afab71c4d900c2faabe301246c9607f97be771b7345848cbb963adcd54407a12","body_hash":"12138283dffe89b249c24adc8cc1f216cc9a3f094796cd026187500eb1627c9e","compiler_version":"v0.83.1","strict":true,"agent_id":"copilot","engine_versions":{"copilot":"1.0.73"}}
# gh-aw-manifest: {"version":1,"secrets":["COPILOT_GITHUB_TOKEN","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN"],"actions":[{"repo":"actions/cache/restore","sha":"55cc8345863c7cc4c66a329aec7e433d2d1c52a9","version":"v6.1.0"},{"repo":"actions/cache/save","sha":"55cc8345863c7cc4c66a329aec7e433d2d1c52a9","version":"v6.1.0"},{"repo":"actions/checkout","sha":"3d3c42e5aac5ba805825da76410c181273ba90b1","version":"v7.0.1"},{"repo":"actions/checkout","sha":"3d3c42e5aac5ba805825da76410c181273ba90b1","version":"v7.0.1"},{"repo":"actions/download-artifact","sha":"3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c","version":"v8.0.1"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"820762786026740c76f36085b0efc47a31fe5020","version":"v7.0.0"},{"repo":"actions/upload-artifact","sha":"043fb46d1a93c77aae656e7c1c64a875d1fc6a0a","version":"v7.0.1"},{"repo":"github/gh-aw-actions/setup","sha":"8bdba8075360648fe6802302a5b4e016361dc6ac","version":"v0.83.1"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.27.38","digest":"sha256:cb928eb62d9139a013c2d278dab19af232d35a2d83dca71a3d98eb431f786243","pinned_image":"ghcr.io/github/gh-aw-firewall/agent:0.27.38@sha256:cb928eb62d9139a013c2d278dab19af232d35a2d83dca71a3d98eb431f786243"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.27.38","digest":"sha256:cd6145620d96acee46e1ede25180a13aa36002467e663db0caa453a8bc8eb60c","pinned_image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.27.38@sha256:cd6145620d96acee46e1ede25180a13aa36002467e663db0caa453a8bc8eb60c"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.27.38","digest":"sha256:6c19094d95aad5f9f128ad5e583f0f2b894b158aa66c3b86dd9bcc90970a2917","pinned_image":"ghcr.io/github/gh-aw-firewall/squid:0.27.38@sha256:6c19094d95aad5f9f128ad5e583f0f2b894b158aa66c3b86dd9bcc90970a2917"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.4.3","digest":"sha256:3c744710ea275cd5ee65db92a1099e0d980754bd9fafda9ce67704c67004dc83","pinned_image":"ghcr.io/github/gh-aw-mcpg:v0.4.3@sha256:3c744710ea275cd5ee65db92a1099e0d980754bd9fafda9ce67704c67004dc83"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b","pinned_image":"ghcr.io/github/gh-aw-node@sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b"},{"image":"ghcr.io/github/github-mcp-server:v1.6.0","digest":"sha256:2b0c48b070f61e9d3969269ead600f62d00fb237b60ac849ef3d166ee7de9ad3","pinned_image":"ghcr.io/github/github-mcp-server:v1.6.0@sha256:2b0c48b070f61e9d3969269ead600f62d00fb237b60ac849ef3d166ee7de9ad3"},{"image":"mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-binlog-mcp-amd64","digest":"sha256:9f1e2c3e8281186eb1190f39918b23accefefb4dd086d0ac1bd3e4ea7d2ed0e0","pinned_image":"mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-binlog-mcp-amd64@sha256:9f1e2c3e8281186eb1190f39918b23accefefb4dd086d0ac1bd3e4ea7d2ed0e0"}]}
# This file was automatically generated by gh-aw (v0.83.1). DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md
#
@@ -27,6 +27,7 @@
#
# Resolved workflow manifest:
# Imports:
+# - shared/build-failure-analysis-fetch.md
# - shared/build-failure-analysis-shared.md
#
# Secrets used:
@@ -305,20 +306,20 @@ jobs:
run: |
bash "${RUNNER_TEMP}/gh-aw/actions/create_prompt_first.sh"
{
- cat << 'GH_AW_PROMPT_79dda3d6a11104c4_EOF'
+ cat << 'GH_AW_PROMPT_b0ed92b2042b5662_EOF'
- GH_AW_PROMPT_79dda3d6a11104c4_EOF
+ GH_AW_PROMPT_b0ed92b2042b5662_EOF
cat "${RUNNER_TEMP}/gh-aw/prompts/xpia.md"
cat "${RUNNER_TEMP}/gh-aw/prompts/temp_folder_prompt.md"
cat "${RUNNER_TEMP}/gh-aw/prompts/markdown.md"
cat "${RUNNER_TEMP}/gh-aw/prompts/safe_outputs_prompt.md"
- cat << 'GH_AW_PROMPT_79dda3d6a11104c4_EOF'
+ cat << 'GH_AW_PROMPT_b0ed92b2042b5662_EOF'
Tools: add_comment(max:5), create_pull_request_review_comment(max:25), missing_tool, missing_data, noop(max:5)
- GH_AW_PROMPT_79dda3d6a11104c4_EOF
+ GH_AW_PROMPT_b0ed92b2042b5662_EOF
cat "${RUNNER_TEMP}/gh-aw/prompts/mcp_cli_tools_prompt.md"
- cat << 'GH_AW_PROMPT_79dda3d6a11104c4_EOF'
+ cat << 'GH_AW_PROMPT_b0ed92b2042b5662_EOF'
The following GitHub context information is available for this workflow:
{{#if github.actor}}
@@ -347,16 +348,17 @@ jobs:
{{/if}}
- GH_AW_PROMPT_79dda3d6a11104c4_EOF
+ GH_AW_PROMPT_b0ed92b2042b5662_EOF
cat "${RUNNER_TEMP}/gh-aw/prompts/github_mcp_tools_with_safeoutputs_prompt.md"
if [ "$GITHUB_EVENT_NAME" = "issue_comment" ] && [ -n "$GH_AW_IS_PR_COMMENT" ] || [ "$GITHUB_EVENT_NAME" = "pull_request_review_comment" ] || [ "$GITHUB_EVENT_NAME" = "pull_request_review" ]; then
cat "${RUNNER_TEMP}/gh-aw/prompts/pr_context_prompt.md"
fi
- cat << 'GH_AW_PROMPT_79dda3d6a11104c4_EOF'
+ cat << 'GH_AW_PROMPT_b0ed92b2042b5662_EOF'
{{#runtime-import .github/workflows/shared/build-failure-analysis-shared.md}}
+ {{#runtime-import .github/workflows/shared/build-failure-analysis-fetch.md}}
{{#runtime-import .github/workflows/build-failure-analysis-command.md}}
- GH_AW_PROMPT_79dda3d6a11104c4_EOF
+ GH_AW_PROMPT_b0ed92b2042b5662_EOF
} > "$GH_AW_PROMPT"
- name: Interpolate variables and render templates
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
@@ -1648,6 +1650,10 @@ jobs:
fetch-binlog:
name: Fetch binlogs (Azure Pipelines)
+ if: >
+ github.event_name == 'workflow_dispatch' || (github.event_name == 'check_run' &&
+ github.event.check_run.name == 'microsoft.testfx' &&
+ github.event.check_run.conclusion == 'failure')
runs-on: ubuntu-latest
permissions:
contents: read
@@ -1673,6 +1679,7 @@ jobs:
echo "GH_HOST=${GH_HOST}" >> "$GITHUB_ENV"
- name: Verify the commenter has write access
id: perm
+ if: github.event.check_run.details_url == '' && github.event.inputs['ado-build-id'] == ''
run: |
set +e
authorized=false
@@ -1714,97 +1721,190 @@ jobs:
env:
COMMENTER: ${{ github.event.comment.user.login || fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').actor }}
GH_TOKEN: ${{ github.token }}
- - name: Download binlogs from the PR's latest failed Azure Pipelines build
+ - name: Download binlogs from the failed Azure Pipelines build
id: fetch
- if: steps.perm.outputs.authorized == 'true'
+ if: github.event.check_run.details_url != '' || github.event.inputs['ado-build-id'] != '' || steps.perm.outputs.authorized == 'true'
run: |
- # Advisory + best-effort. On any gap emit binlog-found=false so the
+ # Advisory + best-effort: on any gap emit binlog-found=false and the
# agent pipeline stays inert.
set +e
set +o pipefail
emit_none() { echo "binlog-found=false" >> "$GITHUB_OUTPUT"; exit 0; }
- [ -z "${PR_NUMBER}" ] && { echo "::warning::No PR number resolved from the slash-command event / aw_context."; emit_none; }
- # PR_NUMBER feeds GitHub API paths and the `refs/pull//merge`
- # branch query; require it numeric so a malformed event/aw_context
- # payload can't reach those URLs with unexpected content.
- if ! printf '%s' "${PR_NUMBER}" | grep -qE '^[0-9]+$'; then
- echo "::warning::Resolved PR number '${PR_NUMBER}' is not numeric; refusing."; emit_none
+ # --- 1. Resolve the Azure DevOps build and the PR it belongs to ---
+ # This is the ONLY part of the job that differs between the two
+ # workflows, because they learn about the build in opposite
+ # directions:
+ #
+ # * `check_run` / manual dispatch are TOLD which build to look at —
+ # the check payload names it in `details_url`, a manual dispatch
+ # passes it explicitly — so the build is resolved first and the PR
+ # is derived from it.
+ # * The slash command is told nothing about a build: it is a request
+ # to re-analyse whatever the PR's newest build is, so the PR comes
+ # first and the build is looked up from it. That build is usable
+ # only once it has COMPLETED; a still running newest build (e.g.
+ # right after a force-push) would otherwise pair an older failure
+ # with the PR's current head.
+ #
+ # Both importing workflows can receive `workflow_dispatch` (the slash
+ # command uses `strategy: centralized`), so the branch is taken on the
+ # payload rather than on the event name: having a build id at all is
+ # what makes this the automatic workflow.
+ if [ -n "${DISPATCH_BUILD_ID}" ] || [ -n "${CHECK_DETAILS_URL}" ]; then
+ ENTRY="build"
+ if [ -n "${DISPATCH_BUILD_ID}" ]; then
+ BUILD_ID="${DISPATCH_BUILD_ID}"
+ else
+ # details_url looks like: .../_build/results?buildId=NNN&view=...
+ BUILD_ID=$(printf '%s' "${CHECK_DETAILS_URL}" | grep -oE 'buildId=[0-9]+' | head -1 | cut -d= -f2)
+ fi
+ echo "Azure DevOps build id: '${BUILD_ID}'"
+ [ -z "${BUILD_ID}" ] && { echo "::warning::Could not resolve an ADO build id."; emit_none; }
+ # The build id feeds directly into ADO API URLs below; require it to
+ # be purely numeric (esp. on workflow_dispatch, where it is free-form
+ # input) so a malformed value can't alter the request path/query.
+ if ! printf '%s' "${BUILD_ID}" | grep -qE '^[0-9]+$'; then
+ echo "::warning::Resolved ADO build id '${BUILD_ID}' is not numeric; refusing."; emit_none
+ fi
+ # The build metadata is the authoritative source for the PR number
+ # (via sourceBranch) as well as for the definition / result /
+ # revision validated in step 3.
+ build_json=$(curl -sSL --retry 3 "${ADO_API}/build/builds/${BUILD_ID}?api-version=7.1")
+ # A PR build's sourceBranch is exactly `refs/pull//merge`, so it
+ # identifies the PR unambiguously — unlike the commit->PRs API,
+ # which can return several PRs in an unspecified order.
+ BUILD_PR_NUM=$(printf '%s' "${build_json}" | jq -r '.sourceBranch // empty' | sed -n 's#^refs/pull/\([0-9]\{1,\}\)/merge$#\1#p')
+ if [ -n "${DISPATCH_BUILD_ID}" ]; then
+ PR_NUMBER="${DISPATCH_PR_NUMBER}"
+ else
+ # Prefer the PR named by the build's own sourceBranch
+ # (authoritative) over check_run.pull_requests[0], whose order
+ # isn't guaranteed and can name a different PR sharing the commit.
+ PR_NUMBER="${BUILD_PR_NUM:-${CHECK_PR_NUMBER}}"
+ fi
+ [ -z "${PR_NUMBER}" ] && { echo "::warning::Could not resolve a PR number."; emit_none; }
+ # PR_NUMBER feeds `gh api .../pulls/` and the `refs/pull//merge`
+ # comparison; require it numeric so a malformed value can't reach the
+ # GitHub API path (traversal-like input) or skew the branch match.
+ if ! printf '%s' "${PR_NUMBER}" | grep -qE '^[0-9]+$'; then
+ echo "::warning::Resolved PR number '${PR_NUMBER}' is not numeric; refusing."; emit_none
+ fi
+ else
+ ENTRY="command"
+ PR_NUMBER="${COMMAND_PR_NUMBER}"
+ [ -z "${PR_NUMBER}" ] && { echo "::warning::No PR number resolved from the slash-command event / aw_context."; emit_none; }
+ # PR_NUMBER feeds GitHub API paths and the `refs/pull//merge`
+ # branch query; require it numeric so a malformed event/aw_context
+ # payload can't reach those URLs with unexpected content.
+ if ! printf '%s' "${PR_NUMBER}" | grep -qE '^[0-9]+$'; then
+ echo "::warning::Resolved PR number '${PR_NUMBER}' is not numeric; refusing."; emit_none
+ fi
+ # Newest build for the PR's merge ref REGARDLESS of status
+ # (queue-time descending), so a build queued after an older failure
+ # is seen rather than the stale one being analysed silently.
+ builds_json=$(curl -sSL --retry 3 \
+ "${ADO_API}/build/builds?definitions=${ADO_BUILD_DEFINITION_ID}&branchName=refs/pull/${PR_NUMBER}/merge&queryOrder=queueTimeDescending&\$top=1&api-version=7.1")
+ BUILD_ID=$(printf '%s' "${builds_json}" | jq -r '.value // [] | .[0].id // empty')
+ BUILD_STATUS=$(printf '%s' "${builds_json}" | jq -r '.value // [] | .[0].status // empty')
+ echo "Newest microsoft.testfx build for PR #${PR_NUMBER}: id='${BUILD_ID}' status='${BUILD_STATUS}'"
+ [ -z "${BUILD_ID}" ] && { echo "::warning::No microsoft.testfx build found for PR #${PR_NUMBER}."; emit_none; }
+ # Require a numeric build id before it feeds subsequent ADO API
+ # URLs, so a malformed query response can't inject path/query.
+ if ! printf '%s' "${BUILD_ID}" | grep -qE '^[0-9]+$'; then
+ echo "::warning::ADO build id '${BUILD_ID}' is not numeric; refusing."; emit_none
+ fi
+ if [ "${BUILD_STATUS}" != "completed" ]; then
+ echo "::warning::PR #${PR_NUMBER}'s newest microsoft.testfx build (${BUILD_ID}) is still '${BUILD_STATUS}'; wait for it to finish before analysing."
+ emit_none
+ fi
+ build_json=$(curl -sSL --retry 3 "${ADO_API}/build/builds/${BUILD_ID}?api-version=7.1")
fi
+ RESULT=$(printf '%s' "${build_json}" | jq -r '.result // empty')
+ DEF_ID=$(printf '%s' "${build_json}" | jq -r '.definition.id // empty')
+ SRC_BRANCH=$(printf '%s' "${build_json}" | jq -r '.sourceBranch // empty')
- # --- Scope check: only analyse PRs targeting main / rel/* ---
+ # --- 2. Scope check: only analyse PRs targeting main / rel/* ---
PR_JSON=$(gh api "repos/${GH_AW_REPO}/pulls/${PR_NUMBER}" 2>/dev/null)
BASE_REF=$(printf '%s' "${PR_JSON}" | jq -r '.base.ref // empty')
- HEAD_SHA=$(printf '%s' "${PR_JSON}" | jq -r '.head.sha // empty')
case "${BASE_REF}" in
main|rel/*) echo "PR #${PR_NUMBER} base '${BASE_REF}' is in scope." ;;
*) echo "::warning::PR #${PR_NUMBER} base '${BASE_REF}' is out of scope (main, rel/*); skipping."; emit_none ;;
esac
- # --- Find the PR's most recent microsoft.testfx build (merge ref) ---
- # Query the newest build REGARDLESS of status (queue-time desc). If
- # the newest build is still queued/running — e.g. right after a
- # force-push — skip: analysing an older completed failure now would
- # pair a stale binlog with the PR's current head. Only proceed when
- # the newest build is completed AND failed. The head SHA is then
- # anchored to that build's own revision (below), so links/suggestions
- # always match the analysed binlog.
- builds_json=$(curl -sSL --retry 3 \
- "${ADO_API}/build/builds?definitions=${ADO_BUILD_DEFINITION_ID}&branchName=refs/pull/${PR_NUMBER}/merge&queryOrder=queueTimeDescending&\$top=1&api-version=7.1")
- BUILD_ID=$(printf '%s' "${builds_json}" | jq -r '.value // [] | .[0].id // empty')
- BUILD_STATUS=$(printf '%s' "${builds_json}" | jq -r '.value // [] | .[0].status // empty')
- BUILD_RESULT=$(printf '%s' "${builds_json}" | jq -r '.value // [] | .[0].result // empty')
- echo "Newest microsoft.testfx build for PR #${PR_NUMBER}: id='${BUILD_ID}' status='${BUILD_STATUS}' result='${BUILD_RESULT}'"
- [ -z "${BUILD_ID}" ] && { echo "::warning::No microsoft.testfx build found for PR #${PR_NUMBER}."; emit_none; }
- # Require a numeric build id before it feeds subsequent ADO API URLs,
- # so a malformed query response can't inject unexpected path/query.
- if ! printf '%s' "${BUILD_ID}" | grep -qE '^[0-9]+$'; then
- echo "::warning::ADO build id '${BUILD_ID}' is not numeric; refusing."; emit_none
+ # --- 3. Validate the build, whichever way it was resolved ---
+ # It must be the microsoft.testfx definition (209), have failed, and
+ # belong to this PR (sourceBranch == refs/pull//merge). No entry
+ # point is fully trusted: `check_run` parses the build id out of a
+ # check payload, dispatch takes the build id and PR number as
+ # independent free-form inputs, and the slash command derives the
+ # build from a query. Validating here — rather than per entry point —
+ # prevents downloading an unrelated build or posting its analysis to
+ # the wrong PR.
+ echo "ADO build ${BUILD_ID}: result='${RESULT}' definition='${DEF_ID}' sourceBranch='${SRC_BRANCH}'"
+ if [ "${DEF_ID}" != "${ADO_BUILD_DEFINITION_ID}" ]; then
+ echo "::warning::ADO build ${BUILD_ID} is definition '${DEF_ID}', not microsoft.testfx (${ADO_BUILD_DEFINITION_ID}); refusing."; emit_none
fi
- if [ "${BUILD_STATUS}" != "completed" ]; then
- echo "::warning::PR #${PR_NUMBER}'s newest microsoft.testfx build (${BUILD_ID}) is still '${BUILD_STATUS}'; wait for it to finish before analysing."
+ if [ "${RESULT}" != "failed" ]; then
+ if [ "${ENTRY}" = "command" ]; then
+ echo "::warning::PR #${PR_NUMBER}'s newest microsoft.testfx build (${BUILD_ID}) result is '${RESULT}', not failed — the failure looks resolved; nothing to analyse."
+ else
+ echo "::warning::ADO build ${BUILD_ID} did not fail (result='${RESULT}'); nothing to analyze."
+ fi
emit_none
fi
- if [ "${BUILD_RESULT}" != "failed" ]; then
- echo "::warning::PR #${PR_NUMBER}'s newest microsoft.testfx build (${BUILD_ID}) result is '${BUILD_RESULT}', not failed — the failure looks resolved; nothing to analyse."
- emit_none
+ if [ "${SRC_BRANCH}" != "refs/pull/${PR_NUMBER}/merge" ]; then
+ echo "::warning::ADO build ${BUILD_ID} sourceBranch '${SRC_BRANCH}' does not match PR #${PR_NUMBER} (refs/pull/${PR_NUMBER}/merge); refusing to avoid posting to the wrong PR."; emit_none
fi
# Require the build's analyzed revision to equal the PR's CURRENT
- # head. gh-aw safe-output review comments carry no `commit_id` (they
- # target the current PR diff), so analyzing a stale revision would
- # misplace/reject inline suggestions. The PR can advance between
- # selecting the build and downloading artifacts, and right after a
- # force-push this query can still return the previous failed build —
- # so re-read the head here and skip if it moved.
- build_json=$(curl -sSL --retry 3 "${ADO_API}/build/builds/${BUILD_ID}?api-version=7.1")
+ # head. gh-aw safe-output review comments carry no `commit_id` — they
+ # target the current PR diff — so analyzing a stale revision would
+ # produce inline suggestions that get rejected or land on the wrong
+ # lines. The PR can advance between selecting the build and reaching
+ # this point, so the head is re-read here rather than reused from the
+ # scope check above.
BUILD_PR_SHA=$(printf '%s' "${build_json}" | jq -r '.triggerInfo["pr.sourceSha"] // empty')
+ # ADO builds GitHub's `refs/pull//merge` ref, so build_json.sourceVersion
+ # is the merge commit GitHub produced at build time and equals the PR's
+ # `merge_commit_sha` then. If the base branch advances (even with the PR
+ # head unchanged) GitHub recomputes that merge and merge_commit_sha
+ # changes, so this catches base-advance staleness the head check misses.
BUILD_MERGE_SHA=$(printf '%s' "${build_json}" | jq -r '.sourceVersion // empty')
- PR_JSON2=$(gh api "repos/${GH_AW_REPO}/pulls/${PR_NUMBER}" 2>/dev/null)
- CURRENT_HEAD=$(printf '%s' "${PR_JSON2}" | jq -r '.head.sha // empty')
- CURRENT_MERGE=$(printf '%s' "${PR_JSON2}" | jq -r '.merge_commit_sha // empty')
- # Fail CLOSED: if either SHA can't be resolved (transient API failure
- # or missing Azure triggerInfo), skip rather than risk analyzing a
- # stale binlog against the current diff.
+ # Re-read the PR rather than reusing the snapshot from the scope check:
+ # selecting the build costs an ADO round trip, and right after a
+ # force-push the newest-build query can still return the previous
+ # failed build. The point of this check is to skip BEFORE paying for
+ # the download, so it should compare against the freshest head
+ # available. A post-download re-read below independently catches a
+ # head that moves while the artifacts are being fetched.
+ PR_JSON=$(gh api "repos/${GH_AW_REPO}/pulls/${PR_NUMBER}" 2>/dev/null)
+ CURRENT_HEAD=$(printf '%s' "${PR_JSON}" | jq -r '.head.sha // empty')
+ CURRENT_MERGE=$(printf '%s' "${PR_JSON}" | jq -r '.merge_commit_sha // empty')
+ # Fail CLOSED: if either the build's analyzed revision or the current
+ # PR head can't be resolved, skip — we must not analyze a possibly
+ # stale binlog against the current diff (inline comments have no
+ # commit_id and target the current PR diff).
if [ -z "${BUILD_PR_SHA}" ] || [ -z "${CURRENT_HEAD}" ]; then
- echo "::warning::Could not resolve build revision ('${BUILD_PR_SHA}') and/or current PR head ('${CURRENT_HEAD}'); skipping."
+ echo "::warning::Could not resolve build revision ('${BUILD_PR_SHA}') and/or current PR head ('${CURRENT_HEAD}'); skipping to avoid analyzing a stale binlog against the current diff."
emit_none
fi
if [ "${BUILD_PR_SHA}" != "${CURRENT_HEAD}" ]; then
- echo "::warning::Build ${BUILD_ID} analyzed revision '${BUILD_PR_SHA}' but PR #${PR_NUMBER} head is now '${CURRENT_HEAD}'; skipping stale build (a newer build will cover the current revision)."
+ echo "::warning::Build ${BUILD_ID} analyzed revision '${BUILD_PR_SHA}' but PR #${PR_NUMBER} head is now '${CURRENT_HEAD}'; skipping stale build (a newer build/check will cover the current revision)."
emit_none
fi
- # ADO builds GitHub's `refs/pull//merge` ref, so build_json.sourceVersion
- # is that merge commit; if the base branch advanced it differs from the
- # PR's current merge_commit_sha even with the head unchanged. Skip stale merges.
+ # When both merge revisions are known and differ, the base branch moved
+ # since the build — the binlog reflects an obsolete merge. Skip.
if [ -n "${BUILD_MERGE_SHA}" ] && [ -n "${CURRENT_MERGE}" ] && [ "${BUILD_MERGE_SHA}" != "${CURRENT_MERGE}" ]; then
echo "::warning::Build ${BUILD_ID} merge revision '${BUILD_MERGE_SHA}' but PR #${PR_NUMBER} current merge is '${CURRENT_MERGE}' (base branch advanced); skipping stale merge."
emit_none
fi
+ # Consistent now: build revision == current PR head. Use it for
+ # permalinks so they line up with the inline comments' diff target.
HEAD_SHA="${CURRENT_HEAD}"
echo "Analyzing build ${BUILD_ID} at PR head revision '${HEAD_SHA}'."
- # --- Download every Logs_Build_* artifact and extract binlogs ---
+ # --- 4. Download every Logs_Build_* artifact and extract binlogs ---
artifacts_json=$(curl -sSL --retry 3 "${ADO_API}/build/builds/${BUILD_ID}/artifacts?api-version=7.1")
mapfile -t names < <(printf '%s' "${artifacts_json}" | jq -r '.value // [] | map(select(.name | test("^Logs_Build_"))) | .[].name')
[ "${#names[@]}" -eq 0 ] && { echo "::warning::No Logs_Build_* artifacts on build ${BUILD_ID}."; emit_none; }
@@ -1911,7 +2011,9 @@ jobs:
rm -rf /tmp/ax /tmp/a.zip
mkdir -p /tmp/ax
# Hard-cap the bytes written to disk regardless of Content-Length:
- # stream through `head -c` (cap + 1) and bound total time.
+ # stream through `head -c` (cap + 1) and bound total time. This
+ # closes the gap where `curl --max-filesize` alone would let a
+ # length-less response write unbounded data before any post-check.
curl -sSL --retry 3 --max-time 300 "${url}" 2>/dev/null | head -c $((MAX_ZIP_BYTES + 1)) > /tmp/a.zip || true
ZIP_BYTES=$(stat -c%s /tmp/a.zip 2>/dev/null || echo 0)
# Bound cumulative *compressed* bytes too: the per-artifact and
@@ -2064,9 +2166,13 @@ jobs:
ADO_API: https://dev.azure.com/dnceng-public/public/_apis
ADO_BUILD_DEFINITION_ID: "209"
ADO_BUILD_UI: https://dev.azure.com/dnceng-public/public/_build/results
+ CHECK_DETAILS_URL: ${{ github.event.check_run.details_url }}
+ CHECK_PR_NUMBER: ${{ github.event.check_run.pull_requests[0].number }}
+ COMMAND_PR_NUMBER: ${{ github.event.issue.number || fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_number }}
+ DISPATCH_BUILD_ID: ${{ github.event.inputs['ado-build-id'] }}
+ DISPATCH_PR_NUMBER: ${{ github.event.inputs['pr-number'] }}
GH_AW_REPO: ${{ github.repository }}
GH_TOKEN: ${{ github.token }}
- PR_NUMBER: ${{ github.event.issue.number || fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_number }}
- name: Upload analysis artifact
if: steps.fetch.outputs.binlog-found == 'true'
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
@@ -2074,7 +2180,7 @@ jobs:
if-no-files-found: warn
name: build-failure-analysis-data
path: /tmp/binlogs
- retention-days: 1
+ retention-days: "1"
pre_activation:
needs: fetch-binlog
diff --git a/.github/workflows/build-failure-analysis-command.md b/.github/workflows/build-failure-analysis-command.md
index 04f7e4af03..d904722ea3 100644
--- a/.github/workflows/build-failure-analysis-command.md
+++ b/.github/workflows/build-failure-analysis-command.md
@@ -57,6 +57,7 @@ network:
imports:
- shared/build-failure-analysis-shared.md
+ - shared/build-failure-analysis-fetch.md
# Live binlog access for the agent — see build-failure-analysis.md for the
# rationale. The fetch-binlog job downloads each build leg's binlog from Azure
@@ -70,460 +71,12 @@ mcp-servers:
- "/tmp/binlogs:/data/binlogs:ro"
allowed: ["*"]
-# Custom job that reuses the binlogs from the PR's most recent failed Azure
-# DevOps `microsoft.testfx` build instead of rebuilding. Mirrors the fetch-binlog job
-# in build-failure-analysis.md; it locates the build by the PR's merge branch
-# (no `check_run` payload is available on a slash command).
-jobs:
- fetch-binlog:
- name: Fetch binlogs (Azure Pipelines)
- runs-on: ubuntu-latest
- timeout-minutes: 15
- permissions:
- contents: read
- pull-requests: read
- outputs:
- binlog-found: ${{ steps.fetch.outputs.binlog-found }}
- pr-number: ${{ steps.fetch.outputs.pr-number }}
- pr-head-sha: ${{ steps.fetch.outputs.pr-head-sha }}
- pr-merge-sha: ${{ steps.fetch.outputs.pr-merge-sha }}
- ado-build-id: ${{ steps.fetch.outputs.ado-build-id }}
- ado-build-url: ${{ steps.fetch.outputs.ado-build-url }}
- missing-legs: ${{ steps.fetch.outputs.missing-legs }}
- steps:
- # Cost + abuse pre-gate. gh-aw's own role check (`roles: [admin,
- # maintainer, write]`) lives in the generated `pre_activation` job, and
- # that job is compiled with `needs: fetch-binlog` — so it only runs
- # *after* this job has already pulled every build leg's logs artifact
- # from Azure DevOps (hundreds of MB). Inverting the dependency would
- # create a cycle, so the same permission check is repeated here, before
- # anything is downloaded. `pre_activation` remains the authoritative
- # role + command-position check; this is purely an early-out.
- #
- # Because the command uses `strategy: centralized`, this workflow is
- # started by `agentic_commands.yml` via `workflow_dispatch`, so there is
- # no `github.event.comment` payload — the original commenter is
- # propagated in `aw_context.actor` (the same place `item_number` comes
- # from above). `route_slash_command.cjs` in the dispatcher performs no
- # permission check of its own, so without this step any commenter on any
- # PR can trigger the full download.
- #
- # Check `role_name` and `permission` together: `role_name` reports the
- # precise role (so `maintain` and `triage` stay distinct) while
- # `permission` is the coarse legacy field, and a custom org role reports
- # a non-standard name in `role_name` while still showing its push access
- # in `permission`. Accepting the union of the two covers every shape
- # without depending on which field carries the role. On any API failure
- # `gh` emits an error document that has neither field, so the check falls
- # into the deny branch; failing closed is the safe direction for a
- # pre-gate.
- - name: Verify the commenter has write access
- id: perm
- env:
- GH_TOKEN: ${{ github.token }}
- COMMENTER: ${{ github.event.comment.user.login || fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').actor }}
- run: |
- set +e
- authorized=false
- # `COMMENTER` has the same untrusted provenance as `PR_NUMBER` below
- # (an `aw_context` payload), and it is interpolated into an API path
- # and into log output, so give it the same shape check. GitHub logins
- # are alphanumerics and hyphens; anything else is a malformed or
- # hostile payload rather than a real account, and is dropped so it
- # lands in the deny branch.
- case "${COMMENTER}" in
- ""|*[!A-Za-z0-9-]*)
- [ -n "${COMMENTER}" ] && echo "::warning::Ignoring implausible actor name from the event payload."
- COMMENTER="" ;;
- esac
- if [ -z "${COMMENTER}" ]; then
- echo "::warning::No actor resolved from the slash-command event / aw_context; skipping the binlog download."
- else
- resp=$(gh api "repos/${GITHUB_REPOSITORY}/collaborators/${COMMENTER}/permission" 2>/dev/null)
- role=$(printf '%s' "${resp}" | jq -r '.role_name // empty' 2>/dev/null)
- perm=$(printf '%s' "${resp}" | jq -r '.permission // empty' 2>/dev/null)
- for r in "${role}" "${perm}"; do
- case "${r}" in
- # `maintainer` is not a value GitHub returns in `role_name`
- # (that spelling is `maintain`); it is listed because it is the
- # spelling gh-aw uses in `GH_AW_REQUIRED_ROLES`, and keeping the
- # two lists identical is what makes this an early-out for the
- # same decision `pre_activation` makes later. Both spellings are
- # accepted so neither source can drift into denying a maintainer.
- admin|maintain|maintainer|write) authorized=true ;;
- esac
- done
- if [ "${authorized}" = "true" ]; then
- echo "'${COMMENTER}' has '${role:-${perm}}' access to ${GITHUB_REPOSITORY}; proceeding."
- else
- echo "::warning::'${COMMENTER}' does not have write access to ${GITHUB_REPOSITORY} (resolved role '${role:-${perm:-none}}'); skipping the binlog download."
- fi
- fi
- echo "authorized=${authorized}" >> "$GITHUB_OUTPUT"
-
- - name: Download binlogs from the PR's latest failed Azure Pipelines build
- id: fetch
- if: steps.perm.outputs.authorized == 'true'
- env:
- GH_TOKEN: ${{ github.token }}
- GH_AW_REPO: ${{ github.repository }}
- ADO_API: "https://dev.azure.com/dnceng-public/public/_apis"
- ADO_BUILD_UI: "https://dev.azure.com/dnceng-public/public/_build/results"
- # microsoft.testfx pipeline definition id in dnceng-public/public.
- ADO_BUILD_DEFINITION_ID: "209"
- PR_NUMBER: ${{ github.event.issue.number || fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_number }}
- run: |
- # Advisory + best-effort. On any gap emit binlog-found=false so the
- # agent pipeline stays inert.
- set +e
- set +o pipefail
- emit_none() { echo "binlog-found=false" >> "$GITHUB_OUTPUT"; exit 0; }
-
- [ -z "${PR_NUMBER}" ] && { echo "::warning::No PR number resolved from the slash-command event / aw_context."; emit_none; }
- # PR_NUMBER feeds GitHub API paths and the `refs/pull//merge`
- # branch query; require it numeric so a malformed event/aw_context
- # payload can't reach those URLs with unexpected content.
- if ! printf '%s' "${PR_NUMBER}" | grep -qE '^[0-9]+$'; then
- echo "::warning::Resolved PR number '${PR_NUMBER}' is not numeric; refusing."; emit_none
- fi
-
- # --- Scope check: only analyse PRs targeting main / rel/* ---
- PR_JSON=$(gh api "repos/${GH_AW_REPO}/pulls/${PR_NUMBER}" 2>/dev/null)
- BASE_REF=$(printf '%s' "${PR_JSON}" | jq -r '.base.ref // empty')
- HEAD_SHA=$(printf '%s' "${PR_JSON}" | jq -r '.head.sha // empty')
- case "${BASE_REF}" in
- main|rel/*) echo "PR #${PR_NUMBER} base '${BASE_REF}' is in scope." ;;
- *) echo "::warning::PR #${PR_NUMBER} base '${BASE_REF}' is out of scope (main, rel/*); skipping."; emit_none ;;
- esac
-
- # --- Find the PR's most recent microsoft.testfx build (merge ref) ---
- # Query the newest build REGARDLESS of status (queue-time desc). If
- # the newest build is still queued/running — e.g. right after a
- # force-push — skip: analysing an older completed failure now would
- # pair a stale binlog with the PR's current head. Only proceed when
- # the newest build is completed AND failed. The head SHA is then
- # anchored to that build's own revision (below), so links/suggestions
- # always match the analysed binlog.
- builds_json=$(curl -sSL --retry 3 \
- "${ADO_API}/build/builds?definitions=${ADO_BUILD_DEFINITION_ID}&branchName=refs/pull/${PR_NUMBER}/merge&queryOrder=queueTimeDescending&\$top=1&api-version=7.1")
- BUILD_ID=$(printf '%s' "${builds_json}" | jq -r '.value // [] | .[0].id // empty')
- BUILD_STATUS=$(printf '%s' "${builds_json}" | jq -r '.value // [] | .[0].status // empty')
- BUILD_RESULT=$(printf '%s' "${builds_json}" | jq -r '.value // [] | .[0].result // empty')
- echo "Newest microsoft.testfx build for PR #${PR_NUMBER}: id='${BUILD_ID}' status='${BUILD_STATUS}' result='${BUILD_RESULT}'"
- [ -z "${BUILD_ID}" ] && { echo "::warning::No microsoft.testfx build found for PR #${PR_NUMBER}."; emit_none; }
- # Require a numeric build id before it feeds subsequent ADO API URLs,
- # so a malformed query response can't inject unexpected path/query.
- if ! printf '%s' "${BUILD_ID}" | grep -qE '^[0-9]+$'; then
- echo "::warning::ADO build id '${BUILD_ID}' is not numeric; refusing."; emit_none
- fi
- if [ "${BUILD_STATUS}" != "completed" ]; then
- echo "::warning::PR #${PR_NUMBER}'s newest microsoft.testfx build (${BUILD_ID}) is still '${BUILD_STATUS}'; wait for it to finish before analysing."
- emit_none
- fi
- if [ "${BUILD_RESULT}" != "failed" ]; then
- echo "::warning::PR #${PR_NUMBER}'s newest microsoft.testfx build (${BUILD_ID}) result is '${BUILD_RESULT}', not failed — the failure looks resolved; nothing to analyse."
- emit_none
- fi
-
- # Require the build's analyzed revision to equal the PR's CURRENT
- # head. gh-aw safe-output review comments carry no `commit_id` (they
- # target the current PR diff), so analyzing a stale revision would
- # misplace/reject inline suggestions. The PR can advance between
- # selecting the build and downloading artifacts, and right after a
- # force-push this query can still return the previous failed build —
- # so re-read the head here and skip if it moved.
- build_json=$(curl -sSL --retry 3 "${ADO_API}/build/builds/${BUILD_ID}?api-version=7.1")
- BUILD_PR_SHA=$(printf '%s' "${build_json}" | jq -r '.triggerInfo["pr.sourceSha"] // empty')
- BUILD_MERGE_SHA=$(printf '%s' "${build_json}" | jq -r '.sourceVersion // empty')
- PR_JSON2=$(gh api "repos/${GH_AW_REPO}/pulls/${PR_NUMBER}" 2>/dev/null)
- CURRENT_HEAD=$(printf '%s' "${PR_JSON2}" | jq -r '.head.sha // empty')
- CURRENT_MERGE=$(printf '%s' "${PR_JSON2}" | jq -r '.merge_commit_sha // empty')
- # Fail CLOSED: if either SHA can't be resolved (transient API failure
- # or missing Azure triggerInfo), skip rather than risk analyzing a
- # stale binlog against the current diff.
- if [ -z "${BUILD_PR_SHA}" ] || [ -z "${CURRENT_HEAD}" ]; then
- echo "::warning::Could not resolve build revision ('${BUILD_PR_SHA}') and/or current PR head ('${CURRENT_HEAD}'); skipping."
- emit_none
- fi
- if [ "${BUILD_PR_SHA}" != "${CURRENT_HEAD}" ]; then
- echo "::warning::Build ${BUILD_ID} analyzed revision '${BUILD_PR_SHA}' but PR #${PR_NUMBER} head is now '${CURRENT_HEAD}'; skipping stale build (a newer build will cover the current revision)."
- emit_none
- fi
- # ADO builds GitHub's `refs/pull//merge` ref, so build_json.sourceVersion
- # is that merge commit; if the base branch advanced it differs from the
- # PR's current merge_commit_sha even with the head unchanged. Skip stale merges.
- if [ -n "${BUILD_MERGE_SHA}" ] && [ -n "${CURRENT_MERGE}" ] && [ "${BUILD_MERGE_SHA}" != "${CURRENT_MERGE}" ]; then
- echo "::warning::Build ${BUILD_ID} merge revision '${BUILD_MERGE_SHA}' but PR #${PR_NUMBER} current merge is '${CURRENT_MERGE}' (base branch advanced); skipping stale merge."
- emit_none
- fi
- HEAD_SHA="${CURRENT_HEAD}"
- echo "Analyzing build ${BUILD_ID} at PR head revision '${HEAD_SHA}'."
-
- # --- Download every Logs_Build_* artifact and extract binlogs ---
- artifacts_json=$(curl -sSL --retry 3 "${ADO_API}/build/builds/${BUILD_ID}/artifacts?api-version=7.1")
- mapfile -t names < <(printf '%s' "${artifacts_json}" | jq -r '.value // [] | map(select(.name | test("^Logs_Build_"))) | .[].name')
- [ "${#names[@]}" -eq 0 ] && { echo "::warning::No Logs_Build_* artifacts on build ${BUILD_ID}."; emit_none; }
-
- # --- 5a. Which failed legs never published logs at all? ---
- # The fail-closed check further down compares staged legs against the
- # artifacts ADO *returned*, so it cannot see a leg that died before
- # publishing its logs artifact — that leg is simply absent from
- # `names`. Ask the timeline instead. This is advisory rather than
- # fail-closed: a failed job that legitimately publishes no logs would
- # otherwise suppress analysis of a real compile break in the same build. The agent is told about the gap so it cannot conclude
- # "no build failure" from the legs that happened to upload.
- #
- # Ask the timeline whether each leg's log *publish* succeeded rather
- # than guessing its artifact name from its display name. The artifact
- # is named from `$(Agent.Os)`, which is not what the job is called:
- # `MacOS Debug` publishes `Logs_Build_Darwin_Debug`, and
- # `WindowsSamples Debug` is named from `$(Agent.JobName)` instead. Name
- # matching reported those healthy legs as missing on real builds —
- # every macOS failure, and every `msbuild_cache_seed` job. Arcade's
- # `Publish logs` task record answers the question directly, so no
- # spelling has to be inferred. A failed job carrying no such task
- # (the `Detect changed paths` classifier, the cache-seed stage) does
- # not publish logs at all and is not treated as a missing leg.
- #
- # `canceled` and `abandoned` legs count alongside `failed`: they also
- # finish without logs, and are a real gap in the artifact set.
- timeline_json=$(curl -sSL --retry 3 --max-time 60 "${ADO_API}/build/builds/${BUILD_ID}/timeline?api-version=7.1" 2>/dev/null || true)
- MISSING_LEGS=""
- # An unreadable timeline must not look like a complete build. A failed
- # request, a non-JSON error page and an ADO error document all left
- # the list empty, which is exactly how "every failed leg published
- # logs" is reported — so a transient outage could let the agent
- # conclude "non-build failure" from an artifact set whose completeness
- # was never established. Probe for the `records` array first and
- # report an explicit unknown when it isn't there.
- timeline_ok=0
- if printf '%s' "${timeline_json}" | jq -e 'type == "object" and has("records")' >/dev/null 2>&1; then
- timeline_ok=1
- fi
- if [ "${timeline_ok}" -eq 1 ]; then
- # Job display names come from the pipeline YAML in the PR branch, so
- # on a fork PR they are attacker-controlled. Strip control characters
- # and bound the length before this value reaches `$GITHUB_OUTPUT` and
- # `$GITHUB_ENV`, where an embedded newline would inject further
- # `key=value` lines. The task name is matched on its alphanumerics
- # because arcade spells it both `Publish logs` and `Publish Logs`,
- # and some pipelines prefix a decorative emoji.
- MISSING_LEGS=$(printf '%s' "${timeline_json}" | jq -r '
- (.records // []) as $records
- | ($records
- | map(select(.type == "Task"
- and (.name | ascii_downcase | gsub("[^a-z0-9]"; "") | test("publishlogs"))))) as $publishes
- | $records
- | map(select(.type == "Job"
- and (.result == "failed" or .result == "canceled" or .result == "abandoned")))
- | map(. as $job
- | ($publishes | map(select(.parentId == $job.id))) as $mine
- | select(($mine | length) > 0
- and (($mine | map(select(.result == "succeeded")) | length) == 0))
- | ($job.name | gsub("[[:cntrl:]]"; " ")))
- | join(", ")' 2>/dev/null | tr -d '\r\n' | cut -c1-400)
- fi
- if [ "${timeline_ok}" -ne 1 ]; then
- MISSING_LEGS="(unknown - could not read the build timeline)"
- echo "::warning::Could not read the timeline for build ${BUILD_ID}; unable to verify that every failed leg published a logs artifact."
- elif [ -n "${MISSING_LEGS}" ]; then
- echo "::warning::Failed leg(s) whose logs were never published: ${MISSING_LEGS}"
- fi
-
- # Guards for untrusted PR-produced archives: cap the compressed
- # download and the reported uncompressed size per artifact, bound
- # extraction time, AND enforce cumulative budgets across all legs so
- # many individually-small artifacts can't collectively exhaust the
- # runner's disk or its network time.
- MAX_ZIP_BYTES=524288000 # 500 MB compressed per artifact
- MAX_UNZIP_BYTES=2147483648 # 2 GB uncompressed per artifact
- MAX_TOTAL_BYTES=4294967296 # 4 GB uncompressed across all artifacts
- MAX_TOTAL_ZIP_BYTES=3221225472 # 3 GB compressed downloaded in total
- MAX_ARTIFACTS=40 # cap only; the real count is path-dependent
- TOTAL_BYTES=0
- TOTAL_ZIP_BYTES=0
- # Bound the work before starting: a pipeline change (or repeated leg
- # retries) could grow the matched set well past today's count. Refuse
- # rather than process a prefix of the list, because a partial view is
- # exactly what the fail-closed check below exists to prevent.
- if [ "${#names[@]}" -gt "${MAX_ARTIFACTS}" ]; then
- echo "::warning::Build ${BUILD_ID} matched ${#names[@]} log artifacts, above the ${MAX_ARTIFACTS} cap; skipping."
- emit_none
- fi
- mkdir -p /tmp/binlogs
- count=0
- staged_legs=0
- ai=0
- for name in "${names[@]}"; do
- # `name` is PR-controlled ADO artifact metadata and the
- # `^Logs_Build_` filter only anchors the prefix, so sanitize it
- # before using it in any on-disk path (guards against `/` or `..`
- # traversal); keep the original `name` for the artifacts_json lookup.
- safe_name=$(printf '%s' "${name}" | tr -c 'A-Za-z0-9._-' '_')
- ai=$((ai + 1))
- url=$(printf '%s' "${artifacts_json}" | jq -r --arg n "${name}" '.value[] | select(.name==$n) | .resource.downloadUrl // empty')
- [ -z "${url}" ] && { echo "::warning::No download URL for ${name}."; continue; }
- rm -rf /tmp/ax /tmp/a.zip
- mkdir -p /tmp/ax
- # Hard-cap the bytes written to disk regardless of Content-Length:
- # stream through `head -c` (cap + 1) and bound total time.
- curl -sSL --retry 3 --max-time 300 "${url}" 2>/dev/null | head -c $((MAX_ZIP_BYTES + 1)) > /tmp/a.zip || true
- ZIP_BYTES=$(stat -c%s /tmp/a.zip 2>/dev/null || echo 0)
- # Bound cumulative *compressed* bytes too: the per-artifact and
- # cumulative-uncompressed caps still allow many mid-sized archives
- # to be pulled over the network before any of them is inspected.
- #
- # Charge the budget here, before the skips below, because the bytes
- # are already on the wire by this point — `curl` above streams into
- # `head -c` and only then is the size known. Charging after the
- # per-artifact skip would let every oversized artifact cost a full
- # MAX_ZIP_BYTES of network without ever being counted, so a build of
- # MAX_ARTIFACTS oversized legs would download far past this budget
- # while appearing to stay inside it.
- TOTAL_ZIP_BYTES=$((TOTAL_ZIP_BYTES + ZIP_BYTES))
- if [ "${TOTAL_ZIP_BYTES}" -gt "${MAX_TOTAL_ZIP_BYTES}" ]; then
- echo "::warning::Cumulative compressed download budget ${MAX_TOTAL_ZIP_BYTES} reached at ${name}; stopping."; break
- fi
- if [ "${ZIP_BYTES}" -eq 0 ]; then
- echo "::warning::Skipping ${name}: empty or failed download."; continue
- fi
- if [ "${ZIP_BYTES}" -gt "${MAX_ZIP_BYTES}" ]; then
- echo "::warning::Skipping ${name}: download exceeded ${MAX_ZIP_BYTES} bytes."; continue
- fi
- UNCOMP=$(unzip -l /tmp/a.zip 2>/dev/null | tail -1 | awk '{print $1}')
- # Fail safe: if the uncompressed size isn't a plain integer (corrupt
- # zip / unexpected `unzip -l` output), we can't verify it — skip the
- # artifact rather than let a non-numeric value bypass the `-gt` guard.
- if ! printf '%s' "${UNCOMP}" | grep -qE '^[0-9]+$'; then
- echo "::warning::Skipping ${name}: could not determine uncompressed size (unparseable unzip output)."; continue
- fi
- # ZIP64 uncompressed sizes can reach ~20 digits — beyond Bash's
- # signed 64-bit range, where `-gt` (and the cumulative `$((...))`
- # below) error out and, under `set +e`, would let an oversized
- # archive slip past the guard. Any value with more digits than the
- # limit is unambiguously larger, so reject on decimal length first;
- # after this, UNCOMP fits safely in the integer range used below.
- if [ "${#UNCOMP}" -gt "${#MAX_UNZIP_BYTES}" ]; then
- echo "::warning::Skipping ${name}: uncompressed size has ${#UNCOMP} digits, exceeding the ${MAX_UNZIP_BYTES} guard (possible zip bomb)."; continue
- fi
- if [ "${UNCOMP}" -gt "${MAX_UNZIP_BYTES}" ]; then
- echo "::warning::Skipping ${name}: uncompressed size ${UNCOMP} exceeds ${MAX_UNZIP_BYTES} guard (possible zip bomb)."; continue
- fi
- if [ $((TOTAL_BYTES + UNCOMP)) -gt "${MAX_TOTAL_BYTES}" ]; then
- echo "::warning::Cumulative uncompressed budget ${MAX_TOTAL_BYTES} reached at ${name}; stopping extraction."; break
- fi
- # Refuse the archive if any entry path is absolute or has a `..`
- # component (defense-in-depth over unzip's own traversal guard),
- # then extract `*.binlog` entries *preserving* their in-archive
- # paths (no `-j`) under a fresh dir + timeout, so two binlogs that
- # share a basename in different folders don't overwrite each other.
- if unzip -Z1 /tmp/a.zip 2>/dev/null | grep -qE '(^/|(^|/)\.\.(/|$))'; then
- echo "::warning::Skipping ${name}: archive has a suspicious (absolute or ..) entry path."; continue
- fi
- # `unzip` exit 11 means "no files matched" — the artifact carries no
- # binlog at all. That is not an extraction failure: the leg did
- # publish its logs, they simply contain no binlog, and the
- # fail-closed check below already accounts for a leg that staged
- # nothing. Reporting it as "extraction failed or timed out" sends
- # the reader chasing a corrupt-archive theory that isn't there. Any
- # other non-zero exit (corrupt archive, timeout) is a real failure.
- #
- # Both cases `continue`, so nothing was written to /tmp/ax and the
- # uncompressed budget below is left untouched. Charging it for an
- # archive that extracted nothing would let one large binlog-free
- # artifact push a genuinely useful later leg past MAX_TOTAL_BYTES.
- uz=0
- timeout 120 unzip -o /tmp/a.zip '*.binlog' -d /tmp/ax >/dev/null 2>&1 || uz=$?
- if [ "${uz}" -eq 11 ]; then
- echo "::warning::${name}: published logs contain no binlog; nothing to analyse from this leg."; continue
- fi
- if [ "${uz}" -ne 0 ]; then
- echo "::warning::Skipping ${name}: extraction failed or timed out (unzip exit ${uz})."; continue
- fi
- # Consume the cumulative budget only once the archive actually
- # extracted — not on a suspicious-path or extraction-failure skip
- # above — so a skipped leg can't wrongly exhaust the budget and
- # force later legs to be dropped as "incomplete".
- TOTAL_BYTES=$((TOTAL_BYTES + UNCOMP))
- i=0
- leg_staged=0
- while IFS= read -r bl; do
- [ -f "${bl}" ] || continue
- # Every destination is uniquely prefixed with the artifact index
- # (`ai`) and a per-file counter (`i`), so neither a cross-artifact
- # sanitize collision nor same-basename entries within one archive
- # can overwrite a previously staged leg's binlog. `safe_name` is
- # kept only for readability.
- dest="/tmp/binlogs/${ai}_${i}_${safe_name}.binlog"
- # Only count a staged binlog when the copy actually succeeds —
- # `set +e` is on, so a failed `cp` must not inflate the counts.
- if cp "${bl}" "${dest}"; then
- count=$((count + 1))
- i=$((i + 1))
- leg_staged=1
- else
- echo "::warning::Failed to stage ${bl}; skipping."
- fi
- done < <(find /tmp/ax -type f -name '*.binlog')
- # This leg produced at least one usable binlog.
- [ "${leg_staged}" -eq 1 ] && staged_legs=$((staged_legs + 1))
- done
- echo "Extracted ${count} binlog(s) from ${staged_legs}/${#names[@]} legs into /tmp/binlogs:"
- ls -la /tmp/binlogs || true
- [ "${count}" -eq 0 ] && { echo "::warning::No *.binlog found in any Logs_Build_* artifact of build ${BUILD_ID}."; emit_none; }
- # Fail CLOSED on a partial set: if any Logs_Build_* leg did not yield
- # a usable binlog (download/extract failure, size-guard skip, or no
- # binlog inside), we cannot see every leg. Activating anyway would let
- # the agent treat the retrieved legs as the whole build and possibly
- # mis-classify a real build break in a missing leg as a clean compile /
- # non-build failure. A later build/check will re-trigger the analysis.
- if [ "${staged_legs}" -ne "${#names[@]}" ]; then
- echo "::warning::Only ${staged_legs} of ${#names[@]} Logs_Build_* legs produced a usable binlog; skipping to avoid analyzing an incomplete build (a missing leg could be the one that failed)."
- emit_none
- fi
-
- # The download/extract loop above can take minutes. Re-read the PR
- # head right before activating and fail CLOSED if it moved or can't
- # be resolved: a force-push during that window would otherwise leave
- # the analyzed binlog stale relative to the current diff (inline
- # comments carry no commit_id and target the current diff).
- LATEST_PR=$(gh api "repos/${GH_AW_REPO}/pulls/${PR_NUMBER}" 2>/dev/null)
- LATEST_HEAD=$(printf '%s' "${LATEST_PR}" | jq -r '.head.sha // empty')
- LATEST_MERGE=$(printf '%s' "${LATEST_PR}" | jq -r '.merge_commit_sha // empty')
- if [ -z "${LATEST_HEAD}" ] || [ "${LATEST_HEAD}" != "${HEAD_SHA}" ]; then
- echo "::warning::PR #${PR_NUMBER} head changed during artifact download ('${HEAD_SHA}' -> '${LATEST_HEAD}') or could not be re-resolved; skipping to avoid posting stale-build suggestions against the new diff."
- emit_none
- fi
- # The base branch may also have advanced during the download; if the
- # merge revision moved from what the build analyzed, skip (stale merge).
- if [ -n "${BUILD_MERGE_SHA}" ] && [ -n "${LATEST_MERGE}" ] && [ "${LATEST_MERGE}" != "${BUILD_MERGE_SHA}" ]; then
- echo "::warning::PR #${PR_NUMBER} merge revision changed during artifact download ('${BUILD_MERGE_SHA}' -> '${LATEST_MERGE}'); skipping stale merge."
- emit_none
- fi
-
- {
- # `missing-legs` is derived from ADO job display names, which come
- # from pipeline YAML in the PR branch and are therefore
- # fork-controlled. It is sanitized where it is assembled, and it is
- # written first here so that even a future regression in that
- # sanitizing cannot let it override a key emitted below.
- echo "missing-legs=${MISSING_LEGS}"
- echo "binlog-found=true"
- echo "pr-number=${PR_NUMBER}"
- echo "pr-head-sha=${HEAD_SHA}"
- echo "pr-merge-sha=${BUILD_MERGE_SHA}"
- echo "ado-build-id=${BUILD_ID}"
- echo "ado-build-url=${ADO_BUILD_UI}?buildId=${BUILD_ID}"
- } >> "$GITHUB_OUTPUT"
-
- - name: Upload analysis artifact
- if: steps.fetch.outputs.binlog-found == 'true'
- uses: actions/upload-artifact@v7.0.1
- with:
- name: build-failure-analysis-data
- path: /tmp/binlogs
- if-no-files-found: warn
- retention-days: 1
+# The `fetch-binlog` job that reuses the binlogs from the failed Azure DevOps
+# build instead of rebuilding is shared with the other Build Failure Analysis
+# workflow and lives in `shared/build-failure-analysis-fetch.md`, imported
+# above. It resolves the build, verifies the PR targets an in-scope base
+# branch, downloads every `Logs_Build_*` artifact, extracts each leg's
+# `*.binlog` and uploads them for the agent job.
# Steps that run in the agent job. The top-level `if:` gates these on binlogs
# having been retrieved, so the agent never runs without something to analyse.
diff --git a/.github/workflows/build-failure-analysis.lock.yml b/.github/workflows/build-failure-analysis.lock.yml
index 2567b8e994..1169b731b5 100644
--- a/.github/workflows/build-failure-analysis.lock.yml
+++ b/.github/workflows/build-failure-analysis.lock.yml
@@ -1,4 +1,4 @@
-# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"f021a149169d42e3e53bfa5b9d5190266facc5755786027c1901fdb3d27f303b","body_hash":"44ed28062e9e0720537ed2d42f6f0c0af015c4d96301ebcb2029755b1e7b3b54","compiler_version":"v0.83.1","strict":true,"agent_id":"copilot","engine_versions":{"copilot":"1.0.73"}}
+# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"6a229fbae76f10de452448e1dedcbf233d5c5d34f5b9d5d98ec3cc217fbe53f1","body_hash":"806439f4425a9fce72c3201fc4677084ce778e327529fdfafb68cdd558ca822d","compiler_version":"v0.83.1","strict":true,"agent_id":"copilot","engine_versions":{"copilot":"1.0.73"}}
# gh-aw-manifest: {"version":1,"secrets":["COPILOT_GITHUB_TOKEN","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN"],"actions":[{"repo":"actions/cache/restore","sha":"55cc8345863c7cc4c66a329aec7e433d2d1c52a9","version":"v6.1.0"},{"repo":"actions/cache/save","sha":"55cc8345863c7cc4c66a329aec7e433d2d1c52a9","version":"v6.1.0"},{"repo":"actions/checkout","sha":"3d3c42e5aac5ba805825da76410c181273ba90b1","version":"v7.0.1"},{"repo":"actions/checkout","sha":"3d3c42e5aac5ba805825da76410c181273ba90b1","version":"v7.0.1"},{"repo":"actions/download-artifact","sha":"3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c","version":"v8.0.1"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"820762786026740c76f36085b0efc47a31fe5020","version":"v7.0.0"},{"repo":"actions/upload-artifact","sha":"043fb46d1a93c77aae656e7c1c64a875d1fc6a0a","version":"v7.0.1"},{"repo":"github/gh-aw-actions/setup","sha":"8bdba8075360648fe6802302a5b4e016361dc6ac","version":"v0.83.1"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.27.38","digest":"sha256:cb928eb62d9139a013c2d278dab19af232d35a2d83dca71a3d98eb431f786243","pinned_image":"ghcr.io/github/gh-aw-firewall/agent:0.27.38@sha256:cb928eb62d9139a013c2d278dab19af232d35a2d83dca71a3d98eb431f786243"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.27.38","digest":"sha256:cd6145620d96acee46e1ede25180a13aa36002467e663db0caa453a8bc8eb60c","pinned_image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.27.38@sha256:cd6145620d96acee46e1ede25180a13aa36002467e663db0caa453a8bc8eb60c"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.27.38","digest":"sha256:6c19094d95aad5f9f128ad5e583f0f2b894b158aa66c3b86dd9bcc90970a2917","pinned_image":"ghcr.io/github/gh-aw-firewall/squid:0.27.38@sha256:6c19094d95aad5f9f128ad5e583f0f2b894b158aa66c3b86dd9bcc90970a2917"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.4.3","digest":"sha256:3c744710ea275cd5ee65db92a1099e0d980754bd9fafda9ce67704c67004dc83","pinned_image":"ghcr.io/github/gh-aw-mcpg:v0.4.3@sha256:3c744710ea275cd5ee65db92a1099e0d980754bd9fafda9ce67704c67004dc83"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b","pinned_image":"ghcr.io/github/gh-aw-node@sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b"},{"image":"ghcr.io/github/github-mcp-server:v1.6.0","digest":"sha256:2b0c48b070f61e9d3969269ead600f62d00fb237b60ac849ef3d166ee7de9ad3","pinned_image":"ghcr.io/github/github-mcp-server:v1.6.0@sha256:2b0c48b070f61e9d3969269ead600f62d00fb237b60ac849ef3d166ee7de9ad3"},{"image":"mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-binlog-mcp-amd64","digest":"sha256:9f1e2c3e8281186eb1190f39918b23accefefb4dd086d0ac1bd3e4ea7d2ed0e0","pinned_image":"mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-binlog-mcp-amd64@sha256:9f1e2c3e8281186eb1190f39918b23accefefb4dd086d0ac1bd3e4ea7d2ed0e0"}]}
# This file was automatically generated by gh-aw (v0.83.1). DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md
#
@@ -27,6 +27,7 @@
#
# Resolved workflow manifest:
# Imports:
+# - shared/build-failure-analysis-fetch.md
# - shared/build-failure-analysis-shared.md
#
# Secrets used:
@@ -270,20 +271,20 @@ jobs:
run: |
bash "${RUNNER_TEMP}/gh-aw/actions/create_prompt_first.sh"
{
- cat << 'GH_AW_PROMPT_d71d5ffb8c5efd70_EOF'
+ cat << 'GH_AW_PROMPT_f5fce482246cb41a_EOF'
- GH_AW_PROMPT_d71d5ffb8c5efd70_EOF
+ GH_AW_PROMPT_f5fce482246cb41a_EOF
cat "${RUNNER_TEMP}/gh-aw/prompts/xpia.md"
cat "${RUNNER_TEMP}/gh-aw/prompts/temp_folder_prompt.md"
cat "${RUNNER_TEMP}/gh-aw/prompts/markdown.md"
cat "${RUNNER_TEMP}/gh-aw/prompts/safe_outputs_prompt.md"
- cat << 'GH_AW_PROMPT_d71d5ffb8c5efd70_EOF'
+ cat << 'GH_AW_PROMPT_f5fce482246cb41a_EOF'
Tools: add_comment(max:5), create_pull_request_review_comment(max:25), missing_tool, missing_data, noop(max:5)
- GH_AW_PROMPT_d71d5ffb8c5efd70_EOF
+ GH_AW_PROMPT_f5fce482246cb41a_EOF
cat "${RUNNER_TEMP}/gh-aw/prompts/mcp_cli_tools_prompt.md"
- cat << 'GH_AW_PROMPT_d71d5ffb8c5efd70_EOF'
+ cat << 'GH_AW_PROMPT_f5fce482246cb41a_EOF'
The following GitHub context information is available for this workflow:
{{#if github.actor}}
@@ -312,13 +313,14 @@ jobs:
{{/if}}
- GH_AW_PROMPT_d71d5ffb8c5efd70_EOF
+ GH_AW_PROMPT_f5fce482246cb41a_EOF
cat "${RUNNER_TEMP}/gh-aw/prompts/github_mcp_tools_with_safeoutputs_prompt.md"
- cat << 'GH_AW_PROMPT_d71d5ffb8c5efd70_EOF'
+ cat << 'GH_AW_PROMPT_f5fce482246cb41a_EOF'
{{#runtime-import .github/workflows/shared/build-failure-analysis-shared.md}}
+ {{#runtime-import .github/workflows/shared/build-failure-analysis-fetch.md}}
{{#runtime-import .github/workflows/build-failure-analysis.md}}
- GH_AW_PROMPT_d71d5ffb8c5efd70_EOF
+ GH_AW_PROMPT_f5fce482246cb41a_EOF
} > "$GH_AW_PROMPT"
- name: Interpolate variables and render templates
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
@@ -1588,7 +1590,9 @@ jobs:
fetch-binlog:
name: Fetch binlogs (Azure Pipelines)
if: >
- github.event_name == 'workflow_dispatch' || (github.event.check_run.name == 'microsoft.testfx' && github.event.check_run.conclusion == 'failure')
+ github.event_name == 'workflow_dispatch' || (github.event_name == 'check_run' &&
+ github.event.check_run.name == 'microsoft.testfx' &&
+ github.event.check_run.conclusion == 'failure')
runs-on: ubuntu-latest
permissions:
contents: read
@@ -1612,8 +1616,53 @@ jobs:
GH_HOST="${GITHUB_SERVER_URL#https://}"
GH_HOST="${GH_HOST#http://}"
echo "GH_HOST=${GH_HOST}" >> "$GITHUB_ENV"
+ - name: Verify the commenter has write access
+ id: perm
+ if: github.event.check_run.details_url == '' && github.event.inputs['ado-build-id'] == ''
+ run: |
+ set +e
+ authorized=false
+ # `COMMENTER` has the same untrusted provenance as `PR_NUMBER` below
+ # (an `aw_context` payload), and it is interpolated into an API path
+ # and into log output, so give it the same shape check. GitHub logins
+ # are alphanumerics and hyphens; anything else is a malformed or
+ # hostile payload rather than a real account, and is dropped so it
+ # lands in the deny branch.
+ case "${COMMENTER}" in
+ ""|*[!A-Za-z0-9-]*)
+ [ -n "${COMMENTER}" ] && echo "::warning::Ignoring implausible actor name from the event payload."
+ COMMENTER="" ;;
+ esac
+ if [ -z "${COMMENTER}" ]; then
+ echo "::warning::No actor resolved from the slash-command event / aw_context; skipping the binlog download."
+ else
+ resp=$(gh api "repos/${GITHUB_REPOSITORY}/collaborators/${COMMENTER}/permission" 2>/dev/null)
+ role=$(printf '%s' "${resp}" | jq -r '.role_name // empty' 2>/dev/null)
+ perm=$(printf '%s' "${resp}" | jq -r '.permission // empty' 2>/dev/null)
+ for r in "${role}" "${perm}"; do
+ case "${r}" in
+ # `maintainer` is not a value GitHub returns in `role_name`
+ # (that spelling is `maintain`); it is listed because it is the
+ # spelling gh-aw uses in `GH_AW_REQUIRED_ROLES`, and keeping the
+ # two lists identical is what makes this an early-out for the
+ # same decision `pre_activation` makes later. Both spellings are
+ # accepted so neither source can drift into denying a maintainer.
+ admin|maintain|maintainer|write) authorized=true ;;
+ esac
+ done
+ if [ "${authorized}" = "true" ]; then
+ echo "'${COMMENTER}' has '${role:-${perm}}' access to ${GITHUB_REPOSITORY}; proceeding."
+ else
+ echo "::warning::'${COMMENTER}' does not have write access to ${GITHUB_REPOSITORY} (resolved role '${role:-${perm:-none}}'); skipping the binlog download."
+ fi
+ fi
+ echo "authorized=${authorized}" >> "$GITHUB_OUTPUT"
+ env:
+ COMMENTER: ${{ github.event.comment.user.login || fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').actor }}
+ GH_TOKEN: ${{ github.token }}
- name: Download binlogs from the failed Azure Pipelines build
id: fetch
+ if: github.event.check_run.details_url != '' || github.event.inputs['ado-build-id'] != '' || steps.perm.outputs.authorized == 'true'
run: |
# Advisory + best-effort: on any gap emit binlog-found=false and the
# agent pipeline stays inert.
@@ -1621,76 +1670,127 @@ jobs:
set +o pipefail
emit_none() { echo "binlog-found=false" >> "$GITHUB_OUTPUT"; exit 0; }
- # --- 1. Resolve the Azure DevOps build id ---
- if [ "${EVENT_NAME}" = "workflow_dispatch" ]; then
- BUILD_ID="${DISPATCH_BUILD_ID}"
+ # --- 1. Resolve the Azure DevOps build and the PR it belongs to ---
+ # This is the ONLY part of the job that differs between the two
+ # workflows, because they learn about the build in opposite
+ # directions:
+ #
+ # * `check_run` / manual dispatch are TOLD which build to look at —
+ # the check payload names it in `details_url`, a manual dispatch
+ # passes it explicitly — so the build is resolved first and the PR
+ # is derived from it.
+ # * The slash command is told nothing about a build: it is a request
+ # to re-analyse whatever the PR's newest build is, so the PR comes
+ # first and the build is looked up from it. That build is usable
+ # only once it has COMPLETED; a still running newest build (e.g.
+ # right after a force-push) would otherwise pair an older failure
+ # with the PR's current head.
+ #
+ # Both importing workflows can receive `workflow_dispatch` (the slash
+ # command uses `strategy: centralized`), so the branch is taken on the
+ # payload rather than on the event name: having a build id at all is
+ # what makes this the automatic workflow.
+ if [ -n "${DISPATCH_BUILD_ID}" ] || [ -n "${CHECK_DETAILS_URL}" ]; then
+ ENTRY="build"
+ if [ -n "${DISPATCH_BUILD_ID}" ]; then
+ BUILD_ID="${DISPATCH_BUILD_ID}"
+ else
+ # details_url looks like: .../_build/results?buildId=NNN&view=...
+ BUILD_ID=$(printf '%s' "${CHECK_DETAILS_URL}" | grep -oE 'buildId=[0-9]+' | head -1 | cut -d= -f2)
+ fi
+ echo "Azure DevOps build id: '${BUILD_ID}'"
+ [ -z "${BUILD_ID}" ] && { echo "::warning::Could not resolve an ADO build id."; emit_none; }
+ # The build id feeds directly into ADO API URLs below; require it to
+ # be purely numeric (esp. on workflow_dispatch, where it is free-form
+ # input) so a malformed value can't alter the request path/query.
+ if ! printf '%s' "${BUILD_ID}" | grep -qE '^[0-9]+$'; then
+ echo "::warning::Resolved ADO build id '${BUILD_ID}' is not numeric; refusing."; emit_none
+ fi
+ # The build metadata is the authoritative source for the PR number
+ # (via sourceBranch) as well as for the definition / result /
+ # revision validated in step 3.
+ build_json=$(curl -sSL --retry 3 "${ADO_API}/build/builds/${BUILD_ID}?api-version=7.1")
+ # A PR build's sourceBranch is exactly `refs/pull//merge`, so it
+ # identifies the PR unambiguously — unlike the commit->PRs API,
+ # which can return several PRs in an unspecified order.
+ BUILD_PR_NUM=$(printf '%s' "${build_json}" | jq -r '.sourceBranch // empty' | sed -n 's#^refs/pull/\([0-9]\{1,\}\)/merge$#\1#p')
+ if [ -n "${DISPATCH_BUILD_ID}" ]; then
+ PR_NUMBER="${DISPATCH_PR_NUMBER}"
+ else
+ # Prefer the PR named by the build's own sourceBranch
+ # (authoritative) over check_run.pull_requests[0], whose order
+ # isn't guaranteed and can name a different PR sharing the commit.
+ PR_NUMBER="${BUILD_PR_NUM:-${CHECK_PR_NUMBER}}"
+ fi
+ [ -z "${PR_NUMBER}" ] && { echo "::warning::Could not resolve a PR number."; emit_none; }
+ # PR_NUMBER feeds `gh api .../pulls/` and the `refs/pull//merge`
+ # comparison; require it numeric so a malformed value can't reach the
+ # GitHub API path (traversal-like input) or skew the branch match.
+ if ! printf '%s' "${PR_NUMBER}" | grep -qE '^[0-9]+$'; then
+ echo "::warning::Resolved PR number '${PR_NUMBER}' is not numeric; refusing."; emit_none
+ fi
else
- # details_url looks like: .../_build/results?buildId=NNN&view=...
- BUILD_ID=$(printf '%s' "${CHECK_DETAILS_URL}" | grep -oE 'buildId=[0-9]+' | head -1 | cut -d= -f2)
- fi
- echo "Azure DevOps build id: '${BUILD_ID}'"
- [ -z "${BUILD_ID}" ] && { echo "::warning::Could not resolve an ADO build id."; emit_none; }
- # The build id feeds directly into ADO API URLs below; require it to
- # be purely numeric (esp. on workflow_dispatch, where it is free-form
- # input) so a malformed value can't alter the request path/query.
- if ! printf '%s' "${BUILD_ID}" | grep -qE '^[0-9]+$'; then
- echo "::warning::Resolved ADO build id '${BUILD_ID}' is not numeric; refusing."; emit_none
+ ENTRY="command"
+ PR_NUMBER="${COMMAND_PR_NUMBER}"
+ [ -z "${PR_NUMBER}" ] && { echo "::warning::No PR number resolved from the slash-command event / aw_context."; emit_none; }
+ # PR_NUMBER feeds GitHub API paths and the `refs/pull//merge`
+ # branch query; require it numeric so a malformed event/aw_context
+ # payload can't reach those URLs with unexpected content.
+ if ! printf '%s' "${PR_NUMBER}" | grep -qE '^[0-9]+$'; then
+ echo "::warning::Resolved PR number '${PR_NUMBER}' is not numeric; refusing."; emit_none
+ fi
+ # Newest build for the PR's merge ref REGARDLESS of status
+ # (queue-time descending), so a build queued after an older failure
+ # is seen rather than the stale one being analysed silently.
+ builds_json=$(curl -sSL --retry 3 \
+ "${ADO_API}/build/builds?definitions=${ADO_BUILD_DEFINITION_ID}&branchName=refs/pull/${PR_NUMBER}/merge&queryOrder=queueTimeDescending&\$top=1&api-version=7.1")
+ BUILD_ID=$(printf '%s' "${builds_json}" | jq -r '.value // [] | .[0].id // empty')
+ BUILD_STATUS=$(printf '%s' "${builds_json}" | jq -r '.value // [] | .[0].status // empty')
+ echo "Newest microsoft.testfx build for PR #${PR_NUMBER}: id='${BUILD_ID}' status='${BUILD_STATUS}'"
+ [ -z "${BUILD_ID}" ] && { echo "::warning::No microsoft.testfx build found for PR #${PR_NUMBER}."; emit_none; }
+ # Require a numeric build id before it feeds subsequent ADO API
+ # URLs, so a malformed query response can't inject path/query.
+ if ! printf '%s' "${BUILD_ID}" | grep -qE '^[0-9]+$'; then
+ echo "::warning::ADO build id '${BUILD_ID}' is not numeric; refusing."; emit_none
+ fi
+ if [ "${BUILD_STATUS}" != "completed" ]; then
+ echo "::warning::PR #${PR_NUMBER}'s newest microsoft.testfx build (${BUILD_ID}) is still '${BUILD_STATUS}'; wait for it to finish before analysing."
+ emit_none
+ fi
+ build_json=$(curl -sSL --retry 3 "${ADO_API}/build/builds/${BUILD_ID}?api-version=7.1")
fi
-
- # Fetch the build metadata once, up front: it is the authoritative
- # source both for the PR number (via sourceBranch) and for the
- # definition/result/revision validated in step 4.
- build_json=$(curl -sSL --retry 3 "${ADO_API}/build/builds/${BUILD_ID}?api-version=7.1")
RESULT=$(printf '%s' "${build_json}" | jq -r '.result // empty')
DEF_ID=$(printf '%s' "${build_json}" | jq -r '.definition.id // empty')
SRC_BRANCH=$(printf '%s' "${build_json}" | jq -r '.sourceBranch // empty')
- # A PR build's sourceBranch is exactly `refs/pull//merge`, so it
- # identifies the PR unambiguously — unlike the commit->PRs API, which
- # can return several PRs in an unspecified order.
- BUILD_PR_NUM=$(printf '%s' "${SRC_BRANCH}" | sed -n 's#^refs/pull/\([0-9]\{1,\}\)/merge$#\1#p')
-
- # --- 2. Resolve the PR number + head SHA ---
- if [ "${EVENT_NAME}" = "workflow_dispatch" ]; then
- PR_NUMBER="${DISPATCH_PR_NUMBER}"
- HEAD_SHA=""
- else
- # Prefer the PR named by the build's own sourceBranch (authoritative:
- # `refs/pull//merge`) over check_run.pull_requests[0], whose order
- # isn't guaranteed and can name a different PR that shares the commit.
- PR_NUMBER="${BUILD_PR_NUM:-${CHECK_PR_NUMBER}}"
- HEAD_SHA="${CHECK_HEAD_SHA}"
- fi
- [ -z "${PR_NUMBER}" ] && { echo "::warning::Could not resolve a PR number."; emit_none; }
- # PR_NUMBER feeds `gh api .../pulls/` and the `refs/pull//merge`
- # comparison; require it numeric so a malformed value can't reach the
- # GitHub API path (traversal-like input) or skew the branch match.
- if ! printf '%s' "${PR_NUMBER}" | grep -qE '^[0-9]+$'; then
- echo "::warning::Resolved PR number '${PR_NUMBER}' is not numeric; refusing."; emit_none
- fi
- # --- 3. Scope check: only analyse PRs targeting main / rel/* ---
+ # --- 2. Scope check: only analyse PRs targeting main / rel/* ---
PR_JSON=$(gh api "repos/${GH_AW_REPO}/pulls/${PR_NUMBER}" 2>/dev/null)
BASE_REF=$(printf '%s' "${PR_JSON}" | jq -r '.base.ref // empty')
- [ -z "${HEAD_SHA}" ] && HEAD_SHA=$(printf '%s' "${PR_JSON}" | jq -r '.head.sha // empty')
case "${BASE_REF}" in
main|rel/*) echo "PR #${PR_NUMBER} base '${BASE_REF}' is in scope." ;;
*) echo "::warning::PR #${PR_NUMBER} base '${BASE_REF}' is out of scope (main, rel/*); skipping."; emit_none ;;
esac
- # --- 4. Validate the build for EVERY trigger (not just dispatch):
- # it must be the microsoft.testfx definition (209), have failed, and
- # belong to this PR (sourceBranch == refs/pull//merge).
- # For `check_run` the build id is parsed from a check payload
- # we don't fully trust; for dispatch the build id and PR
- # number are independent inputs. Validating on both paths
- # prevents downloading an unrelated build or posting its
- # analysis to the wrong PR.
+ # --- 3. Validate the build, whichever way it was resolved ---
+ # It must be the microsoft.testfx definition (209), have failed, and
+ # belong to this PR (sourceBranch == refs/pull//merge). No entry
+ # point is fully trusted: `check_run` parses the build id out of a
+ # check payload, dispatch takes the build id and PR number as
+ # independent free-form inputs, and the slash command derives the
+ # build from a query. Validating here — rather than per entry point —
+ # prevents downloading an unrelated build or posting its analysis to
+ # the wrong PR.
echo "ADO build ${BUILD_ID}: result='${RESULT}' definition='${DEF_ID}' sourceBranch='${SRC_BRANCH}'"
if [ "${DEF_ID}" != "${ADO_BUILD_DEFINITION_ID}" ]; then
echo "::warning::ADO build ${BUILD_ID} is definition '${DEF_ID}', not microsoft.testfx (${ADO_BUILD_DEFINITION_ID}); refusing."; emit_none
fi
if [ "${RESULT}" != "failed" ]; then
- echo "::warning::ADO build ${BUILD_ID} did not fail (result='${RESULT}'); nothing to analyze."; emit_none
+ if [ "${ENTRY}" = "command" ]; then
+ echo "::warning::PR #${PR_NUMBER}'s newest microsoft.testfx build (${BUILD_ID}) result is '${RESULT}', not failed — the failure looks resolved; nothing to analyse."
+ else
+ echo "::warning::ADO build ${BUILD_ID} did not fail (result='${RESULT}'); nothing to analyze."
+ fi
+ emit_none
fi
if [ "${SRC_BRANCH}" != "refs/pull/${PR_NUMBER}/merge" ]; then
echo "::warning::ADO build ${BUILD_ID} sourceBranch '${SRC_BRANCH}' does not match PR #${PR_NUMBER} (refs/pull/${PR_NUMBER}/merge); refusing to avoid posting to the wrong PR."; emit_none
@@ -1700,16 +1800,25 @@ jobs:
# head. gh-aw safe-output review comments carry no `commit_id` — they
# target the current PR diff — so analyzing a stale revision would
# produce inline suggestions that get rejected or land on the wrong
- # lines. If the PR has advanced since this build ran, skip: a newer
- # build/check for the current head will cover it.
+ # lines. The PR can advance between selecting the build and reaching
+ # this point, so the head is re-read here rather than reused from the
+ # scope check above.
BUILD_PR_SHA=$(printf '%s' "${build_json}" | jq -r '.triggerInfo["pr.sourceSha"] // empty')
- CURRENT_HEAD=$(printf '%s' "${PR_JSON}" | jq -r '.head.sha // empty')
# ADO builds GitHub's `refs/pull//merge` ref, so build_json.sourceVersion
# is the merge commit GitHub produced at build time and equals the PR's
# `merge_commit_sha` then. If the base branch advances (even with the PR
# head unchanged) GitHub recomputes that merge and merge_commit_sha
# changes, so this catches base-advance staleness the head check misses.
BUILD_MERGE_SHA=$(printf '%s' "${build_json}" | jq -r '.sourceVersion // empty')
+ # Re-read the PR rather than reusing the snapshot from the scope check:
+ # selecting the build costs an ADO round trip, and right after a
+ # force-push the newest-build query can still return the previous
+ # failed build. The point of this check is to skip BEFORE paying for
+ # the download, so it should compare against the freshest head
+ # available. A post-download re-read below independently catches a
+ # head that moves while the artifacts are being fetched.
+ PR_JSON=$(gh api "repos/${GH_AW_REPO}/pulls/${PR_NUMBER}" 2>/dev/null)
+ CURRENT_HEAD=$(printf '%s' "${PR_JSON}" | jq -r '.head.sha // empty')
CURRENT_MERGE=$(printf '%s' "${PR_JSON}" | jq -r '.merge_commit_sha // empty')
# Fail CLOSED: if either the build's analyzed revision or the current
# PR head can't be resolved, skip — we must not analyze a possibly
@@ -1734,7 +1843,7 @@ jobs:
HEAD_SHA="${CURRENT_HEAD}"
echo "Analyzing build ${BUILD_ID} at PR head revision '${HEAD_SHA}'."
- # --- 5. Download every Logs_Build_* artifact and extract binlogs ---
+ # --- 4. Download every Logs_Build_* artifact and extract binlogs ---
artifacts_json=$(curl -sSL --retry 3 "${ADO_API}/build/builds/${BUILD_ID}/artifacts?api-version=7.1")
mapfile -t names < <(printf '%s' "${artifacts_json}" | jq -r '.value // [] | map(select(.name | test("^Logs_Build_"))) | .[].name')
[ "${#names[@]}" -eq 0 ] && { echo "::warning::No Logs_Build_* artifacts on build ${BUILD_ID}."; emit_none; }
@@ -1997,11 +2106,10 @@ jobs:
ADO_BUILD_DEFINITION_ID: "209"
ADO_BUILD_UI: https://dev.azure.com/dnceng-public/public/_build/results
CHECK_DETAILS_URL: ${{ github.event.check_run.details_url }}
- CHECK_HEAD_SHA: ${{ github.event.check_run.head_sha }}
CHECK_PR_NUMBER: ${{ github.event.check_run.pull_requests[0].number }}
- DISPATCH_BUILD_ID: ${{ inputs['ado-build-id'] }}
- DISPATCH_PR_NUMBER: ${{ inputs['pr-number'] }}
- EVENT_NAME: ${{ github.event_name }}
+ COMMAND_PR_NUMBER: ${{ github.event.issue.number || fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_number }}
+ DISPATCH_BUILD_ID: ${{ github.event.inputs['ado-build-id'] }}
+ DISPATCH_PR_NUMBER: ${{ github.event.inputs['pr-number'] }}
GH_AW_REPO: ${{ github.repository }}
GH_TOKEN: ${{ github.token }}
- name: Upload analysis artifact
@@ -2011,7 +2119,7 @@ jobs:
if-no-files-found: warn
name: build-failure-analysis-data
path: /tmp/binlogs
- retention-days: 1
+ retention-days: "1"
pre_activation:
needs: fetch-binlog
diff --git a/.github/workflows/build-failure-analysis.md b/.github/workflows/build-failure-analysis.md
index d10f945374..c972a798bc 100644
--- a/.github/workflows/build-failure-analysis.md
+++ b/.github/workflows/build-failure-analysis.md
@@ -88,6 +88,7 @@ network:
imports:
- shared/build-failure-analysis-shared.md
+ - shared/build-failure-analysis-fetch.md
# Live binlog access for the agent. The build-leg binlogs are downloaded from
# Azure DevOps by the fetch-binlog job into a directory, uploaded as an
@@ -100,436 +101,12 @@ mcp-servers:
- "/tmp/binlogs:/data/binlogs:ro"
allowed: ["*"]
-# Custom job that reuses the binlogs from the failed Azure DevOps build instead
-# of rebuilding. It resolves the ADO build id (from the check details URL or
-# the dispatch input), verifies the PR targets an in-scope base branch,
-# downloads every `Logs_Build_*` artifact, extracts each leg's `*.binlog`, and
-# uploads them for the agent job.
-jobs:
- fetch-binlog:
- name: Fetch binlogs (Azure Pipelines)
- runs-on: ubuntu-latest
- timeout-minutes: 15
- # `check_run` fires for every check; only act on the testfx PR build check
- # reporting failure (or a manual dispatch).
- if: >
- github.event_name == 'workflow_dispatch' ||
- (github.event.check_run.name == 'microsoft.testfx' && github.event.check_run.conclusion == 'failure')
- permissions:
- contents: read
- pull-requests: read
- outputs:
- binlog-found: ${{ steps.fetch.outputs.binlog-found }}
- pr-number: ${{ steps.fetch.outputs.pr-number }}
- pr-head-sha: ${{ steps.fetch.outputs.pr-head-sha }}
- pr-merge-sha: ${{ steps.fetch.outputs.pr-merge-sha }}
- ado-build-id: ${{ steps.fetch.outputs.ado-build-id }}
- ado-build-url: ${{ steps.fetch.outputs.ado-build-url }}
- missing-legs: ${{ steps.fetch.outputs.missing-legs }}
- steps:
- - name: Download binlogs from the failed Azure Pipelines build
- id: fetch
- env:
- GH_TOKEN: ${{ github.token }}
- GH_AW_REPO: ${{ github.repository }}
- ADO_API: "https://dev.azure.com/dnceng-public/public/_apis"
- ADO_BUILD_UI: "https://dev.azure.com/dnceng-public/public/_build/results"
- # microsoft.testfx pipeline definition id in dnceng-public/public (used to
- # validate a dispatched build id belongs to the right pipeline).
- ADO_BUILD_DEFINITION_ID: "209"
- EVENT_NAME: ${{ github.event_name }}
- CHECK_DETAILS_URL: ${{ github.event.check_run.details_url }}
- CHECK_HEAD_SHA: ${{ github.event.check_run.head_sha }}
- CHECK_PR_NUMBER: ${{ github.event.check_run.pull_requests[0].number }}
- DISPATCH_BUILD_ID: ${{ inputs['ado-build-id'] }}
- DISPATCH_PR_NUMBER: ${{ inputs['pr-number'] }}
- run: |
- # Advisory + best-effort: on any gap emit binlog-found=false and the
- # agent pipeline stays inert.
- set +e
- set +o pipefail
- emit_none() { echo "binlog-found=false" >> "$GITHUB_OUTPUT"; exit 0; }
-
- # --- 1. Resolve the Azure DevOps build id ---
- if [ "${EVENT_NAME}" = "workflow_dispatch" ]; then
- BUILD_ID="${DISPATCH_BUILD_ID}"
- else
- # details_url looks like: .../_build/results?buildId=NNN&view=...
- BUILD_ID=$(printf '%s' "${CHECK_DETAILS_URL}" | grep -oE 'buildId=[0-9]+' | head -1 | cut -d= -f2)
- fi
- echo "Azure DevOps build id: '${BUILD_ID}'"
- [ -z "${BUILD_ID}" ] && { echo "::warning::Could not resolve an ADO build id."; emit_none; }
- # The build id feeds directly into ADO API URLs below; require it to
- # be purely numeric (esp. on workflow_dispatch, where it is free-form
- # input) so a malformed value can't alter the request path/query.
- if ! printf '%s' "${BUILD_ID}" | grep -qE '^[0-9]+$'; then
- echo "::warning::Resolved ADO build id '${BUILD_ID}' is not numeric; refusing."; emit_none
- fi
-
- # Fetch the build metadata once, up front: it is the authoritative
- # source both for the PR number (via sourceBranch) and for the
- # definition/result/revision validated in step 4.
- build_json=$(curl -sSL --retry 3 "${ADO_API}/build/builds/${BUILD_ID}?api-version=7.1")
- RESULT=$(printf '%s' "${build_json}" | jq -r '.result // empty')
- DEF_ID=$(printf '%s' "${build_json}" | jq -r '.definition.id // empty')
- SRC_BRANCH=$(printf '%s' "${build_json}" | jq -r '.sourceBranch // empty')
- # A PR build's sourceBranch is exactly `refs/pull//merge`, so it
- # identifies the PR unambiguously — unlike the commit->PRs API, which
- # can return several PRs in an unspecified order.
- BUILD_PR_NUM=$(printf '%s' "${SRC_BRANCH}" | sed -n 's#^refs/pull/\([0-9]\{1,\}\)/merge$#\1#p')
-
- # --- 2. Resolve the PR number + head SHA ---
- if [ "${EVENT_NAME}" = "workflow_dispatch" ]; then
- PR_NUMBER="${DISPATCH_PR_NUMBER}"
- HEAD_SHA=""
- else
- # Prefer the PR named by the build's own sourceBranch (authoritative:
- # `refs/pull//merge`) over check_run.pull_requests[0], whose order
- # isn't guaranteed and can name a different PR that shares the commit.
- PR_NUMBER="${BUILD_PR_NUM:-${CHECK_PR_NUMBER}}"
- HEAD_SHA="${CHECK_HEAD_SHA}"
- fi
- [ -z "${PR_NUMBER}" ] && { echo "::warning::Could not resolve a PR number."; emit_none; }
- # PR_NUMBER feeds `gh api .../pulls/` and the `refs/pull//merge`
- # comparison; require it numeric so a malformed value can't reach the
- # GitHub API path (traversal-like input) or skew the branch match.
- if ! printf '%s' "${PR_NUMBER}" | grep -qE '^[0-9]+$'; then
- echo "::warning::Resolved PR number '${PR_NUMBER}' is not numeric; refusing."; emit_none
- fi
-
- # --- 3. Scope check: only analyse PRs targeting main / rel/* ---
- PR_JSON=$(gh api "repos/${GH_AW_REPO}/pulls/${PR_NUMBER}" 2>/dev/null)
- BASE_REF=$(printf '%s' "${PR_JSON}" | jq -r '.base.ref // empty')
- [ -z "${HEAD_SHA}" ] && HEAD_SHA=$(printf '%s' "${PR_JSON}" | jq -r '.head.sha // empty')
- case "${BASE_REF}" in
- main|rel/*) echo "PR #${PR_NUMBER} base '${BASE_REF}' is in scope." ;;
- *) echo "::warning::PR #${PR_NUMBER} base '${BASE_REF}' is out of scope (main, rel/*); skipping."; emit_none ;;
- esac
-
- # --- 4. Validate the build for EVERY trigger (not just dispatch):
- # it must be the microsoft.testfx definition (209), have failed, and
- # belong to this PR (sourceBranch == refs/pull//merge).
- # For `check_run` the build id is parsed from a check payload
- # we don't fully trust; for dispatch the build id and PR
- # number are independent inputs. Validating on both paths
- # prevents downloading an unrelated build or posting its
- # analysis to the wrong PR.
- echo "ADO build ${BUILD_ID}: result='${RESULT}' definition='${DEF_ID}' sourceBranch='${SRC_BRANCH}'"
- if [ "${DEF_ID}" != "${ADO_BUILD_DEFINITION_ID}" ]; then
- echo "::warning::ADO build ${BUILD_ID} is definition '${DEF_ID}', not microsoft.testfx (${ADO_BUILD_DEFINITION_ID}); refusing."; emit_none
- fi
- if [ "${RESULT}" != "failed" ]; then
- echo "::warning::ADO build ${BUILD_ID} did not fail (result='${RESULT}'); nothing to analyze."; emit_none
- fi
- if [ "${SRC_BRANCH}" != "refs/pull/${PR_NUMBER}/merge" ]; then
- echo "::warning::ADO build ${BUILD_ID} sourceBranch '${SRC_BRANCH}' does not match PR #${PR_NUMBER} (refs/pull/${PR_NUMBER}/merge); refusing to avoid posting to the wrong PR."; emit_none
- fi
-
- # Require the build's analyzed revision to equal the PR's CURRENT
- # head. gh-aw safe-output review comments carry no `commit_id` — they
- # target the current PR diff — so analyzing a stale revision would
- # produce inline suggestions that get rejected or land on the wrong
- # lines. If the PR has advanced since this build ran, skip: a newer
- # build/check for the current head will cover it.
- BUILD_PR_SHA=$(printf '%s' "${build_json}" | jq -r '.triggerInfo["pr.sourceSha"] // empty')
- CURRENT_HEAD=$(printf '%s' "${PR_JSON}" | jq -r '.head.sha // empty')
- # ADO builds GitHub's `refs/pull//merge` ref, so build_json.sourceVersion
- # is the merge commit GitHub produced at build time and equals the PR's
- # `merge_commit_sha` then. If the base branch advances (even with the PR
- # head unchanged) GitHub recomputes that merge and merge_commit_sha
- # changes, so this catches base-advance staleness the head check misses.
- BUILD_MERGE_SHA=$(printf '%s' "${build_json}" | jq -r '.sourceVersion // empty')
- CURRENT_MERGE=$(printf '%s' "${PR_JSON}" | jq -r '.merge_commit_sha // empty')
- # Fail CLOSED: if either the build's analyzed revision or the current
- # PR head can't be resolved, skip — we must not analyze a possibly
- # stale binlog against the current diff (inline comments have no
- # commit_id and target the current PR diff).
- if [ -z "${BUILD_PR_SHA}" ] || [ -z "${CURRENT_HEAD}" ]; then
- echo "::warning::Could not resolve build revision ('${BUILD_PR_SHA}') and/or current PR head ('${CURRENT_HEAD}'); skipping to avoid analyzing a stale binlog against the current diff."
- emit_none
- fi
- if [ "${BUILD_PR_SHA}" != "${CURRENT_HEAD}" ]; then
- echo "::warning::Build ${BUILD_ID} analyzed revision '${BUILD_PR_SHA}' but PR #${PR_NUMBER} head is now '${CURRENT_HEAD}'; skipping stale build (a newer build/check will cover the current revision)."
- emit_none
- fi
- # When both merge revisions are known and differ, the base branch moved
- # since the build — the binlog reflects an obsolete merge. Skip.
- if [ -n "${BUILD_MERGE_SHA}" ] && [ -n "${CURRENT_MERGE}" ] && [ "${BUILD_MERGE_SHA}" != "${CURRENT_MERGE}" ]; then
- echo "::warning::Build ${BUILD_ID} merge revision '${BUILD_MERGE_SHA}' but PR #${PR_NUMBER} current merge is '${CURRENT_MERGE}' (base branch advanced); skipping stale merge."
- emit_none
- fi
- # Consistent now: build revision == current PR head. Use it for
- # permalinks so they line up with the inline comments' diff target.
- HEAD_SHA="${CURRENT_HEAD}"
- echo "Analyzing build ${BUILD_ID} at PR head revision '${HEAD_SHA}'."
-
- # --- 5. Download every Logs_Build_* artifact and extract binlogs ---
- artifacts_json=$(curl -sSL --retry 3 "${ADO_API}/build/builds/${BUILD_ID}/artifacts?api-version=7.1")
- mapfile -t names < <(printf '%s' "${artifacts_json}" | jq -r '.value // [] | map(select(.name | test("^Logs_Build_"))) | .[].name')
- [ "${#names[@]}" -eq 0 ] && { echo "::warning::No Logs_Build_* artifacts on build ${BUILD_ID}."; emit_none; }
-
- # --- 5a. Which failed legs never published logs at all? ---
- # The fail-closed check further down compares staged legs against the
- # artifacts ADO *returned*, so it cannot see a leg that died before
- # publishing its logs artifact — that leg is simply absent from
- # `names`. Ask the timeline instead. This is advisory rather than
- # fail-closed: a failed job that legitimately publishes no logs would
- # otherwise suppress analysis of a real compile break in the same build. The agent is told about the gap so it cannot conclude
- # "no build failure" from the legs that happened to upload.
- #
- # Ask the timeline whether each leg's log *publish* succeeded rather
- # than guessing its artifact name from its display name. The artifact
- # is named from `$(Agent.Os)`, which is not what the job is called:
- # `MacOS Debug` publishes `Logs_Build_Darwin_Debug`, and
- # `WindowsSamples Debug` is named from `$(Agent.JobName)` instead. Name
- # matching reported those healthy legs as missing on real builds —
- # every macOS failure, and every `msbuild_cache_seed` job. Arcade's
- # `Publish logs` task record answers the question directly, so no
- # spelling has to be inferred. A failed job carrying no such task
- # (the `Detect changed paths` classifier, the cache-seed stage) does
- # not publish logs at all and is not treated as a missing leg.
- #
- # `canceled` and `abandoned` legs count alongside `failed`: they also
- # finish without logs, and are a real gap in the artifact set.
- timeline_json=$(curl -sSL --retry 3 --max-time 60 "${ADO_API}/build/builds/${BUILD_ID}/timeline?api-version=7.1" 2>/dev/null || true)
- MISSING_LEGS=""
- # An unreadable timeline must not look like a complete build. A failed
- # request, a non-JSON error page and an ADO error document all left
- # the list empty, which is exactly how "every failed leg published
- # logs" is reported — so a transient outage could let the agent
- # conclude "non-build failure" from an artifact set whose completeness
- # was never established. Probe for the `records` array first and
- # report an explicit unknown when it isn't there.
- timeline_ok=0
- if printf '%s' "${timeline_json}" | jq -e 'type == "object" and has("records")' >/dev/null 2>&1; then
- timeline_ok=1
- fi
- if [ "${timeline_ok}" -eq 1 ]; then
- # Job display names come from the pipeline YAML in the PR branch, so
- # on a fork PR they are attacker-controlled. Strip control characters
- # and bound the length before this value reaches `$GITHUB_OUTPUT` and
- # `$GITHUB_ENV`, where an embedded newline would inject further
- # `key=value` lines. The task name is matched on its alphanumerics
- # because arcade spells it both `Publish logs` and `Publish Logs`,
- # and some pipelines prefix a decorative emoji.
- MISSING_LEGS=$(printf '%s' "${timeline_json}" | jq -r '
- (.records // []) as $records
- | ($records
- | map(select(.type == "Task"
- and (.name | ascii_downcase | gsub("[^a-z0-9]"; "") | test("publishlogs"))))) as $publishes
- | $records
- | map(select(.type == "Job"
- and (.result == "failed" or .result == "canceled" or .result == "abandoned")))
- | map(. as $job
- | ($publishes | map(select(.parentId == $job.id))) as $mine
- | select(($mine | length) > 0
- and (($mine | map(select(.result == "succeeded")) | length) == 0))
- | ($job.name | gsub("[[:cntrl:]]"; " ")))
- | join(", ")' 2>/dev/null | tr -d '\r\n' | cut -c1-400)
- fi
- if [ "${timeline_ok}" -ne 1 ]; then
- MISSING_LEGS="(unknown - could not read the build timeline)"
- echo "::warning::Could not read the timeline for build ${BUILD_ID}; unable to verify that every failed leg published a logs artifact."
- elif [ -n "${MISSING_LEGS}" ]; then
- echo "::warning::Failed leg(s) whose logs were never published: ${MISSING_LEGS}"
- fi
-
- # Guards for untrusted PR-produced archives: cap the compressed
- # download and the reported uncompressed size per artifact, bound
- # extraction time, AND enforce cumulative budgets across all legs so
- # many individually-small artifacts can't collectively exhaust the
- # runner's disk or its network time.
- MAX_ZIP_BYTES=524288000 # 500 MB compressed per artifact
- MAX_UNZIP_BYTES=2147483648 # 2 GB uncompressed per artifact
- MAX_TOTAL_BYTES=4294967296 # 4 GB uncompressed across all artifacts
- MAX_TOTAL_ZIP_BYTES=3221225472 # 3 GB compressed downloaded in total
- MAX_ARTIFACTS=40 # cap only; the real count is path-dependent
- TOTAL_BYTES=0
- TOTAL_ZIP_BYTES=0
- # Bound the work before starting: a pipeline change (or repeated leg
- # retries) could grow the matched set well past today's count. Refuse
- # rather than process a prefix of the list, because a partial view is
- # exactly what the fail-closed check below exists to prevent.
- if [ "${#names[@]}" -gt "${MAX_ARTIFACTS}" ]; then
- echo "::warning::Build ${BUILD_ID} matched ${#names[@]} log artifacts, above the ${MAX_ARTIFACTS} cap; skipping."
- emit_none
- fi
- mkdir -p /tmp/binlogs
- count=0
- staged_legs=0
- ai=0
- for name in "${names[@]}"; do
- # `name` is PR-controlled ADO artifact metadata and the
- # `^Logs_Build_` filter only anchors the prefix, so sanitize it
- # before using it in any on-disk path (guards against `/` or `..`
- # traversal); keep the original `name` for the artifacts_json lookup.
- safe_name=$(printf '%s' "${name}" | tr -c 'A-Za-z0-9._-' '_')
- ai=$((ai + 1))
- url=$(printf '%s' "${artifacts_json}" | jq -r --arg n "${name}" '.value[] | select(.name==$n) | .resource.downloadUrl // empty')
- [ -z "${url}" ] && { echo "::warning::No download URL for ${name}."; continue; }
- rm -rf /tmp/ax /tmp/a.zip
- mkdir -p /tmp/ax
- # Hard-cap the bytes written to disk regardless of Content-Length:
- # stream through `head -c` (cap + 1) and bound total time. This
- # closes the gap where `curl --max-filesize` alone would let a
- # length-less response write unbounded data before any post-check.
- curl -sSL --retry 3 --max-time 300 "${url}" 2>/dev/null | head -c $((MAX_ZIP_BYTES + 1)) > /tmp/a.zip || true
- ZIP_BYTES=$(stat -c%s /tmp/a.zip 2>/dev/null || echo 0)
- # Bound cumulative *compressed* bytes too: the per-artifact and
- # cumulative-uncompressed caps still allow many mid-sized archives
- # to be pulled over the network before any of them is inspected.
- #
- # Charge the budget here, before the skips below, because the bytes
- # are already on the wire by this point — `curl` above streams into
- # `head -c` and only then is the size known. Charging after the
- # per-artifact skip would let every oversized artifact cost a full
- # MAX_ZIP_BYTES of network without ever being counted, so a build of
- # MAX_ARTIFACTS oversized legs would download far past this budget
- # while appearing to stay inside it.
- TOTAL_ZIP_BYTES=$((TOTAL_ZIP_BYTES + ZIP_BYTES))
- if [ "${TOTAL_ZIP_BYTES}" -gt "${MAX_TOTAL_ZIP_BYTES}" ]; then
- echo "::warning::Cumulative compressed download budget ${MAX_TOTAL_ZIP_BYTES} reached at ${name}; stopping."; break
- fi
- if [ "${ZIP_BYTES}" -eq 0 ]; then
- echo "::warning::Skipping ${name}: empty or failed download."; continue
- fi
- if [ "${ZIP_BYTES}" -gt "${MAX_ZIP_BYTES}" ]; then
- echo "::warning::Skipping ${name}: download exceeded ${MAX_ZIP_BYTES} bytes."; continue
- fi
- UNCOMP=$(unzip -l /tmp/a.zip 2>/dev/null | tail -1 | awk '{print $1}')
- # Fail safe: if the uncompressed size isn't a plain integer (corrupt
- # zip / unexpected `unzip -l` output), we can't verify it — skip the
- # artifact rather than let a non-numeric value bypass the `-gt` guard.
- if ! printf '%s' "${UNCOMP}" | grep -qE '^[0-9]+$'; then
- echo "::warning::Skipping ${name}: could not determine uncompressed size (unparseable unzip output)."; continue
- fi
- # ZIP64 uncompressed sizes can reach ~20 digits — beyond Bash's
- # signed 64-bit range, where `-gt` (and the cumulative `$((...))`
- # below) error out and, under `set +e`, would let an oversized
- # archive slip past the guard. Any value with more digits than the
- # limit is unambiguously larger, so reject on decimal length first;
- # after this, UNCOMP fits safely in the integer range used below.
- if [ "${#UNCOMP}" -gt "${#MAX_UNZIP_BYTES}" ]; then
- echo "::warning::Skipping ${name}: uncompressed size has ${#UNCOMP} digits, exceeding the ${MAX_UNZIP_BYTES} guard (possible zip bomb)."; continue
- fi
- if [ "${UNCOMP}" -gt "${MAX_UNZIP_BYTES}" ]; then
- echo "::warning::Skipping ${name}: uncompressed size ${UNCOMP} exceeds ${MAX_UNZIP_BYTES} guard (possible zip bomb)."; continue
- fi
- if [ $((TOTAL_BYTES + UNCOMP)) -gt "${MAX_TOTAL_BYTES}" ]; then
- echo "::warning::Cumulative uncompressed budget ${MAX_TOTAL_BYTES} reached at ${name}; stopping extraction."; break
- fi
- # Refuse the archive if any entry path is absolute or has a `..`
- # component (defense-in-depth over unzip's own traversal guard),
- # then extract `*.binlog` entries *preserving* their in-archive
- # paths (no `-j`) under a fresh dir + timeout, so two binlogs that
- # share a basename in different folders don't overwrite each other.
- if unzip -Z1 /tmp/a.zip 2>/dev/null | grep -qE '(^/|(^|/)\.\.(/|$))'; then
- echo "::warning::Skipping ${name}: archive has a suspicious (absolute or ..) entry path."; continue
- fi
- # `unzip` exit 11 means "no files matched" — the artifact carries no
- # binlog at all. That is not an extraction failure: the leg did
- # publish its logs, they simply contain no binlog, and the
- # fail-closed check below already accounts for a leg that staged
- # nothing. Reporting it as "extraction failed or timed out" sends
- # the reader chasing a corrupt-archive theory that isn't there. Any
- # other non-zero exit (corrupt archive, timeout) is a real failure.
- #
- # Both cases `continue`, so nothing was written to /tmp/ax and the
- # uncompressed budget below is left untouched. Charging it for an
- # archive that extracted nothing would let one large binlog-free
- # artifact push a genuinely useful later leg past MAX_TOTAL_BYTES.
- uz=0
- timeout 120 unzip -o /tmp/a.zip '*.binlog' -d /tmp/ax >/dev/null 2>&1 || uz=$?
- if [ "${uz}" -eq 11 ]; then
- echo "::warning::${name}: published logs contain no binlog; nothing to analyse from this leg."; continue
- fi
- if [ "${uz}" -ne 0 ]; then
- echo "::warning::Skipping ${name}: extraction failed or timed out (unzip exit ${uz})."; continue
- fi
- # Consume the cumulative budget only once the archive actually
- # extracted — not on a suspicious-path or extraction-failure skip
- # above — so a skipped leg can't wrongly exhaust the budget and
- # force later legs to be dropped as "incomplete".
- TOTAL_BYTES=$((TOTAL_BYTES + UNCOMP))
- i=0
- leg_staged=0
- while IFS= read -r bl; do
- [ -f "${bl}" ] || continue
- # Every destination is uniquely prefixed with the artifact index
- # (`ai`) and a per-file counter (`i`), so neither a cross-artifact
- # sanitize collision nor same-basename entries within one archive
- # can overwrite a previously staged leg's binlog. `safe_name` is
- # kept only for readability.
- dest="/tmp/binlogs/${ai}_${i}_${safe_name}.binlog"
- # Only count a staged binlog when the copy actually succeeds —
- # `set +e` is on, so a failed `cp` must not inflate the counts.
- if cp "${bl}" "${dest}"; then
- count=$((count + 1))
- i=$((i + 1))
- leg_staged=1
- else
- echo "::warning::Failed to stage ${bl}; skipping."
- fi
- done < <(find /tmp/ax -type f -name '*.binlog')
- # This leg produced at least one usable binlog.
- [ "${leg_staged}" -eq 1 ] && staged_legs=$((staged_legs + 1))
- done
- echo "Extracted ${count} binlog(s) from ${staged_legs}/${#names[@]} legs into /tmp/binlogs:"
- ls -la /tmp/binlogs || true
- [ "${count}" -eq 0 ] && { echo "::warning::No *.binlog found in any Logs_Build_* artifact of build ${BUILD_ID}."; emit_none; }
- # Fail CLOSED on a partial set: if any Logs_Build_* leg did not yield
- # a usable binlog (download/extract failure, size-guard skip, or no
- # binlog inside), we cannot see every leg. Activating anyway would let
- # the agent treat the retrieved legs as the whole build and possibly
- # mis-classify a real build break in a missing leg as a clean compile /
- # non-build failure. A later build/check will re-trigger the analysis.
- if [ "${staged_legs}" -ne "${#names[@]}" ]; then
- echo "::warning::Only ${staged_legs} of ${#names[@]} Logs_Build_* legs produced a usable binlog; skipping to avoid analyzing an incomplete build (a missing leg could be the one that failed)."
- emit_none
- fi
-
- # The download/extract loop above can take minutes. Re-read the PR
- # head right before activating and fail CLOSED if it moved or can't
- # be resolved: a force-push during that window would otherwise leave
- # the analyzed binlog stale relative to the current diff (inline
- # comments carry no commit_id and target the current diff).
- LATEST_PR=$(gh api "repos/${GH_AW_REPO}/pulls/${PR_NUMBER}" 2>/dev/null)
- LATEST_HEAD=$(printf '%s' "${LATEST_PR}" | jq -r '.head.sha // empty')
- LATEST_MERGE=$(printf '%s' "${LATEST_PR}" | jq -r '.merge_commit_sha // empty')
- if [ -z "${LATEST_HEAD}" ] || [ "${LATEST_HEAD}" != "${HEAD_SHA}" ]; then
- echo "::warning::PR #${PR_NUMBER} head changed during artifact download ('${HEAD_SHA}' -> '${LATEST_HEAD}') or could not be re-resolved; skipping to avoid posting stale-build suggestions against the new diff."
- emit_none
- fi
- # The base branch may also have advanced during the download; if the
- # merge revision moved from what the build analyzed, skip (stale merge).
- if [ -n "${BUILD_MERGE_SHA}" ] && [ -n "${LATEST_MERGE}" ] && [ "${LATEST_MERGE}" != "${BUILD_MERGE_SHA}" ]; then
- echo "::warning::PR #${PR_NUMBER} merge revision changed during artifact download ('${BUILD_MERGE_SHA}' -> '${LATEST_MERGE}'); skipping stale merge."
- emit_none
- fi
-
- {
- # `missing-legs` is derived from ADO job display names, which come
- # from pipeline YAML in the PR branch and are therefore
- # fork-controlled. It is sanitized where it is assembled, and it is
- # written first here so that even a future regression in that
- # sanitizing cannot let it override a key emitted below.
- echo "missing-legs=${MISSING_LEGS}"
- echo "binlog-found=true"
- echo "pr-number=${PR_NUMBER}"
- echo "pr-head-sha=${HEAD_SHA}"
- echo "pr-merge-sha=${BUILD_MERGE_SHA}"
- echo "ado-build-id=${BUILD_ID}"
- echo "ado-build-url=${ADO_BUILD_UI}?buildId=${BUILD_ID}"
- } >> "$GITHUB_OUTPUT"
-
- - name: Upload analysis artifact
- if: steps.fetch.outputs.binlog-found == 'true'
- uses: actions/upload-artifact@v7.0.1
- with:
- name: build-failure-analysis-data
- path: /tmp/binlogs
- if-no-files-found: warn
- retention-days: 1
+# The `fetch-binlog` job that reuses the binlogs from the failed Azure DevOps
+# build instead of rebuilding is shared with the other Build Failure Analysis
+# workflow and lives in `shared/build-failure-analysis-fetch.md`, imported
+# above. It resolves the build, verifies the PR targets an in-scope base
+# branch, downloads every `Logs_Build_*` artifact, extracts each leg's
+# `*.binlog` and uploads them for the agent job.
# Steps that run in the agent job. Because the top-level `if:` gates activation
# on `needs.fetch-binlog.outputs.binlog-found == 'true'`, these only run once
diff --git a/.github/workflows/shared/build-failure-analysis-fetch.md b/.github/workflows/shared/build-failure-analysis-fetch.md
new file mode 100644
index 0000000000..bb7f213de1
--- /dev/null
+++ b/.github/workflows/shared/build-failure-analysis-fetch.md
@@ -0,0 +1,612 @@
+---
+description: >-
+ Shared `fetch-binlog` job for the Build Failure Analysis workflows. Resolves
+ the PR's failed `microsoft.testfx` Azure DevOps build, downloads the binary
+ logs that build already produced and stages them for the analysis agent. It
+ performs **no build**: it only reads published build artifacts.
+
+# Both Build Failure Analysis workflows — the automatic one (`check_run`) and
+# the `/analyze-build-failure` slash command — need exactly the same download
+# engine, but they cannot be a single workflow: gh-aw's `roles:` is one
+# workflow-scoped gate and the two need different ones. The automatic analysis
+# is advisory and must run on **every** failing PR including external
+# contributors' (`roles: all`), while the slash command spends the download on
+# demand and is restricted to `[admin, maintainer, write]`.
+#
+# So the job lives here instead and both workflows import it. Only the build/PR
+# resolution differs by entry point, and that is a single `if` at the top of the
+# script; everything after it — artifact enumeration, missing-leg detection, the
+# download/extraction budgets and the fail-closed completeness checks — is
+# shared, so a fix lands in both workflows at once.
+jobs:
+ fetch-binlog:
+ name: Fetch binlogs (Azure Pipelines)
+ runs-on: ubuntu-latest
+ timeout-minutes: 15
+ # Cheap pre-gate covering every trigger this job is imported under. Each
+ # importing workflow only ever fires one of these branches.
+ #
+ # `check_run` fires for every check on a commit, so only the
+ # `microsoft.testfx` build check reporting failure is acted on. The
+ # `workflow_dispatch` clause covers both the automatic workflow's manual
+ # rerun entry point and the slash command, which uses
+ # `strategy: centralized` and is therefore started by `agentic_commands.yml`
+ # via `workflow_dispatch` — the permission step below is what guards that
+ # path, since this job runs BEFORE gh-aw's `pre_activation` role check.
+ if: >-
+ github.event_name == 'workflow_dispatch' ||
+ (github.event_name == 'check_run' &&
+ github.event.check_run.name == 'microsoft.testfx' &&
+ github.event.check_run.conclusion == 'failure')
+ permissions:
+ contents: read
+ pull-requests: read
+ outputs:
+ binlog-found: ${{ steps.fetch.outputs.binlog-found }}
+ pr-number: ${{ steps.fetch.outputs.pr-number }}
+ pr-head-sha: ${{ steps.fetch.outputs.pr-head-sha }}
+ pr-merge-sha: ${{ steps.fetch.outputs.pr-merge-sha }}
+ ado-build-id: ${{ steps.fetch.outputs.ado-build-id }}
+ ado-build-url: ${{ steps.fetch.outputs.ado-build-url }}
+ missing-legs: ${{ steps.fetch.outputs.missing-legs }}
+ steps:
+ # Cost + abuse pre-gate for the slash command. gh-aw's own role check
+ # (`roles: [admin, maintainer, write]`) lives in the generated
+ # `pre_activation` job, and that job is compiled with `needs:
+ # fetch-binlog` — so it only runs *after* this job has already pulled
+ # every build leg's logs artifact from Azure DevOps (hundreds of MB).
+ # Inverting the dependency would create a cycle, so the same permission
+ # check is repeated here, before anything is downloaded. `pre_activation`
+ # remains the authoritative role + command-position check; this is purely
+ # an early-out.
+ #
+ # Both importing workflows can receive `workflow_dispatch`, so
+ # `github.event_name` cannot tell them apart. What does distinguish them
+ # is the payload: the automatic workflow is always TOLD a build (a
+ # `check_run` names it in `details_url`, its manual dispatch takes a
+ # required `ado-build-id`), while the centrally-dispatched slash command
+ # carries neither and only names a PR in `aw_context`. So the absence of
+ # both build-id sources is exactly "this is the slash command", and that
+ # is the condition the gate runs under. `route_slash_command.cjs` in the
+ # dispatcher performs no permission check of its own, so without this step
+ # any commenter on any PR could trigger the full download.
+ #
+ # INVARIANT: `build-failure-analysis-command.md` must never gain a
+ # `check_run` trigger or an `ado-build-id` dispatch input. Either one
+ # would make the command path indistinguishable from the automatic path,
+ # and this gate would silently stop running on it. (GitHub drops
+ # `workflow_dispatch` inputs a workflow does not declare, so an attacker
+ # cannot inject `ado-build-id` from outside — only a change to that file
+ # can break this.)
+ #
+ # Check `role_name` and `permission` together: `role_name` reports the
+ # precise role (so `maintain` and `triage` stay distinct) while
+ # `permission` is the coarse legacy field, and a custom org role reports a
+ # non-standard name in `role_name` while still showing its push access in
+ # `permission`. Accepting the union of the two covers every shape without
+ # depending on which field carries the role. On any API failure `gh` emits
+ # an error document that has neither field, so the check falls into the
+ # deny branch; failing closed is the safe direction for a pre-gate.
+ - name: Verify the commenter has write access
+ id: perm
+ if: github.event.check_run.details_url == '' && github.event.inputs['ado-build-id'] == ''
+ env:
+ GH_TOKEN: ${{ github.token }}
+ COMMENTER: ${{ github.event.comment.user.login || fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').actor }}
+ run: |
+ set +e
+ authorized=false
+ # `COMMENTER` has the same untrusted provenance as `PR_NUMBER` below
+ # (an `aw_context` payload), and it is interpolated into an API path
+ # and into log output, so give it the same shape check. GitHub logins
+ # are alphanumerics and hyphens; anything else is a malformed or
+ # hostile payload rather than a real account, and is dropped so it
+ # lands in the deny branch.
+ case "${COMMENTER}" in
+ ""|*[!A-Za-z0-9-]*)
+ [ -n "${COMMENTER}" ] && echo "::warning::Ignoring implausible actor name from the event payload."
+ COMMENTER="" ;;
+ esac
+ if [ -z "${COMMENTER}" ]; then
+ echo "::warning::No actor resolved from the slash-command event / aw_context; skipping the binlog download."
+ else
+ resp=$(gh api "repos/${GITHUB_REPOSITORY}/collaborators/${COMMENTER}/permission" 2>/dev/null)
+ role=$(printf '%s' "${resp}" | jq -r '.role_name // empty' 2>/dev/null)
+ perm=$(printf '%s' "${resp}" | jq -r '.permission // empty' 2>/dev/null)
+ for r in "${role}" "${perm}"; do
+ case "${r}" in
+ # `maintainer` is not a value GitHub returns in `role_name`
+ # (that spelling is `maintain`); it is listed because it is the
+ # spelling gh-aw uses in `GH_AW_REQUIRED_ROLES`, and keeping the
+ # two lists identical is what makes this an early-out for the
+ # same decision `pre_activation` makes later. Both spellings are
+ # accepted so neither source can drift into denying a maintainer.
+ admin|maintain|maintainer|write) authorized=true ;;
+ esac
+ done
+ if [ "${authorized}" = "true" ]; then
+ echo "'${COMMENTER}' has '${role:-${perm}}' access to ${GITHUB_REPOSITORY}; proceeding."
+ else
+ echo "::warning::'${COMMENTER}' does not have write access to ${GITHUB_REPOSITORY} (resolved role '${role:-${perm:-none}}'); skipping the binlog download."
+ fi
+ fi
+ echo "authorized=${authorized}" >> "$GITHUB_OUTPUT"
+
+ - name: Download binlogs from the failed Azure Pipelines build
+ id: fetch
+ # The gate above only runs for the slash command; when the build is
+ # named by a check payload or a dispatch input it is skipped and its
+ # output is empty, so the first two clauses let those paths through
+ # unchanged.
+ if: github.event.check_run.details_url != '' || github.event.inputs['ado-build-id'] != '' || steps.perm.outputs.authorized == 'true'
+ env:
+ GH_TOKEN: ${{ github.token }}
+ GH_AW_REPO: ${{ github.repository }}
+ ADO_API: "https://dev.azure.com/dnceng-public/public/_apis"
+ ADO_BUILD_UI: "https://dev.azure.com/dnceng-public/public/_build/results"
+ # microsoft.testfx pipeline definition id in dnceng-public/public
+ # (used to validate the resolved build belongs to the right pipeline).
+ ADO_BUILD_DEFINITION_ID: "209"
+ # `check_run` payload.
+ CHECK_DETAILS_URL: ${{ github.event.check_run.details_url }}
+ CHECK_PR_NUMBER: ${{ github.event.check_run.pull_requests[0].number }}
+ # `workflow_dispatch` inputs, read from `github.event.inputs` rather
+ # than the `inputs` context: `inputs` is typed per workflow, while
+ # `github.event.inputs` is simply absent (empty) when the importing
+ # workflow does not declare that input, so one shared job can
+ # reference both entry points.
+ DISPATCH_BUILD_ID: ${{ github.event.inputs['ado-build-id'] }}
+ DISPATCH_PR_NUMBER: ${{ github.event.inputs['pr-number'] }}
+ # Slash-command payload (`aw_context` when the command is routed
+ # through the central dispatcher, `issue.number` when inline).
+ COMMAND_PR_NUMBER: ${{ github.event.issue.number || fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_number }}
+ run: |
+ # Advisory + best-effort: on any gap emit binlog-found=false and the
+ # agent pipeline stays inert.
+ set +e
+ set +o pipefail
+ emit_none() { echo "binlog-found=false" >> "$GITHUB_OUTPUT"; exit 0; }
+
+ # --- 1. Resolve the Azure DevOps build and the PR it belongs to ---
+ # This is the ONLY part of the job that differs between the two
+ # workflows, because they learn about the build in opposite
+ # directions:
+ #
+ # * `check_run` / manual dispatch are TOLD which build to look at —
+ # the check payload names it in `details_url`, a manual dispatch
+ # passes it explicitly — so the build is resolved first and the PR
+ # is derived from it.
+ # * The slash command is told nothing about a build: it is a request
+ # to re-analyse whatever the PR's newest build is, so the PR comes
+ # first and the build is looked up from it. That build is usable
+ # only once it has COMPLETED; a still running newest build (e.g.
+ # right after a force-push) would otherwise pair an older failure
+ # with the PR's current head.
+ #
+ # Both importing workflows can receive `workflow_dispatch` (the slash
+ # command uses `strategy: centralized`), so the branch is taken on the
+ # payload rather than on the event name: having a build id at all is
+ # what makes this the automatic workflow.
+ if [ -n "${DISPATCH_BUILD_ID}" ] || [ -n "${CHECK_DETAILS_URL}" ]; then
+ ENTRY="build"
+ if [ -n "${DISPATCH_BUILD_ID}" ]; then
+ BUILD_ID="${DISPATCH_BUILD_ID}"
+ else
+ # details_url looks like: .../_build/results?buildId=NNN&view=...
+ BUILD_ID=$(printf '%s' "${CHECK_DETAILS_URL}" | grep -oE 'buildId=[0-9]+' | head -1 | cut -d= -f2)
+ fi
+ echo "Azure DevOps build id: '${BUILD_ID}'"
+ [ -z "${BUILD_ID}" ] && { echo "::warning::Could not resolve an ADO build id."; emit_none; }
+ # The build id feeds directly into ADO API URLs below; require it to
+ # be purely numeric (esp. on workflow_dispatch, where it is free-form
+ # input) so a malformed value can't alter the request path/query.
+ if ! printf '%s' "${BUILD_ID}" | grep -qE '^[0-9]+$'; then
+ echo "::warning::Resolved ADO build id '${BUILD_ID}' is not numeric; refusing."; emit_none
+ fi
+ # The build metadata is the authoritative source for the PR number
+ # (via sourceBranch) as well as for the definition / result /
+ # revision validated in step 3.
+ build_json=$(curl -sSL --retry 3 "${ADO_API}/build/builds/${BUILD_ID}?api-version=7.1")
+ # A PR build's sourceBranch is exactly `refs/pull//merge`, so it
+ # identifies the PR unambiguously — unlike the commit->PRs API,
+ # which can return several PRs in an unspecified order.
+ BUILD_PR_NUM=$(printf '%s' "${build_json}" | jq -r '.sourceBranch // empty' | sed -n 's#^refs/pull/\([0-9]\{1,\}\)/merge$#\1#p')
+ if [ -n "${DISPATCH_BUILD_ID}" ]; then
+ PR_NUMBER="${DISPATCH_PR_NUMBER}"
+ else
+ # Prefer the PR named by the build's own sourceBranch
+ # (authoritative) over check_run.pull_requests[0], whose order
+ # isn't guaranteed and can name a different PR sharing the commit.
+ PR_NUMBER="${BUILD_PR_NUM:-${CHECK_PR_NUMBER}}"
+ fi
+ [ -z "${PR_NUMBER}" ] && { echo "::warning::Could not resolve a PR number."; emit_none; }
+ # PR_NUMBER feeds `gh api .../pulls/` and the `refs/pull//merge`
+ # comparison; require it numeric so a malformed value can't reach the
+ # GitHub API path (traversal-like input) or skew the branch match.
+ if ! printf '%s' "${PR_NUMBER}" | grep -qE '^[0-9]+$'; then
+ echo "::warning::Resolved PR number '${PR_NUMBER}' is not numeric; refusing."; emit_none
+ fi
+ else
+ ENTRY="command"
+ PR_NUMBER="${COMMAND_PR_NUMBER}"
+ [ -z "${PR_NUMBER}" ] && { echo "::warning::No PR number resolved from the slash-command event / aw_context."; emit_none; }
+ # PR_NUMBER feeds GitHub API paths and the `refs/pull//merge`
+ # branch query; require it numeric so a malformed event/aw_context
+ # payload can't reach those URLs with unexpected content.
+ if ! printf '%s' "${PR_NUMBER}" | grep -qE '^[0-9]+$'; then
+ echo "::warning::Resolved PR number '${PR_NUMBER}' is not numeric; refusing."; emit_none
+ fi
+ # Newest build for the PR's merge ref REGARDLESS of status
+ # (queue-time descending), so a build queued after an older failure
+ # is seen rather than the stale one being analysed silently.
+ builds_json=$(curl -sSL --retry 3 \
+ "${ADO_API}/build/builds?definitions=${ADO_BUILD_DEFINITION_ID}&branchName=refs/pull/${PR_NUMBER}/merge&queryOrder=queueTimeDescending&\$top=1&api-version=7.1")
+ BUILD_ID=$(printf '%s' "${builds_json}" | jq -r '.value // [] | .[0].id // empty')
+ BUILD_STATUS=$(printf '%s' "${builds_json}" | jq -r '.value // [] | .[0].status // empty')
+ echo "Newest microsoft.testfx build for PR #${PR_NUMBER}: id='${BUILD_ID}' status='${BUILD_STATUS}'"
+ [ -z "${BUILD_ID}" ] && { echo "::warning::No microsoft.testfx build found for PR #${PR_NUMBER}."; emit_none; }
+ # Require a numeric build id before it feeds subsequent ADO API
+ # URLs, so a malformed query response can't inject path/query.
+ if ! printf '%s' "${BUILD_ID}" | grep -qE '^[0-9]+$'; then
+ echo "::warning::ADO build id '${BUILD_ID}' is not numeric; refusing."; emit_none
+ fi
+ if [ "${BUILD_STATUS}" != "completed" ]; then
+ echo "::warning::PR #${PR_NUMBER}'s newest microsoft.testfx build (${BUILD_ID}) is still '${BUILD_STATUS}'; wait for it to finish before analysing."
+ emit_none
+ fi
+ build_json=$(curl -sSL --retry 3 "${ADO_API}/build/builds/${BUILD_ID}?api-version=7.1")
+ fi
+ RESULT=$(printf '%s' "${build_json}" | jq -r '.result // empty')
+ DEF_ID=$(printf '%s' "${build_json}" | jq -r '.definition.id // empty')
+ SRC_BRANCH=$(printf '%s' "${build_json}" | jq -r '.sourceBranch // empty')
+
+ # --- 2. Scope check: only analyse PRs targeting main / rel/* ---
+ PR_JSON=$(gh api "repos/${GH_AW_REPO}/pulls/${PR_NUMBER}" 2>/dev/null)
+ BASE_REF=$(printf '%s' "${PR_JSON}" | jq -r '.base.ref // empty')
+ case "${BASE_REF}" in
+ main|rel/*) echo "PR #${PR_NUMBER} base '${BASE_REF}' is in scope." ;;
+ *) echo "::warning::PR #${PR_NUMBER} base '${BASE_REF}' is out of scope (main, rel/*); skipping."; emit_none ;;
+ esac
+
+ # --- 3. Validate the build, whichever way it was resolved ---
+ # It must be the microsoft.testfx definition (209), have failed, and
+ # belong to this PR (sourceBranch == refs/pull//merge). No entry
+ # point is fully trusted: `check_run` parses the build id out of a
+ # check payload, dispatch takes the build id and PR number as
+ # independent free-form inputs, and the slash command derives the
+ # build from a query. Validating here — rather than per entry point —
+ # prevents downloading an unrelated build or posting its analysis to
+ # the wrong PR.
+ echo "ADO build ${BUILD_ID}: result='${RESULT}' definition='${DEF_ID}' sourceBranch='${SRC_BRANCH}'"
+ if [ "${DEF_ID}" != "${ADO_BUILD_DEFINITION_ID}" ]; then
+ echo "::warning::ADO build ${BUILD_ID} is definition '${DEF_ID}', not microsoft.testfx (${ADO_BUILD_DEFINITION_ID}); refusing."; emit_none
+ fi
+ if [ "${RESULT}" != "failed" ]; then
+ if [ "${ENTRY}" = "command" ]; then
+ echo "::warning::PR #${PR_NUMBER}'s newest microsoft.testfx build (${BUILD_ID}) result is '${RESULT}', not failed — the failure looks resolved; nothing to analyse."
+ else
+ echo "::warning::ADO build ${BUILD_ID} did not fail (result='${RESULT}'); nothing to analyze."
+ fi
+ emit_none
+ fi
+ if [ "${SRC_BRANCH}" != "refs/pull/${PR_NUMBER}/merge" ]; then
+ echo "::warning::ADO build ${BUILD_ID} sourceBranch '${SRC_BRANCH}' does not match PR #${PR_NUMBER} (refs/pull/${PR_NUMBER}/merge); refusing to avoid posting to the wrong PR."; emit_none
+ fi
+
+ # Require the build's analyzed revision to equal the PR's CURRENT
+ # head. gh-aw safe-output review comments carry no `commit_id` — they
+ # target the current PR diff — so analyzing a stale revision would
+ # produce inline suggestions that get rejected or land on the wrong
+ # lines. The PR can advance between selecting the build and reaching
+ # this point, so the head is re-read here rather than reused from the
+ # scope check above.
+ BUILD_PR_SHA=$(printf '%s' "${build_json}" | jq -r '.triggerInfo["pr.sourceSha"] // empty')
+ # ADO builds GitHub's `refs/pull//merge` ref, so build_json.sourceVersion
+ # is the merge commit GitHub produced at build time and equals the PR's
+ # `merge_commit_sha` then. If the base branch advances (even with the PR
+ # head unchanged) GitHub recomputes that merge and merge_commit_sha
+ # changes, so this catches base-advance staleness the head check misses.
+ BUILD_MERGE_SHA=$(printf '%s' "${build_json}" | jq -r '.sourceVersion // empty')
+ # Re-read the PR rather than reusing the snapshot from the scope check:
+ # selecting the build costs an ADO round trip, and right after a
+ # force-push the newest-build query can still return the previous
+ # failed build. The point of this check is to skip BEFORE paying for
+ # the download, so it should compare against the freshest head
+ # available. A post-download re-read below independently catches a
+ # head that moves while the artifacts are being fetched.
+ PR_JSON=$(gh api "repos/${GH_AW_REPO}/pulls/${PR_NUMBER}" 2>/dev/null)
+ CURRENT_HEAD=$(printf '%s' "${PR_JSON}" | jq -r '.head.sha // empty')
+ CURRENT_MERGE=$(printf '%s' "${PR_JSON}" | jq -r '.merge_commit_sha // empty')
+ # Fail CLOSED: if either the build's analyzed revision or the current
+ # PR head can't be resolved, skip — we must not analyze a possibly
+ # stale binlog against the current diff (inline comments have no
+ # commit_id and target the current PR diff).
+ if [ -z "${BUILD_PR_SHA}" ] || [ -z "${CURRENT_HEAD}" ]; then
+ echo "::warning::Could not resolve build revision ('${BUILD_PR_SHA}') and/or current PR head ('${CURRENT_HEAD}'); skipping to avoid analyzing a stale binlog against the current diff."
+ emit_none
+ fi
+ if [ "${BUILD_PR_SHA}" != "${CURRENT_HEAD}" ]; then
+ echo "::warning::Build ${BUILD_ID} analyzed revision '${BUILD_PR_SHA}' but PR #${PR_NUMBER} head is now '${CURRENT_HEAD}'; skipping stale build (a newer build/check will cover the current revision)."
+ emit_none
+ fi
+ # When both merge revisions are known and differ, the base branch moved
+ # since the build — the binlog reflects an obsolete merge. Skip.
+ if [ -n "${BUILD_MERGE_SHA}" ] && [ -n "${CURRENT_MERGE}" ] && [ "${BUILD_MERGE_SHA}" != "${CURRENT_MERGE}" ]; then
+ echo "::warning::Build ${BUILD_ID} merge revision '${BUILD_MERGE_SHA}' but PR #${PR_NUMBER} current merge is '${CURRENT_MERGE}' (base branch advanced); skipping stale merge."
+ emit_none
+ fi
+ # Consistent now: build revision == current PR head. Use it for
+ # permalinks so they line up with the inline comments' diff target.
+ HEAD_SHA="${CURRENT_HEAD}"
+ echo "Analyzing build ${BUILD_ID} at PR head revision '${HEAD_SHA}'."
+
+ # --- 4. Download every Logs_Build_* artifact and extract binlogs ---
+ artifacts_json=$(curl -sSL --retry 3 "${ADO_API}/build/builds/${BUILD_ID}/artifacts?api-version=7.1")
+ mapfile -t names < <(printf '%s' "${artifacts_json}" | jq -r '.value // [] | map(select(.name | test("^Logs_Build_"))) | .[].name')
+ [ "${#names[@]}" -eq 0 ] && { echo "::warning::No Logs_Build_* artifacts on build ${BUILD_ID}."; emit_none; }
+
+ # --- 5a. Which failed legs never published logs at all? ---
+ # The fail-closed check further down compares staged legs against the
+ # artifacts ADO *returned*, so it cannot see a leg that died before
+ # publishing its logs artifact — that leg is simply absent from
+ # `names`. Ask the timeline instead. This is advisory rather than
+ # fail-closed: a failed job that legitimately publishes no logs would
+ # otherwise suppress analysis of a real compile break in the same build. The agent is told about the gap so it cannot conclude
+ # "no build failure" from the legs that happened to upload.
+ #
+ # Ask the timeline whether each leg's log *publish* succeeded rather
+ # than guessing its artifact name from its display name. The artifact
+ # is named from `$(Agent.Os)`, which is not what the job is called:
+ # `MacOS Debug` publishes `Logs_Build_Darwin_Debug`, and
+ # `WindowsSamples Debug` is named from `$(Agent.JobName)` instead. Name
+ # matching reported those healthy legs as missing on real builds —
+ # every macOS failure, and every `msbuild_cache_seed` job. Arcade's
+ # `Publish logs` task record answers the question directly, so no
+ # spelling has to be inferred. A failed job carrying no such task
+ # (the `Detect changed paths` classifier, the cache-seed stage) does
+ # not publish logs at all and is not treated as a missing leg.
+ #
+ # `canceled` and `abandoned` legs count alongside `failed`: they also
+ # finish without logs, and are a real gap in the artifact set.
+ timeline_json=$(curl -sSL --retry 3 --max-time 60 "${ADO_API}/build/builds/${BUILD_ID}/timeline?api-version=7.1" 2>/dev/null || true)
+ MISSING_LEGS=""
+ # An unreadable timeline must not look like a complete build. A failed
+ # request, a non-JSON error page and an ADO error document all left
+ # the list empty, which is exactly how "every failed leg published
+ # logs" is reported — so a transient outage could let the agent
+ # conclude "non-build failure" from an artifact set whose completeness
+ # was never established. Probe for the `records` array first and
+ # report an explicit unknown when it isn't there.
+ timeline_ok=0
+ if printf '%s' "${timeline_json}" | jq -e 'type == "object" and has("records")' >/dev/null 2>&1; then
+ timeline_ok=1
+ fi
+ if [ "${timeline_ok}" -eq 1 ]; then
+ # Job display names come from the pipeline YAML in the PR branch, so
+ # on a fork PR they are attacker-controlled. Strip control characters
+ # and bound the length before this value reaches `$GITHUB_OUTPUT` and
+ # `$GITHUB_ENV`, where an embedded newline would inject further
+ # `key=value` lines. The task name is matched on its alphanumerics
+ # because arcade spells it both `Publish logs` and `Publish Logs`,
+ # and some pipelines prefix a decorative emoji.
+ MISSING_LEGS=$(printf '%s' "${timeline_json}" | jq -r '
+ (.records // []) as $records
+ | ($records
+ | map(select(.type == "Task"
+ and (.name | ascii_downcase | gsub("[^a-z0-9]"; "") | test("publishlogs"))))) as $publishes
+ | $records
+ | map(select(.type == "Job"
+ and (.result == "failed" or .result == "canceled" or .result == "abandoned")))
+ | map(. as $job
+ | ($publishes | map(select(.parentId == $job.id))) as $mine
+ | select(($mine | length) > 0
+ and (($mine | map(select(.result == "succeeded")) | length) == 0))
+ | ($job.name | gsub("[[:cntrl:]]"; " ")))
+ | join(", ")' 2>/dev/null | tr -d '\r\n' | cut -c1-400)
+ fi
+ if [ "${timeline_ok}" -ne 1 ]; then
+ MISSING_LEGS="(unknown - could not read the build timeline)"
+ echo "::warning::Could not read the timeline for build ${BUILD_ID}; unable to verify that every failed leg published a logs artifact."
+ elif [ -n "${MISSING_LEGS}" ]; then
+ echo "::warning::Failed leg(s) whose logs were never published: ${MISSING_LEGS}"
+ fi
+
+ # Guards for untrusted PR-produced archives: cap the compressed
+ # download and the reported uncompressed size per artifact, bound
+ # extraction time, AND enforce cumulative budgets across all legs so
+ # many individually-small artifacts can't collectively exhaust the
+ # runner's disk or its network time.
+ MAX_ZIP_BYTES=524288000 # 500 MB compressed per artifact
+ MAX_UNZIP_BYTES=2147483648 # 2 GB uncompressed per artifact
+ MAX_TOTAL_BYTES=4294967296 # 4 GB uncompressed across all artifacts
+ MAX_TOTAL_ZIP_BYTES=3221225472 # 3 GB compressed downloaded in total
+ MAX_ARTIFACTS=40 # cap only; the real count is path-dependent
+ TOTAL_BYTES=0
+ TOTAL_ZIP_BYTES=0
+ # Bound the work before starting: a pipeline change (or repeated leg
+ # retries) could grow the matched set well past today's count. Refuse
+ # rather than process a prefix of the list, because a partial view is
+ # exactly what the fail-closed check below exists to prevent.
+ if [ "${#names[@]}" -gt "${MAX_ARTIFACTS}" ]; then
+ echo "::warning::Build ${BUILD_ID} matched ${#names[@]} log artifacts, above the ${MAX_ARTIFACTS} cap; skipping."
+ emit_none
+ fi
+ mkdir -p /tmp/binlogs
+ count=0
+ staged_legs=0
+ ai=0
+ for name in "${names[@]}"; do
+ # `name` is PR-controlled ADO artifact metadata and the
+ # `^Logs_Build_` filter only anchors the prefix, so sanitize it
+ # before using it in any on-disk path (guards against `/` or `..`
+ # traversal); keep the original `name` for the artifacts_json lookup.
+ safe_name=$(printf '%s' "${name}" | tr -c 'A-Za-z0-9._-' '_')
+ ai=$((ai + 1))
+ url=$(printf '%s' "${artifacts_json}" | jq -r --arg n "${name}" '.value[] | select(.name==$n) | .resource.downloadUrl // empty')
+ [ -z "${url}" ] && { echo "::warning::No download URL for ${name}."; continue; }
+ rm -rf /tmp/ax /tmp/a.zip
+ mkdir -p /tmp/ax
+ # Hard-cap the bytes written to disk regardless of Content-Length:
+ # stream through `head -c` (cap + 1) and bound total time. This
+ # closes the gap where `curl --max-filesize` alone would let a
+ # length-less response write unbounded data before any post-check.
+ curl -sSL --retry 3 --max-time 300 "${url}" 2>/dev/null | head -c $((MAX_ZIP_BYTES + 1)) > /tmp/a.zip || true
+ ZIP_BYTES=$(stat -c%s /tmp/a.zip 2>/dev/null || echo 0)
+ # Bound cumulative *compressed* bytes too: the per-artifact and
+ # cumulative-uncompressed caps still allow many mid-sized archives
+ # to be pulled over the network before any of them is inspected.
+ #
+ # Charge the budget here, before the skips below, because the bytes
+ # are already on the wire by this point — `curl` above streams into
+ # `head -c` and only then is the size known. Charging after the
+ # per-artifact skip would let every oversized artifact cost a full
+ # MAX_ZIP_BYTES of network without ever being counted, so a build of
+ # MAX_ARTIFACTS oversized legs would download far past this budget
+ # while appearing to stay inside it.
+ TOTAL_ZIP_BYTES=$((TOTAL_ZIP_BYTES + ZIP_BYTES))
+ if [ "${TOTAL_ZIP_BYTES}" -gt "${MAX_TOTAL_ZIP_BYTES}" ]; then
+ echo "::warning::Cumulative compressed download budget ${MAX_TOTAL_ZIP_BYTES} reached at ${name}; stopping."; break
+ fi
+ if [ "${ZIP_BYTES}" -eq 0 ]; then
+ echo "::warning::Skipping ${name}: empty or failed download."; continue
+ fi
+ if [ "${ZIP_BYTES}" -gt "${MAX_ZIP_BYTES}" ]; then
+ echo "::warning::Skipping ${name}: download exceeded ${MAX_ZIP_BYTES} bytes."; continue
+ fi
+ UNCOMP=$(unzip -l /tmp/a.zip 2>/dev/null | tail -1 | awk '{print $1}')
+ # Fail safe: if the uncompressed size isn't a plain integer (corrupt
+ # zip / unexpected `unzip -l` output), we can't verify it — skip the
+ # artifact rather than let a non-numeric value bypass the `-gt` guard.
+ if ! printf '%s' "${UNCOMP}" | grep -qE '^[0-9]+$'; then
+ echo "::warning::Skipping ${name}: could not determine uncompressed size (unparseable unzip output)."; continue
+ fi
+ # ZIP64 uncompressed sizes can reach ~20 digits — beyond Bash's
+ # signed 64-bit range, where `-gt` (and the cumulative `$((...))`
+ # below) error out and, under `set +e`, would let an oversized
+ # archive slip past the guard. Any value with more digits than the
+ # limit is unambiguously larger, so reject on decimal length first;
+ # after this, UNCOMP fits safely in the integer range used below.
+ if [ "${#UNCOMP}" -gt "${#MAX_UNZIP_BYTES}" ]; then
+ echo "::warning::Skipping ${name}: uncompressed size has ${#UNCOMP} digits, exceeding the ${MAX_UNZIP_BYTES} guard (possible zip bomb)."; continue
+ fi
+ if [ "${UNCOMP}" -gt "${MAX_UNZIP_BYTES}" ]; then
+ echo "::warning::Skipping ${name}: uncompressed size ${UNCOMP} exceeds ${MAX_UNZIP_BYTES} guard (possible zip bomb)."; continue
+ fi
+ if [ $((TOTAL_BYTES + UNCOMP)) -gt "${MAX_TOTAL_BYTES}" ]; then
+ echo "::warning::Cumulative uncompressed budget ${MAX_TOTAL_BYTES} reached at ${name}; stopping extraction."; break
+ fi
+ # Refuse the archive if any entry path is absolute or has a `..`
+ # component (defense-in-depth over unzip's own traversal guard),
+ # then extract `*.binlog` entries *preserving* their in-archive
+ # paths (no `-j`) under a fresh dir + timeout, so two binlogs that
+ # share a basename in different folders don't overwrite each other.
+ if unzip -Z1 /tmp/a.zip 2>/dev/null | grep -qE '(^/|(^|/)\.\.(/|$))'; then
+ echo "::warning::Skipping ${name}: archive has a suspicious (absolute or ..) entry path."; continue
+ fi
+ # `unzip` exit 11 means "no files matched" — the artifact carries no
+ # binlog at all. That is not an extraction failure: the leg did
+ # publish its logs, they simply contain no binlog, and the
+ # fail-closed check below already accounts for a leg that staged
+ # nothing. Reporting it as "extraction failed or timed out" sends
+ # the reader chasing a corrupt-archive theory that isn't there. Any
+ # other non-zero exit (corrupt archive, timeout) is a real failure.
+ #
+ # Both cases `continue`, so nothing was written to /tmp/ax and the
+ # uncompressed budget below is left untouched. Charging it for an
+ # archive that extracted nothing would let one large binlog-free
+ # artifact push a genuinely useful later leg past MAX_TOTAL_BYTES.
+ uz=0
+ timeout 120 unzip -o /tmp/a.zip '*.binlog' -d /tmp/ax >/dev/null 2>&1 || uz=$?
+ if [ "${uz}" -eq 11 ]; then
+ echo "::warning::${name}: published logs contain no binlog; nothing to analyse from this leg."; continue
+ fi
+ if [ "${uz}" -ne 0 ]; then
+ echo "::warning::Skipping ${name}: extraction failed or timed out (unzip exit ${uz})."; continue
+ fi
+ # Consume the cumulative budget only once the archive actually
+ # extracted — not on a suspicious-path or extraction-failure skip
+ # above — so a skipped leg can't wrongly exhaust the budget and
+ # force later legs to be dropped as "incomplete".
+ TOTAL_BYTES=$((TOTAL_BYTES + UNCOMP))
+ i=0
+ leg_staged=0
+ while IFS= read -r bl; do
+ [ -f "${bl}" ] || continue
+ # Every destination is uniquely prefixed with the artifact index
+ # (`ai`) and a per-file counter (`i`), so neither a cross-artifact
+ # sanitize collision nor same-basename entries within one archive
+ # can overwrite a previously staged leg's binlog. `safe_name` is
+ # kept only for readability.
+ dest="/tmp/binlogs/${ai}_${i}_${safe_name}.binlog"
+ # Only count a staged binlog when the copy actually succeeds —
+ # `set +e` is on, so a failed `cp` must not inflate the counts.
+ if cp "${bl}" "${dest}"; then
+ count=$((count + 1))
+ i=$((i + 1))
+ leg_staged=1
+ else
+ echo "::warning::Failed to stage ${bl}; skipping."
+ fi
+ done < <(find /tmp/ax -type f -name '*.binlog')
+ # This leg produced at least one usable binlog.
+ [ "${leg_staged}" -eq 1 ] && staged_legs=$((staged_legs + 1))
+ done
+ echo "Extracted ${count} binlog(s) from ${staged_legs}/${#names[@]} legs into /tmp/binlogs:"
+ ls -la /tmp/binlogs || true
+ [ "${count}" -eq 0 ] && { echo "::warning::No *.binlog found in any Logs_Build_* artifact of build ${BUILD_ID}."; emit_none; }
+ # Fail CLOSED on a partial set: if any Logs_Build_* leg did not yield
+ # a usable binlog (download/extract failure, size-guard skip, or no
+ # binlog inside), we cannot see every leg. Activating anyway would let
+ # the agent treat the retrieved legs as the whole build and possibly
+ # mis-classify a real build break in a missing leg as a clean compile /
+ # non-build failure. A later build/check will re-trigger the analysis.
+ if [ "${staged_legs}" -ne "${#names[@]}" ]; then
+ echo "::warning::Only ${staged_legs} of ${#names[@]} Logs_Build_* legs produced a usable binlog; skipping to avoid analyzing an incomplete build (a missing leg could be the one that failed)."
+ emit_none
+ fi
+
+ # The download/extract loop above can take minutes. Re-read the PR
+ # head right before activating and fail CLOSED if it moved or can't
+ # be resolved: a force-push during that window would otherwise leave
+ # the analyzed binlog stale relative to the current diff (inline
+ # comments carry no commit_id and target the current diff).
+ LATEST_PR=$(gh api "repos/${GH_AW_REPO}/pulls/${PR_NUMBER}" 2>/dev/null)
+ LATEST_HEAD=$(printf '%s' "${LATEST_PR}" | jq -r '.head.sha // empty')
+ LATEST_MERGE=$(printf '%s' "${LATEST_PR}" | jq -r '.merge_commit_sha // empty')
+ if [ -z "${LATEST_HEAD}" ] || [ "${LATEST_HEAD}" != "${HEAD_SHA}" ]; then
+ echo "::warning::PR #${PR_NUMBER} head changed during artifact download ('${HEAD_SHA}' -> '${LATEST_HEAD}') or could not be re-resolved; skipping to avoid posting stale-build suggestions against the new diff."
+ emit_none
+ fi
+ # The base branch may also have advanced during the download; if the
+ # merge revision moved from what the build analyzed, skip (stale merge).
+ if [ -n "${BUILD_MERGE_SHA}" ] && [ -n "${LATEST_MERGE}" ] && [ "${LATEST_MERGE}" != "${BUILD_MERGE_SHA}" ]; then
+ echo "::warning::PR #${PR_NUMBER} merge revision changed during artifact download ('${BUILD_MERGE_SHA}' -> '${LATEST_MERGE}'); skipping stale merge."
+ emit_none
+ fi
+
+ {
+ # `missing-legs` is derived from ADO job display names, which come
+ # from pipeline YAML in the PR branch and are therefore
+ # fork-controlled. It is sanitized where it is assembled, and it is
+ # written first here so that even a future regression in that
+ # sanitizing cannot let it override a key emitted below.
+ echo "missing-legs=${MISSING_LEGS}"
+ echo "binlog-found=true"
+ echo "pr-number=${PR_NUMBER}"
+ echo "pr-head-sha=${HEAD_SHA}"
+ echo "pr-merge-sha=${BUILD_MERGE_SHA}"
+ echo "ado-build-id=${BUILD_ID}"
+ echo "ado-build-url=${ADO_BUILD_UI}?buildId=${BUILD_ID}"
+ } >> "$GITHUB_OUTPUT"
+
+ - name: Upload analysis artifact
+ if: steps.fetch.outputs.binlog-found == 'true'
+ uses: actions/upload-artifact@v7.0.1
+ with:
+ name: build-failure-analysis-data
+ path: /tmp/binlogs
+ if-no-files-found: warn
+ # Quoted so the import's YAML round-trip keeps it `1` — an unquoted
+ # integer comes back out of the shared-job merge as `1.0`.
+ retention-days: "1"
+---