From ef78e09cc5d47f37f072407f303c75185a1ff019 Mon Sep 17 00:00:00 2001 From: burinc Date: Fri, 20 Nov 2026 12:35:48 +1100 Subject: [PATCH 01/31] fleet: version helpers and fleet.json, with tests --- .github/workflows/test.yml | 14 +++++++++ fleet.json | 4 +++ scripts/lib/version.sh | 57 +++++++++++++++++++++++++++++++++++ test/fixtures/log-nightly.txt | 7 +++++ test/fixtures/log-release.txt | 7 +++++ test/version.bats | 32 ++++++++++++++++++++ 6 files changed, 121 insertions(+) create mode 100644 .github/workflows/test.yml create mode 100644 fleet.json create mode 100644 scripts/lib/version.sh create mode 100644 test/fixtures/log-nightly.txt create mode 100644 test/fixtures/log-release.txt create mode 100644 test/version.bats diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..9d59d3c --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,14 @@ +name: test + +on: + push: + pull_request: + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - run: sudo apt-get install -y bats + - run: bats test/ + - run: shellcheck scripts/lib/*.sh diff --git a/fleet.json b/fleet.json new file mode 100644 index 0000000..9bc8d25 --- /dev/null +++ b/fleet.json @@ -0,0 +1,4 @@ +{"projects": ["glitter", "glitter-gl", "glitter-uikit", "raygui-jlt", "raylib-jlt", "raylib-ios", "raylib-android"], + "excluded": {"jolt-lsp": "its dispatch input releases jolt-lsp; needs a jolt-version input first", + "ci-builds": "this repository", + "demo-repository": "private demo"}} diff --git a/scripts/lib/version.sh b/scripts/lib/version.sh new file mode 100644 index 0000000..d3c9870 --- /dev/null +++ b/scripts/lib/version.sh @@ -0,0 +1,57 @@ +#!/usr/bin/env bash +# Pure helpers for the fleet dashboard. Sourced, so no `set -e` here. + +# installed_version +# Prints the version from the first "jolt v[-N-g]" line (after the +# Actions timestamp), without the leading v. Exits 1 when there is none. +installed_version() { + local line text re='^jolt v([0-9]+\.[0-9]+\.[0-9]+(-[0-9]+-g[0-9a-f]+)?)$' + while IFS= read -r line || [ -n "$line" ]; do + line=${line%$'\r'} + text=$(printf '%s' "$line" | sed -E 's/^[0-9T:.-]+Z //') + if [[ $text =~ $re ]]; then + printf '%s\n' "${BASH_REMATCH[1]}" + return 0 + fi + done < "$1" + return 1 +} + +# version_matches [nightly_sha] +version_matches() { + local requested=$1 installed=$2 sha=${3:-} re='-g([0-9a-f]+)$' + if [ "$requested" = "nightly" ]; then + [ -n "$sha" ] || return 1 + [[ $installed =~ $re ]] || return 1 + [[ $sha == "${BASH_REMATCH[1]}"* ]] + return + fi + [ "${requested#v}" = "$installed" ] +} + +# parse_pin +# Prints the literal version from the first JOLT_VERSION: key line, without v. +# Exits 1 when the file or key is missing or the pin is not a literal version. +parse_pin() { + local line re + re="['\"]v?([0-9]+\\.[0-9]+\\.[0-9]+)['\"]" + [ -r "$1" ] || return 1 + line=$(grep -m1 -E '^[[:space:]]*JOLT_VERSION:' "$1") || return 1 + [[ $line =~ $re ]] || return 1 + printf '%s\n' "${BASH_REMATCH[1]}" +} + +# uncovered_reason +uncovered_reason() { + local has_ci=$2 has_input=$3 in_fleet=$4 excluded=${5:-} + [ "$in_fleet" = "1" ] && return 0 + if [ -n "$excluded" ]; then + printf 'excluded: %s\n' "$excluded" + elif [ "$has_ci" = "0" ]; then + printf 'no ci.yml\n' + elif [ "$has_input" = "0" ]; then + printf 'ci.yml has no jolt-version input\n' + else + printf 'ready, not yet in fleet.json\n' + fi +} diff --git a/test/fixtures/log-nightly.txt b/test/fixtures/log-nightly.txt new file mode 100644 index 0000000..d09497d --- /dev/null +++ b/test/fixtures/log-nightly.txt @@ -0,0 +1,7 @@ +2026-11-18T03:48:25.1000000Z base_url="https://github.com/jolt-lang/jolt/releases/download/v${version}" +2026-11-18T03:48:25.2000000Z Downloading https://github.com/jolt-lang/jolt/releases/download/vnightly/jolt-linux-amd64.tar.gz +2026-11-18T03:48:26.3000000Z Successfully installed jolt vnightly to /home/runner/.local/bin/jolt +2026-11-18T03:48:27.0000000Z ##[group]Run jolt --version +2026-11-18T03:48:27.0500000Z jolt --version +2026-11-18T03:48:27.0669741Z jolt v0.8.27-241-gdd3c4a4b +2026-11-18T03:48:27.1000000Z ##[group]Run jolt -T:test diff --git a/test/fixtures/log-release.txt b/test/fixtures/log-release.txt new file mode 100644 index 0000000..dff218f --- /dev/null +++ b/test/fixtures/log-release.txt @@ -0,0 +1,7 @@ +2026-11-19T09:59:58.1000000Z base_url="https://github.com/jolt-lang/jolt/releases/download/v${version}" +2026-11-19T09:59:58.2000000Z Downloading https://github.com/jolt-lang/jolt/releases/download/v0.8.24/jolt-linux-amd64.tar.gz +2026-11-19T09:59:59.3000000Z Successfully installed jolt v0.8.24 to /home/runner/.local/bin/jolt +2026-11-19T09:59:59.4000000Z ##[group]Run jolt --version +2026-11-19T09:59:59.5000000Z jolt --version +2026-11-19T10:00:00.0000000Z jolt v0.8.24 +2026-11-19T10:00:00.1000000Z ##[group]Run jolt -T:test diff --git a/test/version.bats b/test/version.bats new file mode 100644 index 0000000..c0293d9 --- /dev/null +++ b/test/version.bats @@ -0,0 +1,32 @@ +setup() { source "$BATS_TEST_DIRNAME/../scripts/lib/version.sh"; F="$BATS_TEST_DIRNAME/fixtures"; } + +@test "release log" { run installed_version "$F/log-release.txt"; [ "$output" = "0.8.24" ]; } +@test "nightly log" { run installed_version "$F/log-nightly.txt"; [ "$output" = "0.8.27-241-gdd3c4a4b" ]; } +@test "no version line" { printf 'Successfully installed jolt vnightly to /x\n' > "$BATS_TMPDIR/l"; run installed_version "$BATS_TMPDIR/l"; [ "$status" -eq 1 ]; [ -z "$output" ]; } +@test "v prefix requested" { run version_matches v0.8.24 0.8.24; [ "$status" -eq 0 ]; } +@test "release mismatch" { run version_matches 0.8.27 0.8.24; [ "$status" -eq 1 ]; } +@test "nightly sha match" { run version_matches nightly 0.8.27-241-gdd3c4a4b dd3c4a4b0123456789abcdef0123456789abcdef; [ "$status" -eq 0 ]; } +@test "nightly stale sha" { run version_matches nightly 0.8.27-241-gdd3c4a4b 98e5ef990000000000000000000000000000000a; [ "$status" -eq 1 ]; } +@test "nightly no sha" { run version_matches nightly 0.8.27-241-gdd3c4a4b; [ "$status" -eq 1 ]; } +@test "nightly got a release" { run version_matches nightly 0.8.27 dd3c4a4b00; [ "$status" -eq 1 ]; } + +pin() { printf '%s\n' "$1" > "$BATS_TMPDIR/ci.yml"; run parse_pin "$BATS_TMPDIR/ci.yml"; } + +@test "pin: input with default" { pin " JOLT_VERSION: \${{ inputs.jolt-version || '0.8.24' }}"; [ "$status" -eq 0 ]; [ "$output" = "0.8.24" ]; } +@test "pin: input with v default" { pin " JOLT_VERSION: \${{ inputs.jolt-version || 'v0.8.24' }}"; [ "$status" -eq 0 ]; [ "$output" = "0.8.24" ]; } +@test "pin: quoted literal" { pin ' JOLT_VERSION: "0.8.24"'; [ "$status" -eq 0 ]; [ "$output" = "0.8.24" ]; } +@test "pin: needs output is not literal" { pin " JOLT_VERSION: \${{ needs.jolt-version.outputs.version }}"; [ "$status" -eq 1 ]; [ -z "$output" ]; } +@test "pin: comment mentions are skipped" { + printf '# JOLT_VERSION: 9.9.9 is old\nenv:\n JOLT_VERSION: "0.8.24"\n' > "$BATS_TMPDIR/ci.yml" + run parse_pin "$BATS_TMPDIR/ci.yml"; [ "$status" -eq 0 ]; [ "$output" = "0.8.24" ] +} +@test "pin: no key at all" { printf 'name: x\n' > "$BATS_TMPDIR/ci.yml"; run parse_pin "$BATS_TMPDIR/ci.yml"; [ "$status" -eq 1 ]; [ -z "$output" ]; } +@test "pin: missing file" { run parse_pin "$BATS_TMPDIR/nope.yml"; [ "$status" -eq 1 ]; } + +@test "uncovered: in fleet prints nothing" { run uncovered_reason glitter 1 1 1 ""; [ "$status" -eq 0 ]; [ -z "$output" ]; } +@test "uncovered: in fleet beats excluded" { run uncovered_reason glitter 0 0 1 "why"; [ -z "$output" ]; } +@test "uncovered: excluded" { run uncovered_reason jolt-lsp 1 0 0 "needs input"; [ "$output" = "excluded: needs input" ]; } +@test "uncovered: excluded beats no ci" { run uncovered_reason x 0 0 0 "private demo"; [ "$output" = "excluded: private demo" ]; } +@test "uncovered: no ci.yml" { run uncovered_reason x 0 0 0 ""; [ "$output" = "no ci.yml" ]; } +@test "uncovered: no input" { run uncovered_reason x 1 0 0 ""; [ "$output" = "ci.yml has no jolt-version input" ]; } +@test "uncovered: ready" { run uncovered_reason x 1 1 0 ""; [ "$output" = "ready, not yet in fleet.json" ]; } From 13e5e020b54e7be0f9ed4ce20cf4b4a8db32730a Mon Sep 17 00:00:00 2001 From: burinc Date: Fri, 20 Nov 2026 12:40:54 +1100 Subject: [PATCH 02/31] fleet: installed_version without per-line forks, strict parse_pin --- scripts/lib/version.sh | 16 +++++++++------- test/version.bats | 16 ++++++++++++++++ 2 files changed, 25 insertions(+), 7 deletions(-) diff --git a/scripts/lib/version.sh b/scripts/lib/version.sh index d3c9870..2d35ccc 100644 --- a/scripts/lib/version.sh +++ b/scripts/lib/version.sh @@ -5,12 +5,11 @@ # Prints the version from the first "jolt v[-N-g]" line (after the # Actions timestamp), without the leading v. Exits 1 when there is none. installed_version() { - local line text re='^jolt v([0-9]+\.[0-9]+\.[0-9]+(-[0-9]+-g[0-9a-f]+)?)$' + local line re='^([0-9T:.-]+Z )?jolt v([0-9]+\.[0-9]+\.[0-9]+(-[0-9]+-g[0-9a-f]+)?)$' while IFS= read -r line || [ -n "$line" ]; do line=${line%$'\r'} - text=$(printf '%s' "$line" | sed -E 's/^[0-9T:.-]+Z //') - if [[ $text =~ $re ]]; then - printf '%s\n' "${BASH_REMATCH[1]}" + if [[ $line =~ $re ]]; then + printf '%s\n' "${BASH_REMATCH[2]}" return 0 fi done < "$1" @@ -33,12 +32,15 @@ version_matches() { # Prints the literal version from the first JOLT_VERSION: key line, without v. # Exits 1 when the file or key is missing or the pin is not a literal version. parse_pin() { - local line re - re="['\"]v?([0-9]+\\.[0-9]+\\.[0-9]+)['\"]" + local line v ws='[[:space:]]*' + v="v?([0-9]+\\.[0-9]+\\.[0-9]+)" + local re="^${ws}JOLT_VERSION:${ws}(\\\$\\{\\{${ws}inputs\\.jolt-version${ws}\\|\\|${ws}'${v}'${ws}\\}\\}|\"${v}\"|'${v}'|${v})${ws}\$" [ -r "$1" ] || return 1 line=$(grep -m1 -E '^[[:space:]]*JOLT_VERSION:' "$1") || return 1 + line=${line%% \#*} [[ $line =~ $re ]] || return 1 - printf '%s\n' "${BASH_REMATCH[1]}" + # Exactly one of the four alternatives matched, so one version group is set. + printf '%s\n' "${BASH_REMATCH[2]}${BASH_REMATCH[3]}${BASH_REMATCH[4]}${BASH_REMATCH[5]}" } # uncovered_reason diff --git a/test/version.bats b/test/version.bats index c0293d9..be1722b 100644 --- a/test/version.bats +++ b/test/version.bats @@ -30,3 +30,19 @@ pin() { printf '%s\n' "$1" > "$BATS_TMPDIR/ci.yml"; run parse_pin "$BATS_TMPDIR/ @test "uncovered: no ci.yml" { run uncovered_reason x 0 0 0 ""; [ "$output" = "no ci.yml" ]; } @test "uncovered: no input" { run uncovered_reason x 1 0 0 ""; [ "$output" = "ci.yml has no jolt-version input" ]; } @test "uncovered: ready" { run uncovered_reason x 1 1 0 ""; [ "$output" = "ready, not yet in fleet.json" ]; } + +@test "pin: non-literal with quoted version in a trailing comment" { + pin " JOLT_VERSION: \${{ needs.x.outputs.v }} # was '0.8.24'"; [ "$status" -eq 1 ]; [ -z "$output" ] +} +@test "pin: literal followed by a comment" { pin ' JOLT_VERSION: "0.8.24" # pinned'; [ "$status" -eq 0 ]; [ "$output" = "0.8.24" ]; } +@test "pin: bare literal" { pin ' JOLT_VERSION: v0.8.24'; [ "$status" -eq 0 ]; [ "$output" = "0.8.24" ]; } + +@test "installed: CRLF line" { + printf '2026-11-18T03:48:27.0669741Z jolt v0.8.27-241-gdd3c4a4b\r\n' > "$BATS_TMPDIR/crlf" + run installed_version "$BATS_TMPDIR/crlf"; [ "$status" -eq 0 ]; [ "$output" = "0.8.27-241-gdd3c4a4b" ] +} +@test "installed: 20000-line log, version last" { + { yes '2026-11-18T03:48:27.0000000Z some build output line with jolt in it' | head -n 20000 + printf '2026-11-18T03:48:28.0000000Z jolt v0.8.24\n'; } > "$BATS_TMPDIR/big" + run installed_version "$BATS_TMPDIR/big"; [ "$status" -eq 0 ]; [ "$output" = "0.8.24" ] +} From b5b81a0e5fdb93dec9ea8690a2bb1e3781bbae58 Mon Sep 17 00:00:00 2001 From: burinc Date: Fri, 20 Nov 2026 12:43:18 +1100 Subject: [PATCH 03/31] fanout: read fleet.json, prove the installed jolt, upload results.json --- .github/workflows/fanout.yml | 83 ++++++++++++++++++++++++++++++++++-- 1 file changed, 80 insertions(+), 3 deletions(-) diff --git a/.github/workflows/fanout.yml b/.github/workflows/fanout.yml index 939024f..3fd2612 100644 --- a/.github/workflows/fanout.yml +++ b/.github/workflows/fanout.yml @@ -63,6 +63,10 @@ jobs: version: ${{ steps.version.outputs.version }} steps: + # fleet.json (the project list) and scripts/lib/version.sh live here. + # Under workflow_call this checks out the caller's ref of this same repo. + - uses: actions/checkout@v7 + # Mints a token scoped to the App's seven repositories, valid one hour. # Never a PAT: a PAT would act as whoever created it, and any collaborator # able to run this workflow would be borrowing that identity. @@ -103,8 +107,22 @@ jobs: VERSION: ${{ steps.version.outputs.version }} run: | set -uo pipefail - PROJECTS="glitter glitter-gl glitter-uikit raygui-jlt raylib-jlt raylib-ios raylib-android" - declare -A RUN CONC URL + # shellcheck source=scripts/lib/version.sh + . scripts/lib/version.sh + PROJECTS=$(jq -r '.projects | join(" ")' fleet.json) + declare -A RUN CONC URL INST FSTEP FIN + RES_DIR="${RUNNER_TEMP:-/tmp}/fanout-results" + mkdir -p "$RES_DIR" + + # For nightly, the commit vnightly points at right now. An installed + # jolt whose -g does not prefix this is a different build. + NIGHTLY_SHA="" + if [ "$VERSION" = "nightly" ]; then + NIGHTLY_SHA="$(curl -fsSL https://api.github.com/repos/jolt-lang/jolt/git/refs/tags/vnightly \ + | sed -n 's/.*"sha": *"\([^"]*\)".*/\1/p' | head -1)" + [ -n "$NIGHTLY_SHA" ] || echo "::warning::could not resolve the vnightly sha, every nightly run will read as mismatch" + echo "vnightly is $NIGHTLY_SHA" + fi # A plain string, not an associative array: `${#arr[@]}` and # `${!arr[@]}` on an EMPTY associative array are only safe under # `set -u` from bash 4.4, and the empty case is the normal one here. @@ -207,8 +225,29 @@ jobs: 2>/dev/null | grep -qi 'install jolt'; then cc="toolchain-unavailable" fi + FIN[$p]=$(date -u +%Y-%m-%dT%H:%M:%SZ) + if [ "$cc" = "failure" ]; then + FSTEP[$p]=$(gh api "repos/jlt-commons/$p/actions/runs/${RUN[$p]}/jobs" \ + --jq '[.jobs[].steps[]? | select(.conclusion=="failure") | .name] | first // empty' \ + 2>/dev/null || true) + elif [ "$cc" = "success" ]; then + # A green run is not proof it ran the jolt we asked for: read + # the `jolt --version` line out of each job's log. + inst="" + for jid in $(gh api "repos/jlt-commons/$p/actions/runs/${RUN[$p]}/jobs" \ + --jq '.jobs[].id' 2>/dev/null); do + gh api "repos/jlt-commons/$p/actions/jobs/$jid/logs" \ + > "$RES_DIR/$p-$jid.log" 2>/dev/null || true + if inst=$(installed_version "$RES_DIR/$p-$jid.log"); then break; fi + inst="" + done + INST[$p]="$inst" + if [ -z "$inst" ] || ! version_matches "$VERSION" "$inst" "$NIGHTLY_SHA"; then + cc="mismatch" + fi + fi CONC[$p]="$cc" - echo " $p: $cc" + echo " $p: $cc${INST[$p]:+ (jolt ${INST[$p]})}" else waiting=1 fi @@ -224,6 +263,8 @@ jobs: # Render the table this workflow exists to produce. failed="" infra="" + mismatch="" + : > "$RES_DIR/projects.jsonl" { echo "## jolt \`$VERSION\` across jlt-commons" echo @@ -235,6 +276,8 @@ jobs: case "$c" in success) icon="pass" ;; skipped) icon="skipped" ;; + mismatch) icon="**WRONG JOLT** (ran ${INST[$p]:-no version found})" + mismatch="$mismatch $p"; failed="$failed $p" ;; toolchain-unavailable) icon="**could not install jolt**"; infra="$infra $p" ;; *) icon="**FAIL** ($c)"; failed="$failed $p" ;; @@ -242,11 +285,37 @@ jobs: link="-" [ -n "${URL[$p]:-}" ] && link="[run](${URL[$p]})" echo "| \`$p\` | $icon | $link |" >> "$GITHUB_STEP_SUMMARY" + case "$c" in + success) r=pass ;; + toolchain-unavailable) r=infra ;; + timed-out) r=timed-out ;; + dispatch-failed|no-run-appeared) r=dispatch-failed ;; + mismatch) r=mismatch ;; + skipped) r=not-run ;; + *) r=fail ;; + esac + jq -nc --arg name "$p" --arg result "$r" --arg installed "${INST[$p]:-}" \ + --arg url "${URL[$p]:-}" --arg fin "${FIN[$p]:-}" --arg step "${FSTEP[$p]:-}" \ + '{name: $name, result: $result, + installed: (if $installed == "" then null else $installed end), + run_url: (if $url == "" then null else $url end), + finished_at: (if $fin == "" then null else $fin end), + failed_step: (if $step == "" then null else $step end)}' \ + >> "$RES_DIR/projects.jsonl" done failed="${failed# }" infra="${infra# }" + mismatch="${mismatch# }" + jq -s --arg requested "$VERSION" --arg sha "$NIGHTLY_SHA" \ + --arg fin "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \ + --arg url "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" \ + '{requested: $requested, nightly_sha: $sha, finished_at: $fin, run_url: $url, projects: .}' \ + "$RES_DIR/projects.jsonl" > "$RES_DIR/results.json" + echo "results_dir=$RES_DIR" >> "$GITHUB_OUTPUT" + echo "artifact=results-${VERSION//\//-}" >> "$GITHUB_OUTPUT" { echo + [ -n "$mismatch" ] && echo "**Ran on the wrong jolt:** $mismatch" [ -n "$failed" ] && echo "**Broken by jolt \`$VERSION\`:** $failed" if [ -n "$infra" ]; then echo "**Could not install jolt \`$VERSION\` for:** $infra" @@ -266,3 +335,11 @@ jobs: echo "failed=$failed" >> "$GITHUB_OUTPUT" echo "infra=$infra" >> "$GITHUB_OUTPUT" [ -z "$failed$infra" ] || { echo "failing: ${failed:-none} infra: ${infra:-none}" >&2; exit 1; } + + - name: Upload results.json + if: always() + uses: actions/upload-artifact@v7 + with: + name: ${{ steps.run.outputs.artifact || format('results-{0}', steps.version.outputs.version) }} + path: ${{ steps.run.outputs.results_dir }}/results.json + if-no-files-found: warn From 9da897d703592f45fd5b9e8c1160a6f6c70bad72 Mon Sep 17 00:00:00 2001 From: burinc Date: Fri, 20 Nov 2026 12:47:31 +1100 Subject: [PATCH 04/31] fanout: say why a job log could not be fetched --- .github/workflows/fanout.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/fanout.yml b/.github/workflows/fanout.yml index 3fd2612..8a8a3e7 100644 --- a/.github/workflows/fanout.yml +++ b/.github/workflows/fanout.yml @@ -237,7 +237,8 @@ jobs: for jid in $(gh api "repos/jlt-commons/$p/actions/runs/${RUN[$p]}/jobs" \ --jq '.jobs[].id' 2>/dev/null); do gh api "repos/jlt-commons/$p/actions/jobs/$jid/logs" \ - > "$RES_DIR/$p-$jid.log" 2>/dev/null || true + > "$RES_DIR/$p-$jid.log" 2> "$RES_DIR/$p-$jid.err" \ + || echo "::warning::could not fetch the log of $p job $jid: $(head -c 300 "$RES_DIR/$p-$jid.err")" if inst=$(installed_version "$RES_DIR/$p-$jid.log"); then break; fi inst="" done From 106e378d5db358707fa5731fd6cd69444346c068 Mon Sep 17 00:00:00 2001 From: burinc Date: Fri, 20 Nov 2026 12:52:08 +1100 Subject: [PATCH 05/31] fanout: allow escape sequences in job logs --- .github/workflows/fanout.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/fanout.yml b/.github/workflows/fanout.yml index 8a8a3e7..b7c6f1e 100644 --- a/.github/workflows/fanout.yml +++ b/.github/workflows/fanout.yml @@ -236,9 +236,10 @@ jobs: inst="" for jid in $(gh api "repos/jlt-commons/$p/actions/runs/${RUN[$p]}/jobs" \ --jq '.jobs[].id' 2>/dev/null); do - gh api "repos/jlt-commons/$p/actions/jobs/$jid/logs" \ + gh api --allow-escape-sequences "repos/jlt-commons/$p/actions/jobs/$jid/logs" \ > "$RES_DIR/$p-$jid.log" 2> "$RES_DIR/$p-$jid.err" \ || echo "::warning::could not fetch the log of $p job $jid: $(head -c 300 "$RES_DIR/$p-$jid.err")" + echo " $p job $jid: $(wc -l < "$RES_DIR/$p-$jid.log") log lines, $(grep -c 'jolt v' "$RES_DIR/$p-$jid.log") 'jolt v' lines" if inst=$(installed_version "$RES_DIR/$p-$jid.log"); then break; fi inst="" done From ced3bf77697e057bc8fc87e1f885a0251d481244 Mon Sep 17 00:00:00 2001 From: burinc Date: Fri, 20 Nov 2026 13:06:50 +1100 Subject: [PATCH 06/31] fanout: a run proves the requested jolt if any job installed it (pick_installed) --- .github/workflows/fanout.yml | 12 +++++------- scripts/lib/version.sh | 19 +++++++++++++++++++ test/version.bats | 7 +++++++ 3 files changed, 31 insertions(+), 7 deletions(-) diff --git a/.github/workflows/fanout.yml b/.github/workflows/fanout.yml index b7c6f1e..bdb88a9 100644 --- a/.github/workflows/fanout.yml +++ b/.github/workflows/fanout.yml @@ -233,20 +233,18 @@ jobs: elif [ "$cc" = "success" ]; then # A green run is not proof it ran the jolt we asked for: read # the `jolt --version` line out of each job's log. - inst="" + # One job may install a different jolt on purpose (glitter-gl keeps + # a v0.7.29 job), so the run counts if ANY job ran the requested one. + logs=() for jid in $(gh api "repos/jlt-commons/$p/actions/runs/${RUN[$p]}/jobs" \ --jq '.jobs[].id' 2>/dev/null); do gh api --allow-escape-sequences "repos/jlt-commons/$p/actions/jobs/$jid/logs" \ > "$RES_DIR/$p-$jid.log" 2> "$RES_DIR/$p-$jid.err" \ || echo "::warning::could not fetch the log of $p job $jid: $(head -c 300 "$RES_DIR/$p-$jid.err")" - echo " $p job $jid: $(wc -l < "$RES_DIR/$p-$jid.log") log lines, $(grep -c 'jolt v' "$RES_DIR/$p-$jid.log") 'jolt v' lines" - if inst=$(installed_version "$RES_DIR/$p-$jid.log"); then break; fi - inst="" + logs+=("$RES_DIR/$p-$jid.log") done + if inst=$(pick_installed "$VERSION" "$NIGHTLY_SHA" "${logs[@]}"); then :; else cc="mismatch"; fi INST[$p]="$inst" - if [ -z "$inst" ] || ! version_matches "$VERSION" "$inst" "$NIGHTLY_SHA"; then - cc="mismatch" - fi fi CONC[$p]="$cc" echo " $p: $cc${INST[$p]:+ (jolt ${INST[$p]})}" diff --git a/scripts/lib/version.sh b/scripts/lib/version.sh index 2d35ccc..10355cd 100644 --- a/scripts/lib/version.sh +++ b/scripts/lib/version.sh @@ -28,6 +28,25 @@ version_matches() { [ "${requested#v}" = "$installed" ] } +# pick_installed ... +# Prints the first installed version (across the logs, in order) that matches +# the request and exits 0. If none match, prints the first version found and +# exits 1. If no log has a version, prints nothing and exits 1. +pick_installed() { + local requested=$1 sha=$2 f v first="" + shift 2 + for f in "$@"; do + v=$(installed_version "$f") || continue + [ -n "$first" ] || first=$v + if version_matches "$requested" "$v" "$sha"; then + printf '%s\n' "$v" + return 0 + fi + done + [ -n "$first" ] && printf '%s\n' "$first" + return 1 +} + # parse_pin # Prints the literal version from the first JOLT_VERSION: key line, without v. # Exits 1 when the file or key is missing or the pin is not a literal version. diff --git a/test/version.bats b/test/version.bats index be1722b..c408371 100644 --- a/test/version.bats +++ b/test/version.bats @@ -46,3 +46,10 @@ pin() { printf '%s\n' "$1" > "$BATS_TMPDIR/ci.yml"; run parse_pin "$BATS_TMPDIR/ printf '2026-11-18T03:48:28.0000000Z jolt v0.8.24\n'; } > "$BATS_TMPDIR/big" run installed_version "$BATS_TMPDIR/big"; [ "$status" -eq 0 ]; [ "$output" = "0.8.24" ] } + +logs2() { printf '2026-11-19T01:02:03.0000000Z jolt v%s\n' "$1" > "$BATS_TMPDIR/a.log"; printf '2026-11-19T01:02:04.0000000Z jolt v%s\n' "$2" > "$BATS_TMPDIR/b.log"; } + +@test "pick: matching second log" { logs2 0.7.29 0.8.27; run pick_installed 0.8.27 "" "$BATS_TMPDIR/a.log" "$BATS_TMPDIR/b.log"; [ "$status" -eq 0 ]; [ "$output" = "0.8.27" ]; } +@test "pick: none match reports first" { logs2 0.7.29 0.8.27; run pick_installed 0.8.26 "" "$BATS_TMPDIR/a.log" "$BATS_TMPDIR/b.log"; [ "$status" -eq 1 ]; [ "$output" = "0.7.29" ]; } +@test "pick: nightly sha in second log" { logs2 0.7.29 0.8.27-241-gdd3c4a4b; run pick_installed nightly dd3c4a4b0123456789abcdef0123456789abcdef "$BATS_TMPDIR/a.log" "$BATS_TMPDIR/b.log"; [ "$status" -eq 0 ]; [ "$output" = "0.8.27-241-gdd3c4a4b" ]; } +@test "pick: no versions" { printf 'nothing\n' > "$BATS_TMPDIR/a.log"; run pick_installed 0.8.27 "" "$BATS_TMPDIR/a.log"; [ "$status" -eq 1 ]; [ -z "$output" ]; } From 0aa29e90a98dda8f68ad1666c7bac916b368e170 Mon Sep 17 00:00:00 2001 From: burinc Date: Fri, 20 Nov 2026 13:14:38 +1100 Subject: [PATCH 07/31] fleet: build status.json and history.json from run results --- .github/workflows/test.yml | 2 +- scripts/build-status.sh | 122 +++++++++++++++ test/build-status.bats | 171 ++++++++++++++++++++++ test/fixtures/status/own-pin.json | 5 + test/fixtures/status/prev-history.json | 1 + test/fixtures/status/prev-status.json | 13 ++ test/fixtures/status/results-adhoc.json | 4 + test/fixtures/status/results-latest.json | 5 + test/fixtures/status/results-nightly.json | 5 + test/fixtures/status/uncovered.json | 1 + 10 files changed, 328 insertions(+), 1 deletion(-) create mode 100755 scripts/build-status.sh create mode 100644 test/build-status.bats create mode 100644 test/fixtures/status/own-pin.json create mode 100644 test/fixtures/status/prev-history.json create mode 100644 test/fixtures/status/prev-status.json create mode 100644 test/fixtures/status/results-adhoc.json create mode 100644 test/fixtures/status/results-latest.json create mode 100644 test/fixtures/status/results-nightly.json create mode 100644 test/fixtures/status/uncovered.json diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 9d59d3c..c23f4a5 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -11,4 +11,4 @@ jobs: - uses: actions/checkout@v7 - run: sudo apt-get install -y bats - run: bats test/ - - run: shellcheck scripts/lib/*.sh + - run: shellcheck scripts/lib/*.sh scripts/build-status.sh diff --git a/scripts/build-status.sh b/scripts/build-status.sh new file mode 100755 index 0000000..fd54afe --- /dev/null +++ b/scripts/build-status.sh @@ -0,0 +1,122 @@ +#!/usr/bin/env bash +# Pure merge: fan-out results + own-pin + uncovered + previous status/history +# -> new status.json and history.json. No network, no git. +set -euo pipefail + +usage() { + echo "usage: build-status.sh --prev-status F --prev-history F --own-pin F --uncovered F" >&2 + echo " --latest VERSION --nightly-json JSON|null --canary-run URL --now ISO --out-dir D [results.json ...]" >&2 + exit 2 +} + +prev_status="" prev_history="" own_pin="" uncovered="" latest="" nightly="" canary="" now="" out="" +nightly_set=0 +while [ $# -gt 0 ]; do + case "$1" in + --prev-status) [ $# -ge 2 ] || usage; prev_status=$2; shift 2 ;; + --prev-history) [ $# -ge 2 ] || usage; prev_history=$2; shift 2 ;; + --own-pin) [ $# -ge 2 ] || usage; own_pin=$2; shift 2 ;; + --uncovered) [ $# -ge 2 ] || usage; uncovered=$2; shift 2 ;; + --latest) [ $# -ge 2 ] || usage; latest=$2; shift 2 ;; + --nightly-json) [ $# -ge 2 ] || usage; nightly=$2; nightly_set=1; shift 2 ;; + --canary-run) [ $# -ge 2 ] || usage; canary=$2; shift 2 ;; + --now) [ $# -ge 2 ] || usage; now=$2; shift 2 ;; + --out-dir) [ $# -ge 2 ] || usage; out=$2; shift 2 ;; + --) shift; break ;; + -*) usage ;; + *) break ;; + esac +done +results=("$@") +[ -n "$own_pin" ] && [ -n "$uncovered" ] && [ -n "$latest" ] && [ "$nightly_set" -eq 1 ] \ + && [ -n "$canary" ] && [ -n "$now" ] && [ -n "$out" ] || usage + +mkdir -p "$out" +tmp=$(mktemp -d "$out/.build-status.XXXXXX") +trap 'rm -rf "$tmp"' EXIT + +# A missing previous file counts as empty (null). +slurp_or_null() { if [ -n "$1" ] && [ -f "$1" ]; then cp "$1" "$2"; else echo null > "$2"; fi; } +slurp_or_null "$prev_status" "$tmp/prev-status.json" +slurp_or_null "$prev_history" "$tmp/prev-history.json" + +if [ ${#results[@]} -gt 0 ]; then + jq -s '.' "${results[@]}" > "$tmp/results.json" +else + echo '[]' > "$tmp/results.json" +fi + +jq -n \ + --slurpfile prev "$tmp/prev-status.json" \ + --slurpfile prevh "$tmp/prev-history.json" \ + --slurpfile files "$tmp/results.json" \ + --slurpfile own "$own_pin" \ + --slurpfile unc "$uncovered" \ + --arg latest "$latest" \ + --argjson nj "$nightly" \ + --arg canary "$canary" \ + --arg now "$now" ' + def strip: if type == "string" then sub("^v"; "") else . end; + def valid: ["pass","fail","infra","timed-out","dispatch-failed","mismatch","not-run"]; + def notrun: {result: "not-run"}; + def cell($f): { + result: .result, version: ($f.requested | strip), installed: (.installed // null), + run_url: (.run_url // null), finished_at: (.finished_at // null), + failed_step: (.failed_step // null)}; + def column($f): + if $f.requested == "nightly" then "nightly" + elif ($f.requested | strip) == $latest then "latest" + else "adhoc" end; + + ($prev[0]) as $ps | ($prevh[0]) as $ph | $files[0] as $fs | $own[0] as $op | $unc[0] as $un + | (($op | type) == "array" and all($op[]; (.name | type) == "string" and (.pin | type) == "string") + or error("malformed own-pin")) as $_ + | (($un | type) == "array" or error("malformed uncovered")) as $_ + | (($ps == null or ($ps | type) == "object") or error("malformed prev status")) as $_ + | (($ph == null or ($ph | type) == "object") or error("malformed prev history")) as $_ + | (all($fs[]; type == "object" and (.requested | type) == "string" and (.projects | type) == "array" + and all(.projects[]; (.name | type) == "string" and (.result as $r | valid | any(. == $r)))) + or error("malformed results")) as $_ + + # results this run, in file order + | [ $fs[] as $f | $f.projects[] | {name, col: column($f), cell: cell($f)} ] as $res + + | (if $ps == null then false else ($ps.jolt.latest.version // null) != $latest end) as $latest_stale + | (if $nj == null then false else ($ps.jolt.nightly.sha // null) != $nj.sha end) as $nightly_stale + | ((($ps.projects // []) | map({key: .name, value: .cells}) | from_entries)) as $pc + | ($res | map(select(.col != "adhoc")) | reduce .[] as $e ({}; .[$e.name + "/" + $e.col] = $e.cell)) as $new + + | def pick($n; $c; $stale): + $new[$n + "/" + $c] + // (if $stale then notrun else (($pc[$n] // {})[$c] // notrun) end); + + [ $op[] | . as $p + | {name: $p.name, pin: $p.pin, + cells: { + pin: {result: $p.result, version: $p.pin, installed: null, + run_url: ($p.run_url // null), finished_at: ($p.finished_at // null), + failed_step: ($p.failed_step // null)}, + latest: pick($p.name; "latest"; $latest_stale), + nightly: pick($p.name; "nightly"; $nightly_stale)}} ] as $projects + + | ($projects | map(select(.cells | [.[] | .result | . != "pass" and . != "not-run"] | any)) | map(.name)) as $bad + | ($projects | sort_by([(.name as $n | if $bad | any(. == $n) then 0 else 1 end), .name])) as $sorted + + # history: results this run, then the pin cell when its run is new + | ($res + [ $projects[] | . as $p | {name: $p.name, col: "pin", cell: $p.cells.pin} + | select(((($ph.projects // {})[.name].pin // [])[0].run_url // "__none__") != (.cell.run_url // "__none__") + or ((($ph.projects // {})[.name].pin // []) | length) == 0) ]) as $entries + | ($entries | reduce .[] as $e ($ph.projects // {}; + .[$e.name][$e.col] = ([$e.cell] + (.[$e.name][$e.col] // []))[0:30]) + | map_values({pin: [], latest: [], nightly: [], adhoc: []} + .)) as $hist + + | {status: {schema: 1, generated_at: $now, canary_run: $canary, + jolt: {latest: {version: $latest}, nightly: $nj}, + projects: $sorted, uncovered: $un}, + history: {schema: 1, projects: $hist}} +' > "$tmp/both.json" + +jq '.status' "$tmp/both.json" > "$tmp/status.json" +jq '.history' "$tmp/both.json" > "$tmp/history.json" +mv "$tmp/status.json" "$out/status.json" +mv "$tmp/history.json" "$out/history.json" diff --git a/test/build-status.bats b/test/build-status.bats new file mode 100644 index 0000000..8fef518 --- /dev/null +++ b/test/build-status.bats @@ -0,0 +1,171 @@ +setup() { + F="$BATS_TEST_DIRNAME/fixtures/status" + S="$BATS_TEST_DIRNAME/../scripts/build-status.sh" + OUT="$BATS_TEST_TMPDIR/out" + NJ='{"published_at":"2026-11-20T01:00:00Z","sha":"f4e82fc8eac874cae1658b7976518253027c4f6a","note":"n"}' +} + +# run_bs [extra args] -- results files: uses fixtures for own-pin/uncovered; prev files via PS/PH +run_bs() { + local nj=${NJ_ARG-$NJ} latest=${LATEST:-0.8.27} + run "$S" --prev-status "${PS:-/nonexistent}" --prev-history "${PH:-/nonexistent}" \ + --own-pin "${OP:-$F/own-pin.json}" --uncovered "$F/uncovered.json" \ + --latest "$latest" --nightly-json "$nj" --canary-run https://example/run/1 \ + --now 2026-11-20T04:00:00Z --out-dir "$OUT" "$@" +} +st() { jq -c "$1" "$OUT/status.json"; } +hi() { jq -c "$1" "$OUT/history.json"; } + +@test "first run with no prev files" { + run_bs "$F/results-latest.json" + [ "$status" -eq 0 ] + [ "$(st '.schema')" = 1 ] + [ "$(st '.projects|map(.name)|sort')" = '["ebb","glitter","raygui-jlt"]' ] + [ "$(st '.projects[]|select(.name=="raygui-jlt").cells.latest')" = '{"result":"not-run"}' ] + [ "$(st '.projects[]|select(.name=="raygui-jlt").cells.nightly')" = '{"result":"not-run"}' ] + [ "$(st '.uncovered')" = '[{"name":"duratom","reason":"ci.yml has no jolt-version input"}]' ] + [ "$(st '.generated_at')" = '"2026-11-20T04:00:00Z"' ] + [ "$(hi '.schema')" = 1 ] + [ "$(hi '.projects.glitter.latest|length')" = 1 ] + [ "$(hi '.projects.ebb.latest|length')" = 1 ] + [ "$(hi '.projects.glitter.pin|length')" = 1 ] +} + +@test "pin cell comes from own-pin with installed null" { + run_bs + [ "$(st '.projects[]|select(.name=="glitter").cells.pin|[.result,.version,.installed]')" = '["pass","0.8.24",null]' ] +} + +@test "latest result lands in latest column" { + run_bs "$F/results-latest.json" + [ "$(st '.projects[]|select(.name=="glitter").cells.latest|[.result,.version,.installed]')" = '["pass","0.8.27","0.8.27"]' ] + [ "$(st '.jolt.latest')" = '{"version":"0.8.27"}' ] +} + +@test "v prefix on requested is stripped" { + jq '.requested="v0.8.27"' "$F/results-latest.json" > "$BATS_TEST_TMPDIR/r.json" + run_bs "$BATS_TEST_TMPDIR/r.json" + [ "$(st '.projects[]|select(.name=="glitter").cells.latest.version')" = '"0.8.27"' ] +} + +@test "nightly result lands in nightly column" { + run_bs "$F/results-nightly.json" + [ "$(st '.projects[]|select(.name=="glitter").cells.nightly|[.result,.version,.installed]')" = '["pass","nightly","0.8.27-376-gf4e82fc8"]' ] + [ "$(st '.jolt.nightly.sha')" = '"f4e82fc8eac874cae1658b7976518253027c4f6a"' ] +} + +@test "adhoc result only in history" { + PS="$F/prev-status.json" PH="$F/prev-history.json" run_bs "$F/results-adhoc.json" + [ "$status" -eq 0 ] + [ "$(st '.projects[]|select(.name=="glitter").cells.latest.run_url')" = '"https://github.com/jlt-commons/glitter/actions/runs/42"' ] + [ "$(hi '.projects.glitter.adhoc|length')" = 1 ] + [ "$(hi '.projects.glitter.adhoc[0].version')" = '"0.8.25"' ] + [ "$(hi '.projects.glitter.latest|length')" = 0 ] +} + +@test "results for a project outside own-pin go to history, not the grid" { + jq '.projects[0].name="gone"' "$F/results-latest.json" > "$BATS_TEST_TMPDIR/r.json" + run_bs "$BATS_TEST_TMPDIR/r.json" + [ "$(st '.projects|map(.name)|index("gone")')" = null ] + [ "$(hi '.projects.gone.latest|length')" = 1 ] +} + +@test "carry over with only own-pin input" { + NJ_ARG='{"published_at":"x","sha":"aaaa1111","note":"n"}' PS="$F/prev-status.json" PH="$F/prev-history.json" run_bs + [ "$status" -eq 0 ] + [ "$(st '.projects[]|select(.name=="ebb").cells.latest')" = "$(jq -c '.projects[]|select(.name=="ebb").cells.latest' "$F/prev-status.json")" ] + [ "$(st '.projects[]|select(.name=="glitter").cells.nightly')" = "$(jq -c '.projects[]|select(.name=="glitter").cells.nightly' "$F/prev-status.json")" ] + # raygui-jlt had no prior cells + [ "$(st '.projects[]|select(.name=="raygui-jlt").cells.latest')" = '{"result":"not-run"}' ] +} + +@test "new latest version invalidates carried latest cells" { + NJ_ARG='{"published_at":"x","sha":"aaaa1111","note":"n"}' PS="$F/prev-status.json" PH="$F/prev-history.json" LATEST=0.8.28 run_bs + [ "$(st '.projects[]|select(.name=="ebb").cells.latest')" = '{"result":"not-run"}' ] + [ "$(st '.projects[]|select(.name=="glitter").cells.latest')" = '{"result":"not-run"}' ] + # nightly unaffected + [ "$(st '.projects[]|select(.name=="glitter").cells.nightly.result')" = '"pass"' ] +} + +@test "new nightly sha invalidates carried nightly cells" { + PS="$F/prev-status.json" PH="$F/prev-history.json" run_bs + [ "$(st '.projects[]|select(.name=="glitter").cells.nightly.result')" = '"not-run"' ] + [ "$(st '.projects[]|select(.name=="glitter").cells.latest.result')" = '"pass"' ] +} + +@test "same nightly sha keeps carried nightly cells" { + NJ_ARG='{"published_at":"x","sha":"aaaa1111","note":"n"}' PS="$F/prev-status.json" run_bs + [ "$(st '.projects[]|select(.name=="glitter").cells.nightly.result')" = '"pass"' ] +} + +@test "null nightly-json keeps previous nightly cells and nightly is null" { + NJ_ARG=null PS="$F/prev-status.json" run_bs + [ "$status" -eq 0 ] + [ "$(st '.jolt.nightly')" = null ] + [ "$(st '.projects[]|select(.name=="glitter").cells.nightly.result')" = '"pass"' ] +} + +@test "pin history appended only when run_url is new" { + PS="$F/prev-status.json" PH="$F/prev-history.json" run_bs + # glitter's own-pin run_url equals the newest pin history entry + [ "$(hi '.projects.glitter.pin|length')" = 1 ] + # ebb has no pin history yet + [ "$(hi '.projects.ebb.pin|length')" = 1 ] + # second tick over the first one's output adds nothing + cp "$OUT/history.json" "$BATS_TEST_TMPDIR/h2.json" + PS="$OUT/status.json" PH="$BATS_TEST_TMPDIR/h2.json" run_bs + [ "$(hi '.projects.ebb.pin|length')" = 1 ] + [ "$(hi '.projects["raygui-jlt"].pin|length')" = 1 ] +} + +@test "pin history grows when the pin run changes" { + PS="$F/prev-status.json" PH="$F/prev-history.json" run_bs + jq '.[0].run_url="https://github.com/jlt-commons/glitter/actions/runs/99"' "$F/own-pin.json" > "$BATS_TEST_TMPDIR/op.json" + cp "$OUT/history.json" "$BATS_TEST_TMPDIR/h2.json" + OP="$BATS_TEST_TMPDIR/op.json" PH="$BATS_TEST_TMPDIR/h2.json" run_bs + [ "$(hi '.projects.glitter.pin|length')" = 2 ] + [ "$(hi '.projects.glitter.pin[0].run_url')" = '"https://github.com/jlt-commons/glitter/actions/runs/99"' ] +} + +@test "history capped at 30, newest first" { + jq '.projects.glitter.latest = [range(0;30) | {result:"pass",version:"0.8.26",installed:null,run_url:("old/"+tostring),finished_at:null,failed_step:null}]' \ + "$F/prev-history.json" > "$BATS_TEST_TMPDIR/h.json" + PH="$BATS_TEST_TMPDIR/h.json" run_bs "$F/results-latest.json" + [ "$(hi '.projects.glitter.latest|length')" = 30 ] + [ "$(hi '.projects.glitter.latest[0].run_url')" = '"https://github.com/jlt-commons/glitter/actions/runs/11"' ] + [ "$(hi '.projects.glitter.latest[29].run_url')" = '"old/28"' ] +} + +@test "failing first, then by name" { + # raygui-jlt has a failing own-pin cell + run_bs + [ "$(st '.projects|map(.name)')" = '["raygui-jlt","ebb","glitter"]' ] +} + +@test "mismatch cell sorts before passing ones" { + jq '.[2].result="pass"' "$F/own-pin.json" > "$BATS_TEST_TMPDIR/op.json" + OP="$BATS_TEST_TMPDIR/op.json" run_bs "$F/results-nightly.json" + [ "$(st '.projects|map(.name)')" = '["raygui-jlt","ebb","glitter"]' ] +} + +@test "malformed results: non-zero exit and no files written" { + echo '{"requested":"0.8.27","projects":"nope"}' > "$BATS_TEST_TMPDIR/bad.json" + run_bs "$BATS_TEST_TMPDIR/bad.json" + [ "$status" -ne 0 ] + [ ! -e "$OUT/status.json" ] + [ ! -e "$OUT/history.json" ] +} + +@test "unknown result value is rejected" { + jq '.projects[0].result="weird"' "$F/results-latest.json" > "$BATS_TEST_TMPDIR/bad.json" + run_bs "$BATS_TEST_TMPDIR/bad.json" + [ "$status" -ne 0 ] + [ ! -e "$OUT/status.json" ] +} + +@test "unparseable results file: non-zero exit" { + echo '{not json' > "$BATS_TEST_TMPDIR/bad.json" + run_bs "$BATS_TEST_TMPDIR/bad.json" + [ "$status" -ne 0 ] + [ ! -e "$OUT/status.json" ] +} diff --git a/test/fixtures/status/own-pin.json b/test/fixtures/status/own-pin.json new file mode 100644 index 0000000..285fc59 --- /dev/null +++ b/test/fixtures/status/own-pin.json @@ -0,0 +1,5 @@ +[ + {"name":"glitter","pin":"0.8.24","result":"pass","run_url":"https://github.com/jlt-commons/glitter/actions/runs/1","finished_at":"2026-11-20T01:00:00Z","failed_step":null}, + {"name":"ebb","pin":"0.8.24","result":"pass","run_url":"https://github.com/jlt-commons/ebb/actions/runs/2","finished_at":"2026-11-20T01:01:00Z","failed_step":null}, + {"name":"raygui-jlt","pin":"0.8.24","result":"fail","run_url":"https://github.com/jlt-commons/raygui-jlt/actions/runs/3","finished_at":"2026-11-20T01:02:00Z","failed_step":"Formatting"} +] diff --git a/test/fixtures/status/prev-history.json b/test/fixtures/status/prev-history.json new file mode 100644 index 0000000..458211b --- /dev/null +++ b/test/fixtures/status/prev-history.json @@ -0,0 +1 @@ +{"schema":1,"projects":{"glitter":{"pin":[{"result":"pass","version":"0.8.24","installed":null,"run_url":"https://github.com/jlt-commons/glitter/actions/runs/1","finished_at":"2026-11-20T01:00:00Z","failed_step":null}],"latest":[],"nightly":[],"adhoc":[]}}} diff --git a/test/fixtures/status/prev-status.json b/test/fixtures/status/prev-status.json new file mode 100644 index 0000000..d2f2dcd --- /dev/null +++ b/test/fixtures/status/prev-status.json @@ -0,0 +1,13 @@ +{"schema":1,"generated_at":"2026-11-19T12:00:00Z","canary_run":"https://github.com/jlt-commons/ci-builds/actions/runs/5", + "jolt":{"latest":{"version":"0.8.27"},"nightly":{"published_at":"2026-11-19T03:00:00Z","sha":"aaaa1111","note":"n"}}, + "projects":[ + {"name":"ebb","pin":"0.8.24","cells":{ + "pin":{"result":"pass","version":"0.8.24","installed":null,"run_url":"https://github.com/jlt-commons/ebb/actions/runs/2","finished_at":"2026-11-20T01:01:00Z","failed_step":null}, + "latest":{"result":"fail","version":"0.8.27","installed":"0.8.27","run_url":"https://github.com/jlt-commons/ebb/actions/runs/40","finished_at":"2026-11-19T10:00:00Z","failed_step":"Tests"}, + "nightly":{"result":"pass","version":"nightly","installed":"0.8.27-100-gaaaa1111","run_url":"https://github.com/jlt-commons/ebb/actions/runs/41","finished_at":"2026-11-19T10:05:00Z","failed_step":null}}}, + {"name":"glitter","pin":"0.8.24","cells":{ + "pin":{"result":"pass","version":"0.8.24","installed":null,"run_url":"https://github.com/jlt-commons/glitter/actions/runs/1","finished_at":"2026-11-20T01:00:00Z","failed_step":null}, + "latest":{"result":"pass","version":"0.8.27","installed":"0.8.27","run_url":"https://github.com/jlt-commons/glitter/actions/runs/42","finished_at":"2026-11-19T10:00:00Z","failed_step":null}, + "nightly":{"result":"pass","version":"nightly","installed":"0.8.27-100-gaaaa1111","run_url":"https://github.com/jlt-commons/glitter/actions/runs/43","finished_at":"2026-11-19T10:05:00Z","failed_step":null}}} + ], + "uncovered":[]} diff --git a/test/fixtures/status/results-adhoc.json b/test/fixtures/status/results-adhoc.json new file mode 100644 index 0000000..7d2f825 --- /dev/null +++ b/test/fixtures/status/results-adhoc.json @@ -0,0 +1,4 @@ +{"requested":"0.8.25","nightly_sha":"","finished_at":"2026-11-20T03:00:00Z","run_url":"https://github.com/jlt-commons/ci-builds/actions/runs/30", + "projects":[ + {"name":"glitter","result":"pass","installed":"0.8.25","run_url":"https://github.com/jlt-commons/glitter/actions/runs/31","finished_at":"2026-11-20T02:59:00Z","failed_step":null} + ]} diff --git a/test/fixtures/status/results-latest.json b/test/fixtures/status/results-latest.json new file mode 100644 index 0000000..b3011db --- /dev/null +++ b/test/fixtures/status/results-latest.json @@ -0,0 +1,5 @@ +{"requested":"0.8.27","nightly_sha":"","finished_at":"2026-11-20T02:09:37Z","run_url":"https://github.com/jlt-commons/ci-builds/actions/runs/10", + "projects":[ + {"name":"glitter","result":"pass","installed":"0.8.27","run_url":"https://github.com/jlt-commons/glitter/actions/runs/11","finished_at":"2026-11-20T02:08:07Z","failed_step":null}, + {"name":"ebb","result":"pass","installed":"0.8.27","run_url":"https://github.com/jlt-commons/ebb/actions/runs/12","finished_at":"2026-11-20T02:08:09Z","failed_step":null} + ]} diff --git a/test/fixtures/status/results-nightly.json b/test/fixtures/status/results-nightly.json new file mode 100644 index 0000000..068245c --- /dev/null +++ b/test/fixtures/status/results-nightly.json @@ -0,0 +1,5 @@ +{"requested":"nightly","nightly_sha":"f4e82fc8eac874cae1658b7976518253027c4f6a","finished_at":"2026-11-20T01:59:57Z","run_url":"https://github.com/jlt-commons/ci-builds/actions/runs/20", + "projects":[ + {"name":"glitter","result":"pass","installed":"0.8.27-376-gf4e82fc8","run_url":"https://github.com/jlt-commons/glitter/actions/runs/21","finished_at":"2026-11-20T01:53:34Z","failed_step":null}, + {"name":"raygui-jlt","result":"mismatch","installed":"0.8.27-300-gabcdef01","run_url":"https://github.com/jlt-commons/raygui-jlt/actions/runs/22","finished_at":"2026-11-20T01:55:47Z","failed_step":null} + ]} diff --git a/test/fixtures/status/uncovered.json b/test/fixtures/status/uncovered.json new file mode 100644 index 0000000..ad1d751 --- /dev/null +++ b/test/fixtures/status/uncovered.json @@ -0,0 +1 @@ +[{"name":"duratom","reason":"ci.yml has no jolt-version input"}] From 0bff13ef414f766fa6b46fe19db4aae107b1343f Mon Sep 17 00:00:00 2001 From: burinc Date: Fri, 20 Nov 2026 13:17:14 +1100 Subject: [PATCH 08/31] fleet: strip v from --latest, dedupe history by run_url --- scripts/build-status.sh | 5 ++++- test/build-status.bats | 22 ++++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/scripts/build-status.sh b/scripts/build-status.sh index fd54afe..5d7c870 100755 --- a/scripts/build-status.sh +++ b/scripts/build-status.sh @@ -31,6 +31,7 @@ results=("$@") [ -n "$own_pin" ] && [ -n "$uncovered" ] && [ -n "$latest" ] && [ "$nightly_set" -eq 1 ] \ && [ -n "$canary" ] && [ -n "$now" ] && [ -n "$out" ] || usage +latest=${latest#v} mkdir -p "$out" tmp=$(mktemp -d "$out/.build-status.XXXXXX") trap 'rm -rf "$tmp"' EXIT @@ -107,7 +108,9 @@ jq -n \ | select(((($ph.projects // {})[.name].pin // [])[0].run_url // "__none__") != (.cell.run_url // "__none__") or ((($ph.projects // {})[.name].pin // []) | length) == 0) ]) as $entries | ($entries | reduce .[] as $e ($ph.projects // {}; - .[$e.name][$e.col] = ([$e.cell] + (.[$e.name][$e.col] // []))[0:30]) + if $e.cell.run_url != null and ((.[$e.name][$e.col] // []) | any(.run_url == $e.cell.run_url)) + then . + else .[$e.name][$e.col] = ([$e.cell] + (.[$e.name][$e.col] // []))[0:30] end) | map_values({pin: [], latest: [], nightly: [], adhoc: []} + .)) as $hist | {status: {schema: 1, generated_at: $now, canary_run: $canary, diff --git a/test/build-status.bats b/test/build-status.bats index 8fef518..64a7e70 100644 --- a/test/build-status.bats +++ b/test/build-status.bats @@ -169,3 +169,25 @@ hi() { jq -c "$1" "$OUT/history.json"; } [ "$status" -ne 0 ] [ ! -e "$OUT/status.json" ] } + +@test "--latest with a v prefix matches results and prev" { + NJ_ARG='{"published_at":"x","sha":"aaaa1111","note":"n"}' PS="$F/prev-status.json" LATEST=v0.8.27 run_bs "$F/results-latest.json" + [ "$status" -eq 0 ] + [ "$(st '.jolt.latest.version')" = '"0.8.27"' ] + [ "$(st '.projects[]|select(.name=="glitter").cells.latest.run_url')" = '"https://github.com/jlt-commons/glitter/actions/runs/11"' ] + # no stale reset for a project the results file lacks + [ "$(st '.projects[]|select(.name=="raygui-jlt").cells.latest.result')" = '"not-run"' ] + NJ_ARG='{"published_at":"x","sha":"aaaa1111","note":"n"}' PS="$F/prev-status.json" LATEST=v0.8.27 run_bs + [ "$(st '.projects[]|select(.name=="ebb").cells.latest.result')" = '"fail"' ] +} + +@test "reprocessing the same results does not duplicate history" { + run_bs "$F/results-latest.json" "$F/results-nightly.json" "$F/results-adhoc.json" + cp "$OUT/status.json" "$BATS_TEST_TMPDIR/s1.json"; cp "$OUT/history.json" "$BATS_TEST_TMPDIR/h1.json" + PS="$BATS_TEST_TMPDIR/s1.json" PH="$BATS_TEST_TMPDIR/h1.json" run_bs "$F/results-latest.json" "$F/results-nightly.json" "$F/results-adhoc.json" + [ "$status" -eq 0 ] + [ "$(jq -c . "$OUT/history.json")" = "$(jq -c . "$BATS_TEST_TMPDIR/h1.json")" ] + [ "$(hi '.projects.glitter.adhoc|length')" = 1 ] + [ "$(hi '.projects.glitter.latest|length')" = 1 ] + [ "$(hi '.projects.glitter.nightly|length')" = 1 ] +} From 5c9151387bd3893a255d94dc18f3f10d9371d3d9 Mon Sep 17 00:00:00 2001 From: burinc Date: Fri, 20 Nov 2026 13:24:36 +1100 Subject: [PATCH 09/31] fleet: collect own-pin results and uncovered repos --- .github/workflows/test.yml | 2 +- scripts/collect-own-pin.sh | 68 ++++++++++++++++++ scripts/collect-uncovered.sh | 48 +++++++++++++ test/collect.bats | 91 ++++++++++++++++++++++++ test/fixtures/gh/glitter-gl.branch | 1 + test/fixtures/gh/glitter-gl.ci.yml | 2 + test/fixtures/gh/glitter-gl.jobs.json | 1 + test/fixtures/gh/glitter-gl.runs.json | 1 + test/fixtures/gh/glitter-uikit.branch | 1 + test/fixtures/gh/glitter-uikit.ci.yml | 2 + test/fixtures/gh/glitter-uikit.runs.json | 1 + test/fixtures/gh/glitter.branch | 1 + test/fixtures/gh/glitter.ci.yml | 7 ++ test/fixtures/gh/glitter.runs.json | 1 + test/fixtures/gh/jolt-lsp.ci.yml | 7 ++ test/fixtures/gh/noinput.ci.yml | 7 ++ test/fixtures/gh/org-repos.json | 8 +++ test/fixtures/gh/readyrepo.ci.yml | 7 ++ 18 files changed, 255 insertions(+), 1 deletion(-) create mode 100755 scripts/collect-own-pin.sh create mode 100755 scripts/collect-uncovered.sh create mode 100644 test/collect.bats create mode 100644 test/fixtures/gh/glitter-gl.branch create mode 100644 test/fixtures/gh/glitter-gl.ci.yml create mode 100644 test/fixtures/gh/glitter-gl.jobs.json create mode 100644 test/fixtures/gh/glitter-gl.runs.json create mode 100644 test/fixtures/gh/glitter-uikit.branch create mode 100644 test/fixtures/gh/glitter-uikit.ci.yml create mode 100644 test/fixtures/gh/glitter-uikit.runs.json create mode 100644 test/fixtures/gh/glitter.branch create mode 100644 test/fixtures/gh/glitter.ci.yml create mode 100644 test/fixtures/gh/glitter.runs.json create mode 100644 test/fixtures/gh/jolt-lsp.ci.yml create mode 100644 test/fixtures/gh/noinput.ci.yml create mode 100644 test/fixtures/gh/org-repos.json create mode 100644 test/fixtures/gh/readyrepo.ci.yml diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index c23f4a5..1e82ee2 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -11,4 +11,4 @@ jobs: - uses: actions/checkout@v7 - run: sudo apt-get install -y bats - run: bats test/ - - run: shellcheck scripts/lib/*.sh scripts/build-status.sh + - run: shellcheck -x scripts/lib/*.sh scripts/build-status.sh scripts/collect-own-pin.sh scripts/collect-uncovered.sh diff --git a/scripts/collect-own-pin.sh b/scripts/collect-own-pin.sh new file mode 100755 index 0000000..ac192da --- /dev/null +++ b/scripts/collect-own-pin.sh @@ -0,0 +1,68 @@ +#!/usr/bin/env bash +# For each fleet project: its latest completed push CI run on the default +# branch, plus the pin parsed from ci.yml. Prints own-pin.json on stdout. +# GH is the command used for every call (default: gh), split on spaces. +set -euo pipefail + +root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) +# shellcheck source=scripts/lib/version.sh +source "$root/scripts/lib/version.sh" +read -r -a GHC <<< "${GH:-gh}" +fleet=${FLEET_JSON:-$root/fleet.json} +org=jlt-commons +tmp=$(mktemp -d) +trap 'rm -rf "$tmp"' EXIT + +warn() { echo "collect-own-pin: $*" >&2; } + +# emit +emit() { + jq -n --arg name "$1" --arg pin "$2" --arg result "$3" --arg url "$4" \ + --arg at "$5" --arg step "$6" ' + def nz: if . == "" then null else . end; + {name: $name, pin: ($pin|nz), result: $result, run_url: ($url|nz), + finished_at: ($at|nz), failed_step: ($step|nz)}' +} + +collect() { + local p=$1 branch pin="" runs conc result url at id step="" ci="$tmp/ci.yml" + branch=$("${GHC[@]}" api "repos/$org/$p" --jq .default_branch 2>"$tmp/err") || { + warn "$p: could not read repository: $(tail -n1 "$tmp/err")" + emit "$p" "" not-run "" "" ""; return + } + if "${GHC[@]}" api -H 'Accept: application/vnd.github.raw' \ + "repos/$org/$p/contents/.github/workflows/ci.yml" >"$ci" 2>"$tmp/err"; then + pin=$(parse_pin "$ci") || pin="" + else + warn "$p: could not read ci.yml: $(tail -n1 "$tmp/err")" + fi + runs=$("${GHC[@]}" run list --repo "$org/$p" --workflow ci.yml --branch "$branch" \ + --event push --status completed --limit 1 \ + --json conclusion,url,updatedAt,databaseId 2>"$tmp/err") || { + warn "$p: could not list runs: $(tail -n1 "$tmp/err")" + emit "$p" "$pin" not-run "" "" ""; return + } + if [ "$(jq length <<<"$runs")" -eq 0 ]; then + emit "$p" "$pin" not-run "" "" ""; return + fi + conc=$(jq -r '.[0].conclusion // "none"' <<<"$runs") + case "$conc" in + success) result=pass ;; + failure) result=fail ;; + timed_out) result=timed-out ;; + *) result=not-run ;; + esac + url=$(jq -r '.[0].url // ""' <<<"$runs") + at=$(jq -r '.[0].updatedAt // ""' <<<"$runs") + if [ "$result" = fail ]; then + id=$(jq -r '.[0].databaseId' <<<"$runs") + step=$("${GHC[@]}" run view "$id" --repo "$org/$p" --json jobs \ + --jq '[.jobs[] | select(.conclusion=="failure") | .steps[]? | select(.conclusion=="failure") | .name] | first // ""' \ + 2>"$tmp/err") || { warn "$p: could not read jobs: $(tail -n1 "$tmp/err")"; step=""; } + fi + emit "$p" "$pin" "$result" "$url" "$at" "$step" +} + +while IFS= read -r p; do + collect "$p" +done < <(jq -r '.projects[]' "$fleet") | jq -s . diff --git a/scripts/collect-uncovered.sh b/scripts/collect-uncovered.sh new file mode 100755 index 0000000..27d4047 --- /dev/null +++ b/scripts/collect-uncovered.sh @@ -0,0 +1,48 @@ +#!/usr/bin/env bash +# Public, non-archived org repos that the fleet does not cover, each with a +# reason. Prints uncovered.json on stdout. +# GH is the command used for every call (default: gh), split on spaces. +set -euo pipefail + +root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) +# shellcheck source=scripts/lib/version.sh +source "$root/scripts/lib/version.sh" +read -r -a GHC <<< "${GH:-gh}" +fleet=${FLEET_JSON:-$root/fleet.json} +org=jlt-commons +tmp=$(mktemp -d) +trap 'rm -rf "$tmp"' EXIT + +warn() { echo "collect-uncovered: $*" >&2; } + +reason_for() { + local p=$1 in_fleet=0 excluded has_ci=0 has_input=0 ci="$tmp/ci.yml" + if jq -e --arg p "$p" '.projects | index($p)' "$fleet" >/dev/null; then in_fleet=1; fi + excluded=$(jq -r --arg p "$p" '.excluded[$p] // ""' "$fleet") + if [ "$in_fleet" = 0 ] && [ -z "$excluded" ]; then + if "${GHC[@]}" api -H 'Accept: application/vnd.github.raw' \ + "repos/$org/$p/contents/.github/workflows/ci.yml" >"$ci" 2>"$tmp/err"; then + has_ci=1 + # YAML 1.1 readers may turn the "on" key into boolean true. + if [ "$(yq '(.on // .true) | select(tag == "!!map") | (.workflow_dispatch.inputs // {}) | has("jolt-version")' "$ci" 2>/dev/null)" = true ]; then + has_input=1 + fi + elif grep -q '404' "$tmp/err"; then + has_ci=0 + else + warn "$p: could not read repository: $(tail -n1 "$tmp/err")" + printf 'could not read repository\n'; return + fi + fi + uncovered_reason "$p" "$has_ci" "$has_input" "$in_fleet" "$excluded" +} + +names=$("${GHC[@]}" api --paginate "orgs/$org/repos?type=public&per_page=100" \ + --jq '.[] | select((.archived|not) and (.private|not)) | .name') + +while IFS= read -r p; do + [ -n "$p" ] || continue + r=$(reason_for "$p") + [ -n "$r" ] || continue + jq -n --arg name "$p" --arg reason "$r" '{name: $name, reason: $reason}' +done <<<"$names" | jq -s . diff --git a/test/collect.bats b/test/collect.bats new file mode 100644 index 0000000..b173623 --- /dev/null +++ b/test/collect.bats @@ -0,0 +1,91 @@ +setup() { + ROOT="$BATS_TEST_DIRNAME/.." + cat > "$BATS_TMPDIR/gh-stub" <<'S' +#!/usr/bin/env bash +# Serves canned files from test/fixtures/gh by argument pattern; honours --jq. +D="$FIXTURE_DIR"; a=" $* "; jqf=""; prev="" +for x in "$@"; do [ "$prev" = "--jq" ] && jqf=$x; prev=$x; done +out() { if [ -n "$jqf" ]; then jq -r "$jqf" "$1"; else cat "$1"; fi; } +fail() { echo "gh: stub has no fixture for:$a (HTTP 404)" >&2; exit 1; } +case "$a" in + *"orgs/jlt-commons/repos"*) out "$D/org-repos.json" ;; + *"repos/jlt-commons/brokenrepo/contents/"*) echo "HTTP 500" >&2; exit 1 ;; + *"repos/jlt-commons/"*"/contents/.github/workflows/ci.yml"*) + p=${a#*repos/jlt-commons/}; p=${p%%/*}; [ -f "$D/$p.ci.yml" ] || fail; cat "$D/$p.ci.yml" ;; + " api repos/jlt-commons/"*" --jq .default_branch "|*"api repos/jlt-commons/"*"--jq .default_branch"*) + p=${a#*repos/jlt-commons/}; p=${p%% *}; [ -f "$D/$p.branch" ] || fail; cat "$D/$p.branch" ;; + *"run list --repo jlt-commons/"*) + p=${a#*--repo jlt-commons/}; p=${p%% *}; [ -f "$D/$p.runs.json" ] || fail + case "$a" in *"--branch trunk"*) [ "$p" = glitter-gl ] || fail ;; esac + out "$D/$p.runs.json" ;; + *"run view "*"--repo jlt-commons/"*) + p=${a#*--repo jlt-commons/}; p=${p%% *}; [ -f "$D/$p.jobs.json" ] || fail; out "$D/$p.jobs.json" ;; + *) fail ;; +esac +S + chmod +x "$BATS_TMPDIR/gh-stub" + export GH="$BATS_TMPDIR/gh-stub" FIXTURE_DIR="$ROOT/test/fixtures/gh" + cat > "$BATS_TMPDIR/fleet.json" <<'F' +{"projects":["glitter","glitter-gl","glitter-uikit","ghost"],"excluded":{"jolt-lsp":"releases jolt-lsp","secretrepo":"private"}} +F + export FLEET_JSON="$BATS_TMPDIR/fleet.json" +} + +own() { bash "$ROOT/scripts/collect-own-pin.sh" 2>"$BATS_TMPDIR/err"; } +unc() { bash "$ROOT/scripts/collect-uncovered.sh" 2>"$BATS_TMPDIR/err"; } + +@test "own-pin: one entry per fleet project" { + run own; [ "$status" -eq 0 ] + [ "$(jq length <<<"$output")" -eq 4 ] + [ "$(jq -r '[.[].name]|join(",")' <<<"$output")" = "glitter,glitter-gl,glitter-uikit,ghost" ] +} +@test "own-pin: pass run with literal pin" { + run own + jq -e '.[0] | .pin==null and .result=="pass" and .run_url=="https://github.com/jlt-commons/glitter/actions/runs/1" and .finished_at=="2026-11-19T10:00:00Z" and .failed_step==null' <<<"$output" +} +@test "own-pin: default branch is used, failed run names the failed step, pin parsed" { + run own + jq -e '.[1] | .pin=="0.8.24" and .result=="fail" and .failed_step=="Run tests"' <<<"$output" +} +@test "own-pin: no push run yet is not-run, non-literal pin is null" { + run own + jq -e '.[2] | .result=="not-run" and .pin==null and .run_url==null and .finished_at==null' <<<"$output" +} +@test "own-pin: a repo whose API fails is not-run, warns, and does not abort" { + run own + jq -e '.[3] | .name=="ghost" and .result=="not-run" and .pin==null' <<<"$output" + grep -q 'ghost' "$BATS_TMPDIR/err" +} +@test "own-pin: conclusion mapping" { + for c in success:pass failure:fail timed_out:timed-out cancelled:not-run skipped:not-run neutral:not-run null:not-run; do + echo "[{\"conclusion\":${c%%:*},\"url\":\"u\",\"updatedAt\":\"t\",\"databaseId\":1}]" | sed 's/:\([a-z_]*\),/:"\1",/; s/:"null"/:null/' > "$BATS_TMPDIR/runs.json" + cp "$BATS_TMPDIR/runs.json" "$FIXTURE_DIR/zz.runs.json"; echo main > "$FIXTURE_DIR/zz.branch" + echo '{"projects":["zz"],"excluded":{}}' > "$FLEET_JSON" + run own; [ "$(jq -r '.[0].result' <<<"$output")" = "${c##*:}" ] || { echo "$c -> $output"; rm -f "$FIXTURE_DIR"/zz.*; return 1; } + rm -f "$FIXTURE_DIR"/zz.* + done +} +@test "own-pin: GH may be several words" { + export GH="env X=1 $BATS_TMPDIR/gh-stub" + run own; [ "$(jq length <<<"$output")" -eq 4 ] +} + +@test "uncovered: reasons per repo, fleet members and archived/private skipped" { + run unc; [ "$status" -eq 0 ] + [ "$(jq -r '.[]|select(.name=="jolt-lsp").reason' <<<"$output")" = "excluded: releases jolt-lsp" ] + [ "$(jq -r '.[]|select(.name=="nociyml").reason' <<<"$output")" = "no ci.yml" ] + [ "$(jq -r '.[]|select(.name=="noinput").reason' <<<"$output")" = "ci.yml has no jolt-version input" ] + [ "$(jq -r '.[]|select(.name=="readyrepo").reason' <<<"$output")" = "ready, not yet in fleet.json" ] + [ "$(jq '[.[]|select(.name=="glitter")]|length' <<<"$output")" -eq 0 ] + [ "$(jq '[.[]|select(.name=="oldrepo" or .name=="secretrepo")]|length' <<<"$output")" -eq 0 ] +} +@test "uncovered: a repo that cannot be read gets a reason and a warning" { + run unc + [ "$(jq -r '.[]|select(.name=="brokenrepo").reason' <<<"$output")" = "could not read repository" ] + grep -q brokenrepo "$BATS_TMPDIR/err" +} +@test "uncovered: on key parsed as boolean true still finds the input" { + echo '{"projects":[],"excluded":{}}' > "$FLEET_JSON" + run unc + [ "$(jq -r '.[]|select(.name=="glitter").reason' <<<"$output")" = "ready, not yet in fleet.json" ] +} diff --git a/test/fixtures/gh/glitter-gl.branch b/test/fixtures/gh/glitter-gl.branch new file mode 100644 index 0000000..b5d9bfd --- /dev/null +++ b/test/fixtures/gh/glitter-gl.branch @@ -0,0 +1 @@ +trunk diff --git a/test/fixtures/gh/glitter-gl.ci.yml b/test/fixtures/gh/glitter-gl.ci.yml new file mode 100644 index 0000000..3d205af --- /dev/null +++ b/test/fixtures/gh/glitter-gl.ci.yml @@ -0,0 +1,2 @@ +env: + JOLT_VERSION: ${{ inputs.jolt-version || '0.8.24' }} diff --git a/test/fixtures/gh/glitter-gl.jobs.json b/test/fixtures/gh/glitter-gl.jobs.json new file mode 100644 index 0000000..5e99702 --- /dev/null +++ b/test/fixtures/gh/glitter-gl.jobs.json @@ -0,0 +1 @@ +{"jobs":[{"conclusion":"success","steps":[{"name":"Checkout","conclusion":"success"}]},{"conclusion":"failure","steps":[{"name":"Install","conclusion":"success"},{"name":"Run tests","conclusion":"failure"}]}]} diff --git a/test/fixtures/gh/glitter-gl.runs.json b/test/fixtures/gh/glitter-gl.runs.json new file mode 100644 index 0000000..95fae20 --- /dev/null +++ b/test/fixtures/gh/glitter-gl.runs.json @@ -0,0 +1 @@ +[{"conclusion":"failure","url":"https://github.com/jlt-commons/glitter-gl/actions/runs/2","updatedAt":"2026-11-19T11:00:00Z","databaseId":2}] diff --git a/test/fixtures/gh/glitter-uikit.branch b/test/fixtures/gh/glitter-uikit.branch new file mode 100644 index 0000000..ba2906d --- /dev/null +++ b/test/fixtures/gh/glitter-uikit.branch @@ -0,0 +1 @@ +main diff --git a/test/fixtures/gh/glitter-uikit.ci.yml b/test/fixtures/gh/glitter-uikit.ci.yml new file mode 100644 index 0000000..7cd135b --- /dev/null +++ b/test/fixtures/gh/glitter-uikit.ci.yml @@ -0,0 +1,2 @@ +env: + JOLT_VERSION: ${{ needs.x.outputs.v }} diff --git a/test/fixtures/gh/glitter-uikit.runs.json b/test/fixtures/gh/glitter-uikit.runs.json new file mode 100644 index 0000000..fe51488 --- /dev/null +++ b/test/fixtures/gh/glitter-uikit.runs.json @@ -0,0 +1 @@ +[] diff --git a/test/fixtures/gh/glitter.branch b/test/fixtures/gh/glitter.branch new file mode 100644 index 0000000..ba2906d --- /dev/null +++ b/test/fixtures/gh/glitter.branch @@ -0,0 +1 @@ +main diff --git a/test/fixtures/gh/glitter.ci.yml b/test/fixtures/gh/glitter.ci.yml new file mode 100644 index 0000000..10367c6 --- /dev/null +++ b/test/fixtures/gh/glitter.ci.yml @@ -0,0 +1,7 @@ +name: ci +true: + workflow_dispatch: + inputs: + jolt-version: + type: string +jobs: {} diff --git a/test/fixtures/gh/glitter.runs.json b/test/fixtures/gh/glitter.runs.json new file mode 100644 index 0000000..d6cf47d --- /dev/null +++ b/test/fixtures/gh/glitter.runs.json @@ -0,0 +1 @@ +[{"conclusion":"success","url":"https://github.com/jlt-commons/glitter/actions/runs/1","updatedAt":"2026-11-19T10:00:00Z","databaseId":1}] diff --git a/test/fixtures/gh/jolt-lsp.ci.yml b/test/fixtures/gh/jolt-lsp.ci.yml new file mode 100644 index 0000000..8ccd833 --- /dev/null +++ b/test/fixtures/gh/jolt-lsp.ci.yml @@ -0,0 +1,7 @@ +name: ci +on: + workflow_dispatch: + inputs: + jolt-version: + type: string +jobs: {} diff --git a/test/fixtures/gh/noinput.ci.yml b/test/fixtures/gh/noinput.ci.yml new file mode 100644 index 0000000..83b12fd --- /dev/null +++ b/test/fixtures/gh/noinput.ci.yml @@ -0,0 +1,7 @@ +name: ci +"on": + workflow_dispatch: + inputs: + other: + type: string +jobs: {} diff --git a/test/fixtures/gh/org-repos.json b/test/fixtures/gh/org-repos.json new file mode 100644 index 0000000..8d6106c --- /dev/null +++ b/test/fixtures/gh/org-repos.json @@ -0,0 +1,8 @@ +[{"name":"glitter","archived":false,"private":false}, + {"name":"jolt-lsp","archived":false,"private":false}, + {"name":"nociyml","archived":false,"private":false}, + {"name":"noinput","archived":false,"private":false}, + {"name":"readyrepo","archived":false,"private":false}, + {"name":"brokenrepo","archived":false,"private":false}, + {"name":"oldrepo","archived":true,"private":false}, + {"name":"secretrepo","archived":false,"private":true}] diff --git a/test/fixtures/gh/readyrepo.ci.yml b/test/fixtures/gh/readyrepo.ci.yml new file mode 100644 index 0000000..8ccd833 --- /dev/null +++ b/test/fixtures/gh/readyrepo.ci.yml @@ -0,0 +1,7 @@ +name: ci +on: + workflow_dispatch: + inputs: + jolt-version: + type: string +jobs: {} From 58cae55ceea2ec89966d51132e9015234de4f22e Mon Sep 17 00:00:00 2001 From: burinc Date: Fri, 20 Nov 2026 13:28:15 +1100 Subject: [PATCH 10/31] fleet: collect-uncovered only treats HTTP 404 as missing, fails loud on yq errors --- scripts/collect-uncovered.sh | 12 ++++++++---- test/collect.bats | 16 ++++++++++++++++ test/fixtures/gh/badyaml.ci.yml | 2 ++ test/fixtures/gh/org-repos.json | 2 ++ 4 files changed, 28 insertions(+), 4 deletions(-) create mode 100644 test/fixtures/gh/badyaml.ci.yml diff --git a/scripts/collect-uncovered.sh b/scripts/collect-uncovered.sh index 27d4047..05b1a3d 100755 --- a/scripts/collect-uncovered.sh +++ b/scripts/collect-uncovered.sh @@ -13,10 +13,12 @@ org=jlt-commons tmp=$(mktemp -d) trap 'rm -rf "$tmp"' EXIT +command -v yq >/dev/null 2>&1 || { echo "collect-uncovered: yq is required but not on PATH" >&2; exit 1; } + warn() { echo "collect-uncovered: $*" >&2; } reason_for() { - local p=$1 in_fleet=0 excluded has_ci=0 has_input=0 ci="$tmp/ci.yml" + local out p=$1 in_fleet=0 excluded has_ci=0 has_input=0 ci="$tmp/ci.yml" if jq -e --arg p "$p" '.projects | index($p)' "$fleet" >/dev/null; then in_fleet=1; fi excluded=$(jq -r --arg p "$p" '.excluded[$p] // ""' "$fleet") if [ "$in_fleet" = 0 ] && [ -z "$excluded" ]; then @@ -24,10 +26,12 @@ reason_for() { "repos/$org/$p/contents/.github/workflows/ci.yml" >"$ci" 2>"$tmp/err"; then has_ci=1 # YAML 1.1 readers may turn the "on" key into boolean true. - if [ "$(yq '(.on // .true) | select(tag == "!!map") | (.workflow_dispatch.inputs // {}) | has("jolt-version")' "$ci" 2>/dev/null)" = true ]; then - has_input=1 + if ! out=$(yq '(.on // .true) | select(tag == "!!map") | (.workflow_dispatch.inputs // {}) | has("jolt-version")' "$ci" 2>"$tmp/err"); then + warn "$p: could not parse ci.yml: $(tail -n1 "$tmp/err")" + printf 'could not read repository\n'; return fi - elif grep -q '404' "$tmp/err"; then + [ "$out" = true ] && has_input=1 + elif grep -qE '\(HTTP 404\)[[:space:]]*$' "$tmp/err"; then has_ci=0 else warn "$p: could not read repository: $(tail -n1 "$tmp/err")" diff --git a/test/collect.bats b/test/collect.bats index b173623..b0d3403 100644 --- a/test/collect.bats +++ b/test/collect.bats @@ -9,6 +9,7 @@ out() { if [ -n "$jqf" ]; then jq -r "$jqf" "$1"; else cat "$1"; fi; } fail() { echo "gh: stub has no fixture for:$a (HTTP 404)" >&2; exit 1; } case "$a" in *"orgs/jlt-commons/repos"*) out "$D/org-repos.json" ;; + *"repos/jlt-commons/ratelimited/contents/"*) echo "API rate limit exceeded for installation ID 4040404 (HTTP 403)" >&2; exit 1 ;; *"repos/jlt-commons/brokenrepo/contents/"*) echo "HTTP 500" >&2; exit 1 ;; *"repos/jlt-commons/"*"/contents/.github/workflows/ci.yml"*) p=${a#*repos/jlt-commons/}; p=${p%%/*}; [ -f "$D/$p.ci.yml" ] || fail; cat "$D/$p.ci.yml" ;; @@ -89,3 +90,18 @@ unc() { bash "$ROOT/scripts/collect-uncovered.sh" 2>"$BATS_TMPDIR/err"; } run unc [ "$(jq -r '.[]|select(.name=="glitter").reason' <<<"$output")" = "ready, not yet in fleet.json" ] } +@test "uncovered: a 403 whose text contains 404 is not treated as a missing ci.yml" { + run unc + [ "$(jq -r '.[]|select(.name=="ratelimited").reason' <<<"$output")" = "could not read repository" ] + grep -q ratelimited "$BATS_TMPDIR/err" +} +@test "uncovered: unparsable ci.yml is could not read repository, with a warning" { + run unc + [ "$(jq -r '.[]|select(.name=="badyaml").reason' <<<"$output")" = "could not read repository" ] + grep -q badyaml "$BATS_TMPDIR/err" +} +@test "uncovered: missing yq fails loudly" { + mkdir -p "$BATS_TMPDIR/nobin"; for t in bash jq mktemp rm dirname cat grep tail env; do ln -sf "$(command -v $t)" "$BATS_TMPDIR/nobin/$t"; done + PATH="$BATS_TMPDIR/nobin" run bash "$ROOT/scripts/collect-uncovered.sh" + [ "$status" -ne 0 ]; [[ "$output" == *yq* ]] +} diff --git a/test/fixtures/gh/badyaml.ci.yml b/test/fixtures/gh/badyaml.ci.yml new file mode 100644 index 0000000..20b96c5 --- /dev/null +++ b/test/fixtures/gh/badyaml.ci.yml @@ -0,0 +1,2 @@ +a: [unclosed + b: : : diff --git a/test/fixtures/gh/org-repos.json b/test/fixtures/gh/org-repos.json index 8d6106c..bb870a6 100644 --- a/test/fixtures/gh/org-repos.json +++ b/test/fixtures/gh/org-repos.json @@ -4,5 +4,7 @@ {"name":"noinput","archived":false,"private":false}, {"name":"readyrepo","archived":false,"private":false}, {"name":"brokenrepo","archived":false,"private":false}, + {"name":"ratelimited","archived":false,"private":false}, + {"name":"badyaml","archived":false,"private":false}, {"name":"oldrepo","archived":true,"private":false}, {"name":"secretrepo","archived":false,"private":true}] From 45a059fa58db714c2764a71807389b5c4adfe8d8 Mon Sep 17 00:00:00 2001 From: burinc Date: Fri, 20 Nov 2026 13:35:31 +1100 Subject: [PATCH 11/31] canary: poll every 15 minutes and publish fleet status --- .github/workflows/canary.yml | 207 +++++++++++++++++++++++++++-------- .github/workflows/fanout.yml | 53 +++++++++ .github/workflows/test.yml | 4 +- scripts/publish-status.sh | 75 +++++++++++++ scripts/refresh-status.sh | 31 ++++++ test/publish-status.bats | 112 +++++++++++++++++++ test/refresh-status.bats | 26 +++++ 7 files changed, 461 insertions(+), 47 deletions(-) create mode 100755 scripts/publish-status.sh create mode 100755 scripts/refresh-status.sh create mode 100644 test/publish-status.bats create mode 100644 test/refresh-status.bats diff --git a/.github/workflows/canary.yml b/.github/workflows/canary.yml index 929f1ee..91847cc 100644 --- a/.github/workflows/canary.yml +++ b/.github/workflows/canary.yml @@ -4,16 +4,17 @@ name: canary # Ask, on a schedule, whether the jolt versions this fleet cares about still # build every project. Two of them: # -# pinned what the projects actually pin today. Read from the vars.JOLT_PIN -# repo variable, which is the live source of truth and needs -# bumping by hand once a new release is validated (fan-out it -# manually first); the script's own 0.8.1 fallback only matters if -# that variable is ever unset entirely. # latest jolt's newest published release +# nightly jolt's rolling vnightly prerelease, when fresh (see below) # -# Identical while the fleet is up to date, and the run collapses to one build -# when they are. They diverge the moment jolt ships a release nobody has adopted -# yet, which is precisely the window this is meant to cover. +# What each project pins is no longer a row here. The `status` job reads every +# project's own latest push CI run on its default branch and shows it as the +# "pin" column on the dashboard, so the pin is observed rather than configured +# (vars.JOLT_PIN is not read any more). +# +# Every run also ends with the `status` job, which merges the results into +# status.json and history.json on the `status` branch. The fleet page reads +# those two files. # # NIGHTLY IS AVAILABLE NOW, and this block used to say it was not. jolt-lang/jolt#824 # merged 2026-09-02 and jolt publishes a rolling `vnightly` prerelease from main, @@ -58,30 +59,34 @@ name: canary # would see the literal string "nightly", find it unchanged from yesterday, and # suppress every future nightly run after the first green. # -# The pinned and latest rows are RELEASES, which have none of this problem: a -# release is immutable once published, so its row means what it says. +# The latest row is a RELEASE, which has none of this problem: a release is +# immutable once published, so its row means what it says. # -# TWO GATES, so an hourly tick is cheap: +# TWO GATES, so a 15-minute tick is cheap: # -# interval vars.CANARY_INTERVAL_HOURS (default 1). The cron itself cannot be -# a variable, GitHub requires a literal, so the schedule ticks -# hourly and this decides whether a tick does anything. +# interval vars.CANARY_INTERVAL_HOURS (default 0, meaning no interval gate). +# The cron itself cannot be a variable, GitHub requires a literal, +# so the schedule ticks every 15 minutes and this can hold a tick +# back when set above 0. # change a run is skipped when this exact version set has already been # tested green. Keyed in the Actions cache, so no extra permissions # and nothing to commit back to the repository. # +# A gated tick still runs the `status` job, so the pin column and the dashboard's +# timestamp keep moving while jolt stands still. +# # A manual dispatch ignores both gates. That is the point of a manual dispatch. # --------------------------------------------------------------------------- on: schedule: - # Hourly, at 7 past. Not on the hour, where GitHub's scheduler is most - # congested and most likely to delay or drop a run. - - cron: "7 * * * *" + # Every 15 minutes, offset from the quarter hours, where GitHub's + # scheduler is most congested and most likely to delay or drop a run. + - cron: "7,22,37,52 * * * *" workflow_dispatch: inputs: jolt-version: - description: "Test only this version (blank = the pinned + latest pair)" + description: "Test only this version (blank = latest, plus nightly when fresh)" required: false default: "" @@ -90,6 +95,13 @@ permissions: issues: write actions: read +# One canary at a time. A run that outlives its 15-minute tick must not race +# the next one on the status branch, and cancelling it would lose its results, +# so later runs wait (GitHub keeps only the newest waiting one). +concurrency: + group: canary + cancel-in-progress: false + jobs: plan: name: plan @@ -100,40 +112,43 @@ jobs: reason: ${{ steps.decide.outputs.reason }} key: ${{ steps.decide.outputs.key }} nightly: ${{ steps.decide.outputs.nightly }} + latest: ${{ steps.decide.outputs.latest }} + nightly_json: ${{ steps.decide.outputs.nightly_json }} steps: - name: Work out what to test, and whether to bother id: decide env: REQUESTED: ${{ inputs.jolt-version }} - PIN: ${{ vars.JOLT_PIN }} INTERVAL_HOURS: ${{ vars.CANARY_INTERVAL_HOURS }} NIGHTLY_MAX_AGE_HOURS: ${{ vars.NIGHTLY_MAX_AGE_HOURS }} EVENT: ${{ github.event_name }} GH_TOKEN: ${{ github.token }} run: | set -euo pipefail - pin="${PIN:-0.8.1}" - interval="${INTERVAL_HOURS:-1}" + interval="${INTERVAL_HOURS:-0}" max_age="${NIGHTLY_MAX_AGE_HOURS:-48}" nightly_pub="" nightly="" + nightly_json=null + nsha="" + + # Resolved on every event, a manual dispatch included, because the + # status page shows what latest is whatever was asked for. + latest="$(curl -fsSL https://api.github.com/repos/jolt-lang/jolt/releases/latest \ + | sed -n 's/.*"tag_name": *"\([^"]*\)".*/\1/p' | head -1)" + latest="${latest#v}" + [ -n "$latest" ] || { echo "could not resolve jolt's latest release" >&2; exit 1; } + echo "latest=$latest" >> "$GITHUB_OUTPUT" if [ -n "$REQUESTED" ]; then versions="[\"$REQUESTED\"]" nightly="manual dispatch of $REQUESTED, freshness gate not applied" echo "manual dispatch, testing $REQUESTED only" else - latest="$(curl -fsSL https://api.github.com/repos/jolt-lang/jolt/releases/latest \ - | sed -n 's/.*"tag_name": *"\([^"]*\)".*/\1/p' | head -1)" - latest="${latest#v}" - [ -n "$latest" ] || { echo "could not resolve jolt's latest release" >&2; exit 1; } - - # The release rows first, because the nightly block compares against - # them. $latest is dropped when it equals the pin, so a current fleet - # collapses to one release build. - set -- "$pin" - [ "$latest" != "$pin" ] && set -- "$@" "$latest" + # The release row first, because the nightly block compares against + # it. + set -- "$latest" # The nightly is a PRERELEASE, so releases/latest never returns it and # the two resolutions cannot collide. Read it by tag. @@ -180,12 +195,17 @@ jobs: fi fi - [ -n "$nightly_pub" ] && set -- "$@" "nightly" + if [ -n "$nightly_pub" ]; then + set -- "$@" "nightly" + nightly_json="$(jq -nc --arg p "$nightly_pub" --arg s "$nsha" --arg n "$nightly" \ + '{published_at: $p, sha: $s, note: $n}')" + fi versions="[$(printf '"%s",' "$@" | sed 's/,$//')]" echo "testing $versions" fi echo "versions=$versions" >> "$GITHUB_OUTPUT" echo "nightly=$nightly" >> "$GITHUB_OUTPUT" + echo "nightly_json=$nightly_json" >> "$GITHUB_OUTPUT" echo "$nightly" # The cache key IS the change detector. A new jolt release changes the @@ -205,12 +225,19 @@ jobs: exit 0 fi + # Interval 0 means no gate: every tick may run. + if [ "$interval" = "0" ]; then + echo "proceed=true" >> "$GITHUB_OUTPUT" + echo "reason=no interval gate" >> "$GITHUB_OUTPUT" + exit 0 + fi + # Interval gate, measured from the last canary that actually BUILT # something, not the last tick. # # A gated tick still finishes as a run whose conclusion is "success" - # (plan succeeded, everything downstream skipped), so counting runs - # would reset the clock every hour and an interval above 1 would never + # (plan and status succeeded, the matrix skipped), so counting runs + # would reset the clock every tick and an interval above 1 would never # come due. The tell is whether a run has any `jolt ` job: # those exist only when the matrix actually ran. last="" @@ -277,8 +304,8 @@ jobs: strategy: fail-fast: false # ONE version at a time. Each leg's fan-out dispatches every project's - # own ci.yml on `main`, and with two or three legs in flight together - # that is two or three near-simultaneous workflow_dispatch calls + # own ci.yml on `main`, and with both legs in flight together + # that is two near-simultaneous workflow_dispatch calls # against the SAME project on the SAME ref. raylib-ios's concurrency # group cancels unconditionally (`cancel-in-progress: true`, no ref # guard), so its earlier dispatches die within a couple of seconds of @@ -294,17 +321,74 @@ jobs: # #5) for a version nothing actually failed against - every leg that # finished normally that run was green. max-parallel: 1 removes the # race outright: legs run one after another, so no project is ever - # dispatched twice at once. Costs wall-clock (up to ~3x on a run that - # tests all three rows), not correctness, and an hourly cron has the - # room. + # dispatched twice at once. Costs wall-clock (up to ~2x on a run that + # tests both rows), not correctness, and the concurrency group keeps + # overlapping ticks from stacking up. max-parallel: 1 matrix: version: ${{ fromJSON(needs.plan.outputs.versions) }} + # A called workflow cannot hold more than its caller grants, and fan-out's + # ad-hoc publish job asks for contents: write. It skips under canary, but + # GitHub checks the request when it parses the file, so the cap is raised + # here. fan-out's own jobs still declare contents: read. + permissions: + contents: write + actions: read uses: ./.github/workflows/fanout.yml with: jolt-version: ${{ matrix.version }} secrets: inherit + # Merge this run's results into status.json and history.json on the `status` + # branch. Runs on gated ticks too (no results files then), so the pin column + # and the timestamp keep moving. contents: write is granted here and nowhere + # else; the App token is only for the collectors' cross-repo reads. + status: + needs: [plan, fleet] + if: always() && needs.plan.result == 'success' + runs-on: ubuntu-latest + permissions: + contents: write + actions: read + steps: + - uses: actions/checkout@v7 + + - name: Mint an installation token + id: token + uses: actions/create-github-app-token@v3 + with: + client-id: ${{ secrets.APP_CLIENT_ID }} + private-key: ${{ secrets.APP_PRIVATE_KEY }} + owner: jlt-commons + + # Reusable-workflow artifacts belong to this (the caller's) run. A gated + # tick has none, which downloads nothing and is not an error. + - uses: actions/download-artifact@v8 + with: + pattern: results-* + path: results + + - name: Publish the fleet status + env: + GH_TOKEN: ${{ steps.token.outputs.token }} + LATEST: ${{ needs.plan.outputs.latest }} + NIGHTLY_JSON: ${{ needs.plan.outputs.nightly_json }} + CANARY_RUN: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + set -euo pipefail + # REBUILD is a command string for publish-status.sh to run with sh -c, + # so the quotes are meant literally. + # shellcheck disable=SC2089,SC2090 + REBUILD='bash scripts/refresh-status.sh "$OUT_DIR"' + if [ -d results ]; then + while IFS= read -r f; do REBUILD="$REBUILD '$PWD/$f'"; done \ + < <(find results -name results.json | sort) + fi + # shellcheck disable=SC2090 + export REBUILD + echo "REBUILD: $REBUILD" + bash scripts/publish-status.sh "$RUNNER_TEMP/status-out" + report: needs: [plan, fleet] if: always() && needs.plan.outputs.proceed == 'true' @@ -319,15 +403,21 @@ jobs: owner: jlt-commons repositories: ci-builds + # needs.fleet.outputs.failed holds one matrix leg's value, so the verdict + # is read from every leg's results file instead. + - uses: actions/download-artifact@v8 + with: + pattern: results-* + path: results + - name: Open, update or close the canary issue env: GH_TOKEN: ${{ steps.token.outputs.token }} RESULT: ${{ needs.fleet.result }} - FAILED: ${{ needs.fleet.outputs.failed }} - INFRA: ${{ needs.fleet.outputs.infra }} VERSIONS: ${{ needs.plan.outputs.versions }} NIGHTLY: ${{ needs.plan.outputs.nightly }} RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + DASHBOARD: https://jlt-commons.github.io/fleet/ run: | set -euo pipefail TITLE="canary: jolt breaks the fleet" @@ -335,10 +425,34 @@ jobs: --search "$TITLE in:title" --limit 1 \ --json number --jq '.[0].number // ""') - if [ "$RESULT" = "success" ]; then + # Verdict from the merged results: "name (version)" per bad cell. + # fail, mismatch, timed-out and dispatch-failed are findings about + # jolt or the build; infra is our own misconfiguration and is + # reported separately. + files=() + if [ -d results ]; then + while IFS= read -r f; do files+=("$f"); done < <(find results -name results.json | sort) + fi + FAILED="" INFRA="" + if [ "${#files[@]}" -gt 0 ]; then + FAILED=$(jq -rs '[.[] | .requested as $v | .projects[] + | select(.result | IN("fail","mismatch","timed-out","dispatch-failed")) + | "\(.name) (\($v))"] | unique | join(", ")' "${files[@]}") + INFRA=$(jq -rs '[.[] | .requested as $v | .projects[] + | select(.result == "infra") | "\(.name) (\($v))"] | unique | join(", ")' "${files[@]}") + fi + + # The fleet job failed but no project says why (a leg crashed before + # uploading results): still a failure, never a quiet green. + unclassified="" + if [ -z "$FAILED" ] && [ -z "$INFRA" ] && [ "$RESULT" != "success" ]; then + unclassified=1 + fi + + if [ -z "$FAILED" ] && [ -z "$INFRA" ] && [ -z "$unclassified" ]; then if [ -n "$existing" ]; then gh issue comment "$existing" --repo "$GITHUB_REPOSITORY" \ - --body "Recovered. The fleet builds against ${VERSIONS}. ${NIGHTLY}. [Run](${RUN_URL})" + --body "Recovered. The fleet builds against ${VERSIONS}. ${NIGHTLY}. [Run](${RUN_URL}) Dashboard: ${DASHBOARD}" gh issue close "$existing" --repo "$GITHUB_REPOSITORY" echo "closed #$existing" else @@ -354,7 +468,7 @@ jobs: # A failure that is really our own misconfiguration should not be # filed as a fact about jolt. fanout reports those separately. - if [ -n "${INFRA:-}" ] && [ -z "${FAILED:-}" ]; then + if [ -n "$INFRA" ] && [ -z "$FAILED" ]; then body=$(printf '%s\n' \ "jolt could not be INSTALLED for: ${INFRA}" \ "" \ @@ -365,16 +479,17 @@ jobs: "" \ "**Versions tested:** ${VERSIONS}" \ "" \ - "[Run](${RUN_URL}) has the per-project table.") + "[Run](${RUN_URL}) has the per-project table. Dashboard: ${DASHBOARD}") else body=$(printf '%s\n' \ "The fleet does not build against every jolt version it is meant to." \ "" \ "**Versions tested:** ${VERSIONS}" \ - "**Failing:** ${broke:-see the run}" \ + "**Failing:** ${FAILED:-${broke:-see the run}}" \ "**Nightly:** ${NIGHTLY:-not resolved}" \ "" \ "[Run](${RUN_URL}) has a per-project table for each version." \ + "Dashboard: ${DASHBOARD}" \ "" \ "This issue closes itself once a later canary passes. Reproduce one" \ "project by dispatching its own ci.yml with the \`jolt-version\` input.") diff --git a/.github/workflows/fanout.yml b/.github/workflows/fanout.yml index bdb88a9..6d2a3c3 100644 --- a/.github/workflows/fanout.yml +++ b/.github/workflows/fanout.yml @@ -343,3 +343,56 @@ jobs: name: ${{ steps.run.outputs.artifact || format('results-{0}', steps.version.outputs.version) }} path: ${{ steps.run.outputs.results_dir }}/results.json if-no-files-found: warn + + # An ad-hoc (workflow_dispatch) fan-out publishes its own result to the status + # page's history. Under workflow_call github.workflow is the CALLER's name, so + # this skips under canary, whose own `status` job publishes instead. It adds + # to history only: --nightly-json null keeps the grid's nightly cells as they + # were. + publish-adhoc: + needs: fanout + if: always() && github.workflow == 'fan-out' + runs-on: ubuntu-latest + permissions: + contents: write + actions: read + steps: + - uses: actions/checkout@v7 + + - name: Mint an installation token + id: token + uses: actions/create-github-app-token@v3 + with: + client-id: ${{ secrets.APP_CLIENT_ID }} + private-key: ${{ secrets.APP_PRIVATE_KEY }} + owner: jlt-commons + + - uses: actions/download-artifact@v8 + with: + pattern: results-* + path: results + + - name: Publish the fleet status + env: + GH_TOKEN: ${{ steps.token.outputs.token }} + NIGHTLY_JSON: "null" + CANARY_RUN: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + set -euo pipefail + latest="$(curl -fsSL https://api.github.com/repos/jolt-lang/jolt/releases/latest \ + | sed -n 's/.*"tag_name": *"\([^"]*\)".*/\1/p' | head -1)" + latest="${latest#v}" + [ -n "$latest" ] || { echo "could not resolve jolt's latest release" >&2; exit 1; } + export LATEST="$latest" + # REBUILD is a command string for publish-status.sh to run with sh -c, + # so the quotes are meant literally. + # shellcheck disable=SC2089,SC2090 + REBUILD='bash scripts/refresh-status.sh "$OUT_DIR"' + if [ -d results ]; then + while IFS= read -r f; do REBUILD="$REBUILD '$PWD/$f'"; done \ + < <(find results -name results.json | sort) + fi + # shellcheck disable=SC2090 + export REBUILD + echo "REBUILD: $REBUILD" + bash scripts/publish-status.sh "$RUNNER_TEMP/status-out" diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 1e82ee2..d273447 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -2,6 +2,8 @@ name: test on: push: + # The status branch holds data files only. + branches-ignore: [status] pull_request: jobs: @@ -11,4 +13,4 @@ jobs: - uses: actions/checkout@v7 - run: sudo apt-get install -y bats - run: bats test/ - - run: shellcheck -x scripts/lib/*.sh scripts/build-status.sh scripts/collect-own-pin.sh scripts/collect-uncovered.sh + - run: shellcheck -x scripts/lib/*.sh scripts/build-status.sh scripts/collect-own-pin.sh scripts/collect-uncovered.sh scripts/publish-status.sh scripts/refresh-status.sh diff --git a/scripts/publish-status.sh b/scripts/publish-status.sh new file mode 100755 index 0000000..d7d4c2c --- /dev/null +++ b/scripts/publish-status.sh @@ -0,0 +1,75 @@ +#!/usr/bin/env bash +# Commit status.json and history.json to the orphan `status` branch of origin. +# +# usage: REBUILD='' publish-status.sh +# +# Run inside a checkout whose origin it can push to. REBUILD runs on every +# attempt, the first included, with PREV_DIR (the freshly fetched status-branch +# files, which may be absent) and OUT_DIR () in its environment, and +# must write OUT_DIR/status.json and OUT_DIR/history.json. Per attempt: fetch, +# worktree at the branch tip, REBUILD, compare, commit, push. A rejected push +# means someone else published meanwhile, so the next attempt rebuilds on top +# of their result. Three attempts, then non-zero. +# +# "Unchanged" ignores generated_at and canary_run in status.json (both change +# every tick) and is byte-exact for history.json. +set -euo pipefail + +[ $# -eq 1 ] || { echo "usage: REBUILD=... publish-status.sh " >&2; exit 2; } +[ -n "${REBUILD:-}" ] || { echo "publish-status: REBUILD is required" >&2; exit 2; } +out=$1 +mkdir -p "$out" +out=$(cd "$out" && pwd) + +tmp=$(mktemp -d) +wt="$tmp/wt" +trap 'git worktree remove --force "$wt" 2>/dev/null || true; git worktree prune; rm -rf "$tmp"' EXIT + +norm() { jq -S 'del(.generated_at, .canary_run)' "$1"; } +bot=(-c user.name="github-actions[bot]" -c user.email="41898282+github-actions[bot]@users.noreply.github.com") + +for attempt in 1 2 3; do + rm -rf "$tmp/prev"; mkdir -p "$tmp/prev" + git worktree remove --force "$wt" 2>/dev/null || true + rm -rf "$wt" + + rc=0 + git ls-remote --exit-code --heads origin status >/dev/null 2>&1 || rc=$? + case "$rc" in + 0) + git fetch --quiet origin +refs/heads/status:refs/remotes/origin/status + git worktree add --quiet --detach "$wt" refs/remotes/origin/status + for f in status.json history.json; do + [ -f "$wt/$f" ] && cp "$wt/$f" "$tmp/prev/$f" + done + ;; + 2) + git worktree add --quiet --detach "$wt" HEAD + git -C "$wt" checkout --quiet --orphan status + git -C "$wt" rm -rfq . + ;; + *) echo "publish-status: cannot reach origin (ls-remote exit $rc)" >&2; exit 1 ;; + esac + + PREV_DIR="$tmp/prev" OUT_DIR="$out" sh -c "$REBUILD" + [ -f "$out/status.json" ] && [ -f "$out/history.json" ] \ + || { echo "publish-status: REBUILD did not write both files in $out" >&2; exit 1; } + + if [ -f "$wt/status.json" ] && [ -f "$wt/history.json" ] \ + && cmp -s "$out/history.json" "$wt/history.json" \ + && [ "$(norm "$out/status.json")" = "$(norm "$wt/status.json")" ]; then + echo "status: unchanged" + exit 0 + fi + + cp "$out/status.json" "$out/history.json" "$wt/" + git -C "$wt" add status.json history.json + git -C "$wt" "${bot[@]}" commit --quiet -m "status: update fleet status" + if git -C "$wt" push --quiet origin HEAD:refs/heads/status; then + echo "status: published (attempt $attempt)" + exit 0 + fi + echo "publish-status: push rejected on attempt $attempt, retrying" >&2 +done +echo "publish-status: gave up after 3 rejected pushes" >&2 +exit 1 diff --git a/scripts/refresh-status.sh b/scripts/refresh-status.sh new file mode 100755 index 0000000..bbd309d --- /dev/null +++ b/scripts/refresh-status.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +# Collect and build the fleet status files; publish-status.sh calls this as its +# REBUILD command, and so does the ad-hoc publish job in fanout.yml. +# +# usage: refresh-status.sh [results.json ...] +# env: LATEST jolt's latest release (a leading v is fine) +# NIGHTLY_JSON compact {"published_at","sha","note"} or the literal null +# CANARY_RUN URL of the run that is publishing +# PREV_DIR directory holding the previous status.json/history.json +# (may be absent or empty); set by publish-status.sh +# GH_TOKEN, GH, FLEET_JSON as for the collectors +set -euo pipefail + +[ $# -ge 1 ] || { echo "usage: refresh-status.sh [results.json ...]" >&2; exit 2; } +for v in LATEST NIGHTLY_JSON CANARY_RUN; do + [ -n "${!v:-}" ] || { echo "refresh-status: $v is required" >&2; exit 2; } +done +out=$1; shift +root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) +prev=${PREV_DIR:-/nonexistent} +tmp=$(mktemp -d) +trap 'rm -rf "$tmp"' EXIT + +"$root/scripts/collect-own-pin.sh" > "$tmp/own-pin.json" +"$root/scripts/collect-uncovered.sh" > "$tmp/uncovered.json" + +"$root/scripts/build-status.sh" \ + --prev-status "$prev/status.json" --prev-history "$prev/history.json" \ + --own-pin "$tmp/own-pin.json" --uncovered "$tmp/uncovered.json" \ + --latest "$LATEST" --nightly-json "$NIGHTLY_JSON" --canary-run "$CANARY_RUN" \ + --now "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --out-dir "$out" "$@" diff --git a/test/publish-status.bats b/test/publish-status.bats new file mode 100644 index 0000000..3cd0be9 --- /dev/null +++ b/test/publish-status.bats @@ -0,0 +1,112 @@ +setup() { + ROOT="$BATS_TEST_DIRNAME/.." + T=$(mktemp -d "$BATS_TMPDIR/pub.XXXXXX") + git init -q --bare "$T/origin.git" + git init -q -b main "$T/work" + git -C "$T/work" config user.email t@example.com + git -C "$T/work" config user.name t + git -C "$T/work" remote add origin "$T/origin.git" + echo x > "$T/work/README" + git -C "$T/work" add README + git -C "$T/work" commit -q -m init + git -C "$T/work" push -q origin main + export T + # Default REBUILD: write fixed files regardless of PREV_DIR. + cat > "$T/rebuild-fixed.sh" <<'R' +#!/usr/bin/env bash +mkdir -p "$OUT_DIR" +echo "{\"schema\":1,\"generated_at\":\"$(date +%s%N)\",\"canary_run\":\"run-$(date +%s%N)\",\"projects\":[\"a\"]}" > "$OUT_DIR/status.json" +echo '{"schema":1,"adhoc":[]}' > "$OUT_DIR/history.json" +R + chmod +x "$T/rebuild-fixed.sh" +} + +pub() { (cd "$T/work" && REBUILD="$1" bash "$ROOT/scripts/publish-status.sh" "$T/out"); } +remote_show() { git -C "$T/origin.git" show "status:$1"; } + +@test "creates the branch on first publish" { + run pub "$T/rebuild-fixed.sh" + [ "$status" -eq 0 ] + [ "$(git -C "$T/origin.git" rev-list --count status)" -eq 1 ] + [ "$(remote_show status.json | jq '.projects|length')" -eq 1 ] + [ "$(remote_show history.json | jq .schema)" -eq 1 ] + # orphan: no README from main + run git -C "$T/origin.git" show status:README + [ "$status" -ne 0 ] + [ "$(git -C "$T/origin.git" log -1 --format=%an status)" = "github-actions[bot]" ] +} + +@test "no commit when only generated_at and canary_run changed" { + pub "$T/rebuild-fixed.sh" + before=$(git -C "$T/origin.git" rev-parse status) + run pub "$T/rebuild-fixed.sh" + [ "$status" -eq 0 ] + [[ "$output" == *"status: unchanged"* ]] + [ "$(git -C "$T/origin.git" rev-parse status)" = "$before" ] +} + +@test "commits when history.json changes" { + pub "$T/rebuild-fixed.sh" + before=$(git -C "$T/origin.git" rev-parse status) + cat > "$T/rebuild-hist.sh" <<'R' +#!/usr/bin/env bash +echo '{"schema":1,"projects":["a"]}' > "$OUT_DIR/status.json" +echo '{"schema":1,"adhoc":[1]}' > "$OUT_DIR/history.json" +R + run pub "bash $T/rebuild-hist.sh" + [ "$status" -eq 0 ] + [ "$(git -C "$T/origin.git" rev-parse status)" != "$before" ] + [ "$(remote_show history.json | jq '.adhoc|length')" -eq 1 ] +} + +@test "retries after a concurrent push and keeps both results" { + pub "$T/rebuild-fixed.sh" + # REBUILD adds its own project to whatever PREV_DIR holds. On the first + # attempt it also pushes a competing commit (project "theirs") after the + # fetch, so our push is rejected and attempt 2 must rebuild on top of it. + cat > "$T/rebuild-merge.sh" <<'R' +#!/usr/bin/env bash +set -e +n=$(cat "$T/attempts" 2>/dev/null || echo 0); n=$((n+1)); echo "$n" > "$T/attempts" +if [ "$n" -eq 1 ]; then + c=$(mktemp -d "$T/rival.XXXXXX") + git clone -q --branch status "$T/origin.git" "$c" + jq '.projects += ["theirs"]' "$c/status.json" > "$c/s" && mv "$c/s" "$c/status.json" + git -C "$c" -c user.email=r@example.com -c user.name=rival commit -q -am rival + git -C "$c" push -q origin status +fi +mkdir -p "$OUT_DIR" +jq '.projects += ["ours"]' "$PREV_DIR/status.json" > "$OUT_DIR/status.json" +cp "$PREV_DIR/history.json" "$OUT_DIR/history.json" +R + run pub "bash $T/rebuild-merge.sh" + [ "$status" -eq 0 ] + [ "$(cat "$T/attempts")" -eq 2 ] + [ "$(remote_show status.json | jq -c '.projects|sort')" = '["a","ours","theirs"]' ] +} + +@test "gives up after 3 rejections with non-zero exit" { + pub "$T/rebuild-fixed.sh" + cat > "$T/rebuild-lose.sh" <<'R' +#!/usr/bin/env bash +set -e +n=$(cat "$T/attempts" 2>/dev/null || echo 0); n=$((n+1)); echo "$n" > "$T/attempts" +c=$(mktemp -d "$T/rival.XXXXXX") +git clone -q --branch status "$T/origin.git" "$c" +echo "{\"schema\":1,\"projects\":[\"rival$n\"]}" > "$c/status.json" +git -C "$c" -c user.email=r@example.com -c user.name=rival commit -q -am "rival $n" +git -C "$c" push -q origin status +mkdir -p "$OUT_DIR" +echo "{\"schema\":1,\"projects\":[\"ours$n\"]}" > "$OUT_DIR/status.json" +echo '{"schema":1}' > "$OUT_DIR/history.json" +R + run pub "bash $T/rebuild-lose.sh" + [ "$status" -ne 0 ] + [ "$(cat "$T/attempts")" -eq 3 ] +} + +@test "fails without REBUILD" { + run bash -c "cd '$T/work' && env -u REBUILD bash '$ROOT/scripts/publish-status.sh' '$T/out'" + [ "$status" -ne 0 ] + [[ "$output" == *"REBUILD"* ]] +} diff --git a/test/refresh-status.bats b/test/refresh-status.bats new file mode 100644 index 0000000..ed758a4 --- /dev/null +++ b/test/refresh-status.bats @@ -0,0 +1,26 @@ +setup() { + ROOT="$BATS_TEST_DIRNAME/.." + F="$ROOT/test/fixtures/status" + # Copy the scripts so the network collectors can be replaced by stubs that + # print fixtures; refresh-status.sh finds its siblings relative to itself. + S="$BATS_TEST_TMPDIR/ci" + mkdir -p "$S" + cp -R "$ROOT/scripts" "$S/scripts" + printf '#!/usr/bin/env bash\ncat %q\n' "$F/own-pin.json" > "$S/scripts/collect-own-pin.sh" + printf '#!/usr/bin/env bash\ncat %q\n' "$F/uncovered.json" > "$S/scripts/collect-uncovered.sh" +} + +@test "refresh-status writes status.json and history.json from collectors and results" { + export LATEST=0.8.27 NIGHTLY_JSON=null CANARY_RUN=https://example/run/1 + PREV_DIR="$BATS_TEST_TMPDIR/none" run bash "$S/scripts/refresh-status.sh" "$BATS_TEST_TMPDIR/out" "$F/results-latest.json" + [ "$status" -eq 0 ] + [ "$(jq .schema "$BATS_TEST_TMPDIR/out/status.json")" -eq 1 ] + [ "$(jq -c '.projects|map(.name)|sort' "$BATS_TEST_TMPDIR/out/status.json")" = '["ebb","glitter","raygui-jlt"]' ] + [ "$(jq .schema "$BATS_TEST_TMPDIR/out/history.json")" -eq 1 ] +} + +@test "refresh-status needs LATEST" { + run env -u LATEST NIGHTLY_JSON=null CANARY_RUN=x bash "$S/scripts/refresh-status.sh" "$BATS_TEST_TMPDIR/out" + [ "$status" -ne 0 ] + [[ "$output" == *"LATEST"* ]] +} From eecd418551ad57c3f0bb7a6ce7c6716d91d8cca4 Mon Sep 17 00:00:00 2001 From: burinc Date: Fri, 20 Nov 2026 13:53:23 +1100 Subject: [PATCH 12/31] fleet: keep previous jolt.nightly on null nightly-json; record vnightly for manual nightly dispatch --- .github/workflows/canary.yml | 12 ++++++++++++ scripts/build-status.sh | 2 +- test/build-status.bats | 10 ++++++++-- 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/.github/workflows/canary.yml b/.github/workflows/canary.yml index 91847cc..6c6129c 100644 --- a/.github/workflows/canary.yml +++ b/.github/workflows/canary.yml @@ -145,6 +145,18 @@ jobs: versions="[\"$REQUESTED\"]" nightly="manual dispatch of $REQUESTED, freshness gate not applied" echo "manual dispatch, testing $REQUESTED only" + # Asking for the nightly still records which build it was, so the + # status page can show it. Only the freshness and duplicate checks + # are skipped. + if [ "$REQUESTED" = "nightly" ]; then + pub="$(curl -fsSL https://api.github.com/repos/jolt-lang/jolt/releases/tags/vnightly \ + | sed -n 's/.*"published_at": *"\([^"]*\)".*/\1/p' | head -1)" + nsha="$(curl -fsSL https://api.github.com/repos/jolt-lang/jolt/git/refs/tags/vnightly \ + | sed -n 's/.*"sha": *"\([^"]*\)".*/\1/p' | head -1)" + [ -n "$pub" ] && [ -n "$nsha" ] || { echo "could not resolve vnightly" >&2; exit 1; } + nightly_json="$(jq -nc --arg p "$pub" --arg s "$nsha" --arg n "$nightly" \ + '{published_at: $p, sha: $s, note: $n}')" + fi else # The release row first, because the nightly block compares against # it. diff --git a/scripts/build-status.sh b/scripts/build-status.sh index 5d7c870..fd58de8 100755 --- a/scripts/build-status.sh +++ b/scripts/build-status.sh @@ -114,7 +114,7 @@ jq -n \ | map_values({pin: [], latest: [], nightly: [], adhoc: []} + .)) as $hist | {status: {schema: 1, generated_at: $now, canary_run: $canary, - jolt: {latest: {version: $latest}, nightly: $nj}, + jolt: {latest: {version: $latest}, nightly: ($nj // $ps.jolt.nightly // null)}, projects: $sorted, uncovered: $un}, history: {schema: 1, projects: $hist}} ' > "$tmp/both.json" diff --git a/test/build-status.bats b/test/build-status.bats index 64a7e70..f5d81d3 100644 --- a/test/build-status.bats +++ b/test/build-status.bats @@ -93,15 +93,21 @@ hi() { jq -c "$1" "$OUT/history.json"; } [ "$(st '.projects[]|select(.name=="glitter").cells.latest.result')" = '"pass"' ] } +@test "null nightly-json with no previous status gives null jolt.nightly" { + NJ_ARG=null run_bs + [ "$status" -eq 0 ] + [ "$(st '.jolt.nightly')" = null ] +} + @test "same nightly sha keeps carried nightly cells" { NJ_ARG='{"published_at":"x","sha":"aaaa1111","note":"n"}' PS="$F/prev-status.json" run_bs [ "$(st '.projects[]|select(.name=="glitter").cells.nightly.result')" = '"pass"' ] } -@test "null nightly-json keeps previous nightly cells and nightly is null" { +@test "null nightly-json keeps previous nightly cells and previous jolt.nightly" { NJ_ARG=null PS="$F/prev-status.json" run_bs [ "$status" -eq 0 ] - [ "$(st '.jolt.nightly')" = null ] + [ "$(st '.jolt.nightly')" = "$(jq -c '.jolt.nightly' "$F/prev-status.json")" ] [ "$(st '.projects[]|select(.name=="glitter").cells.nightly.result')" = '"pass"' ] } From a4c2ea7a39e8c4f1c91b1e6b65bdf1c68e3f9afb Mon Sep 17 00:00:00 2001 From: burinc Date: Fri, 20 Nov 2026 14:01:10 +1100 Subject: [PATCH 13/31] canary: stable nightly note in status.json, skip artifact download on gated ticks --- .github/workflows/canary.yml | 12 ++++++++++-- test/refresh-status.bats | 21 +++++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/.github/workflows/canary.yml b/.github/workflows/canary.yml index 6c6129c..4265842 100644 --- a/.github/workflows/canary.yml +++ b/.github/workflows/canary.yml @@ -131,6 +131,7 @@ jobs: nightly_pub="" nightly="" nightly_json=null + nightly_note="" nsha="" # Resolved on every event, a manual dispatch included, because the @@ -203,13 +204,17 @@ jobs: else nightly_pub="$pub" nightly="nightly published $pub, ${age}h old, at ${nsha:0:8}" + # The note that reaches status.json must be the same on every + # tick for this nightly, or each tick would commit. No age: + # the page works it out from published_at. + nightly_note="nightly published $pub at ${nsha:0:8}" fi fi fi if [ -n "$nightly_pub" ]; then set -- "$@" "nightly" - nightly_json="$(jq -nc --arg p "$nightly_pub" --arg s "$nsha" --arg n "$nightly" \ + nightly_json="$(jq -nc --arg p "$nightly_pub" --arg s "$nsha" --arg n "$nightly_note" \ '{published_at: $p, sha: $s, note: $n}')" fi versions="[$(printf '"%s",' "$@" | sed 's/,$//')]" @@ -374,8 +379,10 @@ jobs: owner: jlt-commons # Reusable-workflow artifacts belong to this (the caller's) run. A gated - # tick has none, which downloads nothing and is not an error. + # tick has none, so the step is skipped there rather than trusting the + # action to treat "no match" as success; the script copes with no results. - uses: actions/download-artifact@v8 + if: needs.fleet.result != 'skipped' with: pattern: results-* path: results @@ -418,6 +425,7 @@ jobs: # needs.fleet.outputs.failed holds one matrix leg's value, so the verdict # is read from every leg's results file instead. - uses: actions/download-artifact@v8 + if: needs.fleet.result != 'skipped' with: pattern: results-* path: results diff --git a/test/refresh-status.bats b/test/refresh-status.bats index ed758a4..239a032 100644 --- a/test/refresh-status.bats +++ b/test/refresh-status.bats @@ -24,3 +24,24 @@ setup() { [ "$status" -ne 0 ] [[ "$output" == *"LATEST"* ]] } + +@test "two publishes whose only differences are the clock and canary_run make one commit" { + T="$BATS_TEST_TMPDIR/pub"; mkdir -p "$T" + git init -q --bare "$T/origin.git" + git init -q -b main "$T/work" + git -C "$T/work" config user.email t@example.com; git -C "$T/work" config user.name t + git -C "$T/work" remote add origin "$T/origin.git" + echo x > "$T/work/README"; git -C "$T/work" add README; git -C "$T/work" commit -q -m init + git -C "$T/work" push -q origin main + export LATEST=0.8.27 + # The stable note the canary plan job now emits: no age in it. + export NIGHTLY_JSON='{"published_at":"2026-11-20T01:00:00Z","sha":"f4e82fc8eac874cae1658b7976518253027c4f6a","note":"nightly published 2026-11-20T01:00:00Z at f4e82fc8"}' + export REBUILD="bash $S/scripts/refresh-status.sh \"\$OUT_DIR\" $F/results-latest.json" + cd "$T/work" + CANARY_RUN=https://example/run/1 bash "$S/scripts/publish-status.sh" "$T/out1" + sleep 1 + CANARY_RUN=https://example/run/2 run bash "$S/scripts/publish-status.sh" "$T/out2" + [ "$status" -eq 0 ] + [[ "$output" == *"status: unchanged"* ]] + [ "$(git -C "$T/origin.git" rev-list --count status)" -eq 1 ] +} From 2431787df11a888dde8b7e1e7281c414a3973d62 Mon Sep 17 00:00:00 2001 From: burinc Date: Fri, 20 Nov 2026 14:06:47 +1100 Subject: [PATCH 14/31] fanout: a failed dependency download is infra, not a jolt break --- .github/workflows/fanout.yml | 45 +++++++++++++++++++++++++++--- scripts/lib/version.sh | 16 +++++++++++ test/fixtures/log-maven-429.txt | 4 +++ test/fixtures/log-maven-absent.txt | 4 +++ test/fixtures/log-test-failure.txt | 5 ++++ test/version.bats | 6 ++++ 6 files changed, 76 insertions(+), 4 deletions(-) create mode 100644 test/fixtures/log-maven-429.txt create mode 100644 test/fixtures/log-maven-absent.txt create mode 100644 test/fixtures/log-test-failure.txt diff --git a/.github/workflows/fanout.yml b/.github/workflows/fanout.yml index 6d2a3c3..8133746 100644 --- a/.github/workflows/fanout.yml +++ b/.github/workflows/fanout.yml @@ -225,8 +225,28 @@ jobs: 2>/dev/null | grep -qi 'install jolt'; then cc="toolchain-unavailable" fi - FIN[$p]=$(date -u +%Y-%m-%dT%H:%M:%SZ) + # A project can also fail because a dependency would not download + # (Maven Central rate limiting or a missing artifact). That is the + # registry's problem, not a break in jolt. Read only the failed + # jobs' logs. If a log cannot be fetched we have no evidence, so + # the run stays a failure. if [ "$cc" = "failure" ]; then + logs=() + for jid in $(gh api "repos/jlt-commons/$p/actions/runs/${RUN[$p]}/jobs" \ + --jq '.jobs[] | select(.conclusion=="failure") | .id' 2>/dev/null); do + if gh api --allow-escape-sequences "repos/jlt-commons/$p/actions/jobs/$jid/logs" \ + > "$RES_DIR/$p-$jid.log" 2> "$RES_DIR/$p-$jid.err"; then + logs+=("$RES_DIR/$p-$jid.log") + else + echo "::warning::could not fetch the log of $p job $jid: $(head -c 300 "$RES_DIR/$p-$jid.err")" + fi + done + if [ "${#logs[@]}" -gt 0 ] && download_failure "${logs[@]}"; then + cc="deps-unavailable" + fi + fi + FIN[$p]=$(date -u +%Y-%m-%dT%H:%M:%SZ) + if [ "$cc" = "failure" ] || [ "$cc" = "deps-unavailable" ]; then FSTEP[$p]=$(gh api "repos/jlt-commons/$p/actions/runs/${RUN[$p]}/jobs" \ --jq '[.jobs[].steps[]? | select(.conclusion=="failure") | .name] | first // empty' \ 2>/dev/null || true) @@ -263,6 +283,7 @@ jobs: # Render the table this workflow exists to produce. failed="" infra="" + nodeps="" mismatch="" : > "$RES_DIR/projects.jsonl" { @@ -280,6 +301,8 @@ jobs: mismatch="$mismatch $p"; failed="$failed $p" ;; toolchain-unavailable) icon="**could not install jolt**"; infra="$infra $p" ;; + deps-unavailable) + icon="**could not download dependencies**"; infra="$infra $p"; nodeps="$nodeps $p" ;; *) icon="**FAIL** ($c)"; failed="$failed $p" ;; esac link="-" @@ -287,7 +310,7 @@ jobs: echo "| \`$p\` | $icon | $link |" >> "$GITHUB_STEP_SUMMARY" case "$c" in success) r=pass ;; - toolchain-unavailable) r=infra ;; + toolchain-unavailable|deps-unavailable) r=infra ;; timed-out) r=timed-out ;; dispatch-failed|no-run-appeared) r=dispatch-failed ;; mismatch) r=mismatch ;; @@ -305,6 +328,7 @@ jobs: done failed="${failed# }" infra="${infra# }" + nodeps="${nodeps# }" mismatch="${mismatch# }" jq -s --arg requested "$VERSION" --arg sha "$NIGHTLY_SHA" \ --arg fin "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \ @@ -317,14 +341,27 @@ jobs: echo [ -n "$mismatch" ] && echo "**Ran on the wrong jolt:** $mismatch" [ -n "$failed" ] && echo "**Broken by jolt \`$VERSION\`:** $failed" - if [ -n "$infra" ]; then - echo "**Could not install jolt \`$VERSION\` for:** $infra" + # infra holds both causes. Name the install failures as those that + # are in infra but not in nodeps. + noinstall="" + for p in $infra; do + case " $nodeps " in *" $p "*) ;; *) noinstall="$noinstall $p" ;; esac + done + noinstall="${noinstall# }" + if [ -n "$noinstall" ]; then + echo "**Could not install jolt \`$VERSION\` for:** $noinstall" echo echo "That is this fleet's own problem, not a fact about jolt. Usually" echo "the version does not exist in the repository being installed" echo "from: check each project's \`JOLT_REPO\`, which should be unset" echo "unless deliberately pointed at a fork." fi + if [ -n "$nodeps" ]; then + echo "**Could not download dependencies for:** $nodeps" + echo + echo "That is a package-registry problem, often Maven Central rate" + echo "limiting while several projects build at once, not a fact about jolt." + fi # Counted from PROJECTS rather than written out. The literal said five # for as long as there were five, then went on saying it after there # were six, which is what a count kept by hand beside the list it diff --git a/scripts/lib/version.sh b/scripts/lib/version.sh index 10355cd..8a78ee7 100644 --- a/scripts/lib/version.sh +++ b/scripts/lib/version.sh @@ -76,3 +76,19 @@ uncovered_reason() { printf 'ready, not yet in fleet.json\n' fi } + +# download_failure ... +# Exits 0 when any log shows a dependency download failure (a package registry +# refusing or lacking an artifact), otherwise 1. Prints nothing. An unreadable +# log counts as no match. +download_failure() { + [ "$#" -gt 0 ] || return 1 + grep -sqF \ + -e 'status code: 429' \ + -e 'Too Many Requests' \ + -e 'Could not transfer artifact' \ + -e 'Could not find artifact' \ + -e 'Classpath lookup failed' \ + -e 'Failed to read artifact descriptor' \ + -- "$@" +} diff --git a/test/fixtures/log-maven-429.txt b/test/fixtures/log-maven-429.txt new file mode 100644 index 0000000..8630f18 --- /dev/null +++ b/test/fixtures/log-maven-429.txt @@ -0,0 +1,4 @@ +2026-11-20T01:55:20.0000000Z [ERROR] Classpath lookup failed when running `/tmp/usr/local/opt/ClojureTools/bin/clojure -A:test:dev -Spath`. Some features may not work properly. +2026-11-20T01:55:20.1000000Z Error building classpath. Failed to read artifact descriptor for org.clojure:clojure:jar:1.12.7 +2026-11-20T01:55:20.2000000Z Caused by: org.eclipse.aether.transfer.ArtifactTransferException: Could not transfer artifact org.clojure:clojure:pom:1.12.7 from/to central (https://repo1.maven.org/maven2/): status code: 429, reason phrase: Too Many Requests (429) +2026-11-20T01:55:23.8756969Z ##[error]Process completed with exit code 1. diff --git a/test/fixtures/log-maven-absent.txt b/test/fixtures/log-maven-absent.txt new file mode 100644 index 0000000..0bc5c76 --- /dev/null +++ b/test/fixtures/log-maven-absent.txt @@ -0,0 +1,4 @@ +2026-11-20T01:45:00.0000000Z Ran 180 tests. 565 assertions passed, 0 failures, 0 errors. +2026-11-20T01:45:10.0000000Z [ERROR] Classpath lookup failed when running `/tmp/usr/local/opt/ClojureTools/bin/clojure -A:test -Spath`. Some features may not work properly. +2026-11-20T01:45:10.1000000Z Error building classpath. The following artifacts could not be resolved: org.clojure:clojure:jar:1.12.7 (absent): Could not find artifact org.clojure:clojure:jar:1.12.7 in +2026-11-20T01:45:11.0000000Z ##[error]Process completed with exit code 1. diff --git a/test/fixtures/log-test-failure.txt b/test/fixtures/log-test-failure.txt new file mode 100644 index 0000000..cf0d5a6 --- /dev/null +++ b/test/fixtures/log-test-failure.txt @@ -0,0 +1,5 @@ +2026-11-20T01:50:00.0000000Z FAIL in (vec-add-test) (vector_test.clj:12) +2026-11-20T01:50:00.1000000Z expected: [1 2] +2026-11-20T01:50:00.2000000Z actual: [2 1] +2026-11-20T01:50:01.0000000Z Ran 180 tests. 564 assertions passed, 1 failures, 0 errors. +2026-11-20T01:50:02.0000000Z ##[error]Process completed with exit code 1. diff --git a/test/version.bats b/test/version.bats index c408371..8c34775 100644 --- a/test/version.bats +++ b/test/version.bats @@ -53,3 +53,9 @@ logs2() { printf '2026-11-19T01:02:03.0000000Z jolt v%s\n' "$1" > "$BATS_TMPDIR/ @test "pick: none match reports first" { logs2 0.7.29 0.8.27; run pick_installed 0.8.26 "" "$BATS_TMPDIR/a.log" "$BATS_TMPDIR/b.log"; [ "$status" -eq 1 ]; [ "$output" = "0.7.29" ]; } @test "pick: nightly sha in second log" { logs2 0.7.29 0.8.27-241-gdd3c4a4b; run pick_installed nightly dd3c4a4b0123456789abcdef0123456789abcdef "$BATS_TMPDIR/a.log" "$BATS_TMPDIR/b.log"; [ "$status" -eq 0 ]; [ "$output" = "0.8.27-241-gdd3c4a4b" ]; } @test "pick: no versions" { printf 'nothing\n' > "$BATS_TMPDIR/a.log"; run pick_installed 0.8.27 "" "$BATS_TMPDIR/a.log"; [ "$status" -eq 1 ]; [ -z "$output" ]; } + +@test "download_failure: maven 429" { run download_failure "$F/log-maven-429.txt"; [ "$status" -eq 0 ]; [ -z "$output" ]; } +@test "download_failure: maven absent" { run download_failure "$F/log-maven-absent.txt"; [ "$status" -eq 0 ]; } +@test "download_failure: test failure" { run download_failure "$F/log-test-failure.txt"; [ "$status" -eq 1 ]; [ -z "$output" ]; } +@test "download_failure: any of several logs" { run download_failure "$F/log-test-failure.txt" "$F/log-maven-429.txt"; [ "$status" -eq 0 ]; } +@test "download_failure: no args" { run download_failure; [ "$status" -eq 1 ]; } From 85b889650c593c29f9bb3e5bf870e5bd74d6ce56 Mon Sep 17 00:00:00 2001 From: burinc Date: Fri, 20 Nov 2026 14:12:39 +1100 Subject: [PATCH 15/31] fanout: classify infra per failed step and per job; canary issue names both infra causes --- .github/workflows/canary.yml | 20 +++++++++++------- .github/workflows/fanout.yml | 10 ++++++--- scripts/lib/version.sh | 34 ++++++++++++++++++++---------- test/fixtures/log-early-429.txt | 7 ++++++ test/fixtures/log-maven-429.txt | 1 + test/fixtures/log-maven-absent.txt | 1 + test/fixtures/log-no-error.txt | 2 ++ test/fixtures/log-test-failure.txt | 1 + test/version.bats | 10 ++++++++- 9 files changed, 63 insertions(+), 23 deletions(-) create mode 100644 test/fixtures/log-early-429.txt create mode 100644 test/fixtures/log-no-error.txt diff --git a/.github/workflows/canary.yml b/.github/workflows/canary.yml index 4265842..8d1d2eb 100644 --- a/.github/workflows/canary.yml +++ b/.github/workflows/canary.yml @@ -447,8 +447,9 @@ jobs: # Verdict from the merged results: "name (version)" per bad cell. # fail, mismatch, timed-out and dispatch-failed are findings about - # jolt or the build; infra is our own misconfiguration and is - # reported separately. + # jolt or the build; infra (jolt not installable, or a dependency + # not downloadable) is not a finding about jolt and is reported + # separately. files=() if [ -d results ]; then while IFS= read -r f; do files+=("$f"); done < <(find results -name results.json | sort) @@ -459,7 +460,8 @@ jobs: | select(.result | IN("fail","mismatch","timed-out","dispatch-failed")) | "\(.name) (\($v))"] | unique | join(", ")' "${files[@]}") INFRA=$(jq -rs '[.[] | .requested as $v | .projects[] - | select(.result == "infra") | "\(.name) (\($v))"] | unique | join(", ")' "${files[@]}") + | select(.result == "infra") + | "\(.name) (\($v)\(if .failed_step then ", failed step: " + .failed_step else "" end))"] | unique | join(", ")' "${files[@]}") fi # The fleet job failed but no project says why (a leg crashed before @@ -490,12 +492,14 @@ jobs: # filed as a fact about jolt. fanout reports those separately. if [ -n "$INFRA" ] && [ -z "$FAILED" ]; then body=$(printf '%s\n' \ - "jolt could not be INSTALLED for: ${INFRA}" \ + "Infra problems, not findings about jolt: ${INFRA}" \ "" \ - "This is not a finding about jolt. The fleet asked for a version it" \ - "could not fetch, which usually means a project's \`JOLT_REPO\` points" \ - "at a repository that does not publish it. It should be unset unless" \ - "deliberately aimed at a fork." \ + "A project either could not install jolt (check its \`JOLT_REPO\`," \ + "which should be unset unless deliberately aimed at a fork, since the" \ + "version may not exist in the repository it installs from) or could" \ + "not download a dependency (a package registry problem, often Maven" \ + "Central rate limiting while several projects build at once). The" \ + "failed step in parentheses above shows which." \ "" \ "**Versions tested:** ${VERSIONS}" \ "" \ diff --git a/.github/workflows/fanout.yml b/.github/workflows/fanout.yml index 8133746..44c370f 100644 --- a/.github/workflows/fanout.yml +++ b/.github/workflows/fanout.yml @@ -228,25 +228,29 @@ jobs: # A project can also fail because a dependency would not download # (Maven Central rate limiting or a missing artifact). That is the # registry's problem, not a break in jolt. Read only the failed - # jobs' logs. If a log cannot be fetched we have no evidence, so + # jobs' logs. If any log cannot be fetched we have no evidence, so # the run stays a failure. if [ "$cc" = "failure" ]; then logs=() + allfetched=1 for jid in $(gh api "repos/jlt-commons/$p/actions/runs/${RUN[$p]}/jobs" \ --jq '.jobs[] | select(.conclusion=="failure") | .id' 2>/dev/null); do if gh api --allow-escape-sequences "repos/jlt-commons/$p/actions/jobs/$jid/logs" \ > "$RES_DIR/$p-$jid.log" 2> "$RES_DIR/$p-$jid.err"; then logs+=("$RES_DIR/$p-$jid.log") else + allfetched=0 echo "::warning::could not fetch the log of $p job $jid: $(head -c 300 "$RES_DIR/$p-$jid.err")" fi done - if [ "${#logs[@]}" -gt 0 ] && download_failure "${logs[@]}"; then + # Every failed job must show a download failure in its failed + # step. A job whose log we could not read counts against it. + if [ "$allfetched" = "1" ] && [ "${#logs[@]}" -gt 0 ] && download_failure "${logs[@]}"; then cc="deps-unavailable" fi fi FIN[$p]=$(date -u +%Y-%m-%dT%H:%M:%SZ) - if [ "$cc" = "failure" ] || [ "$cc" = "deps-unavailable" ]; then + if [ "$cc" = "failure" ] || [ "$cc" = "deps-unavailable" ] || [ "$cc" = "toolchain-unavailable" ]; then FSTEP[$p]=$(gh api "repos/jlt-commons/$p/actions/runs/${RUN[$p]}/jobs" \ --jq '[.jobs[].steps[]? | select(.conclusion=="failure") | .name] | first // empty' \ 2>/dev/null || true) diff --git a/scripts/lib/version.sh b/scripts/lib/version.sh index 8a78ee7..8dedf13 100644 --- a/scripts/lib/version.sh +++ b/scripts/lib/version.sh @@ -78,17 +78,29 @@ uncovered_reason() { } # download_failure ... -# Exits 0 when any log shows a dependency download failure (a package registry -# refusing or lacking an artifact), otherwise 1. Prints nothing. An unreadable -# log counts as no match. +# Exits 0 only when EVERY given log shows a dependency download failure (a +# package registry refusing or lacking an artifact) inside its failed step. +# The failed step is the text from the last "##[group]Run " line before the +# log's first "##[error]" line, up to that error line. A log with no +# "##[error]" line, an unreadable log, or no logs at all is not a match. +# Prints nothing. Pass exactly the failed jobs' logs, so one real break among +# them keeps the whole run a failure. download_failure() { [ "$#" -gt 0 ] || return 1 - grep -sqF \ - -e 'status code: 429' \ - -e 'Too Many Requests' \ - -e 'Could not transfer artifact' \ - -e 'Could not find artifact' \ - -e 'Classpath lookup failed' \ - -e 'Failed to read artifact descriptor' \ - -- "$@" + local f section + for f in "$@"; do + [ -r "$f" ] || return 1 + section=$(awk ' + $2 == "##[group]Run" { buf = $0; next } + $2 ~ /^##\[error\]/ { print buf; exit } + { buf = buf "\n" $0 } + ' "$f") + [ -n "$section" ] || return 1 + printf '%s\n' "$section" | grep -qF \ + -e 'status code: 429' \ + -e 'Too Many Requests' \ + -e 'Could not transfer artifact' \ + -e 'Could not find artifact' \ + -e 'Failed to read artifact descriptor' || return 1 + done } diff --git a/test/fixtures/log-early-429.txt b/test/fixtures/log-early-429.txt new file mode 100644 index 0000000..ac9b1c6 --- /dev/null +++ b/test/fixtures/log-early-429.txt @@ -0,0 +1,7 @@ +2026-11-20T01:00:00.0000000Z ##[group]Run bb install-deps +2026-11-20T01:00:01.0000000Z Warning: Too Many Requests (429), retried and succeeded +2026-11-20T01:00:02.0000000Z ##[endgroup] +2026-11-20T01:50:00.0000000Z ##[group]Run bb test +2026-11-20T01:50:00.1000000Z FAIL in (vec-add-test) (vector_test.clj:12) +2026-11-20T01:50:01.0000000Z Ran 180 tests. 564 assertions passed, 1 failures, 0 errors. +2026-11-20T01:50:02.0000000Z ##[error]Process completed with exit code 1. diff --git a/test/fixtures/log-maven-429.txt b/test/fixtures/log-maven-429.txt index 8630f18..c30c04d 100644 --- a/test/fixtures/log-maven-429.txt +++ b/test/fixtures/log-maven-429.txt @@ -1,3 +1,4 @@ +2026-11-20T01:00:00.0000000Z ##[group]Run bb lsp:format-check 2026-11-20T01:55:20.0000000Z [ERROR] Classpath lookup failed when running `/tmp/usr/local/opt/ClojureTools/bin/clojure -A:test:dev -Spath`. Some features may not work properly. 2026-11-20T01:55:20.1000000Z Error building classpath. Failed to read artifact descriptor for org.clojure:clojure:jar:1.12.7 2026-11-20T01:55:20.2000000Z Caused by: org.eclipse.aether.transfer.ArtifactTransferException: Could not transfer artifact org.clojure:clojure:pom:1.12.7 from/to central (https://repo1.maven.org/maven2/): status code: 429, reason phrase: Too Many Requests (429) diff --git a/test/fixtures/log-maven-absent.txt b/test/fixtures/log-maven-absent.txt index 0bc5c76..c67788f 100644 --- a/test/fixtures/log-maven-absent.txt +++ b/test/fixtures/log-maven-absent.txt @@ -1,3 +1,4 @@ +2026-11-20T01:00:00.0000000Z ##[group]Run bb lsp:format-check 2026-11-20T01:45:00.0000000Z Ran 180 tests. 565 assertions passed, 0 failures, 0 errors. 2026-11-20T01:45:10.0000000Z [ERROR] Classpath lookup failed when running `/tmp/usr/local/opt/ClojureTools/bin/clojure -A:test -Spath`. Some features may not work properly. 2026-11-20T01:45:10.1000000Z Error building classpath. The following artifacts could not be resolved: org.clojure:clojure:jar:1.12.7 (absent): Could not find artifact org.clojure:clojure:jar:1.12.7 in diff --git a/test/fixtures/log-no-error.txt b/test/fixtures/log-no-error.txt new file mode 100644 index 0000000..984cb3f --- /dev/null +++ b/test/fixtures/log-no-error.txt @@ -0,0 +1,2 @@ +2026-11-20T01:00:00.0000000Z ##[group]Run bb test +2026-11-20T01:00:01.0000000Z Could not transfer artifact x from/to central: status code: 429 diff --git a/test/fixtures/log-test-failure.txt b/test/fixtures/log-test-failure.txt index cf0d5a6..35b3a0c 100644 --- a/test/fixtures/log-test-failure.txt +++ b/test/fixtures/log-test-failure.txt @@ -1,3 +1,4 @@ +2026-11-20T01:00:00.0000000Z ##[group]Run bb lsp:format-check 2026-11-20T01:50:00.0000000Z FAIL in (vec-add-test) (vector_test.clj:12) 2026-11-20T01:50:00.1000000Z expected: [1 2] 2026-11-20T01:50:00.2000000Z actual: [2 1] diff --git a/test/version.bats b/test/version.bats index 8c34775..917616d 100644 --- a/test/version.bats +++ b/test/version.bats @@ -57,5 +57,13 @@ logs2() { printf '2026-11-19T01:02:03.0000000Z jolt v%s\n' "$1" > "$BATS_TMPDIR/ @test "download_failure: maven 429" { run download_failure "$F/log-maven-429.txt"; [ "$status" -eq 0 ]; [ -z "$output" ]; } @test "download_failure: maven absent" { run download_failure "$F/log-maven-absent.txt"; [ "$status" -eq 0 ]; } @test "download_failure: test failure" { run download_failure "$F/log-test-failure.txt"; [ "$status" -eq 1 ]; [ -z "$output" ]; } -@test "download_failure: any of several logs" { run download_failure "$F/log-test-failure.txt" "$F/log-maven-429.txt"; [ "$status" -eq 0 ]; } @test "download_failure: no args" { run download_failure; [ "$status" -eq 1 ]; } + +@test "download_failure: earlier step printed 429, failed step is a test" { run download_failure "$F/log-early-429.txt"; [ "$status" -eq 1 ]; } +@test "download_failure: one deps log and one test log is not infra" { run download_failure "$F/log-maven-429.txt" "$F/log-test-failure.txt"; [ "$status" -eq 1 ]; } +@test "download_failure: both deps logs" { run download_failure "$F/log-maven-429.txt" "$F/log-maven-absent.txt"; [ "$status" -eq 0 ]; } +@test "download_failure: no ##[error] line" { run download_failure "$F/log-no-error.txt"; [ "$status" -eq 1 ]; } +@test "download_failure: Classpath lookup failed alone is not enough" { + printf '%s\n' '2026-11-20T01:00:00.0000000Z ##[group]Run x' '2026-11-20T01:00:01.0000000Z [ERROR] Classpath lookup failed' '2026-11-20T01:00:02.0000000Z ##[error]Process completed with exit code 1.' > "$BATS_TMPDIR/cp.txt" + run download_failure "$BATS_TMPDIR/cp.txt"; [ "$status" -eq 1 ] +} From 5702e957b541e4387b0ebdddbc94dd2f96b3aeb6 Mon Sep 17 00:00:00 2001 From: burinc Date: Fri, 20 Nov 2026 14:23:09 +1100 Subject: [PATCH 16/31] fleet: version, status and GitHub client in jolt (part 1 of the port) --- deps.edn | 21 ++++ src/fleet/github.clj | 81 +++++++++++++++ src/fleet/status.clj | 130 +++++++++++++++++++++++ src/fleet/version.clj | 92 +++++++++++++++++ test/fleet/github_test.clj | 87 ++++++++++++++++ test/fleet/status_test.clj | 200 ++++++++++++++++++++++++++++++++++++ test/fleet/version_test.clj | 180 ++++++++++++++++++++++++++++++++ 7 files changed, 791 insertions(+) create mode 100644 deps.edn create mode 100644 src/fleet/github.clj create mode 100644 src/fleet/status.clj create mode 100644 src/fleet/version.clj create mode 100644 test/fleet/github_test.clj create mode 100644 test/fleet/status_test.clj create mode 100644 test/fleet/version_test.clj diff --git a/deps.edn b/deps.edn new file mode 100644 index 0000000..2053f56 --- /dev/null +++ b/deps.edn @@ -0,0 +1,21 @@ +;; deps.edn: the fleet dashboard tools, plain Clojure run by jolt as +;; `jolt `. The git shas below are the heads of main, measured +;; 2026-11-20 with git ls-remote. babashka.process, babashka.fs, +;; cheshire.core and clojure.test come bundled with jolt. +{:paths ["src" "test" "resources"] + :deps {io.github.jolt-lang/http-client {:git/url "https://github.com/jolt-lang/http-client.git" + :git/sha "03267126e0bebe172936e9618b9ff6cd678edaac"} + io.github.jolt-lang/yaml {:git/url "https://github.com/jolt-lang/yaml.git" + :git/sha "ecbeb028bd319cbcccce6de83eca8eae5fedc7f4"} + io.github.jolt-lang/time {:git/url "https://github.com/jolt-lang/time.git" + :git/sha "6c12a58d08586ca60421099d2d3d0bcd473238ac"}} + + :tasks {test {:doc "Run every fleet.*-test namespace; exit 1 on any failure or error" + :requires ([clojure.test :as t] + [fleet.github-test] + [fleet.status-test] + [fleet.version-test]) + :task (let [{:keys [fail error]} (t/run-tests 'fleet.github-test + 'fleet.status-test + 'fleet.version-test)] + (when (pos? (+ fail error)) (System/exit 1)))}}} diff --git a/src/fleet/github.clj b/src/fleet/github.clj new file mode 100644 index 0000000..3761ef9 --- /dev/null +++ b/src/fleet/github.clj @@ -0,0 +1,81 @@ +(ns fleet.github + "A small GitHub REST client over jolt.http-client. IO sits behind a request + function so tests stub it. A non-2xx response throws ex-info with + {:status n :path p :body b}; callers branch on (:status (ex-data e))." + (:require [cheshire.core :as json] + [clojure.string :as str] + [jolt.http-client :as http])) + +(def api-base "https://api.github.com") + +(defn- header + "Case-insensitive header lookup." + [headers k] + (some (fn [[hk v]] (when (= (str/lower-case (name hk)) k) v)) headers)) + +(defn next-link + "The rel=\"next\" URL from a Link header value, or nil." + [link-header] + (when link-header + (some (fn [part] + (when-let [[_ url rel] (re-find #"<([^>]*)>\s*;\s*rel=\"?([^\";]+)\"?" part)] + (when (= "next" rel) url))) + (str/split link-header #",\s*(?=<)")))) + +(defn- url-for [path] + (cond + (re-find #"^https?://" path) path + (str/starts-with? path "/") (str api-base path) + :else (str api-base "/" path))) + +(defn- with-per-page [path] + (if (re-find #"[?&]per_page=" path) + path + (str path (if (str/includes? path "?") "&" "?") "per_page=100"))) + +(defn- default-request [req] (http/get (:url req) (dissoc req :url))) + +(defn- request! + "One GET. Returns the response map, or throws ex-info on a non-2xx status." + [{:keys [token request]} path accept] + (let [resp ((or request default-request) + {:url (url-for path) + :throw-exceptions false + :headers (cond-> {"Accept" accept + "X-GitHub-Api-Version" "2022-11-28"} + (seq token) (assoc "Authorization" (str "Bearer " token)))}) + status (:status resp)] + (if (and (integer? status) (<= 200 status 299)) + resp + (throw (ex-info (str "GitHub API " status " for " path) + {:status status :path path :body (:body resp)}))))) + +(def ^:private json-accept "application/vnd.github+json") + +(defn- parse [body] (json/parse-string body true)) + +(defn client + "A map of fns {:get-json :get-raw :get-paginated}, each taking a path + (\"repos/o/r\", \"/repos/o/r\" or a full URL). opts: :token, :request (a fn + from {:url :headers :throw-exceptions} to {:status :headers :body})." + [opts] + {:get-json (fn [path] (parse (:body (request! opts path json-accept)))) + :get-raw (fn [path] (:body (request! opts path "application/vnd.github.raw+json"))) + :get-paginated (fn [path] + (loop [url (with-per-page path) acc []] + (let [resp (request! opts url json-accept) + body (parse (:body resp)) + acc (if (sequential? body) (into acc body) (conj acc body))] + (if-let [nxt (next-link (header (:headers resp) "link"))] + (recur nxt acc) + acc))))}) + +(defn env-client + "A client with the token from GH_TOKEN (none when unset)." + [] + (client {:token (System/getenv "GH_TOKEN")})) + +(defn status-of + "The HTTP status carried by an exception from this namespace, or nil." + [e] + (:status (ex-data e))) diff --git a/src/fleet/status.clj b/src/fleet/status.clj new file mode 100644 index 0000000..a7a54ca --- /dev/null +++ b/src/fleet/status.clj @@ -0,0 +1,130 @@ +(ns fleet.status + "Pure merge: fan-out results, own-pin, uncovered, and the previous status + and history in; the new status and history out. No IO." + (:require [clojure.string :as str])) + +(def ^:private valid-results + #{"pass" "fail" "infra" "timed-out" "dispatch-failed" "mismatch" "not-run"}) + +(def ^:private columns [:pin :latest :nightly :adhoc]) + +(def ^:private history-cap 30) + +(defn- strip-v [s] + (if (string? s) (str/replace-first s #"^v" "") s)) + +(defn- not-run [] {:result "not-run"}) + +(defn- result->cell [r requested] + {:result (:result r) + :version (strip-v requested) + :installed (:installed r) + :run_url (:run_url r) + :finished_at (:finished_at r) + :failed_step (:failed_step r)}) + +(defn- column [requested latest] + (cond + (= "nightly" requested) :nightly + (= latest (strip-v requested)) :latest + :else :adhoc)) + +(defn- fail! [msg data] + (throw (ex-info msg data))) + +(defn- validate! + [{:keys [prev-status prev-history own-pin uncovered results]}] + (when-not (and (sequential? own-pin) + (every? #(and (string? (:name %)) (string? (:pin %))) own-pin)) + (fail! "malformed own-pin" {})) + (when-not (sequential? uncovered) (fail! "malformed uncovered" {})) + (when-not (or (nil? prev-status) (map? prev-status)) (fail! "malformed prev status" {})) + (when-not (or (nil? prev-history) (map? prev-history)) (fail! "malformed prev history" {})) + (when-not (every? (fn [f] + (and (map? f) + (string? (:requested f)) + (sequential? (:projects f)) + (every? #(and (string? (:name %)) + (contains? valid-results (:result %))) + (:projects f)))) + results) + (fail! "malformed results" {}))) + +(defn- bad? [project] + (boolean (some #(not (#{"pass" "not-run"} (:result %))) (vals (:cells project))))) + +(defn- add-entry + "Prepend a cell to a project's column unless its run_url is already there. + Keeps the newest 30." + [hist {:keys [name col cell]}] + (let [k (keyword name) + existing (get-in hist [k col] [])] + (if (and (some? (:run_url cell)) + (some #(= (:run_url cell) (:run_url %)) existing)) + hist + (assoc-in hist [k col] (vec (take history-cap (cons cell existing))))))) + +(defn build + "Merge into {:status m :history m}. Keys of the input map: :prev-status, + :prev-history (nil when absent), :own-pin, :uncovered, :latest, :nightly + (a map, or nil to keep the previous one, R22), :canary-run, :now, :results + (a seq of fan-out results maps). Throws ex-info on malformed input." + [{:keys [prev-status prev-history own-pin uncovered latest nightly canary-run now results] + :as in}] + (validate! in) + (let [latest (strip-v latest) + res (vec (for [f results + p (:projects f)] + {:name (:name p) + :col (column (:requested f) latest) + :cell (result->cell p (:requested f))})) + latest-stale? (and (some? prev-status) + (not= (get-in prev-status [:jolt :latest :version]) latest)) + nightly-stale? (and (some? nightly) + (not= (get-in prev-status [:jolt :nightly :sha]) (:sha nightly))) + prev-cells (into {} (map (juxt :name :cells)) (:projects prev-status)) + fresh (reduce (fn [m {:keys [name col cell]}] + (if (= col :adhoc) m (assoc m [name col] cell))) + {} res) + pick (fn [n c stale?] + (or (get fresh [n c]) + (if stale? (not-run) (or (get-in prev-cells [n c]) (not-run))))) + projects (vec (for [p own-pin] + {:name (:name p) + :pin (:pin p) + :cells {:pin {:result (:result p) + :version (:pin p) + :installed nil + :run_url (:run_url p) + :finished_at (:finished_at p) + :failed_step (:failed_step p)} + :latest (pick (:name p) :latest latest-stale?) + :nightly (pick (:name p) :nightly nightly-stale?)}})) + sorted (vec (sort-by (fn [p] [(if (bad? p) 0 1) (:name p)]) projects)) + prev-hist (:projects prev-history) + pin-entries (for [p projects + :let [pin-hist (get-in prev-hist [(keyword (:name p)) :pin]) + cell (get-in p [:cells :pin])] + :when (or (not= (or (:run_url (first pin-hist)) "__none__") + (or (:run_url cell) "__none__")) + (empty? pin-hist))] + {:name (:name p) :col :pin :cell cell}) + hist (reduce add-entry (or prev-hist {}) (concat res pin-entries)) + hist (into {} (map (fn [[k v]] + [k (merge (zipmap columns (repeat [])) v)])) + hist)] + {:status {:schema 1 + :generated_at now + :canary_run canary-run + :jolt {:latest {:version latest} + :nightly (or nightly (get-in prev-status [:jolt :nightly]))} + :projects sorted + :uncovered (vec uncovered)} + :history {:schema 1 :projects hist}})) + +(defn unchanged? + "R12: two statuses are the same when they differ only in generated_at and + canary_run." + [old-status new-status] + (let [norm #(dissoc % :generated_at :canary_run)] + (= (norm old-status) (norm new-status)))) diff --git a/src/fleet/version.clj b/src/fleet/version.clj new file mode 100644 index 0000000..deaf753 --- /dev/null +++ b/src/fleet/version.clj @@ -0,0 +1,92 @@ +(ns fleet.version + "Pure helpers for the fleet dashboard: text in, values out." + (:require [clojure.string :as str])) + +(def ^:private version-line + #"^([0-9T:.-]+Z )?jolt v([0-9]+\.[0-9]+\.[0-9]+(-[0-9]+-g[0-9a-f]+)?)$") + +(defn installed-version + "The version from the first \"jolt v[-N-g]\" line of a log + (after the Actions timestamp), without the leading v. nil when none." + [log-text] + (some (fn [line] + (when-let [m (re-matches version-line (str/replace line #"\r$" ""))] + (nth m 2))) + (str/split-lines (or log-text "")))) + +(defn version-matches? + "Does the installed version satisfy the request? A nightly request needs + the installed -g suffix to be a prefix of nightly-sha." + [requested installed nightly-sha] + (if (= "nightly" requested) + (boolean + (when (seq nightly-sha) + (when-let [[_ sha] (re-find #"-g([0-9a-f]+)$" (or installed ""))] + (str/starts-with? nightly-sha sha)))) + (= (str/replace-first requested #"^v" "") installed))) + +(defn pick-installed + "First installed version across the logs that matches the request (R4), + else the first version found, else nil." + [requested nightly-sha log-texts] + (let [versions (keep installed-version log-texts) + hit (first (filter #(version-matches? requested % nightly-sha) versions))] + (if hit + {:installed hit :match? true} + {:installed (first versions) :match? false}))) + +(def ^:private ws "[ \t]*") +(def ^:private ver "v?([0-9]+\\.[0-9]+\\.[0-9]+)") + +(def ^:private pin-re + (re-pattern + (str "^" ws "JOLT_VERSION:" ws + "(?:\\$\\{\\{" ws "inputs\\.jolt-version" ws "\\|\\|" ws "'" ver "'" ws "\\}\\}" + "|\"" ver "\"|'" ver "'|" ver ")" ws "$"))) + +(defn parse-pin + "The literal version from the first JOLT_VERSION: key line of a ci.yml, + without v. nil when the key is missing or the pin is not a literal." + [ci-yml-text] + (when ci-yml-text + (when-let [line (some #(when (re-find #"^\s*JOLT_VERSION:" %) %) + (str/split-lines ci-yml-text))] + (let [line (str/replace line #" #.*$" "")] + (some-> (re-matches pin-re line) rest (->> (some identity))))))) + +(defn uncovered-reason + "Why a repo is not in the fleet, or nil when it is." + [{:keys [has-ci? has-input? in-fleet? excluded]}] + (cond + in-fleet? nil + (seq excluded) (str "excluded: " excluded) + (not has-ci?) "no ci.yml" + (not has-input?) "ci.yml has no jolt-version input" + :else "ready, not yet in fleet.json")) + +(defn- failed-step-section + "Text from the last \"##[group]Run \" line before the log's first + \"##[error]\" line, up to that error line. nil when there is no error." + [log-text] + (loop [lines (str/split-lines (or log-text "")) buf []] + (when-let [line (first lines)] + (let [tok (second (str/split line #" " 3))] + (cond + (= tok "##[group]Run") (recur (rest lines) [line]) + (and tok (str/starts-with? tok "##[error]")) (str/join "\n" buf) + :else (recur (rest lines) (conj buf line))))))) + +(def ^:private download-patterns + ["status code: 429" "Too Many Requests" "Could not transfer artifact" + "Could not find artifact" "Failed to read artifact descriptor"]) + +(defn download-failure? + "True only when every given log shows a dependency download failure inside + its failed step (R24). No logs, or a log without an error line, is false." + [log-texts] + (boolean + (and (seq log-texts) + (every? (fn [t] + (when-let [section (failed-step-section t)] + (some #(str/includes? section %) download-patterns))) + log-texts)))) diff --git a/test/fleet/github_test.clj b/test/fleet/github_test.clj new file mode 100644 index 0000000..11d8973 --- /dev/null +++ b/test/fleet/github_test.clj @@ -0,0 +1,87 @@ +(ns fleet.github-test + (:require [clojure.test :refer [deftest is]] + [fleet.github :as gh])) + +(defn- stub + "A request fn answering from a map of url -> response; records the requests." + [responses seen] + (fn [req] + (swap! seen conj req) + (or (get responses (:url req)) {:status 404 :headers {} :body "{\"message\":\"Not Found\"}"}))) + +(deftest next-link-parses-rel-next + (is (= "https://api.github.com/x?page=2" + (gh/next-link "; rel=\"next\", ; rel=\"last\"")))) + +(deftest next-link-last-page-has-none + (is (nil? (gh/next-link "; rel=\"prev\", ; rel=\"first\""))) + (is (nil? (gh/next-link nil)))) + +(deftest next-link-next-listed-second + (is (= "https://api.github.com/x?page=3" + (gh/next-link "; rel=\"prev\", ; rel=\"next\"")))) + +(deftest get-json-parses-and-sends-auth + (let [seen (atom []) + c (gh/client {:token "tok" + :request (stub {"https://api.github.com/repos/o/r" + {:status 200 :headers {} :body "{\"name\":\"r\",\"tags\":[1,2]}"}} + seen)})] + (is (= {:name "r" :tags [1 2]} ((:get-json c) "repos/o/r"))) + (is (= "Bearer tok" (get-in (first @seen) [:headers "Authorization"]))) + (is (= false (:throw-exceptions (first @seen)))))) + +(deftest no-token-no-authorization-header + (let [seen (atom []) + c (gh/client {:request (stub {"https://api.github.com/a" {:status 200 :headers {} :body "{}"}} seen)})] + ((:get-json c) "/a") + (is (not (contains? (:headers (first @seen)) "Authorization"))))) + +(deftest get-raw-asks-for-raw-and-returns-text + (let [seen (atom []) + c (gh/client {:request (stub {"https://api.github.com/repos/o/r/contents/f" + {:status 200 :headers {} :body "plain: text\n"}} seen)})] + (is (= "plain: text\n" ((:get-raw c) "repos/o/r/contents/f"))) + (is (= "application/vnd.github.raw+json" (get-in (first @seen) [:headers "Accept"]))))) + +(deftest non-2xx-throws-ex-info-with-status-path-body + (let [c (gh/client {:request (stub {} (atom []))}) + e (try ((:get-json c) "repos/o/missing") nil (catch Exception e e))] + (is (some? e)) + (is (= 404 (:status (ex-data e)))) + (is (= "repos/o/missing" (:path (ex-data e)))) + (is (= "{\"message\":\"Not Found\"}" (:body (ex-data e)))) + (is (= 404 (gh/status-of e))))) + +(deftest get-raw-non-2xx-also-throws + (let [c (gh/client {:request (stub {"https://api.github.com/x" {:status 403 :headers {} :body "rate"}} (atom []))}) + e (try ((:get-raw c) "x") nil (catch Exception e e))] + (is (= 403 (gh/status-of e))))) + +(deftest get-paginated-follows-next-and-concatenates + (let [seen (atom []) + p1 "https://api.github.com/orgs/o/repos?per_page=100" + p2 "https://api.github.com/orgs/o/repos?per_page=100&page=2" + c (gh/client {:request (stub {p1 {:status 200 + :headers {"link" (str "<" p2 ">; rel=\"next\"")} + :body "[{\"n\":1},{\"n\":2}]"} + p2 {:status 200 :headers {"Link" "; rel=\"prev\""} + :body "[{\"n\":3}]"}} + seen)})] + (is (= [{:n 1} {:n 2} {:n 3}] ((:get-paginated c) "orgs/o/repos"))) + (is (= [p1 p2] (mapv :url @seen))))) + +(deftest get-paginated-keeps-an-explicit-per-page + (let [seen (atom []) + c (gh/client {:request (stub {"https://api.github.com/x?per_page=5" {:status 200 :headers {} :body "[]"}} seen)})] + (is (= [] ((:get-paginated c) "x?per_page=5"))) + (is (= ["https://api.github.com/x?per_page=5"] (mapv :url @seen))))) + +(deftest get-paginated-error-on-a-later-page-throws + (let [p1 "https://api.github.com/x?per_page=100" + p2 "https://api.github.com/x?page=2" + c (gh/client {:request (stub {p1 {:status 200 :headers {"link" (str "<" p2 ">; rel=\"next\"")} :body "[1]"} + p2 {:status 502 :headers {} :body "bad gateway"}} + (atom []))}) + e (try ((:get-paginated c) "x") nil (catch Exception e e))] + (is (= 502 (gh/status-of e))))) diff --git a/test/fleet/status_test.clj b/test/fleet/status_test.clj new file mode 100644 index 0000000..8f06b90 --- /dev/null +++ b/test/fleet/status_test.clj @@ -0,0 +1,200 @@ +(ns fleet.status-test + (:require [cheshire.core :as json] + [clojure.test :refer [deftest is]] + [fleet.status :as status])) + +(defn- fx + "Parse a status fixture. cheshire under jolt returns arrays as lazy seqs, so + a top-level array is made a vector for assoc-in." + [name] + (let [d (json/parse-string (slurp (str "test/fixtures/status/" name)) true)] + (if (sequential? d) (vec d) d))) + +(def ^:private nj + {:published_at "2026-11-20T01:00:00Z" + :sha "f4e82fc8eac874cae1658b7976518253027c4f6a" + :note "n"}) + +(def ^:private nj-aaaa {:published_at "x" :sha "aaaa1111" :note "n"}) + +(defn- run-bs + "build with the bats defaults. Opts override: :ps :ph :op :latest :nj + (use ::none for a nil nightly)." + [{:keys [ps ph op latest nightly] :or {latest "0.8.27" nightly nj}} & results] + (status/build {:prev-status ps + :prev-history ph + :own-pin (or op (fx "own-pin.json")) + :uncovered (fx "uncovered.json") + :latest latest + :nightly (when-not (= ::none nightly) nightly) + :canary-run "https://example/run/1" + :now "2026-11-20T04:00:00Z" + :results results})) + +(defn- cells [out name col] + (->> (get-in out [:status :projects]) (filter #(= name (:name %))) first :cells col)) + +(defn- hist [out name col] (get-in out [:history :projects (keyword name) col])) + +(defn- names [out] (mapv :name (get-in out [:status :projects]))) + +(defn- prev-cell [name col] + (->> (:projects (fx "prev-status.json")) (filter #(= name (:name %))) first :cells col)) + +(def ^:private prev-s (fx "prev-status.json")) +(def ^:private prev-h (fx "prev-history.json")) +(def ^:private not-run {:result "not-run"}) + +(deftest first-run-with-no-prev-files + (let [out (run-bs {} (fx "results-latest.json"))] + (is (= 1 (get-in out [:status :schema]))) + (is (= ["ebb" "glitter" "raygui-jlt"] (sort (names out)))) + (is (= not-run (cells out "raygui-jlt" :latest))) + (is (= not-run (cells out "raygui-jlt" :nightly))) + (is (= [{:name "duratom" :reason "ci.yml has no jolt-version input"}] + (get-in out [:status :uncovered]))) + (is (= "2026-11-20T04:00:00Z" (get-in out [:status :generated_at]))) + (is (= 1 (get-in out [:history :schema]))) + (is (= 1 (count (hist out "glitter" :latest)))) + (is (= 1 (count (hist out "ebb" :latest)))) + (is (= 1 (count (hist out "glitter" :pin)))))) + +(deftest pin-cell-comes-from-own-pin-with-installed-null + (let [c (cells (run-bs {}) "glitter" :pin)] + (is (= ["pass" "0.8.24" nil] ((juxt :result :version :installed) c))) + (is (contains? c :installed)))) + +(deftest latest-result-lands-in-latest-column + (let [out (run-bs {} (fx "results-latest.json"))] + (is (= ["pass" "0.8.27" "0.8.27"] + ((juxt :result :version :installed) (cells out "glitter" :latest)))) + (is (= {:version "0.8.27"} (get-in out [:status :jolt :latest]))))) + +(deftest v-prefix-on-requested-is-stripped + (let [out (run-bs {} (assoc (fx "results-latest.json") :requested "v0.8.27"))] + (is (= "0.8.27" (:version (cells out "glitter" :latest)))))) + +(deftest nightly-result-lands-in-nightly-column + (let [out (run-bs {} (fx "results-nightly.json"))] + (is (= ["pass" "nightly" "0.8.27-376-gf4e82fc8"] + ((juxt :result :version :installed) (cells out "glitter" :nightly)))) + (is (= "f4e82fc8eac874cae1658b7976518253027c4f6a" (get-in out [:status :jolt :nightly :sha]))))) + +(deftest adhoc-result-only-in-history + (let [out (run-bs {:ps prev-s :ph prev-h} (fx "results-adhoc.json"))] + (is (= "https://github.com/jlt-commons/glitter/actions/runs/42" + (:run_url (cells out "glitter" :latest)))) + (is (= 1 (count (hist out "glitter" :adhoc)))) + (is (= "0.8.25" (:version (first (hist out "glitter" :adhoc))))) + (is (= 0 (count (hist out "glitter" :latest)))))) + +(deftest results-for-a-project-outside-own-pin-go-to-history-not-the-grid + (let [r (assoc-in (fx "results-latest.json") [:projects 0 :name] "gone") + out (run-bs {} r)] + (is (nil? (some #{"gone"} (names out)))) + (is (= 1 (count (hist out "gone" :latest)))))) + +(deftest carry-over-with-only-own-pin-input + (let [out (run-bs {:nightly nj-aaaa :ps prev-s :ph prev-h})] + (is (= (prev-cell "ebb" :latest) (cells out "ebb" :latest))) + (is (= (prev-cell "glitter" :nightly) (cells out "glitter" :nightly))) + (is (= not-run (cells out "raygui-jlt" :latest))))) + +(deftest new-latest-version-invalidates-carried-latest-cells + (let [out (run-bs {:nightly nj-aaaa :ps prev-s :ph prev-h :latest "0.8.28"})] + (is (= not-run (cells out "ebb" :latest))) + (is (= not-run (cells out "glitter" :latest))) + (is (= "pass" (:result (cells out "glitter" :nightly)))))) + +(deftest new-nightly-sha-invalidates-carried-nightly-cells + (let [out (run-bs {:ps prev-s :ph prev-h})] + (is (= "not-run" (:result (cells out "glitter" :nightly)))) + (is (= "pass" (:result (cells out "glitter" :latest)))))) + +(deftest null-nightly-json-with-no-previous-status-gives-null-jolt-nightly + (let [out (run-bs {:nightly ::none})] + (is (contains? (get-in out [:status :jolt]) :nightly)) + (is (nil? (get-in out [:status :jolt :nightly]))))) + +(deftest same-nightly-sha-keeps-carried-nightly-cells + (let [out (run-bs {:nightly nj-aaaa :ps prev-s})] + (is (= "pass" (:result (cells out "glitter" :nightly)))))) + +(deftest null-nightly-json-keeps-previous-nightly-cells-and-previous-jolt-nightly + (let [out (run-bs {:nightly ::none :ps prev-s})] + (is (= (get-in prev-s [:jolt :nightly]) (get-in out [:status :jolt :nightly]))) + (is (= "pass" (:result (cells out "glitter" :nightly)))))) + +(deftest pin-history-appended-only-when-run-url-is-new + (let [out (run-bs {:ps prev-s :ph prev-h})] + (is (= 1 (count (hist out "glitter" :pin)))) + (is (= 1 (count (hist out "ebb" :pin)))) + (let [out2 (run-bs {:ps (:status out) :ph (:history out)})] + (is (= 1 (count (hist out2 "ebb" :pin)))) + (is (= 1 (count (hist out2 "raygui-jlt" :pin))))))) + +(deftest pin-history-grows-when-the-pin-run-changes + (let [out (run-bs {:ps prev-s :ph prev-h}) + op (assoc-in (fx "own-pin.json") [0 :run_url] + "https://github.com/jlt-commons/glitter/actions/runs/99") + out2 (run-bs {:op op :ph (:history out)})] + (is (= 2 (count (hist out2 "glitter" :pin)))) + (is (= "https://github.com/jlt-commons/glitter/actions/runs/99" + (:run_url (first (hist out2 "glitter" :pin))))))) + +(deftest history-capped-at-30-newest-first + (let [old (vec (for [i (range 30)] + {:result "pass" :version "0.8.26" :installed nil + :run_url (str "old/" i) :finished_at nil :failed_step nil})) + ph (assoc-in prev-h [:projects :glitter :latest] old) + out (run-bs {:ph ph} (fx "results-latest.json")) + l (hist out "glitter" :latest)] + (is (= 30 (count l))) + (is (= "https://github.com/jlt-commons/glitter/actions/runs/11" (:run_url (first l)))) + (is (= "old/28" (:run_url (nth l 29)))))) + +(deftest failing-first-then-by-name + (is (= ["raygui-jlt" "ebb" "glitter"] (names (run-bs {}))))) + +(deftest mismatch-cell-sorts-before-passing-ones + (let [op (assoc-in (fx "own-pin.json") [2 :result] "pass")] + (is (= ["raygui-jlt" "ebb" "glitter"] (names (run-bs {:op op} (fx "results-nightly.json"))))))) + +(deftest malformed-results-throw + (is (thrown? Exception + (run-bs {} {:requested "0.8.27" :projects "nope"})))) + +(deftest unknown-result-value-is-rejected + (is (thrown? Exception + (run-bs {} (assoc-in (fx "results-latest.json") [:projects 0 :result] "weird"))))) + +;; The bats case "unparseable results file" is the file-reading edge. Here it +;; is the shape a failed parse gives the pure function: not a map. +(deftest unparseable-results-input-is-rejected + (is (thrown? Exception (run-bs {} nil))) + (is (thrown? Exception (run-bs {} "{not json")))) + +(deftest latest-with-a-v-prefix-matches-results-and-prev + (let [out (run-bs {:nightly nj-aaaa :ps prev-s :latest "v0.8.27"} (fx "results-latest.json"))] + (is (= "0.8.27" (get-in out [:status :jolt :latest :version]))) + (is (= "https://github.com/jlt-commons/glitter/actions/runs/11" + (:run_url (cells out "glitter" :latest)))) + (is (= "not-run" (:result (cells out "raygui-jlt" :latest))))) + (let [out (run-bs {:nightly nj-aaaa :ps prev-s :latest "v0.8.27"})] + (is (= "fail" (:result (cells out "ebb" :latest)))))) + +(deftest reprocessing-the-same-results-does-not-duplicate-history + (let [rs [(fx "results-latest.json") (fx "results-nightly.json") (fx "results-adhoc.json")] + o1 (apply run-bs {} rs) + o2 (apply run-bs {:ps (:status o1) :ph (:history o1)} rs)] + (is (= (:history o1) (:history o2))) + (is (= 1 (count (hist o2 "glitter" :adhoc)))) + (is (= 1 (count (hist o2 "glitter" :latest)))) + (is (= 1 (count (hist o2 "glitter" :nightly)))))) + +(deftest unchanged-ignores-generated-at-and-canary-run + (let [s (:status (run-bs {}))] + (is (true? (status/unchanged? s (assoc s :generated_at "2030-01-01T00:00:00Z" + :canary_run "https://example/run/2")))) + (is (false? (status/unchanged? s (assoc-in s [:jolt :latest :version] "0.8.28")))) + (is (false? (status/unchanged? s (assoc s :uncovered [])))))) diff --git a/test/fleet/version_test.clj b/test/fleet/version_test.clj new file mode 100644 index 0000000..9c73ff1 --- /dev/null +++ b/test/fleet/version_test.clj @@ -0,0 +1,180 @@ +(ns fleet.version-test + (:require [clojure.string :as str] + [clojure.test :refer [deftest is]] + [fleet.version :as v])) + +(defn- fx [name] (slurp (str "test/fixtures/" name))) + +(defn- ts-line [ts s] (str "2026-11-19T01:02:0" ts ".0000000Z " s "\n")) + +(deftest release-log + (is (= "0.8.24" (v/installed-version (fx "log-release.txt"))))) + +(deftest nightly-log + (is (= "0.8.27-241-gdd3c4a4b" (v/installed-version (fx "log-nightly.txt"))))) + +(deftest no-version-line + (is (nil? (v/installed-version "Successfully installed jolt vnightly to /x\n")))) + +(deftest v-prefix-requested + (is (true? (v/version-matches? "v0.8.24" "0.8.24" nil)))) + +(deftest release-mismatch + (is (false? (v/version-matches? "0.8.27" "0.8.24" nil)))) + +(deftest nightly-sha-match + (is (true? (v/version-matches? "nightly" "0.8.27-241-gdd3c4a4b" + "dd3c4a4b0123456789abcdef0123456789abcdef")))) + +(deftest nightly-stale-sha + (is (false? (v/version-matches? "nightly" "0.8.27-241-gdd3c4a4b" + "98e5ef990000000000000000000000000000000a")))) + +(deftest nightly-no-sha + (is (false? (v/version-matches? "nightly" "0.8.27-241-gdd3c4a4b" nil))) + (is (false? (v/version-matches? "nightly" "0.8.27-241-gdd3c4a4b" "")))) + +(deftest nightly-got-a-release + (is (false? (v/version-matches? "nightly" "0.8.27" "dd3c4a4b00")))) + +(defn- pin [line] (v/parse-pin (str line "\n"))) + +(deftest pin-input-with-default + (is (= "0.8.24" (pin " JOLT_VERSION: ${{ inputs.jolt-version || '0.8.24' }}")))) + +(deftest pin-input-with-v-default + (is (= "0.8.24" (pin " JOLT_VERSION: ${{ inputs.jolt-version || 'v0.8.24' }}")))) + +(deftest pin-quoted-literal + (is (= "0.8.24" (pin " JOLT_VERSION: \"0.8.24\"")))) + +(deftest pin-needs-output-is-not-literal + (is (nil? (pin " JOLT_VERSION: ${{ needs.jolt-version.outputs.version }}")))) + +(deftest pin-comment-mentions-are-skipped + (is (= "0.8.24" (v/parse-pin "# JOLT_VERSION: 9.9.9 is old\nenv:\n JOLT_VERSION: \"0.8.24\"\n")))) + +(deftest pin-no-key-at-all + (is (nil? (v/parse-pin "name: x\n")))) + +(deftest pin-missing-file + (is (nil? (v/parse-pin nil)))) + +(deftest uncovered-in-fleet-prints-nothing + (is (nil? (v/uncovered-reason {:has-ci? true :has-input? true :in-fleet? true :excluded ""})))) + +(deftest uncovered-in-fleet-beats-excluded + (is (nil? (v/uncovered-reason {:has-ci? false :has-input? false :in-fleet? true :excluded "why"})))) + +(deftest uncovered-excluded + (is (= "excluded: needs input" + (v/uncovered-reason {:has-ci? true :has-input? false :in-fleet? false :excluded "needs input"})))) + +(deftest uncovered-excluded-beats-no-ci + (is (= "excluded: private demo" + (v/uncovered-reason {:has-ci? false :has-input? false :in-fleet? false :excluded "private demo"})))) + +(deftest uncovered-no-ci-yml + (is (= "no ci.yml" + (v/uncovered-reason {:has-ci? false :has-input? false :in-fleet? false :excluded ""})))) + +(deftest uncovered-no-input + (is (= "ci.yml has no jolt-version input" + (v/uncovered-reason {:has-ci? true :has-input? false :in-fleet? false :excluded ""})))) + +(deftest uncovered-ready + (is (= "ready, not yet in fleet.json" + (v/uncovered-reason {:has-ci? true :has-input? true :in-fleet? false :excluded ""})))) + +(deftest pin-non-literal-with-quoted-version-in-a-trailing-comment + (is (nil? (pin " JOLT_VERSION: ${{ needs.x.outputs.v }} # was '0.8.24'")))) + +(deftest pin-literal-followed-by-a-comment + (is (= "0.8.24" (pin " JOLT_VERSION: \"0.8.24\" # pinned")))) + +(deftest pin-bare-literal + (is (= "0.8.24" (pin " JOLT_VERSION: v0.8.24")))) + +(deftest installed-crlf-line + (is (= "0.8.27-241-gdd3c4a4b" + (v/installed-version "2026-11-18T03:48:27.0669741Z jolt v0.8.27-241-gdd3c4a4b\r\n")))) + +(deftest installed-20000-line-log-version-last + (let [filler (apply str (repeat 20000 "2026-11-18T03:48:27.0000000Z some build output line with jolt in it\n"))] + (is (= "0.8.24" (v/installed-version (str filler "2026-11-18T03:48:28.0000000Z jolt v0.8.24\n")))))) + +(defn- logs2 [a b] [(ts-line 3 (str "jolt v" a)) (ts-line 4 (str "jolt v" b))]) + +(deftest pick-matching-second-log + (is (= {:installed "0.8.27" :match? true} + (v/pick-installed "0.8.27" "" (logs2 "0.7.29" "0.8.27"))))) + +(deftest pick-none-match-reports-first + (is (= {:installed "0.7.29" :match? false} + (v/pick-installed "0.8.26" "" (logs2 "0.7.29" "0.8.27"))))) + +(deftest pick-nightly-sha-in-second-log + (is (= {:installed "0.8.27-241-gdd3c4a4b" :match? true} + (v/pick-installed "nightly" "dd3c4a4b0123456789abcdef0123456789abcdef" + (logs2 "0.7.29" "0.8.27-241-gdd3c4a4b"))))) + +(deftest pick-no-versions + (is (= {:installed nil :match? false} + (v/pick-installed "0.8.27" "" ["nothing\n"])))) + +(deftest download-failure-maven-429 + (is (true? (v/download-failure? [(fx "log-maven-429.txt")])))) + +(deftest download-failure-maven-absent + (is (true? (v/download-failure? [(fx "log-maven-absent.txt")])))) + +(deftest download-failure-test-failure + (is (false? (v/download-failure? [(fx "log-test-failure.txt")])))) + +(deftest download-failure-no-args + (is (false? (v/download-failure? [])))) + +(deftest download-failure-earlier-step-printed-429-failed-step-is-a-test + (is (false? (v/download-failure? [(fx "log-early-429.txt")])))) + +(deftest download-failure-one-deps-log-and-one-test-log-is-not-infra + (is (false? (v/download-failure? [(fx "log-maven-429.txt") (fx "log-test-failure.txt")])))) + +(deftest download-failure-both-deps-logs + (is (true? (v/download-failure? [(fx "log-maven-429.txt") (fx "log-maven-absent.txt")])))) + +(deftest download-failure-no-error-line + (is (false? (v/download-failure? [(fx "log-no-error.txt")])))) + +(deftest download-failure-classpath-lookup-failed-alone-is-not-enough + (is (false? (v/download-failure? + [(str/join "\n" ["2026-11-20T01:00:00.0000000Z ##[group]Run x" + "2026-11-20T01:00:01.0000000Z [ERROR] Classpath lookup failed" + "2026-11-20T01:00:02.0000000Z ##[error]Process completed with exit code 1."])])))) + +;; Real-shaped fixtures the reviewer asked for. + +(def ^:private lsp-429-failed-step + (str/join "\n" + ["2026-11-20T02:00:00.0000000Z ##[group]Run bb lsp:format-check" + "2026-11-20T02:00:01.0000000Z bb lsp:format-check" + "2026-11-20T02:00:05.0000000Z ##[endgroup]" + "2026-11-20T02:00:06.0000000Z Downloading from central: https://repo1.maven.org/maven2/x.pom" + "2026-11-20T02:00:07.0000000Z Error building classpath. Could not transfer artifact x:x:pom:1 from/to central: status code: 429, reason phrase: Too Many Requests (429)" + "2026-11-20T02:00:08.0000000Z ##[error]Process completed with exit code 1."])) + +(deftest download-failure-group-run-then-429-then-error + (is (true? (v/download-failure? [lsp-429-failed-step])))) + +(def ^:private test-failure-then-post-step-429 + (str/join "\n" + ["2026-11-20T02:00:00.0000000Z ##[group]Run bb test" + "2026-11-20T02:00:01.0000000Z FAIL in (vec-add-test) (vector_test.clj:12)" + "2026-11-20T02:00:02.0000000Z ##[error]Process completed with exit code 1." + "2026-11-20T02:00:03.0000000Z Post job cleanup." + "2026-11-20T02:00:04.0000000Z ##[group]Run post-step" + "2026-11-20T02:00:05.0000000Z Cache save failed: status code: 429" + "2026-11-20T02:00:06.0000000Z ##[error]cache save failed"])) + +(deftest download-failure-first-error-is-a-test-failure-later-429 + (is (false? (v/download-failure? [test-failure-then-post-step-429])))) From b093efa695c2a77e7d80f8c28ee1afa26541fe45 Mon Sep 17 00:00:00 2001 From: burinc Date: Fri, 20 Nov 2026 14:41:39 +1100 Subject: [PATCH 17/31] fleet: collectors, publish, refresh and the fleet:* tasks in jolt (part 2 of the port) Ports collect.bats (13), publish-status.bats (6, plus a worktree cleanup case) and refresh-status.bats (3) to clojure.test. The GitHub client sends the token to api.github.com only and does not follow redirects. test.yml gains a jolt job. --- .github/workflows/test.yml | 22 +++++ .gitignore | 1 + deps.edn | 32 ++++++- src/fleet/cli.clj | 167 +++++++++++++++++++++++++++++++++ src/fleet/collect.clj | 121 ++++++++++++++++++++++++ src/fleet/github.clj | 31 ++++++- src/fleet/publish.clj | 116 +++++++++++++++++++++++ src/fleet/refresh.clj | 65 +++++++++++++ test/fleet/cli_test.clj | 123 +++++++++++++++++++++++++ test/fleet/collect_test.clj | 178 ++++++++++++++++++++++++++++++++++++ test/fleet/github_test.clj | 50 +++++++++- test/fleet/publish_test.clj | 139 ++++++++++++++++++++++++++++ test/fleet/refresh_test.clj | 74 +++++++++++++++ 13 files changed, 1111 insertions(+), 8 deletions(-) create mode 100644 .gitignore create mode 100644 src/fleet/cli.clj create mode 100644 src/fleet/collect.clj create mode 100644 src/fleet/publish.clj create mode 100644 src/fleet/refresh.clj create mode 100644 test/fleet/cli_test.clj create mode 100644 test/fleet/collect_test.clj create mode 100644 test/fleet/publish_test.clj create mode 100644 test/fleet/refresh_test.clj diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index d273447..b5e9736 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -6,6 +6,15 @@ on: branches-ignore: [status] pull_request: +permissions: + contents: read + +env: + # The tool jolt: runs the fleet tools and their tests. Pinned so a release + # published overnight can't turn this red on an untouched tree. This is not + # the jolt the fleet is tested against. + TOOLS_JOLT_VERSION: ${{ vars.TOOLS_JOLT_VERSION || '0.8.27' }} + jobs: test: runs-on: ubuntu-latest @@ -14,3 +23,16 @@ jobs: - run: sudo apt-get install -y bats - run: bats test/ - run: shellcheck -x scripts/lib/*.sh scripts/build-status.sh scripts/collect-own-pin.sh scripts/collect-uncovered.sh scripts/publish-status.sh scripts/refresh-status.sh + + jolt: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: jlt-commons/setup-jolt@v1 + with: + version: ${{ env.TOOLS_JOLT_VERSION }} + - uses: actions/cache@v6.1.0 + with: + path: ~/.jolt/gitlibs + key: jolt-gitlibs-${{ hashFiles('deps.edn') }} + - run: jolt test diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d337e6d --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.jolt/ diff --git a/deps.edn b/deps.edn index 2053f56..2c19e8e 100644 --- a/deps.edn +++ b/deps.edn @@ -12,10 +12,38 @@ :tasks {test {:doc "Run every fleet.*-test namespace; exit 1 on any failure or error" :requires ([clojure.test :as t] + [fleet.cli-test] + [fleet.collect-test] [fleet.github-test] + [fleet.publish-test] + [fleet.refresh-test] [fleet.status-test] [fleet.version-test]) - :task (let [{:keys [fail error]} (t/run-tests 'fleet.github-test + :task (let [{:keys [fail error]} (t/run-tests 'fleet.cli-test + 'fleet.collect-test + 'fleet.github-test + 'fleet.publish-test + 'fleet.refresh-test 'fleet.status-test 'fleet.version-test)] - (when (pos? (+ fail error)) (System/exit 1)))}}} + (when (pos? (+ fail error)) (System/exit 1)))} + + fleet:own-pin {:doc "Print each fleet project's latest push run and pin as JSON (env: GH_TOKEN, FLEET_JSON)" + :requires ([fleet.cli :as cli]) + :task (System/exit (cli/own-pin-main *command-line-args*))} + + fleet:uncovered {:doc "Print the org repos the fleet does not cover, with reasons, as JSON" + :requires ([fleet.cli :as cli]) + :task (System/exit (cli/uncovered-main *command-line-args*))} + + fleet:status {:doc "Merge results into status.json and history.json: --prev-status F --prev-history F --own-pin F --uncovered F --latest V --nightly-json J|null --canary-run URL --now ISO --out-dir D [results.json ...]" + :requires ([fleet.cli :as cli]) + :task (System/exit (cli/status-main *command-line-args*))} + + fleet:refresh {:doc "Collect, merge and write /status.json and history.json [results.json ...] (env: LATEST NIGHTLY_JSON CANARY_RUN, PREV_DIR)" + :requires ([fleet.cli :as cli]) + :task (System/exit (cli/refresh-main *command-line-args*))} + + fleet:publish {:doc "Refresh and commit to origin's status branch: [results.json ...] (env: LATEST NIGHTLY_JSON CANARY_RUN)" + :requires ([fleet.cli :as cli]) + :task (System/exit (cli/publish-main *command-line-args*))}}} diff --git a/src/fleet/cli.clj b/src/fleet/cli.clj new file mode 100644 index 0000000..3dcba53 --- /dev/null +++ b/src/fleet/cli.clj @@ -0,0 +1,167 @@ +(ns fleet.cli + "Command-line entry points behind the fleet:* tasks. Each *-main takes its + arguments (and, where it reads the environment, an env map) and returns an + exit code; the task wrapper in deps.edn passes it to System/exit. Failures + print one line to stderr, exit 1, and write no files. Usage errors exit 2." + (:require [cheshire.core :as json] + [clojure.string :as str] + [fleet.collect :as collect] + [fleet.github :as github] + [fleet.publish :as publish] + [fleet.refresh :as refresh] + [fleet.status :as status])) + +(defn- err [& xs] (binding [*out* *err*] (println (str/join " " xs)))) + +(defn- usage-error [usage msg] + (err (str "usage: " usage)) + (when msg (err msg)) + 2) + +(defn- guarded + "Run f. An integer result is the exit code, anything else counts as 0; an + exception prints one line and becomes exit 1." + [who f] + (try (let [r (f)] (if (integer? r) r 0)) + (catch Exception e + (err (str who ":") (ex-message e)) + 1))) + +(defn- now-iso [] + (str (.truncatedTo (java.time.Instant/now) java.time.temporal.ChronoUnit/SECONDS))) + +(defn- parse-nightly + "NIGHTLY_JSON / --nightly-json: the literal null, or a JSON object." + [text] + (let [v (try (json/parse-string text true) + (catch Exception _ (throw (ex-info "nightly JSON is not valid JSON" {}))))] + (when-not (or (nil? v) (map? v)) + (throw (ex-info "nightly JSON must be an object or null" {}))) + v)) + +(defn- load-fleet [env] + (refresh/read-json-file (or (get env "FLEET_JSON") "fleet.json") false)) + +(defn- gh-of [deps] (or (:gh deps) (github/env-client))) + +(defn- print-json [rows] (print (refresh/json-str rows)) (flush)) + +(defn own-pin-main + "fleet:own-pin: print own-pin.json on stdout." + ([args] (own-pin-main args (into {} (System/getenv)) {})) + ([_args env deps] + (guarded "own-pin" #(print-json (collect/own-pin (gh-of deps) (load-fleet env)))))) + +(defn uncovered-main + "fleet:uncovered: print uncovered.json on stdout." + ([args] (uncovered-main args (into {} (System/getenv)) {})) + ([_args env deps] + (guarded "uncovered" #(print-json (collect/uncovered (gh-of deps) (load-fleet env)))))) + +(def ^:private status-usage + (str "status --prev-status F --prev-history F --own-pin F --uncovered F\n" + " --latest VERSION --nightly-json JSON|null --canary-run URL --now ISO --out-dir D [results.json ...]")) + +(def ^:private status-flags + {"--prev-status" :prev-status "--prev-history" :prev-history "--own-pin" :own-pin + "--uncovered" :uncovered "--latest" :latest "--nightly-json" :nightly-json + "--canary-run" :canary-run "--now" :now "--out-dir" :out-dir}) + +(defn- parse-status-args + "{:opts m :results [paths]} or {:error msg}." + [args] + (loop [args (seq args) opts {} results []] + (cond + (nil? args) {:opts opts :results results} + (= "--" (first args)) {:opts opts :results (into results (rest args))} + (str/starts-with? (first args) "-") + (if-let [k (status-flags (first args))] + (if (next args) + (recur (nnext args) (assoc opts k (second args)) results) + {:error (str (first args) " needs a value")}) + {:error (str "unknown flag " (first args))}) + :else (recur (next args) opts (conj results (first args)))))) + +(defn status-main + "fleet:status: the pure merge, with build-status.sh's flags." + [args] + (let [{:keys [opts results error]} (parse-status-args args) + missing (remove opts [:own-pin :uncovered :latest :nightly-json :canary-run :now :out-dir])] + (cond + error (usage-error status-usage error) + (seq missing) (usage-error status-usage (str "missing " (str/join ", " (map name missing)))) + :else + (guarded "build-status" + #(let [{:keys [prev-status prev-history own-pin uncovered latest nightly-json + canary-run now out-dir]} opts + read (fn [p optional?] (refresh/read-json-file p optional?)) + built (status/build {:prev-status (read prev-status true) + :prev-history (read prev-history true) + :own-pin (read own-pin false) + :uncovered (read uncovered false) + :latest latest + :nightly (parse-nightly nightly-json) + :canary-run canary-run + :now now + :results (mapv (fn [f] (read f false)) results)})] + (refresh/write-outputs! out-dir built)))))) + +(def ^:private refresh-usage "refresh [results.json ...] (env: LATEST NIGHTLY_JSON CANARY_RUN)") + +(defn- require-env + "The first missing name among names, or nil." + [env names] + (first (remove #(seq (get env %)) names))) + +(defn- refresh-opts + "The refresh! options for [results ...] under env. Throws on a + bad NIGHTLY_JSON." + [[out-dir & results] env deps] + (let [fleet (load-fleet env) + gh (gh-of deps)] + {:out-dir out-dir + :prev-dir (get env "PREV_DIR") + :latest (get env "LATEST") + :nightly (parse-nightly (get env "NIGHTLY_JSON")) + :canary-run (get env "CANARY_RUN") + :results-files (vec results) + :own-pin #(collect/own-pin gh fleet) + :uncovered #(collect/uncovered gh fleet) + :now (now-iso)})) + +(defn refresh-main + "fleet:refresh: collect, build and write /status.json and + history.json. Env: LATEST, NIGHTLY_JSON, CANARY_RUN (required), PREV_DIR, + FLEET_JSON, GH_TOKEN." + ([args] (refresh-main args (into {} (System/getenv)) {})) + ([args env deps] + (if-let [v (require-env env ["LATEST" "NIGHTLY_JSON" "CANARY_RUN"])] + (do (err (str "refresh-status: " v " is required")) (usage-error refresh-usage nil)) + (if (empty? args) + (usage-error refresh-usage nil) + (guarded "refresh-status" #(refresh/refresh! (refresh-opts args env deps))))))) + +(defn publish-main + "fleet:publish: run in a checkout whose origin it can push to. Refreshes + in-process on every attempt, then commits to origin's status branch." + ([args] (publish-main args (into {} (System/getenv)) {})) + ([args env deps] + (if-let [v (require-env env ["LATEST" "NIGHTLY_JSON" "CANARY_RUN"])] + (do (err (str "publish-status: " v " is required")) + (usage-error "publish [results.json ...] (env: LATEST NIGHTLY_JSON CANARY_RUN)" nil)) + (if (empty? args) + (usage-error "publish [results.json ...]" nil) + (guarded "publish-status" + #(let [[out-dir & results] args + base (refresh-opts [out-dir] env deps) + res (publish/publish! + {:repo-dir "." :out-dir out-dir :sh publish/sh + :rebuild (fn [{:keys [prev-dir out-dir]}] + (refresh/refresh! (assoc base + :out-dir out-dir + :prev-dir prev-dir + :results-files (vec results) + :now (now-iso))))})] + (println (if (= :unchanged (:result res)) + "status: unchanged" + (str "status: published (attempt " (:attempt res) ")"))))))))) diff --git a/src/fleet/collect.clj b/src/fleet/collect.clj new file mode 100644 index 0000000..7af3c48 --- /dev/null +++ b/src/fleet/collect.clj @@ -0,0 +1,121 @@ +(ns fleet.collect + "The network collectors: each fleet project's latest push CI run with its + pin, and the org repos the fleet does not cover. gh is a map of the + fleet.github fns ({:get-json :get-raw :get-paginated}), so tests stub it. + Any failure to read one repo degrades that repo's row and warns on stderr; + it never aborts the collection." + (:require [clojure.string :as str] + [fleet.version :as version] + [jolt.yaml :as yaml])) + +(def org "jlt-commons") + +(defn- warn [who & msg] + (binding [*out* *err*] + (println (str who ": " (str/join " " msg))))) + +(defn- explain [e] + (str (or (some-> (ex-data e) :status (->> (str "HTTP "))) + "error") + ": " (ex-message e))) + +(defn- ci-path [p] (str "repos/" org "/" p "/contents/.github/workflows/ci.yml")) + +(defn- run-row [name pin result run-url at step] + {:name name :pin pin :result result :run_url run-url :finished_at at :failed_step step}) + +(defn- conclusion->result [conclusion] + (case conclusion + "success" "pass" + "failure" "fail" + "timed_out" "timed-out" + "not-run")) + +(defn- failed-step [gh p run-id] + (try + (let [jobs (:jobs ((:get-json gh) (str "repos/" org "/" p "/actions/runs/" run-id "/jobs?per_page=100")))] + (->> jobs + (filter #(= "failure" (:conclusion %))) + (mapcat :steps) + (filter #(= "failure" (:conclusion %))) + first + :name)) + (catch Exception e + (warn "collect-own-pin" p "could not read jobs" (explain e)) + nil))) + +(defn- own-pin-of [gh p] + (let [branch (try (:default_branch ((:get-json gh) (str "repos/" org "/" p))) + (catch Exception e + (warn "collect-own-pin" p "could not read repository:" (explain e)) + nil))] + (if-not branch + (run-row p nil "not-run" nil nil nil) + (let [pin (try (version/parse-pin ((:get-raw gh) (ci-path p))) + (catch Exception e + (warn "collect-own-pin" p "could not read ci.yml:" (explain e)) + nil)) + runs (try (:workflow_runs + ((:get-json gh) + (str "repos/" org "/" p "/actions/workflows/ci.yml/runs?branch=" + (java.net.URLEncoder/encode ^String branch "UTF-8") + "&event=push&status=completed&per_page=1"))) + (catch Exception e + (warn "collect-own-pin" p "could not list runs:" (explain e)) + ::failed))] + (cond + (= ::failed runs) (run-row p pin "not-run" nil nil nil) + (empty? runs) (run-row p pin "not-run" nil nil nil) + :else + (let [r (first runs) + result (conclusion->result (:conclusion r))] + (run-row p pin result (:html_url r) (:updated_at r) + (when (= "fail" result) (failed-step gh p (:id r)))))))))) + +(defn own-pin + "One row per fleet project, in fleet order: {:name :pin :result :run_url + :finished_at :failed_step}. fleet is {:projects [...] :excluded {...}}." + [gh fleet] + (mapv #(own-pin-of gh %) (:projects fleet))) + +(defn- has-input? + "Does the workflow declare a workflow_dispatch input named jolt-version? + YAML 1.1 readers turn an unquoted `on` key into boolean true." + [doc] + (let [on (or (get doc "on") (get doc true))] + (boolean (and (map? on) + (let [inputs (get-in on ["workflow_dispatch" "inputs"])] + (and (map? inputs) (contains? inputs "jolt-version"))))))) + +(def ^:private unreadable "could not read repository") + +(defn- reason-for [gh fleet p] + (let [in-fleet? (boolean (some #{p} (:projects fleet))) + excluded (get (:excluded fleet) (keyword p))] + (if (or in-fleet? (seq excluded)) + (version/uncovered-reason {:in-fleet? in-fleet? :excluded excluded}) + (let [ci (try {:text ((:get-raw gh) (ci-path p))} + (catch Exception e + (if (= 404 (:status (ex-data e))) + {:missing true} + (do (warn "collect-uncovered" p unreadable ":" (explain e)) + {:error true}))))] + (cond + (:error ci) unreadable + (:missing ci) (version/uncovered-reason {:has-ci? false}) + :else + (try (version/uncovered-reason {:has-ci? true :has-input? (has-input? (yaml/load (:text ci)))}) + (catch Exception e + (warn "collect-uncovered" p "could not parse ci.yml:" (explain e)) + unreadable))))))) + +(defn uncovered + "Public, non-archived org repos the fleet does not cover, each with a + reason: [{:name :reason}]." + [gh fleet] + (->> ((:get-paginated gh) (str "orgs/" org "/repos?type=public")) + (filter #(and (not (:archived %)) (not (:private %)))) + (keep (fn [{:keys [name]}] + (when-let [r (reason-for gh fleet name)] + {:name name :reason r}))) + vec)) diff --git a/src/fleet/github.clj b/src/fleet/github.clj index 3761ef9..e5c046a 100644 --- a/src/fleet/github.clj +++ b/src/fleet/github.clj @@ -22,18 +22,39 @@ (when (= "next" rel) url))) (str/split link-header #",\s*(?=<)")))) -(defn- url-for [path] +(defn- api-url? + "True for api-base itself or a URL under it. The character after the host + must be /, ? or the end, so api.github.com.evil.example and + api.github.com@evil.example do not pass." + [url] + (and (str/starts-with? url api-base) + (let [c (get url (count api-base))] + (or (nil? c) (= \/ c) (= \? c))))) + +(defn- url-for + "The request URL for a path. A full URL must be on api-base: the token + rides on every request, so any other host throws ex-info with + {:reason :foreign-host} before a request is made." + [path] (cond - (re-find #"^https?://" path) path - (str/starts-with? path "/") (str api-base path) - :else (str api-base "/" path))) + (re-find #"^[a-zA-Z][a-zA-Z0-9+.-]*://" path) + (if (api-url? path) + path + (throw (ex-info (str "refusing to send the GitHub token to a foreign host: " path) + {:reason :foreign-host :url path}))) + (str/starts-with? path "/") (str api-base path) + :else (str api-base "/" path))) (defn- with-per-page [path] (if (re-find #"[?&]per_page=" path) path (str path (if (str/includes? path "?") "&" "?") "per_page=100"))) -(defn- default-request [req] (http/get (:url req) (dissoc req :url))) +(defn- default-request + "No redirects: the client would replay the Authorization header to a + redirect target on any host." + [req] + (http/get (:url req) (assoc (dissoc req :url) :follow-redirects false))) (defn- request! "One GET. Returns the response map, or throws ex-info on a non-2xx status." diff --git a/src/fleet/publish.clj b/src/fleet/publish.clj new file mode 100644 index 0000000..630e649 --- /dev/null +++ b/src/fleet/publish.clj @@ -0,0 +1,116 @@ +(ns fleet.publish + "Commit status.json and history.json to the orphan `status` branch of + origin (R11-R13). Git runs through an injected sh fn, so tests can point + it at a local bare repository." + (:require [babashka.fs :as fs] + [babashka.process :as p] + [cheshire.core :as json] + [clojure.string :as str] + [fleet.status :as status])) + +(def ^:private attempts 3) + +(def ^:private bot ["-c" "user.name=github-actions[bot]" + "-c" "user.email=41898282+github-actions[bot]@users.noreply.github.com"]) + +(defn sh + "Run a command in dir. Returns {:exit :out :err}; never throws on a + non-zero exit." + [dir & args] + (let [{:keys [exit out err]} (apply p/sh {:dir dir} args)] + {:exit exit :out out :err err})) + +(defn- git! + "git in dir via sh; throws ex-info on a non-zero exit." + [sh dir & args] + (let [{:keys [exit err] :as r} (apply sh dir "git" args)] + (when-not (zero? exit) + (throw (ex-info (str "git " (str/join " " args) " failed: " (str/trim (str err))) + {:exit exit :args args}))) + r)) + +(defn- warn [& msg] (binding [*out* *err*] (println (str "publish-status: " (str/join " " msg))))) + +(defn- read-json [path] (json/parse-string (slurp path) true)) + +(defn- open-worktree! + "Add a detached worktree at wt on the tip of origin's status branch, or on + a fresh orphan when the branch does not exist yet. Copies the previous + status.json and history.json (when present) into prev." + [sh repo-dir wt prev] + (let [rc (:exit (sh repo-dir "git" "ls-remote" "--exit-code" "--heads" "origin" "status"))] + (case rc + 0 (do (git! sh repo-dir "fetch" "--quiet" "origin" "+refs/heads/status:refs/remotes/origin/status") + (git! sh repo-dir "worktree" "add" "--quiet" "--detach" wt "refs/remotes/origin/status") + (doseq [f ["status.json" "history.json"] + :when (fs/exists? (str wt "/" f))] + (fs/copy (str wt "/" f) (str prev "/" f)))) + 2 (do (git! sh repo-dir "worktree" "add" "--quiet" "--detach" wt "HEAD") + (git! sh wt "checkout" "--quiet" "--orphan" "status") + (git! sh wt "rm" "-rfq" ".")) + (throw (ex-info (str "publish-status: cannot reach origin (ls-remote exit " rc ")") + {:exit rc}))))) + +(defn- unchanged? + "R12: history.json byte-identical, status.json equal apart from + generated_at and canary_run." + [out wt] + (and (fs/exists? (str wt "/status.json")) + (fs/exists? (str wt "/history.json")) + (= (slurp (str wt "/history.json")) (slurp (str out "/history.json"))) + (status/unchanged? (read-json (str wt "/status.json")) + (read-json (str out "/status.json"))))) + +(defn- attempt! + "One try. Returns :unchanged, :published or :rejected." + [{:keys [sh repo-dir rebuild]} out tmp] + (let [wt (str tmp "/wt") + prev (str tmp "/prev")] + (fs/delete-tree prev) + (fs/create-dirs prev) + (try + (open-worktree! sh repo-dir wt prev) + (rebuild {:prev-dir prev :out-dir out}) + (when-not (and (fs/exists? (str out "/status.json")) (fs/exists? (str out "/history.json"))) + (throw (ex-info (str "publish-status: rebuild did not write both files in " out) {}))) + (if (unchanged? out wt) + :unchanged + (do (fs/copy (str out "/status.json") (str wt "/status.json") {:replace-existing true}) + (fs/copy (str out "/history.json") (str wt "/history.json") {:replace-existing true}) + (git! sh wt "add" "status.json" "history.json") + (apply git! sh wt (concat bot ["commit" "--quiet" "-m" "status: update fleet status"])) + (if (zero? (:exit (sh wt "git" "push" "--quiet" "origin" "HEAD:refs/heads/status"))) + :published + :rejected))) + (finally + (sh repo-dir "git" "worktree" "remove" "--force" wt) + (fs/delete-tree wt) + (sh repo-dir "git" "worktree" "prune"))))) + +(defn publish! + "Publish the status files to origin's status branch. + + opts: :repo-dir (a checkout whose origin it can push to), :out-dir, + :rebuild (a fn of {:prev-dir :out-dir} that writes status.json and + history.json into :out-dir; run on every attempt, the first included, with + :prev-dir holding the freshly fetched files, which may be absent) and :sh + (see `sh`). A rejected push means someone published meanwhile, so the next + attempt rebuilds on top of their result. Returns {:result :published + :attempt n} or {:result :unchanged}; throws after 3 rejected pushes." + [{:keys [out-dir rebuild] :as opts}] + (when-not rebuild + (throw (ex-info "publish-status: rebuild is required" {}))) + (fs/create-dirs out-dir) + (let [out (str (fs/canonicalize out-dir)) + tmp (str (fs/create-temp-dir))] + (try + (loop [n 1] + (let [r (attempt! opts out tmp)] + (cond + (= :unchanged r) {:result :unchanged} + (= :published r) {:result :published :attempt n} + (< n attempts) (do (warn (str "push rejected on attempt " n ", retrying")) + (recur (inc n))) + :else (throw (ex-info (str "publish-status: gave up after " attempts " rejected pushes") + {:attempts attempts}))))) + (finally (fs/delete-tree tmp))))) diff --git a/src/fleet/refresh.clj b/src/fleet/refresh.clj new file mode 100644 index 0000000..1a9a0db --- /dev/null +++ b/src/fleet/refresh.clj @@ -0,0 +1,65 @@ +(ns fleet.refresh + "Collect, build and write the status files: the one sequence the canary + and the ad-hoc fan-out publish both run (R18). Pure of CLI concerns; see + fleet.cli for flags and environment." + (:require [babashka.fs :as fs] + [cheshire.core :as json] + [fleet.status :as status])) + +(defn read-json-file + "Parse a JSON file. A top-level array comes back as a vector. nil for a + missing file when optional?; otherwise throws ex-info naming the file." + [path optional?] + (cond + (and optional? (or (nil? path) (not (fs/exists? path)))) nil + (not (and path (fs/exists? path))) (throw (ex-info (str "cannot read " path) {:path path})) + :else + (try (let [v (json/parse-string (slurp path) true)] + (if (sequential? v) (vec v) v)) + (catch Exception e + (throw (ex-info (str "cannot parse " path ": " (ex-message e)) {:path path})))))) + +(defn- canonical + "Maps become sorted maps all the way down, so the same data always + serialises to the same bytes (publish compares history.json byte for byte)." + [x] + (cond + (map? x) (into (sorted-map) (map (fn [[k v]] [k (canonical v)])) x) + (sequential? x) (mapv canonical x) + :else x)) + +(defn json-str + "Deterministic, pretty JSON with a trailing newline." + [x] + (str (json/generate-string (canonical x) {:pretty true}) "\n")) + +(defn write-outputs! + "Write {:status m :history m} as status.json and history.json under + out-dir, creating it. Call only once the build has succeeded." + [out-dir {:keys [status history]}] + (fs/create-dirs out-dir) + (spit (str out-dir "/status.json") (json-str status)) + (spit (str out-dir "/history.json") (json-str history))) + +(defn refresh! + "Collect, merge and write status.json and history.json into :out-dir. + + opts: :out-dir, :prev-dir (holds the previous files; nil or empty is fine), + :latest, :nightly (a map, or nil to keep the previous cell), :canary-run, + :results-files (paths), :own-pin and :uncovered (thunks returning the + collectors' rows) and :now (an ISO string). Nothing is written unless the + whole build succeeds." + [{:keys [out-dir prev-dir latest nightly canary-run results-files own-pin uncovered now]}] + (let [prev (fn [f] (read-json-file (when prev-dir (str prev-dir "/" f)) true)) + results (mapv #(read-json-file % false) results-files) + built (status/build {:prev-status (prev "status.json") + :prev-history (prev "history.json") + :own-pin (own-pin) + :uncovered (uncovered) + :latest latest + :nightly nightly + :canary-run canary-run + :now now + :results results})] + (write-outputs! out-dir built) + built)) diff --git a/test/fleet/cli_test.clj b/test/fleet/cli_test.clj new file mode 100644 index 0000000..69e36b6 --- /dev/null +++ b/test/fleet/cli_test.clj @@ -0,0 +1,123 @@ +(ns fleet.cli-test + "9a review fix (c): the CLI layer writes no files on malformed input." + (:require [babashka.fs :as fs] + [clojure.string :as str] + [clojure.test :refer [deftest is testing]] + [fleet.cli :as cli]) + (:import (java.io StringWriter))) + +(def ^:private fx "test/fixtures/status/") + +(defn- tmp-dir [] (str (fs/create-temp-dir))) + +(defn- run + "Call f with stdout and stderr captured; {:rc :out :err}." + [f] + (let [o (StringWriter.) e (StringWriter.) + rc (binding [*out* o *err* e] (f))] + {:rc rc :out (str o) :err (str e)})) + +(defn- status-args [dir & {:as over}] + (let [m (merge {"--prev-status" (str dir "/none-status.json") + "--prev-history" (str dir "/none-history.json") + "--own-pin" (str fx "own-pin.json") + "--uncovered" (str fx "uncovered.json") + "--latest" "0.8.27" + "--nightly-json" "null" + "--canary-run" "https://example/run/1" + "--now" "2026-11-20T02:00:00Z" + "--out-dir" (str dir "/out")} + over)] + (vec (mapcat identity (remove (comp nil? val) m))))) + +(defn- nothing-written? [dir] (not (fs/exists? (str dir "/out")))) + +(defn- write! [dir name text] (spit (str dir "/" name) text) (str dir "/" name)) + +(deftest status-writes-both-files-on-good-input + (let [d (tmp-dir) + r (run #(cli/status-main (concat (status-args d) [(str fx "results-latest.json")])))] + (is (= 0 (:rc r))) + (is (fs/exists? (str d "/out/status.json"))) + (is (fs/exists? (str d "/out/history.json"))))) + +(deftest status-writes-nothing-on-malformed-input + (testing "unparsable own-pin JSON" + (let [d (tmp-dir) + r (run #(cli/status-main (status-args d "--own-pin" (write! d "bad.json" "[{"))))] + (is (= 1 (:rc r))) + (is (nothing-written? d)))) + (testing "own-pin of the wrong shape" + (let [d (tmp-dir) + r (run #(cli/status-main (status-args d "--own-pin" (write! d "op.json" "{\"a\":1}"))))] + (is (= 1 (:rc r))) + (is (str/includes? (:err r) "malformed own-pin")) + (is (nothing-written? d)))) + (testing "a results file with an unknown result" + (let [d (tmp-dir) + f (write! d "res.json" "{\"requested\":\"0.8.27\",\"projects\":[{\"name\":\"a\",\"result\":\"bogus\"}]}") + r (run #(cli/status-main (concat (status-args d) [f])))] + (is (= 1 (:rc r))) + (is (str/includes? (:err r) "malformed results")) + (is (nothing-written? d)))) + (testing "a missing results file" + (let [d (tmp-dir) + r (run #(cli/status-main (concat (status-args d) [(str d "/missing.json")])))] + (is (= 1 (:rc r))) + (is (nothing-written? d)))) + (testing "a previous status that is not an object" + (let [d (tmp-dir) + r (run #(cli/status-main (status-args d "--prev-status" (write! d "ps.json" "[1]"))))] + (is (= 1 (:rc r))) + (is (str/includes? (:err r) "malformed prev status")) + (is (nothing-written? d)))) + (testing "an unparsable --nightly-json" + (let [d (tmp-dir) + r (run #(cli/status-main (status-args d "--nightly-json" "{nope")))] + (is (= 1 (:rc r))) + (is (nothing-written? d))))) + +(deftest status-usage-errors-exit-2-and-write-nothing + (let [d (tmp-dir)] + (doseq [args [(status-args d "--latest" nil) + (status-args d "--bogus" "x") + (conj (status-args d) "--now")]] + (let [r (run #(cli/status-main args))] + (is (= 2 (:rc r))) + (is (str/includes? (:err r) "usage")) + (is (nothing-written? d)))))) + +(deftest refresh-writes-nothing-on-malformed-input + (let [env {"LATEST" "0.8.27" "NIGHTLY_JSON" "null" "CANARY_RUN" "https://example/run/1"} + fleet (fn [d] (write! d "fleet.json" "{\"projects\":[],\"excluded\":{}}")) + gh {:get-json (fn [_] (throw (ex-info "no" {:status 404}))) + :get-raw (fn [_] (throw (ex-info "no" {:status 404}))) + :get-paginated (fn [_] [])}] + (testing "a results file of the wrong shape" + (let [d (tmp-dir) + f (write! d "res.json" "{\"requested\":1}") + r (run #(cli/refresh-main [(str d "/out") f] (assoc env "FLEET_JSON" (fleet d)) {:gh gh}))] + (is (= 1 (:rc r))) + (is (nothing-written? d)))) + (testing "an unparsable results file" + (let [d (tmp-dir) + f (write! d "res.json" "{[") + r (run #(cli/refresh-main [(str d "/out") f] (assoc env "FLEET_JSON" (fleet d)) {:gh gh}))] + (is (= 1 (:rc r))) + (is (nothing-written? d)))) + (testing "an unparsable NIGHTLY_JSON" + (let [d (tmp-dir) + r (run #(cli/refresh-main [(str d "/out")] (assoc env "FLEET_JSON" (fleet d) "NIGHTLY_JSON" "{x") {:gh gh}))] + (is (= 1 (:rc r))) + (is (nothing-written? d)))) + (testing "a collector failure" + (let [d (tmp-dir) + bad (assoc gh :get-paginated (fn [_] (throw (ex-info "boom" {})))) + r (run #(cli/refresh-main [(str d "/out")] (assoc env "FLEET_JSON" (fleet d)) {:gh bad}))] + (is (= 1 (:rc r))) + (is (nothing-written? d)))) + (testing "good input still writes both files" + (let [d (tmp-dir) + r (run #(cli/refresh-main [(str d "/out")] (assoc env "FLEET_JSON" (fleet d)) {:gh gh}))] + (is (= 0 (:rc r))) + (is (fs/exists? (str d "/out/status.json"))))))) diff --git a/test/fleet/collect_test.clj b/test/fleet/collect_test.clj new file mode 100644 index 0000000..3d192cd --- /dev/null +++ b/test/fleet/collect_test.clj @@ -0,0 +1,178 @@ +(ns fleet.collect-test + "Ports test/collect.bats. gh is a map of stub fns over a data 'world' read + from test/fixtures/gh, so no network is touched." + (:require [cheshire.core :as json] + [clojure.string :as str] + [clojure.test :refer [deftest is testing]] + [fleet.collect :as collect]) + (:import (java.io StringWriter))) + +(def ^:private dir "test/fixtures/gh/") + +(defn- fx [name] (slurp (str dir name))) + +(defn- not-found [path] (ex-info (str "GitHub API 404 for " path) {:status 404 :path path})) + +(defn- cli->rest + "A gh-CLI-shaped runs fixture as the REST workflow runs response." + [runs] + {:workflow_runs (mapv (fn [r] {:conclusion (:conclusion r) :html_url (:url r) + :updated_at (:updatedAt r) :id (:databaseId r)}) + runs)}) + +(defn- world + "Fixture-backed state: :branch, :runs (CLI shape), :jobs, :ci (text, or an + exception to throw) per repo name, and the org :repos." + [] + (let [names (->> (json/parse-string (fx "org-repos.json") true) (map :name)) + names (concat names ["glitter-gl" "glitter-uikit"]) + exists (fn [f] (.exists (java.io.File. (str dir f)))) + pick (fn [suffix read] (into {} (for [n (distinct names) :when (exists (str n suffix))] + [n (read (fx (str n suffix)))])))] + {:repos (json/parse-string (fx "org-repos.json") true) + :branch (pick ".branch" str/trim) + :runs (pick ".runs.json" #(json/parse-string % true)) + :jobs (pick ".jobs.json" #(json/parse-string % true)) + :ci (assoc (pick ".ci.yml" identity) + "ratelimited" (ex-info "GitHub API 403 for ratelimited" + {:status 403 :body "rate limit exceeded, see docs (404 is not this)"}) + "brokenrepo" (ex-info "GitHub API 500" {:status 500}))})) + +(defn- stub-gh [{:keys [repos branch runs jobs ci]}] + (letfn [(repo-of [path] (second (re-find #"^/?repos/jlt-commons/([^/?]+)" path)))] + {:get-json + (fn [path] + (let [p (repo-of path)] + (cond + (re-find #"/actions/workflows/ci\.yml/runs\?" path) + (let [b (second (re-find #"branch=([^&]+)" path))] + (if (and (contains? runs p) (= b (get branch p))) + (cli->rest (get runs p)) + (throw (not-found path)))) + + (re-find #"/actions/runs/\d+/jobs" path) + (or (get jobs p) (throw (not-found path))) + + (contains? branch p) {:default_branch (get branch p)} + :else (throw (not-found path))))) + :get-raw + (fn [path] + (let [v (get ci (repo-of path))] + (cond (instance? Throwable v) (throw v) + (string? v) v + :else (throw (not-found path))))) + :get-paginated + (fn [path] + (if (re-find #"^orgs/jlt-commons/repos\?type=public" path) + (vec repos) + (throw (not-found path))))})) + +(def ^:private fleet + {:projects ["glitter" "glitter-gl" "glitter-uikit" "ghost"] + :excluded {:jolt-lsp "releases jolt-lsp" :secretrepo "private"}}) + +(defn- warnings-of + "Run f with stderr captured; [result stderr-text]." + [f] + (let [w (StringWriter.)] + (binding [*err* w] [(f) (str w)]))) + +(defn- own* [w & [fl]] (collect/own-pin (stub-gh w) (or fl fleet))) +(defn- unc* [w & [fl]] (collect/uncovered (stub-gh w) (or fl fleet))) +(defn- own [w & [fl]] (first (warnings-of #(own* w fl)))) +(defn- unc [w & [fl]] (first (warnings-of #(unc* w fl)))) +(defn- by-name [rows n] (first (filter #(= n (:name %)) rows))) + +(deftest own-pin-one-entry-per-fleet-project + (let [rows (own (world))] + (is (= ["glitter" "glitter-gl" "glitter-uikit" "ghost"] (mapv :name rows))))) + +(deftest own-pin-pass-run-with-literal-pin + (is (= {:name "glitter" :pin nil :result "pass" + :run_url "https://github.com/jlt-commons/glitter/actions/runs/1" + :finished_at "2026-11-19T10:00:00Z" :failed_step nil} + (by-name (own (world)) "glitter")))) + +(deftest own-pin-default-branch-used-failed-step-named-pin-parsed + (let [row (by-name (own (world)) "glitter-gl")] + (is (= "0.8.24" (:pin row))) + (is (= "fail" (:result row))) + (is (= "Run tests" (:failed_step row))))) + +(deftest own-pin-no-push-run-is-not-run-and-non-literal-pin-is-null + (is (= {:name "glitter-uikit" :pin nil :result "not-run" + :run_url nil :finished_at nil :failed_step nil} + (by-name (own (world)) "glitter-uikit")))) + +(deftest own-pin-failing-api-is-not-run-warns-and-does-not-abort + (let [[rows err] (warnings-of #(own* (world)))] + (is (= {:name "ghost" :pin nil :result "not-run" + :run_url nil :finished_at nil :failed_step nil} + (by-name rows "ghost"))) + (is (str/includes? err "ghost")) + (is (= 4 (count rows))))) + +(deftest own-pin-conclusion-mapping + (doseq [[conclusion result] [["success" "pass"] ["failure" "fail"] ["timed_out" "timed-out"] + ["cancelled" "not-run"] ["skipped" "not-run"] + ["neutral" "not-run"] [nil "not-run"]]] + (let [w (-> (world) + (assoc-in [:branch "zz"] "main") + (assoc-in [:runs "zz"] [{:conclusion conclusion :url "u" :updatedAt "t" :databaseId 1}]) + (assoc-in [:jobs "zz"] {:jobs []})) + row (by-name (own w {:projects ["zz"] :excluded {}}) "zz")] + (testing (str conclusion " -> " result) + (is (= result (:result row))))))) + +(deftest own-pin-transport-failure-listing-runs-keeps-the-pin + ;; Replaces "GH may be several words", which has no jolt counterpart: gh is + ;; a map of fns here. A transport error has no :status and must degrade the + ;; same way an HTTP error does. + (let [gh (assoc (stub-gh (world)) :get-json + (fn [path] + (cond (re-find #"/actions/workflows/" path) (throw (ex-info "connection reset" {})) + (str/ends-with? path "/glitter-gl") {:default_branch "trunk"} + :else (throw (not-found path))))) + [rows err] (warnings-of #(collect/own-pin gh {:projects ["glitter-gl"] :excluded {}}))] + (is (= [{:name "glitter-gl" :pin "0.8.24" :result "not-run" + :run_url nil :finished_at nil :failed_step nil}] + rows)) + (is (str/includes? err "glitter-gl")))) + +(deftest uncovered-reasons-per-repo-fleet-members-and-archived-private-skipped + (let [rows (unc (world)) + r (fn [n] (:reason (by-name rows n)))] + (is (= "excluded: releases jolt-lsp" (r "jolt-lsp"))) + (is (= "no ci.yml" (r "nociyml"))) + (is (= "ci.yml has no jolt-version input" (r "noinput"))) + (is (= "ready, not yet in fleet.json" (r "readyrepo"))) + (is (nil? (by-name rows "glitter"))) + (is (nil? (by-name rows "oldrepo"))) + (is (nil? (by-name rows "secretrepo"))))) + +(deftest uncovered-unreadable-repo-gets-a-reason-and-a-warning + (let [[rows err] (warnings-of #(unc* (world)))] + (is (= "could not read repository" (:reason (by-name rows "brokenrepo")))) + (is (str/includes? err "brokenrepo")))) + +(deftest uncovered-on-key-parsed-as-boolean-true-still-finds-the-input + (is (= "ready, not yet in fleet.json" + (:reason (by-name (unc (world) {:projects [] :excluded {}}) "glitter"))))) + +(deftest uncovered-403-containing-404-is-not-a-missing-ci-yml + (let [[rows err] (warnings-of #(unc* (world)))] + (is (= "could not read repository" (:reason (by-name rows "ratelimited")))) + (is (str/includes? err "ratelimited")))) + +(deftest uncovered-unparsable-ci-yml-is-could-not-read-with-a-warning + (let [[rows err] (warnings-of #(unc* (world)))] + (is (= "could not read repository" (:reason (by-name rows "badyaml")))) + (is (str/includes? err "badyaml")))) + +(deftest uncovered-transport-failure-is-could-not-read-not-no-ci-yml + ;; Replaces "missing yq fails loudly": jolt parses YAML in-process, so there + ;; is no external tool to miss. The matching risk is a transport error (no + ;; :status) being mistaken for an explicit 404. + (let [w (assoc-in (world) [:ci "readyrepo"] (ex-info "connection refused" {})) + [rows _err] (warnings-of #(unc* w))] + (is (= "could not read repository" (:reason (by-name rows "readyrepo")))))) diff --git a/test/fleet/github_test.clj b/test/fleet/github_test.clj index 11d8973..076e162 100644 --- a/test/fleet/github_test.clj +++ b/test/fleet/github_test.clj @@ -1,5 +1,5 @@ (ns fleet.github-test - (:require [clojure.test :refer [deftest is]] + (:require [clojure.test :refer [deftest is testing]] [fleet.github :as gh])) (defn- stub @@ -85,3 +85,51 @@ (atom []))}) e (try ((:get-paginated c) "x") nil (catch Exception e e))] (is (= 502 (gh/status-of e))))) + +;; 9a review fix (a): the token goes to api.github.com only. + +(defn- foreign-host? [e] (= :foreign-host (:reason (ex-data e)))) + +(deftest full-url-on-another-host-throws-and-sends-nothing + (doseq [url ["https://evil.example/repos/o/r" + "http://api.github.com/repos/o/r" + "https://api.github.com.evil.example/repos/o/r" + "https://api.github.com@evil.example/repos/o/r" + "https://api.github.com:8443/repos/o/r"]] + (testing url + (let [seen (atom []) + c (gh/client {:token "tok" :request (stub {} seen)})] + (doseq [f [:get-json :get-raw :get-paginated]] + (let [e (try ((f c) url) nil (catch Exception e e))] + (is (foreign-host? e)) + (is (nil? (gh/status-of e))))) + (is (= [] @seen)))))) + +(deftest full-url-on-api-github-com-still-works-with-the-token + (let [seen (atom []) + url "https://api.github.com/repos/o/r" + c (gh/client {:token "tok" :request (stub {url {:status 200 :headers {} :body "{}"}} seen)})] + (is (= {} ((:get-json c) url))) + (is (= "Bearer tok" (get-in (first @seen) [:headers "Authorization"]))))) + +(deftest link-next-on-another-host-is-refused-after-the-first-page + (let [seen (atom []) + p1 "https://api.github.com/x?per_page=100" + c (gh/client {:token "tok" + :request (stub {p1 {:status 200 + :headers {"link" "; rel=\"next\""} + :body "[1]"}} + seen)}) + e (try ((:get-paginated c) "x") nil (catch Exception e e))] + (is (foreign-host? e)) + (is (= [p1] (mapv :url @seen))))) + +;; 9a review fix (b): a transport failure carries no :status. + +(deftest transport-exception-propagates-with-no-status + (let [boom (ex-info "connection refused" {}) + c (gh/client {:request (fn [_] (throw boom))})] + (doseq [f [:get-json :get-raw :get-paginated]] + (let [e (try ((f c) "repos/o/r") nil (catch Exception e e))] + (is (identical? boom e)) + (is (nil? (gh/status-of e))))))) diff --git a/test/fleet/publish_test.clj b/test/fleet/publish_test.clj new file mode 100644 index 0000000..e61562e --- /dev/null +++ b/test/fleet/publish_test.clj @@ -0,0 +1,139 @@ +(ns fleet.publish-test + "Ports test/publish-status.bats: a local bare repo stands in for origin, and + rebuild is a function (the in-process REBUILD)." + (:require [babashka.fs :as fs] + [cheshire.core :as json] + [clojure.string :as str] + [clojure.test :refer [deftest is]] + [fleet.publish :as publish])) + +(defn- git + "Run git in dir, return trimmed stdout; throw on a non-zero exit." + [dir & args] + (let [{:keys [exit out err]} (apply publish/sh dir "git" args)] + (when-not (zero? exit) + (throw (ex-info (str "git " (str/join " " args) " failed: " err) {:exit exit}))) + (str/trim out))) + +(defn- tmp-dir [] (str (fs/create-temp-dir))) + +(defn- repo + "A work clone with an initial commit on main, pushed to a fresh bare origin. + Returns {:work :origin :out :root}." + [] + (let [root (tmp-dir) + origin (str root "/origin.git") + work (str root "/work")] + (git root "init" "-q" "--bare" origin) + (git root "init" "-q" "-b" "main" work) + (git work "config" "user.email" "t@example.com") + (git work "config" "user.name" "t") + (git work "remote" "add" "origin" origin) + (spit (str work "/README") "x\n") + (git work "add" "README") + (git work "commit" "-q" "-m" "init") + (git work "push" "-q" "origin" "main") + {:root root :origin origin :work work :out (str root "/out")})) + +(defn- write-json! [path m] (spit path (json/generate-string m))) + +(defn- rebuild-fixed + "Writes the same content each time except generated_at and canary_run." + [{:keys [out-dir]}] + (fs/create-dirs out-dir) + (write-json! (str out-dir "/status.json") + {:schema 1 :generated_at (str (System/nanoTime)) :canary_run (str "run-" (System/nanoTime)) + :projects ["a"]}) + (write-json! (str out-dir "/history.json") {:schema 1 :adhoc []})) + +(defn- pub [{:keys [work out]} rebuild] + (publish/publish! {:repo-dir work :out-dir out :rebuild rebuild :sh publish/sh})) + +(defn- remote-show [{:keys [origin]} f] + (json/parse-string (git origin "show" (str "status:" f)) true)) + +(defn- remote-head [{:keys [origin]}] (git origin "rev-parse" "status")) + +(deftest creates-the-branch-on-first-publish + (let [r (repo) + res (pub r rebuild-fixed)] + (is (= :published (:result res))) + (is (= "1" (git (:origin r) "rev-list" "--count" "status"))) + (is (= 1 (count (:projects (remote-show r "status.json"))))) + (is (= 1 (:schema (remote-show r "history.json")))) + ;; orphan: no README from main + (is (not (zero? (:exit (publish/sh (:origin r) "git" "show" "status:README"))))) + (is (= "github-actions[bot]" (git (:origin r) "log" "-1" "--format=%an" "status"))))) + +(deftest no-commit-when-only-generated-at-and-canary-run-changed + (let [r (repo) + _ (pub r rebuild-fixed) + before (remote-head r) + res (pub r rebuild-fixed)] + (is (= :unchanged (:result res))) + (is (= before (remote-head r))))) + +(deftest commits-when-history-changes + (let [r (repo) + _ (pub r rebuild-fixed) + before (remote-head r) + res (pub r (fn [{:keys [out-dir]}] + (write-json! (str out-dir "/status.json") {:schema 1 :projects ["a"]}) + (write-json! (str out-dir "/history.json") {:schema 1 :adhoc [1]})))] + (is (= :published (:result res))) + (is (not= before (remote-head r))) + (is (= 1 (count (:adhoc (remote-show r "history.json"))))))) + +(defn- rival-push! + "Clone the status branch, replace status.json with m, commit as someone + else and push: a competing publish." + [{:keys [origin root]} m msg] + (let [c (str (tmp-dir) "/rival")] + (git root "clone" "-q" "--branch" "status" origin c) + (write-json! (str c "/status.json") m) + (git c "-c" "user.email=r@example.com" "-c" "user.name=rival" "commit" "-q" "-am" msg) + (git c "push" "-q" "origin" "status"))) + +(deftest retries-after-a-concurrent-push-and-keeps-both-results + (let [r (repo) + _ (pub r rebuild-fixed) + attempts (atom 0) + ;; Adds its own project to whatever prev-dir holds. On the first + ;; attempt a rival pushes "theirs" after the fetch, so our push is + ;; rejected and attempt 2 must rebuild on top of it. + rebuild (fn [{:keys [prev-dir out-dir]}] + (when (= 1 (swap! attempts inc)) + (rival-push! r {:schema 1 :projects ["a" "theirs"]} "rival")) + (let [prev (json/parse-string (slurp (str prev-dir "/status.json")) true)] + (write-json! (str out-dir "/status.json") (update prev :projects conj "ours")) + (spit (str out-dir "/history.json") (slurp (str prev-dir "/history.json"))))) + res (pub r rebuild)] + (is (= :published (:result res))) + (is (= 2 (:attempt res))) + (is (= 2 @attempts)) + (is (= ["a" "ours" "theirs"] (sort (:projects (remote-show r "status.json"))))))) + +(deftest gives-up-after-three-rejections + (let [r (repo) + _ (pub r rebuild-fixed) + attempts (atom 0) + rebuild (fn [{:keys [out-dir]}] + (let [n (swap! attempts inc)] + (rival-push! r {:schema 1 :projects [(str "rival" n)]} (str "rival " n)) + (write-json! (str out-dir "/status.json") {:schema 1 :projects [(str "ours" n)]}) + (write-json! (str out-dir "/history.json") {:schema 1}))) + e (try (pub r rebuild) nil (catch Exception e e))] + (is (some? e)) + (is (str/includes? (ex-message e) "gave up after 3")) + (is (= 3 @attempts)))) + +(deftest fails-without-rebuild + (let [r (repo) + e (try (pub r nil) nil (catch Exception e e))] + (is (some? e)) + (is (str/includes? (ex-message e) "rebuild")))) + +(deftest leaves-no-worktree-behind + (let [r (repo)] + (pub r rebuild-fixed) + (is (= 1 (count (str/split-lines (git (:work r) "worktree" "list"))))))) diff --git a/test/fleet/refresh_test.clj b/test/fleet/refresh_test.clj new file mode 100644 index 0000000..8481f57 --- /dev/null +++ b/test/fleet/refresh_test.clj @@ -0,0 +1,74 @@ +(ns fleet.refresh-test + "Ports test/refresh-status.bats. The collectors are thunks returning the + status fixtures, so nothing touches the network." + (:require [babashka.fs :as fs] + [cheshire.core :as json] + [clojure.test :refer [deftest is]] + [fleet.cli :as cli] + [fleet.publish :as publish] + [fleet.refresh :as refresh]) + (:import (java.io StringWriter))) + +(def ^:private fx "test/fixtures/status/") + +(defn- fixture [name] (json/parse-string (slurp (str fx name)) true)) + +(defn- tmp-dir [] (str (fs/create-temp-dir))) + +(defn- opts [out & more] + (apply assoc {:out-dir out + :latest "0.8.27" + :nightly nil + :canary-run "https://example/run/1" + :results-files [(str fx "results-latest.json")] + :own-pin #(vec (fixture "own-pin.json")) + :uncovered #(vec (fixture "uncovered.json")) + :now "2026-11-20T02:00:00Z"} + more)) + +(deftest refresh-writes-status-and-history-from-collectors-and-results + (let [out (str (tmp-dir) "/out")] + (refresh/refresh! (opts out)) + (let [s (json/parse-string (slurp (str out "/status.json")) true) + h (json/parse-string (slurp (str out "/history.json")) true)] + (is (= 1 (:schema s))) + (is (= ["ebb" "glitter" "raygui-jlt"] (sort (map :name (:projects s))))) + (is (= 1 (:schema h)))))) + +(deftest refresh-needs-latest + (let [out (str (tmp-dir) "/out") + err (StringWriter.) + rc (binding [*err* err] + (cli/refresh-main [out] {"NIGHTLY_JSON" "null" "CANARY_RUN" "x"} {}))] + (is (= 2 rc)) + (is (re-find #"LATEST" (str err))) + (is (not (fs/exists? out))))) + +(deftest two-publishes-differing-only-in-clock-and-canary-run-make-one-commit + (let [root (tmp-dir) + origin (str root "/origin.git") + work (str root "/work") + g (fn [dir & args] (apply publish/sh dir "git" args)) + nightly {:published_at "2026-11-20T01:00:00Z" :sha "f4e82fc8eac874cae1658b7976518253027c4f6a" + :note "nightly published 2026-11-20T01:00:00Z at f4e82fc8"} + run (fn [n] + (publish/publish! + {:repo-dir work :out-dir (str root "/out" n) :sh publish/sh + :rebuild (fn [{:keys [prev-dir out-dir]}] + (refresh/refresh! (opts out-dir + :prev-dir prev-dir + :nightly nightly + :canary-run (str "https://example/run/" n) + :now (str "2026-11-20T02:00:0" n "Z"))))}))] + (g root "init" "-q" "--bare" origin) + (g root "init" "-q" "-b" "main" work) + (g work "config" "user.email" "t@example.com") + (g work "config" "user.name" "t") + (g work "remote" "add" "origin" origin) + (spit (str work "/README") "x\n") + (g work "add" "README") + (g work "commit" "-q" "-m" "init") + (g work "push" "-q" "origin" "main") + (is (= :published (:result (run 1)))) + (is (= :unchanged (:result (run 2)))) + (is (= "1\n" (:out (g origin "rev-list" "--count" "status")))))) From 23bbda2477f2ec83219991f4ade718d5baae2abf Mon Sep 17 00:00:00 2001 From: burinc Date: Fri, 20 Nov 2026 14:43:28 +1100 Subject: [PATCH 18/31] fleet: status build accepts a null pin so one non-literal JOLT_VERSION cannot stop the dashboard (R26) --- src/fleet/status.clj | 2 +- test/fleet/status_test.clj | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/fleet/status.clj b/src/fleet/status.clj index a7a54ca..410ba94 100644 --- a/src/fleet/status.clj +++ b/src/fleet/status.clj @@ -35,7 +35,7 @@ (defn- validate! [{:keys [prev-status prev-history own-pin uncovered results]}] (when-not (and (sequential? own-pin) - (every? #(and (string? (:name %)) (string? (:pin %))) own-pin)) + (every? #(and (string? (:name %)) (or (nil? (:pin %)) (string? (:pin %)))) own-pin)) (fail! "malformed own-pin" {})) (when-not (sequential? uncovered) (fail! "malformed uncovered" {})) (when-not (or (nil? prev-status) (map? prev-status)) (fail! "malformed prev status" {})) diff --git a/test/fleet/status_test.clj b/test/fleet/status_test.clj index 8f06b90..bd58da3 100644 --- a/test/fleet/status_test.clj +++ b/test/fleet/status_test.clj @@ -198,3 +198,16 @@ :canary_run "https://example/run/2")))) (is (false? (status/unchanged? s (assoc-in s [:jolt :latest :version] "0.8.28")))) (is (false? (status/unchanged? s (assoc s :uncovered [])))))) + +(deftest nil-pin-is-accepted-and-the-project-still-appears + ;; R26: a project with a non-literal JOLT_VERSION has pin nil. It must not + ;; stop the whole dashboard from updating. + (let [op (-> (fx "own-pin.json") + (assoc-in [0 :pin] nil) + (assoc-in [0 :result] "fail")) + out (run-bs {:op op}) + p (first (filter #(= "glitter" (:name %)) (:projects (:status out))))] + (is (= ["ebb" "glitter" "raygui-jlt"] (sort (map :name (:projects (:status out)))))) + (is (nil? (:version (:pin (:cells p))))) + (is (= "fail" (:result (:pin (:cells p))))) + (is (nil? (:installed (:pin (:cells p))))))) From 25527fe224503a9fd8bd66b7a0d36b33770adcc1 Mon Sep 17 00:00:00 2001 From: burinc Date: Fri, 20 Nov 2026 14:57:28 +1100 Subject: [PATCH 19/31] fanout: the dispatch-and-wait loop in jolt --- .github/workflows/fanout.yml | 357 ++++-------------------------- deps.edn | 6 + src/fleet/cli.clj | 18 ++ src/fleet/fanout.clj | 418 +++++++++++++++++++++++++++++++++++ src/fleet/github.clj | 39 +++- test/fleet/cli_test.clj | 10 + test/fleet/fanout_test.clj | 331 +++++++++++++++++++++++++++ test/fleet/github_test.clj | 45 +++- 8 files changed, 908 insertions(+), 316 deletions(-) create mode 100644 src/fleet/fanout.clj create mode 100644 test/fleet/fanout_test.clj diff --git a/.github/workflows/fanout.yml b/.github/workflows/fanout.yml index 44c370f..9e5bdf4 100644 --- a/.github/workflows/fanout.yml +++ b/.github/workflows/fanout.yml @@ -52,6 +52,9 @@ on: permissions: contents: read +env: + TOOLS_JOLT_VERSION: ${{ vars.TOOLS_JOLT_VERSION || '0.8.27' }} + jobs: fanout: name: fan-out @@ -60,13 +63,28 @@ jobs: outputs: failed: ${{ steps.run.outputs.failed }} infra: ${{ steps.run.outputs.infra }} - version: ${{ steps.version.outputs.version }} + version: ${{ steps.run.outputs.version }} steps: - # fleet.json (the project list) and scripts/lib/version.sh live here. + # fleet.json (the project list) and src/fleet live here. # Under workflow_call this checks out the caller's ref of this same repo. - uses: actions/checkout@v7 + # The tool jolt runs the fan-out loop. Pinned, and never the jolt under + # test: a release published overnight must not change the tool. + - uses: jlt-commons/setup-jolt@v1 + with: + version: ${{ env.TOOLS_JOLT_VERSION }} + + - uses: actions/cache@v6.1.0 + with: + path: ~/.jolt/gitlibs + key: jolt-gitlibs-${{ hashFiles('deps.edn') }} + + # jolt.yaml loads libyaml, which the runner image carries today. Say so + # explicitly so an image change cannot break the tools silently. + - run: sudo apt-get install -y libyaml-0-2 + # Mints a token scoped to the App's seven repositories, valid one hour. # Never a PAT: a PAT would act as whoever created it, and any collaborator # able to run this workflow would be borrowing that identity. @@ -78,310 +96,20 @@ jobs: private-key: ${{ secrets.APP_PRIVATE_KEY }} owner: jlt-commons - - name: Resolve the jolt version - id: version - env: - REQUESTED: ${{ inputs.jolt-version }} - GH_TOKEN: ${{ steps.token.outputs.token }} - run: | - set -euo pipefail - if [ -n "$REQUESTED" ]; then - version="$REQUESTED" - echo "Using the requested jolt $version" - else - # The App cannot read jolt-lang (a different org), but the release - # list is public, so an unauthenticated read is both sufficient and - # correct here. - version="$(curl -fsSL https://api.github.com/repos/jolt-lang/jolt/releases/latest \ - | sed -n 's/.*"tag_name": *"\([^"]*\)".*/\1/p' | head -1)" - version="${version#v}" - [ -n "$version" ] || { echo "could not resolve jolt's latest release" >&2; exit 1; } - echo "Using jolt's latest release, $version" - fi - echo "version=$version" >> "$GITHUB_OUTPUT" - - name: Dispatch every project and wait id: run env: GH_TOKEN: ${{ steps.token.outputs.token }} - VERSION: ${{ steps.version.outputs.version }} - run: | - set -uo pipefail - # shellcheck source=scripts/lib/version.sh - . scripts/lib/version.sh - PROJECTS=$(jq -r '.projects | join(" ")' fleet.json) - declare -A RUN CONC URL INST FSTEP FIN - RES_DIR="${RUNNER_TEMP:-/tmp}/fanout-results" - mkdir -p "$RES_DIR" - - # For nightly, the commit vnightly points at right now. An installed - # jolt whose -g does not prefix this is a different build. - NIGHTLY_SHA="" - if [ "$VERSION" = "nightly" ]; then - NIGHTLY_SHA="$(curl -fsSL https://api.github.com/repos/jolt-lang/jolt/git/refs/tags/vnightly \ - | sed -n 's/.*"sha": *"\([^"]*\)".*/\1/p' | head -1)" - [ -n "$NIGHTLY_SHA" ] || echo "::warning::could not resolve the vnightly sha, every nightly run will read as mismatch" - echo "vnightly is $NIGHTLY_SHA" - fi - # A plain string, not an associative array: `${#arr[@]}` and - # `${!arr[@]}` on an EMPTY associative array are only safe under - # `set -u` from bash 4.4, and the empty case is the normal one here. - # A string list behaves the same on every bash and is testable locally. - NEEDID="" - - # `gh workflow run` prints the URL of the run it created, so READ THAT - # rather than guessing. The guess this replaced was "the newest - # workflow_dispatch run above a baseline recorded before dispatching", - # which is a positive control: it always returns a plausible id, and - # nothing in the output describes the gap between that id and the run - # you meant. - # - # It was not merely theoretical. Canary run 33682325150 ran two fan-out - # legs at once, 0.8.0 and 0.8.1, and BOTH claimed glitter run - # 33682354193. gh had printed 33682349678 to the 0.8.1 leg and - # 33682354193 to the 0.8.0 leg, and gh was right both times: - # ...9678 installed v0.8.1 and ...4193 installed v0.8.0. So the 0.8.1 - # row reported a result for a build of 0.8.0. Both were green, which is - # the only reason the wrong answer was harmless that day. - # - # Reading gh's own output removes the guess instead of narrowing it, and - # it holds however many fan-outs run at once: a manual dispatch during - # the nightly canary, three matrix legs, anything. - echo "::group::dispatch jolt $VERSION" - for p in $PROJECTS; do - if out=$(gh workflow run ci.yml --repo "jlt-commons/$p" -f jolt-version="$VERSION" 2>&1); then - printf '%s\n' "$out" | sed 's/^/ /' - id=$(printf '%s' "$out" | sed -n 's#.*/actions/runs/\([0-9][0-9]*\).*#\1#p' | head -1) - if [ -n "$id" ]; then - RUN[$p]=$id - URL[$p]="https://github.com/jlt-commons/$p/actions/runs/$id" - echo " dispatched $p -> run $id" - else - # An older gh prints no URL. Rather than silently fall back to the - # heuristic this replaced, say so: the result is still produced, - # and a human is told the attribution is a guess. - NEEDID="$NEEDID $p" - echo "::warning::gh printed no run URL for $p, falling back to newest-run matching. That is unreliable when fan-outs overlap." - echo " dispatched $p, run id unknown" - fi - else - echo " FAILED to dispatch $p" - CONC[$p]="dispatch-failed" - fi - done - echo "::endgroup::" - - # Only for projects whose id gh did not give us. - if [ -n "$NEEDID" ]; then - echo "::group::identify runs (fallback)" - sleep 10 - for _ in $(seq 1 40); do - waiting=0 - for p in $NEEDID; do - [ -n "${RUN[$p]:-}" ] && continue - [ -n "${CONC[$p]:-}" ] && continue - id=$(gh run list --repo "jlt-commons/$p" --workflow ci.yml \ - --event workflow_dispatch --limit 1 \ - --json databaseId --jq '.[0].databaseId // 0' 2>/dev/null || echo 0) - if [ "$id" != "0" ]; then - RUN[$p]=$id - URL[$p]="https://github.com/jlt-commons/$p/actions/runs/$id" - echo " $p -> run $id (guessed)" - else - waiting=1 - fi - done - [ "$waiting" = "0" ] && break - sleep 5 - done - for p in $NEEDID; do - if [ -z "${RUN[$p]:-}" ] && [ -z "${CONC[$p]:-}" ]; then - CONC[$p]="no-run-appeared" - echo " $p: no run appeared within the window" - fi - done - echo "::endgroup::" - fi - - echo "::group::wait for completion" - for _ in $(seq 1 150); do - waiting=0 - for p in $PROJECTS; do - [ -n "${CONC[$p]:-}" ] && continue - read -r st cc < <(gh run view "${RUN[$p]}" --repo "jlt-commons/$p" \ - --json status,conclusion \ - --jq '"\(.status) \(.conclusion // "-")"' 2>/dev/null || echo "unknown -") - if [ "$st" = "completed" ]; then - # "jolt broke this project" and "we could not install jolt" both - # arrive as a failed run naming a project, and they call for - # opposite responses: one is a finding about jolt, the other is - # this fleet's own misconfiguration. Measured 2026-09-02: - # JOLT_REPO was left pointing at a fork that publishes only - # nightlies, so asking for 0.8.0 and 0.8.1 gave curl 404 and two - # scheduled canaries reported the fleet broken when it was fine. - if [ "$cc" = "failure" ] && gh api \ - "repos/jlt-commons/$p/actions/runs/${RUN[$p]}/jobs" \ - --jq '.jobs[].steps[]? | select(.conclusion=="failure") | .name' \ - 2>/dev/null | grep -qi 'install jolt'; then - cc="toolchain-unavailable" - fi - # A project can also fail because a dependency would not download - # (Maven Central rate limiting or a missing artifact). That is the - # registry's problem, not a break in jolt. Read only the failed - # jobs' logs. If any log cannot be fetched we have no evidence, so - # the run stays a failure. - if [ "$cc" = "failure" ]; then - logs=() - allfetched=1 - for jid in $(gh api "repos/jlt-commons/$p/actions/runs/${RUN[$p]}/jobs" \ - --jq '.jobs[] | select(.conclusion=="failure") | .id' 2>/dev/null); do - if gh api --allow-escape-sequences "repos/jlt-commons/$p/actions/jobs/$jid/logs" \ - > "$RES_DIR/$p-$jid.log" 2> "$RES_DIR/$p-$jid.err"; then - logs+=("$RES_DIR/$p-$jid.log") - else - allfetched=0 - echo "::warning::could not fetch the log of $p job $jid: $(head -c 300 "$RES_DIR/$p-$jid.err")" - fi - done - # Every failed job must show a download failure in its failed - # step. A job whose log we could not read counts against it. - if [ "$allfetched" = "1" ] && [ "${#logs[@]}" -gt 0 ] && download_failure "${logs[@]}"; then - cc="deps-unavailable" - fi - fi - FIN[$p]=$(date -u +%Y-%m-%dT%H:%M:%SZ) - if [ "$cc" = "failure" ] || [ "$cc" = "deps-unavailable" ] || [ "$cc" = "toolchain-unavailable" ]; then - FSTEP[$p]=$(gh api "repos/jlt-commons/$p/actions/runs/${RUN[$p]}/jobs" \ - --jq '[.jobs[].steps[]? | select(.conclusion=="failure") | .name] | first // empty' \ - 2>/dev/null || true) - elif [ "$cc" = "success" ]; then - # A green run is not proof it ran the jolt we asked for: read - # the `jolt --version` line out of each job's log. - # One job may install a different jolt on purpose (glitter-gl keeps - # a v0.7.29 job), so the run counts if ANY job ran the requested one. - logs=() - for jid in $(gh api "repos/jlt-commons/$p/actions/runs/${RUN[$p]}/jobs" \ - --jq '.jobs[].id' 2>/dev/null); do - gh api --allow-escape-sequences "repos/jlt-commons/$p/actions/jobs/$jid/logs" \ - > "$RES_DIR/$p-$jid.log" 2> "$RES_DIR/$p-$jid.err" \ - || echo "::warning::could not fetch the log of $p job $jid: $(head -c 300 "$RES_DIR/$p-$jid.err")" - logs+=("$RES_DIR/$p-$jid.log") - done - if inst=$(pick_installed "$VERSION" "$NIGHTLY_SHA" "${logs[@]}"); then :; else cc="mismatch"; fi - INST[$p]="$inst" - fi - CONC[$p]="$cc" - echo " $p: $cc${INST[$p]:+ (jolt ${INST[$p]})}" - else - waiting=1 - fi - done - [ "$waiting" = "0" ] && break - sleep 20 - done - for p in $PROJECTS; do - [ -z "${CONC[$p]:-}" ] && CONC[$p]="timed-out" - done - echo "::endgroup::" - - # Render the table this workflow exists to produce. - failed="" - infra="" - nodeps="" - mismatch="" - : > "$RES_DIR/projects.jsonl" - { - echo "## jolt \`$VERSION\` across jlt-commons" - echo - echo "| project | result | run |" - echo "|---|---|---|" - } >> "$GITHUB_STEP_SUMMARY" - for p in $PROJECTS; do - c="${CONC[$p]}" - case "$c" in - success) icon="pass" ;; - skipped) icon="skipped" ;; - mismatch) icon="**WRONG JOLT** (ran ${INST[$p]:-no version found})" - mismatch="$mismatch $p"; failed="$failed $p" ;; - toolchain-unavailable) - icon="**could not install jolt**"; infra="$infra $p" ;; - deps-unavailable) - icon="**could not download dependencies**"; infra="$infra $p"; nodeps="$nodeps $p" ;; - *) icon="**FAIL** ($c)"; failed="$failed $p" ;; - esac - link="-" - [ -n "${URL[$p]:-}" ] && link="[run](${URL[$p]})" - echo "| \`$p\` | $icon | $link |" >> "$GITHUB_STEP_SUMMARY" - case "$c" in - success) r=pass ;; - toolchain-unavailable|deps-unavailable) r=infra ;; - timed-out) r=timed-out ;; - dispatch-failed|no-run-appeared) r=dispatch-failed ;; - mismatch) r=mismatch ;; - skipped) r=not-run ;; - *) r=fail ;; - esac - jq -nc --arg name "$p" --arg result "$r" --arg installed "${INST[$p]:-}" \ - --arg url "${URL[$p]:-}" --arg fin "${FIN[$p]:-}" --arg step "${FSTEP[$p]:-}" \ - '{name: $name, result: $result, - installed: (if $installed == "" then null else $installed end), - run_url: (if $url == "" then null else $url end), - finished_at: (if $fin == "" then null else $fin end), - failed_step: (if $step == "" then null else $step end)}' \ - >> "$RES_DIR/projects.jsonl" - done - failed="${failed# }" - infra="${infra# }" - nodeps="${nodeps# }" - mismatch="${mismatch# }" - jq -s --arg requested "$VERSION" --arg sha "$NIGHTLY_SHA" \ - --arg fin "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \ - --arg url "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" \ - '{requested: $requested, nightly_sha: $sha, finished_at: $fin, run_url: $url, projects: .}' \ - "$RES_DIR/projects.jsonl" > "$RES_DIR/results.json" - echo "results_dir=$RES_DIR" >> "$GITHUB_OUTPUT" - echo "artifact=results-${VERSION//\//-}" >> "$GITHUB_OUTPUT" - { - echo - [ -n "$mismatch" ] && echo "**Ran on the wrong jolt:** $mismatch" - [ -n "$failed" ] && echo "**Broken by jolt \`$VERSION\`:** $failed" - # infra holds both causes. Name the install failures as those that - # are in infra but not in nodeps. - noinstall="" - for p in $infra; do - case " $nodeps " in *" $p "*) ;; *) noinstall="$noinstall $p" ;; esac - done - noinstall="${noinstall# }" - if [ -n "$noinstall" ]; then - echo "**Could not install jolt \`$VERSION\` for:** $noinstall" - echo - echo "That is this fleet's own problem, not a fact about jolt. Usually" - echo "the version does not exist in the repository being installed" - echo "from: check each project's \`JOLT_REPO\`, which should be unset" - echo "unless deliberately pointed at a fork." - fi - if [ -n "$nodeps" ]; then - echo "**Could not download dependencies for:** $nodeps" - echo - echo "That is a package-registry problem, often Maven Central rate" - echo "limiting while several projects build at once, not a fact about jolt." - fi - # Counted from PROJECTS rather than written out. The literal said five - # for as long as there were five, then went on saying it after there - # were six, which is what a count kept by hand beside the list it - # counts always does eventually. - [ -z "$failed$infra" ] && echo "All $(set -- $PROJECTS; echo $#) projects build against jolt \`$VERSION\`." - } >> "$GITHUB_STEP_SUMMARY" - - echo "failed=$failed" >> "$GITHUB_OUTPUT" - echo "infra=$infra" >> "$GITHUB_OUTPUT" - [ -z "$failed$infra" ] || { echo "failing: ${failed:-none} infra: ${infra:-none}" >&2; exit 1; } + VERSION: ${{ inputs.jolt-version }} + # The loop lives in src/fleet/fanout.clj, which says why each rule + # exists. A blank VERSION means jolt's latest release. + run: jolt fleet:fanout "$VERSION" - name: Upload results.json if: always() uses: actions/upload-artifact@v7 with: - name: ${{ steps.run.outputs.artifact || format('results-{0}', steps.version.outputs.version) }} + name: ${{ steps.run.outputs.artifact || format('results-{0}', steps.run.outputs.version) }} path: ${{ steps.run.outputs.results_dir }}/results.json if-no-files-found: warn @@ -400,6 +128,17 @@ jobs: steps: - uses: actions/checkout@v7 + - uses: jlt-commons/setup-jolt@v1 + with: + version: ${{ env.TOOLS_JOLT_VERSION }} + + - uses: actions/cache@v6.1.0 + with: + path: ~/.jolt/gitlibs + key: jolt-gitlibs-${{ hashFiles('deps.edn') }} + + - run: sudo apt-get install -y libyaml-0-2 + - name: Mint an installation token id: token uses: actions/create-github-app-token@v3 @@ -420,20 +159,14 @@ jobs: CANARY_RUN: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} run: | set -euo pipefail - latest="$(curl -fsSL https://api.github.com/repos/jolt-lang/jolt/releases/latest \ - | sed -n 's/.*"tag_name": *"\([^"]*\)".*/\1/p' | head -1)" - latest="${latest#v}" - [ -n "$latest" ] || { echo "could not resolve jolt's latest release" >&2; exit 1; } - export LATEST="$latest" - # REBUILD is a command string for publish-status.sh to run with sh -c, - # so the quotes are meant literally. - # shellcheck disable=SC2089,SC2090 - REBUILD='bash scripts/refresh-status.sh "$OUT_DIR"' + tag="$(gh api repos/jolt-lang/jolt/releases/latest --jq .tag_name)" + [ -n "$tag" ] || { echo "could not resolve jolt's latest release" >&2; exit 1; } + export LATEST="${tag#v}" + # fleet:publish refreshes in-process on every attempt (R27), so the + # results files are plain arguments. if [ -d results ]; then - while IFS= read -r f; do REBUILD="$REBUILD '$PWD/$f'"; done \ - < <(find results -name results.json | sort) + mapfile -t files < <(find results -name results.json | sort) + else + files=() fi - # shellcheck disable=SC2090 - export REBUILD - echo "REBUILD: $REBUILD" - bash scripts/publish-status.sh "$RUNNER_TEMP/status-out" + jolt fleet:publish "$RUNNER_TEMP/status-out" "${files[@]}" diff --git a/deps.edn b/deps.edn index 2c19e8e..1496edd 100644 --- a/deps.edn +++ b/deps.edn @@ -14,6 +14,7 @@ :requires ([clojure.test :as t] [fleet.cli-test] [fleet.collect-test] + [fleet.fanout-test] [fleet.github-test] [fleet.publish-test] [fleet.refresh-test] @@ -21,6 +22,7 @@ [fleet.version-test]) :task (let [{:keys [fail error]} (t/run-tests 'fleet.cli-test 'fleet.collect-test + 'fleet.fanout-test 'fleet.github-test 'fleet.publish-test 'fleet.refresh-test @@ -28,6 +30,10 @@ 'fleet.version-test)] (when (pos? (+ fail error)) (System/exit 1)))} + fleet:fanout {:doc "Dispatch every fleet project against a jolt version and wait: [version] (blank = latest release; env: GH_TOKEN, FLEET_JSON)" + :requires ([fleet.cli :as cli]) + :task (System/exit (cli/fanout-main *command-line-args*))} + fleet:own-pin {:doc "Print each fleet project's latest push run and pin as JSON (env: GH_TOKEN, FLEET_JSON)" :requires ([fleet.cli :as cli]) :task (System/exit (cli/own-pin-main *command-line-args*))} diff --git a/src/fleet/cli.clj b/src/fleet/cli.clj index 3dcba53..5bc2f68 100644 --- a/src/fleet/cli.clj +++ b/src/fleet/cli.clj @@ -6,6 +6,7 @@ (:require [cheshire.core :as json] [clojure.string :as str] [fleet.collect :as collect] + [fleet.fanout :as fanout] [fleet.github :as github] [fleet.publish :as publish] [fleet.refresh :as refresh] @@ -165,3 +166,20 @@ (println (if (= :unchanged (:result res)) "status: unchanged" (str "status: published (attempt " (:attempt res) ")"))))))))) + +(defn fanout-main + "fleet:fanout [version]: dispatch every fleet project against a jolt + version and wait. A blank or missing version means jolt's latest release. + Exit 1 when anything failed or was infra. Env: GH_TOKEN, FLEET_JSON and + the GITHUB_* variables fan-out writes its outputs to. deps may carry + :gh, :sh, :sleep and :now fns." + ([args] (fanout-main args (into {} (System/getenv)) {})) + ([args env deps] + (if (> (count args) 1) + (usage-error "fanout [version]" nil) + (guarded "fanout" + #(fanout/run! (merge (select-keys deps [:sh :sleep :now]) + {:version (first args) + :projects (:projects (load-fleet env)) + :gh (gh-of deps) + :env (fn [k] (get env k))})))))) diff --git a/src/fleet/fanout.clj b/src/fleet/fanout.clj new file mode 100644 index 0000000..1685d46 --- /dev/null +++ b/src/fleet/fanout.clj @@ -0,0 +1,418 @@ +(ns fleet.fanout + "Build every jlt-commons project against one jolt version and report the + whole fleet in a single table. + + This does NOT rebuild anything itself. Each project's own ci.yml already + knows how to build it (raygui needs raylib natives, glitter-uikit needs + AppKit and GTK4, glitter-gl needs a GL context under Xvfb, raylib-ios runs + its pure scenes under jolt on Linux because its real target is a phone), + and every one of them accepts a `jolt-version` dispatch input that overrides + its pinned JOLT_VERSION for a single run. So this dispatches those and + collects the answers. Reimplementing five build environments here would + rot, and would test something other than what a contributor actually hits. + + Why it exists: jolt v0.8.0 reversed jolt.ffi/write's last two arguments + (jolt-lang/jolt#802). Both spellings are plain integers, so a mismatch + writes to the wrong address and reports nothing. Finding that out one + repository at a time, days apart, is what this replaces. + + Run ids come from gh's own output. `gh workflow run` prints the URL of the + run it created, so the id is READ from that. The guess this replaced was + \"the newest workflow_dispatch run above a baseline recorded before + dispatching\", a positive control that always returns a plausible id. It + failed for real: canary run 33682325150 ran two fan-out legs at once, 0.8.0 + and 0.8.1, and BOTH claimed glitter run 33682354193, though gh had printed + 33682349678 to the 0.8.1 leg. The 0.8.1 row reported a result for a build + of 0.8.0. Reading gh's output holds however many fan-outs overlap. Only an + older gh that prints no URL falls back to the newest workflow_dispatch run, + with a ::warning:: saying the attribution is a guess. + + Result classes, all per project: + - pass: the run succeeded and a job installed the requested jolt (R4: ANY + job counts, because glitter-gl deliberately keeps a 0.7.29 job). + - mismatch: the run succeeded but no job's `jolt --version` is the + requested one (nightly republished between resolve and install, or a + project ignoring the input). Never reported as pass. + - infra: a failed run whose cause is not jolt. Two causes. Either the + install-jolt step failed (measured 2026-09-02: JOLT_REPO was left + pointing at a fork that publishes only nightlies, so asking for 0.8.0 + gave curl 404 and two scheduled canaries called the fleet broken), or + every failed job's failed step shows a dependency download failure + (R21/R24, Maven Central 429s and missing artifacts). The failed step is + recorded for both (R25). + - fail: any other non-success conclusion. timed-out and dispatch-failed + come from this loop, not from GitHub. + - not-run: GitHub concluded `skipped` (R5). + + IO sits behind injected fns, so a test drives a whole fan-out with no + network and no sleeping: gh (the fleet.github client map), sh, env, sleep + and now." + (:refer-clojure :exclude [run!]) + (:require [babashka.fs :as fs] + [babashka.process :as p] + [cheshire.core :as json] + [clojure.string :as str] + [fleet.version :as version])) + +(def org "jlt-commons") + +(def ^:private jolt-repo "repos/jolt-lang/jolt") + +(def ^:private poll-tries 150) +(def ^:private poll-interval-ms 20000) + +;; --------------------------------------------------------------------------- +;; Pure: classification and rendering + +(defn- failed-steps + "Names of every failed step across the jobs, in job then step order." + [jobs] + (for [j jobs, s (:steps j) :when (= "failure" (:conclusion s))] (:name s))) + +(defn- deps-unavailable? + "R24: every failed job's log was fetched and each shows a download failure + in its failed step. A log we could not read is no evidence, so it counts + against infra." + [jobs logs] + (let [failed (filter #(= "failure" (:conclusion %)) jobs) + texts (map #(get logs (:id %)) failed)] + (boolean (and (seq failed) + (every? some? texts) + (version/download-failure? texts))))) + +(defn classify + "One finished run to {:result :installed :failed-step :cause :detail}. + + conclusion is GitHub's. jobs are the run's job maps ({:id :conclusion + :steps [{:name :conclusion}]}). logs maps job id to log text, nil for a log + that could not be fetched. :cause is :install or :deps for infra, else + nil. :detail is the conclusion, kept for the table's FAIL (x) text." + [{:keys [requested nightly-sha conclusion jobs logs]}] + (let [base {:installed nil :failed-step nil :cause nil :detail conclusion}] + (case conclusion + "success" + (let [{:keys [installed match?]} + (version/pick-installed requested nightly-sha + (keep #(get logs (:id %)) jobs))] + (assoc base :result (if match? "pass" "mismatch") :installed installed)) + + "skipped" (assoc base :result "not-run") + + "failure" + (let [steps (failed-steps jobs) + cause (cond + (some #(re-find #"(?i)install jolt" %) steps) :install + (deps-unavailable? jobs logs) :deps)] + (assoc base + :result (if cause "infra" "fail") + :cause cause + :failed-step (first steps))) + + (assoc base :result "fail")))) + +(defn- joined [names] (str/join " " names)) + +(defn- icon [{:keys [result cause detail installed]}] + (case result + "pass" "pass" + "not-run" "skipped" + "mismatch" (str "**WRONG JOLT** (ran " (or installed "no version found") ")") + "infra" (if (= :deps cause) + "**could not download dependencies**" + "**could not install jolt**") + (str "**FAIL** (" detail ")"))) + +(defn- split-names + "Project names by outcome, in fleet order: {:failed :infra :nodeps + :mismatch :noinstall}. failed holds mismatches too, as the table always + did." + [projects] + (let [names (fn [pred] (mapv :name (filter pred projects)))] + {:mismatch (names #(= "mismatch" (:result %))) + :failed (names #(contains? #{"mismatch" "fail" "timed-out" "dispatch-failed"} (:result %))) + :infra (names #(= "infra" (:result %))) + :nodeps (names #(and (= "infra" (:result %)) (= :deps (:cause %)))) + :noinstall (names #(and (= "infra" (:result %)) (not= :deps (:cause %))))})) + +(defn summary-md + "The step summary: a row per project, then a line per kind of trouble." + [{:keys [version projects]}] + (let [{:keys [mismatch failed infra nodeps noinstall]} (split-names projects) + lines + (concat + [(str "## jolt `" version "` across " org) "" "| project | result | run |" "|---|---|---|"] + (for [pr projects] + (str "| `" (:name pr) "` | " (icon pr) " | " + (if (:run-url pr) (str "[run](" (:run-url pr) ")") "-") " |")) + [""] + (when (seq mismatch) [(str "**Ran on the wrong jolt:** " (joined mismatch))]) + (when (seq failed) [(str "**Broken by jolt `" version "`:** " (joined failed))]) + (when (seq noinstall) + [(str "**Could not install jolt `" version "` for:** " (joined noinstall)) + "" + "That is this fleet's own problem, not a fact about jolt. Usually" + "the version does not exist in the repository being installed" + "from: check each project's `JOLT_REPO`, which should be unset" + "unless deliberately pointed at a fork."]) + (when (seq nodeps) + [(str "**Could not download dependencies for:** " (joined nodeps)) + "" + "That is a package-registry problem, often Maven Central rate" + "limiting while several projects build at once, not a fact about jolt."]) + ;; Counted from the projects rather than written out, so the number + ;; cannot go stale beside the list it counts. + (when (and (empty? failed) (empty? infra)) + [(str "All " (count projects) " projects build against jolt `" version "`.")]))] + (str (str/join "\n" lines) "\n"))) + +(defn results-json + "The results.json map: the artifact the status build reads." + [{:keys [requested nightly-sha finished-at run-url projects]}] + {:requested requested + :nightly_sha (or nightly-sha "") + :finished_at finished-at + :run_url run-url + :projects (mapv (fn [pr] + {:name (:name pr) + :result (:result pr) + :installed (:installed pr) + :run_url (:run-url pr) + :finished_at (:finished-at pr) + :failed_step (:failed-step pr)}) + projects)}) + +;; --------------------------------------------------------------------------- +;; Edges + +(defn default-sh + "Run args with env added to the environment. Returns {:exit :out :err}; + never throws on a non-zero exit." + [args env] + (let [{:keys [exit out err]} (apply p/sh {:extra-env env} args)] + {:exit exit :out out :err err})) + +(defn- now-iso [] + (str (.truncatedTo (java.time.Instant/now) java.time.temporal.ChronoUnit/SECONDS))) + +(defn- log [& xs] (println (str/join " " xs)) (flush)) + +(defn- warn [& xs] (log (str "::warning::" (str/join " " xs)))) + +(defn- explain [e] + (str (or (some-> (ex-data e) :status (->> (str "HTTP "))) "error") ": " (ex-message e))) + +(defn resolve-version + "The version to test: requested when given (a leading v is kept as is), + else the tag of jolt's latest release without its v. The release list is + public, but it goes through the client like every other call." + [gh requested] + (if (seq requested) + requested + (let [tag (some-> ((:get-json gh) (str jolt-repo "/releases/latest")) :tag_name) + v (some-> tag (str/replace-first #"^v" ""))] + (when (str/blank? v) + (throw (ex-info "could not resolve jolt's latest release" {}))) + v))) + +(defn nightly-sha + "The commit vnightly points at right now, or nil with a warning. An + installed jolt whose -g does not prefix it is a different build." + [gh] + (let [sha (try (get-in ((:get-json gh) (str jolt-repo "/git/refs/tags/vnightly")) [:object :sha]) + (catch Exception e (warn "vnightly lookup failed:" (explain e)) nil))] + (when (str/blank? sha) + (warn "could not resolve the vnightly sha, every nightly run will read as mismatch")) + (when-not (str/blank? sha) sha))) + +(defn- run-id-from + "The run id in the URL gh printed, or nil." + [text] + (second (re-find #"/actions/runs/([0-9]+)" (or text "")))) + +(defn- run-url [project id] (str "https://github.com/" org "/" project "/actions/runs/" id)) + +(defn- dispatch-all! + "Dispatch ci.yml in each project. Returns {project {:run-id :need-id? :detail}} + where :detail \"dispatch-failed\" marks a failed dispatch." + [{:keys [sh token]} version projects] + (log (str "::group::dispatch jolt " version)) + (let [res (reduce + (fn [acc pr] + (let [{:keys [exit out err]} + (sh ["gh" "workflow" "run" "ci.yml" "--repo" (str org "/" pr) + "-f" (str "jolt-version=" version)] + {"GH_TOKEN" token})] + (if (zero? exit) + (let [text (str out err) + id (run-id-from text)] + (doseq [l (str/split-lines text)] (log (str " " l))) + (if id + (do (log (str " dispatched " pr " -> run " id)) + (assoc acc pr {:run-id id})) + (do (warn "gh printed no run URL for" pr + ", falling back to newest-run matching. That is unreliable when fan-outs overlap.") + (log (str " dispatched " pr ", run id unknown")) + (assoc acc pr {:need-id? true})))) + (do (log (str " FAILED to dispatch " pr)) + (assoc acc pr {:detail "dispatch-failed"}))))) + {} projects)] + (log "::endgroup::") + res)) + +(defn- newest-dispatch-run-id + "The newest workflow_dispatch run of ci.yml, or nil." + [gh pr] + (try (some-> ((:get-json gh) (str "repos/" org "/" pr + "/actions/workflows/ci.yml/runs?event=workflow_dispatch&per_page=1")) + :workflow_runs vec first :id str) + (catch Exception _ nil))) + +(defn- identify-fallback! + "For projects whose id gh did not print: the newest workflow_dispatch run, + waiting up to about 3.5 minutes. Returns the updated dispatch map." + [{:keys [gh sleep]} dispatched] + (let [need (vec (filter #(:need-id? (get dispatched %)) (keys dispatched)))] + (if (empty? need) + dispatched + (do (log "::group::identify runs (fallback)") + (sleep 10000) + (let [found (loop [i 0 found {}] + (let [found (reduce (fn [f pr] + (if (contains? f pr) + f + (if-let [id (newest-dispatch-run-id gh pr)] + (do (log (str " " pr " -> run " id " (guessed)")) + (assoc f pr id)) + f))) + found need)] + (if (or (= (count found) (count need)) (>= i 39)) + found + (do (sleep 5000) (recur (inc i) found))))) + out (reduce (fn [d pr] + (if-let [id (get found pr)] + (assoc d pr {:run-id id}) + (do (log (str " " pr ": no run appeared within the window")) + (assoc d pr {:detail "no-run-appeared"})))) + dispatched need)] + (log "::endgroup::") + out))))) + +(defn- fetch-log + "A job's log text, or nil with a warning." + [gh pr job-id] + (try ((:get-redirected-log gh) (str "repos/" org "/" pr "/actions/jobs/" job-id "/logs")) + (catch Exception e + (warn (str "could not fetch the log of " pr " job " job-id ": " + (subs (explain e) 0 (min 300 (count (explain e)))))) + nil))) + +(defn- run-jobs [gh pr id] + (try (vec (:jobs ((:get-json gh) (str "repos/" org "/" pr "/actions/runs/" id "/jobs?per_page=100")))) + (catch Exception e + (warn (str "could not list the jobs of " pr " run " id ": " (explain e))) + []))) + +(defn- finish + "Read the finished run's jobs and the logs the verdict needs, then classify. + Logs are fetched only here, for completed runs: the failed jobs' for a + failure (install and download failures live there), every job's for a + success (to read the `jolt --version` line)." + [{:keys [gh now requested nightly-sha]} pr id conclusion] + (let [jobs (run-jobs gh pr id) + want (case conclusion + "success" jobs + "failure" (filter #(= "failure" (:conclusion %)) jobs) + []) + logs (into {} (map (fn [j] [(:id j) (fetch-log gh pr (:id j))])) want) + c (classify {:requested requested :nightly-sha nightly-sha + :conclusion conclusion :jobs jobs :logs logs})] + (assoc c :finished-at (now)))) + +(defn- poll! + "Wait for every dispatched run to complete. Returns {project verdict}, polling in + fleet order. A + transport error while polling is just 'not yet'. Projects still running + after the last try are timed-out." + [{:keys [gh sleep] :as ctx} projects runs] + (log "::group::wait for completion") + (let [out (loop [i 0 pending (filterv runs projects) done {}] + (if (or (empty? pending) (>= i poll-tries)) + done + (let [step (reduce + (fn [{:keys [pending done]} pr] + (let [id (:run-id (get runs pr)) + run (try ((:get-json gh) (str "repos/" org "/" pr "/actions/runs/" id)) + (catch Exception _ nil))] + (if (= "completed" (:status run)) + (let [v (finish ctx pr id (:conclusion run))] + (log (str " " pr ": " (:detail v) + (when (:installed v) (str " (jolt " (:installed v) ")")))) + {:pending pending :done (assoc done pr v)}) + {:pending (conj pending pr) :done done}))) + {:pending [] :done done} pending)] + (when (seq (:pending step)) (sleep poll-interval-ms)) + (recur (inc i) (:pending step) (:done step)))))] + (log "::endgroup::") + out)) + +(defn- append! [path text] + (if (seq path) + (spit path text :append true) + (print text))) + +(defn run! + "Dispatch every project, wait, write the results and return an exit code + (1 when anything failed or was infra, else 0). + + opts: :version (blank means jolt's latest release), :projects (names), + :gh (fleet.github client map), :sh (fn [args env] -> {:exit :out :err}), + :env (fn name -> string or nil), :sleep (fn ms), :now (fn -> ISO string). + Reads GH_TOKEN, GITHUB_STEP_SUMMARY, GITHUB_OUTPUT, GITHUB_SERVER_URL, + GITHUB_REPOSITORY, GITHUB_RUN_ID and RUNNER_TEMP from env. Writes + results.json under RUNNER_TEMP/fanout-results, appends the summary, and + writes failed, infra, artifact, results_dir and version to GITHUB_OUTPUT." + [{:keys [version projects gh sh env sleep now] + :or {sh default-sh now now-iso sleep #(Thread/sleep (long %))}}] + (let [requested (resolve-version gh version) + sha (when (= "nightly" requested) (nightly-sha gh)) + _ (when sha (log "vnightly is" sha)) + ctx {:gh gh :sh sh :sleep sleep :now now :token (env "GH_TOKEN") + :requested requested :nightly-sha sha} + dispatched (identify-fallback! ctx (dispatch-all! ctx requested projects)) + verdicts (poll! ctx projects (into {} (filter (comp :run-id val)) dispatched)) + rows (mapv (fn [pr] + (let [d (get dispatched pr) + id (:run-id d) + v (get verdicts pr) + url (when id (run-url pr id))] + (merge {:name pr :run-url url :installed nil :failed-step nil + :cause nil :finished-at nil} + (cond + v v + (:detail d) {:result (:detail d) :detail (:detail d)} + :else {:result "timed-out" :detail "timed-out"})))) + projects) + {:keys [failed infra]} (split-names rows) + dir (str (or (env "RUNNER_TEMP") "/tmp") "/fanout-results") + run-link (str (env "GITHUB_SERVER_URL") "/" (env "GITHUB_REPOSITORY") + "/actions/runs/" (env "GITHUB_RUN_ID")) + artifact (str "results-" (str/replace requested "/" "-"))] + (fs/create-dirs dir) + (spit (str dir "/results.json") + (json/generate-string + (results-json {:requested requested :nightly-sha sha :finished-at (now) + :run-url run-link :projects rows}) + {:pretty true})) + (append! (env "GITHUB_STEP_SUMMARY") (summary-md {:version requested :projects rows})) + (append! (env "GITHUB_OUTPUT") + (str "results_dir=" dir "\n" + "artifact=" artifact "\n" + "version=" requested "\n" + "failed=" (joined failed) "\n" + "infra=" (joined infra) "\n")) + (if (and (empty? failed) (empty? infra)) + 0 + (do (binding [*out* *err*] + (println (str "failing: " (if (seq failed) (joined failed) "none") + " infra: " (if (seq infra) (joined infra) "none")))) + 1)))) diff --git a/src/fleet/github.clj b/src/fleet/github.clj index e5c046a..60d7269 100644 --- a/src/fleet/github.clj +++ b/src/fleet/github.clj @@ -71,13 +71,45 @@ (throw (ex-info (str "GitHub API " status " for " path) {:status status :path path :body (:body resp)}))))) +(defn- redirected-log! + "GET path with the token. GitHub answers a job-log request with a 302 to a + signed blob-storage URL. That URL is fetched WITHOUT the Authorization + header: the signature is the credential, and the token must not go to a + host we did not choose. A 2xx on the first request is returned as is. A + Location that is not https throws {:reason :bad-redirect}." + [{:keys [token request]} path] + (let [req (or request default-request) + resp (req {:url (url-for path) + :throw-exceptions false + :headers (cond-> {"Accept" "application/vnd.github+json" + "X-GitHub-Api-Version" "2022-11-28"} + (seq token) (assoc "Authorization" (str "Bearer " token)))}) + status (:status resp) + loc (header (:headers resp) "location")] + (cond + (and (integer? status) (<= 200 status 299)) (:body resp) + + (and (contains? #{301 302 303 307 308} status) (seq loc)) + (do (when-not (str/starts-with? loc "https://") + (throw (ex-info (str "refusing a non-https log redirect for " path) + {:reason :bad-redirect :path path}))) + (let [r2 (req {:url loc :throw-exceptions false :headers {}}) + s2 (:status r2)] + (if (and (integer? s2) (<= 200 s2 299)) + (:body r2) + (throw (ex-info (str "log host answered " s2 " for " path) + {:status s2 :path path :body (:body r2)}))))) + + :else (throw (ex-info (str "GitHub API " status " for " path) + {:status status :path path :body (:body resp)}))))) + (def ^:private json-accept "application/vnd.github+json") (defn- parse [body] (json/parse-string body true)) (defn client - "A map of fns {:get-json :get-raw :get-paginated}, each taking a path - (\"repos/o/r\", \"/repos/o/r\" or a full URL). opts: :token, :request (a fn + "A map of fns {:get-json :get-raw :get-paginated :get-redirected-log}, each + taking a path (\"repos/o/r\", \"/repos/o/r\" or a full URL). opts: :token, :request (a fn from {:url :headers :throw-exceptions} to {:status :headers :body})." [opts] {:get-json (fn [path] (parse (:body (request! opts path json-accept)))) @@ -89,7 +121,8 @@ acc (if (sequential? body) (into acc body) (conj acc body))] (if-let [nxt (next-link (header (:headers resp) "link"))] (recur nxt acc) - acc))))}) + acc)))) + :get-redirected-log (fn [path] (redirected-log! opts path))}) (defn env-client "A client with the token from GH_TOKEN (none when unset)." diff --git a/test/fleet/cli_test.clj b/test/fleet/cli_test.clj index 69e36b6..a369918 100644 --- a/test/fleet/cli_test.clj +++ b/test/fleet/cli_test.clj @@ -121,3 +121,13 @@ r (run #(cli/refresh-main [(str d "/out")] (assoc env "FLEET_JSON" (fleet d)) {:gh gh}))] (is (= 0 (:rc r))) (is (fs/exists? (str d "/out/status.json"))))))) + +(deftest fanout-rejects-extra-arguments + (let [r (run #(cli/fanout-main ["0.8.27" "extra"] {} {}))] + (is (= 2 (:rc r))) + (is (str/includes? (:err r) "usage: fanout [version]")))) + +(deftest fanout-without-a-fleet-file-exits-1-with-one-line + (let [r (run #(cli/fanout-main ["0.8.27"] {"FLEET_JSON" "/nonexistent/fleet.json"} {}))] + (is (= 1 (:rc r))) + (is (str/includes? (:err r) "fanout: cannot read /nonexistent/fleet.json")))) diff --git a/test/fleet/fanout_test.clj b/test/fleet/fanout_test.clj new file mode 100644 index 0000000..4249c47 --- /dev/null +++ b/test/fleet/fanout_test.clj @@ -0,0 +1,331 @@ +(ns fleet.fanout-test + (:require [babashka.fs :as fs] + [cheshire.core :as json] + [clojure.string :as str] + [clojure.test :refer [deftest is testing]] + [fleet.fanout :as fanout])) + +(def ^:private fx "test/fixtures/") + +(defn- fixture [name] (slurp (str fx name))) + +(defn- job + ([id conclusion] (job id conclusion [])) + ([id conclusion steps] {:id id :conclusion conclusion :steps steps})) + +(defn- step [name conclusion] {:name name :conclusion conclusion}) + +(def ^:private release-log (fixture "log-release.txt")) +(def ^:private nightly-log (fixture "log-nightly.txt")) + +(defn- jolt-log [v] (str "2026-11-20T01:00:00.0000000Z jolt v" v "\n")) + +;; --------------------------------------------------------------------------- +;; classify + +(deftest success-on-the-requested-jolt-is-pass + (is (= {:result "pass" :installed "0.8.24" :failed-step nil :cause nil :detail "success"} + (fanout/classify {:requested "0.8.24" :conclusion "success" + :jobs [(job 1 "success")] :logs {1 release-log}})))) + +(deftest r4-one-matching-job-is-enough + (testing "glitter-gl's deliberate 0.7.29 job beside the main one" + (is (= {:result "pass" :installed "0.8.27"} + (select-keys (fanout/classify {:requested "0.8.27" :conclusion "success" + :jobs [(job 1 "success") (job 2 "success")] + :logs {1 (jolt-log "0.7.29") 2 (jolt-log "0.8.27")}}) + [:result :installed]))))) + +(deftest a-green-run_on_the_wrong_jolt_is_mismatch_never_pass + (is (= {:result "mismatch" :installed "0.7.29"} + (select-keys (fanout/classify {:requested "0.8.27" :conclusion "success" + :jobs [(job 1 "success")] :logs {1 (jolt-log "0.7.29")}}) + [:result :installed])))) + +(deftest a-green-run-with-no-version-line-is-mismatch + (is (= {:result "mismatch" :installed nil} + (select-keys (fanout/classify {:requested "0.8.27" :conclusion "success" + :jobs [(job 1 "success")] :logs {1 nil}}) + [:result :installed])))) + +(deftest nightly-needs-the-vnightly-sha-prefix + (let [base {:requested "nightly" :conclusion "success" :jobs [(job 1 "success")] :logs {1 nightly-log}}] + (is (= {:result "pass" :installed "0.8.27-241-gdd3c4a4b"} + (select-keys (fanout/classify (assoc base :nightly-sha "dd3c4a4b0123456789abcdef0123456789abcdef")) + [:result :installed]))) + (testing "vnightly moved on after the install" + (is (= {:result "mismatch" :installed "0.8.27-241-gdd3c4a4b"} + (select-keys (fanout/classify (assoc base :nightly-sha "f4e82fc8eac874cae1658b7976518253027c4f6a")) + [:result :installed])))) + (testing "sha unresolved reads as mismatch" + (is (= "mismatch" (:result (fanout/classify base))))))) + +(deftest r5-skipped-is-not-run + (is (= "not-run" (:result (fanout/classify {:requested "0.8.27" :conclusion "skipped" :jobs [] :logs {}}))))) + +(deftest a-failed-install-jolt-step-is-infra-and-keeps-the-step-name + (is (= {:result "infra" :cause :install :failed-step "Install jolt"} + (select-keys (fanout/classify {:requested "0.8.0" :conclusion "failure" + :jobs [(job 1 "failure" [(step "Checkout" "success") + (step "Install jolt" "failure")])] + :logs {1 (fixture "log-test-failure.txt")}}) + [:result :cause :failed-step])))) + +(deftest r21-r24-a-maven-429-in-the-failed-step-is-infra-deps + (testing "raygui-jlt's Formatting 429" + (is (= {:result "infra" :cause :deps :failed-step "Formatting"} + (select-keys (fanout/classify {:requested "nightly" :conclusion "failure" + :jobs [(job 1 "failure" [(step "Formatting" "failure")])] + :logs {1 (fixture "log-maven-429.txt")}}) + [:result :cause :failed-step]))))) + +(deftest r24-every-failed-job-must-match + (let [jobs [(job 1 "failure" [(step "Formatting" "failure")]) + (job 2 "failure" [(step "Test" "failure")])]] + (is (= "fail" (:result (fanout/classify {:requested "0.8.27" :conclusion "failure" :jobs jobs + :logs {1 (fixture "log-maven-429.txt") + 2 (fixture "log-test-failure.txt")}})))) + (is (= "infra" (:result (fanout/classify {:requested "0.8.27" :conclusion "failure" :jobs jobs + :logs {1 (fixture "log-maven-429.txt") + 2 (fixture "log-maven-absent.txt")}})))))) + +(deftest an-unreadable-log-is-no-evidence + (is (= "fail" (:result (fanout/classify {:requested "0.8.27" :conclusion "failure" + :jobs [(job 1 "failure" [(step "Formatting" "failure")])] + :logs {1 nil}}))))) + +(deftest a-429-outside-the-failed-step-stays-fail + (is (= "fail" (:result (fanout/classify {:requested "0.8.27" :conclusion "failure" + :jobs [(job 1 "failure" [(step "Test" "failure")])] + :logs {1 (fixture "log-early-429.txt")}}))))) + +(deftest an-ordinary-failure-is-fail-with-its-first-failed-step + (is (= {:result "fail" :cause nil :failed-step "Test"} + (select-keys (fanout/classify {:requested "0.8.27" :conclusion "failure" + :jobs [(job 1 "failure" [(step "Checkout" "success") + (step "Test" "failure")]) + (job 2 "failure" [(step "Other" "failure")])] + :logs {1 (fixture "log-test-failure.txt") + 2 (fixture "log-test-failure.txt")}}) + [:result :cause :failed-step])))) + +(deftest other-conclusions-are-fail-without-a-step + (is (= {:result "fail" :failed-step nil :detail "cancelled"} + (select-keys (fanout/classify {:requested "0.8.27" :conclusion "cancelled" :jobs [] :logs {}}) + [:result :failed-step :detail])))) + +;; --------------------------------------------------------------------------- +;; summary-md + +(defn- row [name result & {:as more}] + (merge {:name name :result result :detail "x" :run-url (str "https://r/" name)} more)) + +(deftest summary-all-pass + (is (= (str "## jolt `0.8.27` across jlt-commons\n\n" + "| project | result | run |\n|---|---|---|\n" + "| `a` | pass | [run](https://r/a) |\n" + "| `b` | skipped | [run](https://r/b) |\n\n" + "All 2 projects build against jolt `0.8.27`.\n") + (fanout/summary-md {:version "0.8.27" + :projects [(row "a" "pass") (row "b" "not-run")]})))) + +(deftest summary-names-each-kind-of-trouble + (let [md (fanout/summary-md + {:version "nightly" + :projects [(row "m" "mismatch" :installed "0.7.29") + (row "f" "fail" :detail "failure") + (row "t" "timed-out" :detail "timed-out" :run-url nil) + (row "i" "infra" :cause :install) + (row "d" "infra" :cause :deps)]})] + (is (str/includes? md "| `m` | **WRONG JOLT** (ran 0.7.29) | [run](https://r/m) |")) + (is (str/includes? md "| `f` | **FAIL** (failure) |")) + (is (str/includes? md "| `t` | **FAIL** (timed-out) | - |")) + (is (str/includes? md "| `i` | **could not install jolt** |")) + (is (str/includes? md "| `d` | **could not download dependencies** |")) + (is (str/includes? md "**Ran on the wrong jolt:** m\n")) + (is (str/includes? md "**Broken by jolt `nightly`:** m f t\n")) + (is (str/includes? md "**Could not install jolt `nightly` for:** i\n")) + (is (str/includes? md "check each project's `JOLT_REPO`")) + (is (str/includes? md "**Could not download dependencies for:** d\n")) + (is (str/includes? md "package-registry problem")) + (is (not (str/includes? md "All "))))) + +(deftest summary-mismatch-without-a-version + (is (str/includes? (fanout/summary-md {:version "1" :projects [(row "m" "mismatch")]}) + "**WRONG JOLT** (ran no version found)"))) + +;; --------------------------------------------------------------------------- +;; run! over a fake fleet + +(def ^:private run-ids {"alpha" "101" "beta" "202"}) + +(defn- fake-world + "Fakes for run!. runs: project -> vector of run responses handed out one + per poll. jobs: project -> job vector. logs: job id -> text or :fail. + Records every call in :calls." + [{:keys [runs jobs logs dispatch print-url? latest vnightly] + :or {print-url? true latest "0.9.0" vnightly "dd3c4a4b0123456789abcdef0123456789abcdef"}}] + (let [calls (atom []) + polls (atom {}) + sleeps (atom []) + by-path (fn [path] + (or (when-let [[_ pr] (re-matches #"repos/jlt-commons/([^/]+)/actions/runs/\d+" path)] + (let [n (get (swap! polls update pr (fnil inc 0)) pr) + rs (get runs pr)] + (get rs (min (dec n) (dec (count rs)))))) + (when-let [[_ pr] (re-matches #"repos/jlt-commons/([^/]+)/actions/runs/\d+/jobs\?per_page=100" path)] + {:jobs (get jobs pr)}) + (when (= path "repos/jolt-lang/jolt/releases/latest") {:tag_name (str "v" latest)}) + (when (= path "repos/jolt-lang/jolt/git/refs/tags/vnightly") {:object {:sha vnightly}}) + (when-let [[_ pr] (re-matches #"repos/jlt-commons/([^/]+)/actions/workflows/ci.yml/runs\?event=workflow_dispatch&per_page=1" path)] + {:workflow_runs [{:id (Long/parseLong (get run-ids pr))}]}) + (throw (ex-info (str "unexpected " path) {:status 404}))))] + {:calls calls :sleeps sleeps + :gh {:get-json (fn [path] (swap! calls conj [:get path]) (by-path path)) + :get-redirected-log + (fn [path] + (swap! calls conj [:log path]) + (let [id (Long/parseLong (second (re-find #"jobs/(\d+)/logs" path))) + txt (get logs id)] + (if (= :fail txt) (throw (ex-info "gone" {:status 410})) txt)))} + :sh (fn [args env] + (swap! calls conj [:sh args env]) + (let [pr (second (re-find #"jlt-commons/(.*)" (nth args 5)))] + (cond + (and dispatch (= :fail (get dispatch pr))) {:exit 1 :out "" :err "HTTP 422"} + print-url? {:exit 0 :out (str "https://github.com/jlt-commons/" pr "/actions/runs/" (get run-ids pr) "\n") :err ""} + :else {:exit 0 :out "" :err ""}))) + :sleep (fn [ms] (swap! sleeps conj ms)) + :now (constantly "2026-11-20T03:00:00Z")})) + +(defn- env-for [dir] + (let [m {"GH_TOKEN" "tok" "RUNNER_TEMP" dir + "GITHUB_STEP_SUMMARY" (str dir "/summary.md") "GITHUB_OUTPUT" (str dir "/output.txt") + "GITHUB_SERVER_URL" "https://github.com" "GITHUB_REPOSITORY" "jlt-commons/ci-builds" + "GITHUB_RUN_ID" "999"}] + #(get m %))) + +(defn- tmp [] (str (fs/create-temp-dir))) + +(defn- run-fake [world version] + (let [dir (tmp) + out (java.io.StringWriter.) + err (java.io.StringWriter.) + rc (binding [*out* out *err* err] + (fanout/run! (assoc (select-keys world [:gh :sh :sleep :now]) + :version version :projects ["alpha" "beta"] :env (env-for dir))))] + {:rc rc :dir dir :stdout (str out) :stderr (str err) + :results (json/parse-string (slurp (str dir "/fanout-results/results.json")) true) + :summary (slurp (str dir "/summary.md")) + :output (slurp (str dir "/output.txt"))})) + +(def ^:private ok-run {:status "completed" :conclusion "success"}) + +(deftest run-passes-two-projects-after-waiting-once + (let [w (fake-world {:runs {"alpha" [{:status "in_progress"} ok-run] "beta" [ok-run]} + :jobs {"alpha" [(job 1 "success")] "beta" [(job 2 "success")]} + :logs {1 (jolt-log "0.8.27") 2 (jolt-log "0.8.27")}}) + r (run-fake w "0.8.27")] + (is (= 0 (:rc r))) + (is (= [20000] @(:sleeps w))) + (testing "dispatch used gh with the token and the version" + (is (= [:sh ["gh" "workflow" "run" "ci.yml" "--repo" "jlt-commons/alpha" "-f" "jolt-version=0.8.27"] + {"GH_TOKEN" "tok"}] + (first (filter #(= :sh (first %)) @(:calls w)))))) + (testing "logs came only after completion, for every job of a success" + (is (= [[:log "repos/jlt-commons/beta/actions/jobs/2/logs"] + [:log "repos/jlt-commons/alpha/actions/jobs/1/logs"]] + (filterv #(= :log (first %)) @(:calls w))))) + (testing "results.json has the bash-era shape" + (is (= {:requested "0.8.27" :nightly_sha "" + :finished_at "2026-11-20T03:00:00Z" + :run_url "https://github.com/jlt-commons/ci-builds/actions/runs/999" + :projects [{:name "alpha" :result "pass" :installed "0.8.27" + :run_url "https://github.com/jlt-commons/alpha/actions/runs/101" + :finished_at "2026-11-20T03:00:00Z" :failed_step nil} + {:name "beta" :result "pass" :installed "0.8.27" + :run_url "https://github.com/jlt-commons/beta/actions/runs/202" + :finished_at "2026-11-20T03:00:00Z" :failed_step nil}]} + (:results r)))) + (is (str/includes? (:summary r) "All 2 projects build against jolt `0.8.27`.")) + (is (= (str "results_dir=" (:dir r) "/fanout-results\nartifact=results-0.8.27\nversion=0.8.27\nfailed=\ninfra=\n") + (:output r))))) + +(deftest run-reports-failures-and-infra-and-exits-1 + (let [w (fake-world {:runs {"alpha" [{:status "completed" :conclusion "failure"}] + "beta" [{:status "completed" :conclusion "failure"}]} + :jobs {"alpha" [(job 1 "failure" [(step "Formatting" "failure")])] + "beta" [(job 2 "failure" [(step "Install jolt" "failure")])]} + :logs {1 (fixture "log-maven-429.txt") 2 "boom\n"}}) + r (run-fake w "nightly")] + (is (= 1 (:rc r))) + (is (= [{:name "alpha" :result "infra" :failed_step "Formatting" :installed nil} + {:name "beta" :result "infra" :failed_step "Install jolt" :installed nil}] + (mapv #(select-keys % [:name :result :failed_step :installed]) (:projects (:results r))))) + (is (= "dd3c4a4b0123456789abcdef0123456789abcdef" (:nightly_sha (:results r)))) + (is (str/includes? (:summary r) "**Could not install jolt `nightly` for:** beta")) + (is (str/includes? (:summary r) "**Could not download dependencies for:** alpha")) + (is (str/includes? (:output r) "failed=\ninfra=alpha beta\n")) + (is (str/includes? (:stderr r) "infra: alpha beta")))) + +(deftest run-wrong-jolt-is-mismatch-and-failed + (let [w (fake-world {:runs {"alpha" [ok-run] "beta" [ok-run]} + :jobs {"alpha" [(job 1 "success")] "beta" [(job 2 "success")]} + :logs {1 (jolt-log "0.8.27") 2 (jolt-log "0.8.26")}}) + r (run-fake w "0.8.27")] + (is (= 1 (:rc r))) + (is (= ["pass" "mismatch"] (mapv :result (:projects (:results r))))) + (is (= "0.8.26" (:installed (second (:projects (:results r)))))) + (is (str/includes? (:summary r) "**Ran on the wrong jolt:** beta")) + (is (str/includes? (:output r) "failed=beta\n")))) + +(deftest run-a-dispatch-failure-is-dispatch-failed-and-never-polled + (let [w (fake-world {:dispatch {"beta" :fail} + :runs {"alpha" [ok-run]} + :jobs {"alpha" [(job 1 "success")]} + :logs {1 (jolt-log "0.8.27")}}) + r (run-fake w "0.8.27") + b (second (:projects (:results r)))] + (is (= 1 (:rc r))) + (is (= {:result "dispatch-failed" :run_url nil :finished_at nil} (select-keys b [:result :run_url :finished_at]))) + (is (not-any? #(and (= :get (first %)) (str/includes? (second %) "beta")) @(:calls w))))) + +(deftest run-gives-up-after-150-polls-as-timed-out + (let [w (fake-world {:runs {"alpha" [{:status "in_progress"}] "beta" [ok-run]} + :jobs {"beta" [(job 2 "success")]} + :logs {2 (jolt-log "0.8.27")}}) + r (run-fake w "0.8.27")] + (is (= 1 (:rc r))) + (is (= 150 (count @(:sleeps w)))) + (is (= ["timed-out" "pass"] (mapv :result (:projects (:results r))))) + (is (str/includes? (:summary r) "| `alpha` | **FAIL** (timed-out) |")))) + +(deftest run-without-a-printed-url-warns-and-takes-the-newest-dispatch-run + (let [w (fake-world {:print-url? false + :runs {"alpha" [ok-run] "beta" [ok-run]} + :jobs {"alpha" [(job 1 "success")] "beta" [(job 2 "success")]} + :logs {1 (jolt-log "0.8.27") 2 (jolt-log "0.8.27")}}) + r (run-fake w "0.8.27")] + (is (= 0 (:rc r))) + (is (str/includes? (:stdout r) "::warning::gh printed no run URL for alpha")) + (is (= "https://github.com/jlt-commons/alpha/actions/runs/101" (:run_url (first (:projects (:results r)))))) + (is (= 10000 (first @(:sleeps w)))))) + +(deftest run-a-log-that-cannot-be-fetched-warns-and-is-no-evidence + (let [w (fake-world {:runs {"alpha" [{:status "completed" :conclusion "failure"}] "beta" [ok-run]} + :jobs {"alpha" [(job 1 "failure" [(step "Formatting" "failure")])] + "beta" [(job 2 "success")]} + :logs {1 :fail 2 (jolt-log "0.8.27")}}) + r (run-fake w "0.8.27")] + (is (= "fail" (:result (first (:projects (:results r)))))) + (is (str/includes? (:stdout r) "::warning::could not fetch the log of alpha job 1")))) + +(deftest run-blank-version-tests-the-latest-release + (let [w (fake-world {:latest "0.9.1" + :runs {"alpha" [ok-run] "beta" [ok-run]} + :jobs {"alpha" [(job 1 "success")] "beta" [(job 2 "success")]} + :logs {1 (jolt-log "0.9.1") 2 (jolt-log "0.9.1")}}) + r (run-fake w "")] + (is (= "0.9.1" (:requested (:results r)))) + (is (str/includes? (:output r) "version=0.9.1\n")) + (is (= "jolt-version=0.9.1" (nth (second (first (filter #(= :sh (first %)) @(:calls w)))) 7))))) diff --git a/test/fleet/github_test.clj b/test/fleet/github_test.clj index 076e162..ee24a20 100644 --- a/test/fleet/github_test.clj +++ b/test/fleet/github_test.clj @@ -1,5 +1,6 @@ (ns fleet.github-test - (:require [clojure.test :refer [deftest is testing]] + (:require [clojure.string :as str] + [clojure.test :refer [deftest is testing]] [fleet.github :as gh])) (defn- stub @@ -133,3 +134,45 @@ (let [e (try ((f c) "repos/o/r") nil (catch Exception e e))] (is (identical? boom e)) (is (nil? (gh/status-of e))))))) + +(deftest get-redirected-log-follows-the-302-without-the-token + (let [seen (atom []) + blob "https://productionresultssa1.blob.core.windows.net/logs/1?sig=abc" + c (gh/client {:token "tok" + :request (stub {"https://api.github.com/repos/o/r/actions/jobs/7/logs" + {:status 302 :headers {"Location" blob} :body ""} + blob {:status 200 :headers {} :body "log text\n"}} + seen)})] + (is (= "log text\n" ((:get-redirected-log c) "repos/o/r/actions/jobs/7/logs"))) + (is (= 2 (count @seen))) + (is (= "Bearer tok" (get-in (first @seen) [:headers "Authorization"]))) + (is (= blob (:url (second @seen)))) + (is (not-any? #(= "authorization" (str/lower-case (name %))) + (keys (:headers (second @seen))))))) + +(deftest get-redirected-log-accepts-a-direct-200 + (let [c (gh/client {:token "tok" + :request (stub {"https://api.github.com/l" {:status 200 :headers {} :body "direct"}} (atom []))})] + (is (= "direct" ((:get-redirected-log c) "l"))))) + +(deftest get-redirected-log-refuses-a-non-https-location + (let [seen (atom []) + c (gh/client {:token "tok" + :request (stub {"https://api.github.com/l" + {:status 302 :headers {"location" "http://evil.example/x"} :body ""}} + seen)}) + e (try ((:get-redirected-log c) "l") nil (catch Exception e e))] + (is (= :bad-redirect (:reason (ex-data e)))) + (is (= 1 (count @seen))))) + +(deftest get-redirected-log-redirect-without-location-throws + (let [c (gh/client {:request (stub {"https://api.github.com/l" {:status 302 :headers {} :body ""}} (atom []))}) + e (try ((:get-redirected-log c) "l") nil (catch Exception e e))] + (is (= 302 (gh/status-of e))))) + +(deftest get-redirected-log-error-from-the-blob-host-throws + (let [blob "https://blob.example/x" + c (gh/client {:request (stub {"https://api.github.com/l" {:status 302 :headers {"Location" blob} :body ""} + blob {:status 403 :headers {} :body "expired"}} (atom []))}) + e (try ((:get-redirected-log c) "l") nil (catch Exception e e))] + (is (= 403 (gh/status-of e))))) From 1746e8e899799f7518882ab80ec4daf62c79553b Mon Sep 17 00:00:00 2001 From: burinc Date: Fri, 20 Nov 2026 15:14:59 +1100 Subject: [PATCH 20/31] fanout: no-run-appeared is dispatch-failed, per-project errors do not drop results, LATEST via the client --- .github/workflows/fanout.yml | 3 -- src/fleet/cli.clj | 9 +++--- src/fleet/fanout.clj | 13 +++++--- test/fleet/cli_test.clj | 28 ++++++++++++++++ test/fleet/fanout_test.clj | 62 ++++++++++++++++++++++++++++++++++++ test/fleet/refresh_test.clj | 6 ++-- 6 files changed, 107 insertions(+), 14 deletions(-) diff --git a/.github/workflows/fanout.yml b/.github/workflows/fanout.yml index 9e5bdf4..5310b8f 100644 --- a/.github/workflows/fanout.yml +++ b/.github/workflows/fanout.yml @@ -159,9 +159,6 @@ jobs: CANARY_RUN: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} run: | set -euo pipefail - tag="$(gh api repos/jolt-lang/jolt/releases/latest --jq .tag_name)" - [ -n "$tag" ] || { echo "could not resolve jolt's latest release" >&2; exit 1; } - export LATEST="${tag#v}" # fleet:publish refreshes in-process on every attempt (R27), so the # results files are plain arguments. if [ -d results ]; then diff --git a/src/fleet/cli.clj b/src/fleet/cli.clj index 5bc2f68..ffcbe83 100644 --- a/src/fleet/cli.clj +++ b/src/fleet/cli.clj @@ -122,7 +122,8 @@ gh (gh-of deps)] {:out-dir out-dir :prev-dir (get env "PREV_DIR") - :latest (get env "LATEST") + :latest (or (not-empty (get env "LATEST")) + (fanout/resolve-version gh "")) :nightly (parse-nightly (get env "NIGHTLY_JSON")) :canary-run (get env "CANARY_RUN") :results-files (vec results) @@ -132,11 +133,11 @@ (defn refresh-main "fleet:refresh: collect, build and write /status.json and - history.json. Env: LATEST, NIGHTLY_JSON, CANARY_RUN (required), PREV_DIR, + history.json. Env: NIGHTLY_JSON, CANARY_RUN (required), LATEST (default: jolt's latest release via the GitHub client), PREV_DIR, FLEET_JSON, GH_TOKEN." ([args] (refresh-main args (into {} (System/getenv)) {})) ([args env deps] - (if-let [v (require-env env ["LATEST" "NIGHTLY_JSON" "CANARY_RUN"])] + (if-let [v (require-env env ["NIGHTLY_JSON" "CANARY_RUN"])] (do (err (str "refresh-status: " v " is required")) (usage-error refresh-usage nil)) (if (empty? args) (usage-error refresh-usage nil) @@ -147,7 +148,7 @@ in-process on every attempt, then commits to origin's status branch." ([args] (publish-main args (into {} (System/getenv)) {})) ([args env deps] - (if-let [v (require-env env ["LATEST" "NIGHTLY_JSON" "CANARY_RUN"])] + (if-let [v (require-env env ["NIGHTLY_JSON" "CANARY_RUN"])] (do (err (str "publish-status: " v " is required")) (usage-error "publish [results.json ...] (env: LATEST NIGHTLY_JSON CANARY_RUN)" nil)) (if (empty? args) diff --git a/src/fleet/fanout.clj b/src/fleet/fanout.clj index 1685d46..8211bea 100644 --- a/src/fleet/fanout.clj +++ b/src/fleet/fanout.clj @@ -67,7 +67,7 @@ (defn- failed-steps "Names of every failed step across the jobs, in job then step order." [jobs] - (for [j jobs, s (:steps j) :when (= "failure" (:conclusion s))] (:name s))) + (for [j jobs, s (when (sequential? (:steps j)) (:steps j)) :when (= "failure" (:conclusion s))] (str (:name s)))) (defn- deps-unavailable? "R24: every failed job's log was fetched and each shows a download failure @@ -292,7 +292,7 @@ (if-let [id (get found pr)] (assoc d pr {:run-id id}) (do (log (str " " pr ": no run appeared within the window")) - (assoc d pr {:detail "no-run-appeared"})))) + (assoc d pr {:detail "no-run-appeared" :result "dispatch-failed"})))) dispatched need)] (log "::endgroup::") out))))) @@ -344,7 +344,12 @@ run (try ((:get-json gh) (str "repos/" org "/" pr "/actions/runs/" id)) (catch Exception _ nil))] (if (= "completed" (:status run)) - (let [v (finish ctx pr id (:conclusion run))] + (let [v (try (finish ctx pr id (:conclusion run)) + (catch Exception e + ;; One project's bad payload must not drop the others' results. + (warn (str "could not classify " pr " run " id ": " (ex-message e))) + {:result "fail" :detail "error" :installed nil + :failed-step nil :cause nil :finished-at ((:now ctx))}))] (log (str " " pr ": " (:detail v) (when (:installed v) (str " (jolt " (:installed v) ")")))) {:pending pending :done (assoc done pr v)}) @@ -389,7 +394,7 @@ :cause nil :finished-at nil} (cond v v - (:detail d) {:result (:detail d) :detail (:detail d)} + (:detail d) {:result (or (:result d) (:detail d)) :detail (:detail d)} :else {:result "timed-out" :detail "timed-out"})))) projects) {:keys [failed infra]} (split-names rows) diff --git a/test/fleet/cli_test.clj b/test/fleet/cli_test.clj index a369918..bf3a575 100644 --- a/test/fleet/cli_test.clj +++ b/test/fleet/cli_test.clj @@ -131,3 +131,31 @@ (let [r (run #(cli/fanout-main ["0.8.27"] {"FLEET_JSON" "/nonexistent/fleet.json"} {}))] (is (= 1 (:rc r))) (is (str/includes? (:err r) "fanout: cannot read /nonexistent/fleet.json")))) + +(deftest refresh-without-latest-asks-the-client-and-strips-the-v + (let [d (tmp-dir) + asked (atom []) + gh {:get-json (fn [path] + (swap! asked conj path) + (if (= "repos/jolt-lang/jolt/releases/latest" path) + {:tag_name "v0.9.4"} + (throw (ex-info "no" {:status 404})))) + :get-raw (fn [_] (throw (ex-info "no" {:status 404}))) + :get-paginated (fn [_] [])} + env {"NIGHTLY_JSON" "null" "CANARY_RUN" "https://example/run/1" + "FLEET_JSON" (write! d "fleet.json" "{\"projects\":[],\"excluded\":{}}")} + r (run #(cli/refresh-main [(str d "/out")] env {:gh gh}))] + (is (= 0 (:rc r))) + (is (= ["repos/jolt-lang/jolt/releases/latest"] @asked)) + (is (str/includes? (slurp (str d "/out/status.json")) "0.9.4")) + (is (not (str/includes? (slurp (str d "/out/status.json")) "v0.9.4"))))) + +(deftest refresh-with-latest-set-does-not-ask + (let [d (tmp-dir) + gh {:get-json (fn [path] (throw (ex-info (str "unexpected " path) {:status 404}))) + :get-raw (fn [_] (throw (ex-info "no" {:status 404}))) + :get-paginated (fn [_] [])} + env {"LATEST" "0.8.27" "NIGHTLY_JSON" "null" "CANARY_RUN" "x" + "FLEET_JSON" (write! d "fleet.json" "{\"projects\":[],\"excluded\":{}}")} + r (run #(cli/refresh-main [(str d "/out")] env {:gh gh}))] + (is (= 0 (:rc r))))) diff --git a/test/fleet/fanout_test.clj b/test/fleet/fanout_test.clj index 4249c47..5cdcf74 100644 --- a/test/fleet/fanout_test.clj +++ b/test/fleet/fanout_test.clj @@ -329,3 +329,65 @@ (is (= "0.9.1" (:requested (:results r)))) (is (str/includes? (:output r) "version=0.9.1\n")) (is (= "jolt-version=0.9.1" (nth (second (first (filter #(= :sh (first %)) @(:calls w)))) 7))))) + +(deftest run-a-fallback-that-finds-no-run-is-dispatch-failed-and-failed + (let [w (-> (fake-world {:print-url? false + :runs {"beta" [ok-run]} + :jobs {"beta" [(job 2 "success")]} + :logs {2 (jolt-log "0.8.27")}}) + (update :gh assoc :get-json + (let [base (:get-json (:gh (fake-world {:print-url? false + :runs {"beta" [ok-run]} + :jobs {"beta" [(job 2 "success")]} + :logs {2 (jolt-log "0.8.27")}})))] + (fn [path] + (if (str/includes? path "/alpha/actions/workflows/") + {:workflow_runs []} + (base path)))))) + r (run-fake w "0.8.27") + a (first (:projects (:results r)))] + (is (= 1 (:rc r))) + (is (= {:result "dispatch-failed" :run_url nil} (select-keys a [:result :run_url]))) + (is (str/includes? (:output r) "failed=alpha\n")) + (is (str/includes? (:summary r) "| `alpha` | **FAIL** (no-run-appeared) | - |")) + (is (str/includes? (:summary r) "**Broken by jolt `0.8.27`:** alpha")) + (is (not (str/includes? (:summary r) "All "))))) + +(deftest run-one-malformed-project-is-fail-and_does_not_drop_the_others + (let [w (fake-world {:runs {"alpha" [{:status "completed" :conclusion "failure"}] "beta" [ok-run]} + :jobs {"alpha" [{:id 1 :conclusion "failure" :steps 42}] + "beta" [(job 2 "success")]} + :logs {1 "x" 2 (jolt-log "0.8.27")}}) + w (update w :gh assoc :get-json + (let [base (:get-json (:gh w))] + (fn [path] + (if (str/includes? path "/alpha/actions/runs/101/jobs") + (throw (ex-info "boom secret-data" {:token "SECRET"})) + (base path))))) + r (run-fake w "0.8.27")] + (is (= 1 (:rc r))) + (is (= [{:name "alpha" :result "fail" :failed_step nil} + {:name "beta" :result "pass" :failed_step nil}] + (mapv #(select-keys % [:name :result :failed_step]) (:projects (:results r))))) + (is (str/includes? (:output r) "failed=alpha\n")))) + +(deftest run-an-exception-while-classifying-is-fail-with-a-warning-without-ex-data + (let [w (fake-world {:runs {"alpha" [{:status "completed" :conclusion "failure"}] "beta" [ok-run]} + :jobs {"alpha" [(job 1 "failure" [(step nil "failure")])] + "beta" [(job 2 "success")]} + :logs {1 "x" 2 (jolt-log "0.8.27")}}) + w (update w :gh assoc :get-redirected-log + (let [base (:get-redirected-log (:gh w))] + (fn [path] + (if (str/includes? path "/jobs/1/") + (throw (RuntimeException. "log layer exploded")) + (base path))))) + r (run-fake w "0.8.27")] + (is (= 1 (:rc r))) + (is (= ["fail" "pass"] (mapv :result (:projects (:results r))))))) + +(deftest classify-tolerates-malformed-steps + (is (= "fail" (:result (fanout/classify {:requested "1" :conclusion "failure" + :jobs [{:id 1 :conclusion "failure" :steps 42} + {:id 2 :conclusion "failure" :steps [{:conclusion "failure"}]}] + :logs {1 "x" 2 "x"}}))))) diff --git a/test/fleet/refresh_test.clj b/test/fleet/refresh_test.clj index 8481f57..9cb4f1c 100644 --- a/test/fleet/refresh_test.clj +++ b/test/fleet/refresh_test.clj @@ -35,13 +35,13 @@ (is (= ["ebb" "glitter" "raygui-jlt"] (sort (map :name (:projects s))))) (is (= 1 (:schema h)))))) -(deftest refresh-needs-latest +(deftest refresh-needs-canary-run (let [out (str (tmp-dir) "/out") err (StringWriter.) rc (binding [*err* err] - (cli/refresh-main [out] {"NIGHTLY_JSON" "null" "CANARY_RUN" "x"} {}))] + (cli/refresh-main [out] {"NIGHTLY_JSON" "null"} {}))] (is (= 2 rc)) - (is (re-find #"LATEST" (str err))) + (is (re-find #"CANARY_RUN" (str err))) (is (not (fs/exists? out))))) (deftest two-publishes-differing-only-in-clock-and-canary-run-make-one-commit From 91514ab81064fe02fa89024f6afc3b8080d86611 Mon Sep 17 00:00:00 2001 From: burinc Date: Fri, 20 Nov 2026 15:21:37 +1100 Subject: [PATCH 21/31] canary: plan and issue logic in jolt --- .github/workflows/canary.yml | 407 +++++++---------------------------- deps.edn | 12 +- src/fleet/canary.clj | 377 ++++++++++++++++++++++++++++++++ src/fleet/cli.clj | 87 +++++++- src/fleet/github.clj | 38 ++-- test/fleet/canary_test.clj | 388 +++++++++++++++++++++++++++++++++ test/fleet/cli_test.clj | 81 +++++++ test/fleet/github_test.clj | 47 +++- 8 files changed, 1091 insertions(+), 346 deletions(-) create mode 100644 src/fleet/canary.clj create mode 100644 test/fleet/canary_test.clj diff --git a/.github/workflows/canary.yml b/.github/workflows/canary.yml index 8d1d2eb..d31cc04 100644 --- a/.github/workflows/canary.yml +++ b/.github/workflows/canary.yml @@ -5,76 +5,28 @@ name: canary # build every project. Two of them: # # latest jolt's newest published release -# nightly jolt's rolling vnightly prerelease, when fresh (see below) +# nightly jolt's rolling vnightly prerelease, when fresh # -# What each project pins is no longer a row here. The `status` job reads every +# The decisions live in src/fleet/canary.clj, which says why each rule exists: +# the nightly freshness and duplicate-of-release checks, the cache key that +# carries the nightly's published_at, the interval gate, and what the issue +# says. This file wires them to jobs. The plan job runs `jolt fleet:plan` +# (what to test, and the interval gate), then an actions/cache lookup (the +# change gate, which a task cannot do), then `jolt fleet:plan --final` to +# combine the two. The report job runs `jolt fleet:report`. +# +# What each project pins is not a row here. The `status` job reads every # project's own latest push CI run on its default branch and shows it as the -# "pin" column on the dashboard, so the pin is observed rather than configured -# (vars.JOLT_PIN is not read any more). +# "pin" column on the dashboard, so the pin is observed rather than configured. # # Every run also ends with the `status` job, which merges the results into # status.json and history.json on the `status` branch. The fleet page reads -# those two files. -# -# NIGHTLY IS AVAILABLE NOW, and this block used to say it was not. jolt-lang/jolt#824 -# merged 2026-09-02 and jolt publishes a rolling `vnightly` prerelease from main, -# so `install --version nightly` resolves it and the whole "build it from source -# against Chez on two operating systems" plan this file used to describe is moot. -# The fleet has been run against it: fan-out 33691047983, all five green, every -# project's log showing `Successfully installed jolt vnightly`. -# -# It is in the matrix, BEHIND A FRESHNESS CHECK, and the check is the whole reason -# the row can be trusted. jolt's publish-nightly runs only after its `libraries` -# and `libraries-db` gates, and it publishes by staging a draft, DELETING the old -# release, then moving the tag. So a lagging downstream library withholds the NEW -# artifact while the PREVIOUS vnightly stays up and installs perfectly. -# -# That is not hypothetical. jolt's own first nightly run published nothing at all, -# because `library db`, `library db (postgres)` and `library transit-jolt` were -# failing on main with "No dependency provides Locale ... a library supplies one by -# declaring :jolt/provides (RFC 0014)", the same breaking change v0.8.1 announced. -# -# Without a check, a `nightly` row that goes green cannot distinguish "main is -# healthy" from "main broke four days ago and we keep testing Tuesday's binary", -# and a green row that cannot go red is worse than no row, because it reads as -# coverage. So: read the vnightly release's published_at, SKIP the row when the -# artifact is older than vars.NIGHTLY_MAX_AGE_HOURS (default 48), and stamp the -# age on every result either way. A skipped row says so; it never passes quietly. -# -# FRESH IS NOT ENOUGH, which the first version of this got wrong. jolt tags -# vnightly at whatever main was when the nightly job ran, and that is often the -# release tag itself. Measured 2026-09-02: vnightly and v0.8.1 both pointed at -# 9b768395, identical, three hours old and perfectly fresh, while main had -# already moved 7 commits past both. Recorded as tag-plus-SHA on purpose: that SHA sat on upstream's PRE-FORCE-PUSH line. jolt force-pushed main on -# 2026-09-03 and moved both 0.8.x tags to byte-identical commits, so it no -# longer resolves against upstream's history. Which is the argument for this -# check comparing tags at RUNTIME rather than trusting a recorded id: a SHA is -# a label that can be orphaned, and `git rev-parse` still answers cheerfully -# from a local object store when it has been. The row ran, went green, and reported the -# same commit the 0.8.1 row had just built as if it were a second answer. So the -# nightly's commit is compared against the release rows' too, and a match skips -# it as redundant rather than double-counting one build as two. -# -# The published_at also goes into the cache key. Without that, the change gate -# would see the literal string "nightly", find it unchanged from yesterday, and -# suppress every future nightly run after the first green. -# -# The latest row is a RELEASE, which has none of this problem: a release is -# immutable once published, so its row means what it says. -# -# TWO GATES, so a 15-minute tick is cheap: -# -# interval vars.CANARY_INTERVAL_HOURS (default 0, meaning no interval gate). -# The cron itself cannot be a variable, GitHub requires a literal, -# so the schedule ticks every 15 minutes and this can hold a tick -# back when set above 0. -# change a run is skipped when this exact version set has already been -# tested green. Keyed in the Actions cache, so no extra permissions -# and nothing to commit back to the repository. -# -# A gated tick still runs the `status` job, so the pin column and the dashboard's -# timestamp keep moving while jolt stands still. +# those two files. A gated tick still runs it, so the pin column and the +# dashboard's timestamp keep moving while jolt stands still. # +# vars.CANARY_INTERVAL_HOURS (default 0, no interval gate) holds a scheduled +# tick back. The cron itself cannot be a variable, GitHub requires a literal. +# vars.NIGHTLY_MAX_AGE_HOURS (default 48) is the nightly freshness limit. # A manual dispatch ignores both gates. That is the point of a manual dispatch. # --------------------------------------------------------------------------- @@ -95,6 +47,10 @@ permissions: issues: write actions: read +env: + # The tool jolt: runs the fleet tools. Pinned, and never the jolt under test. + TOOLS_JOLT_VERSION: ${{ vars.TOOLS_JOLT_VERSION || '0.8.27' }} + # One canary at a time. A run that outlives its 15-minute tick must not race # the next one on the status branch, and cancelling it would lose its results, # so later runs wait (GitHub keeps only the newest waiting one). @@ -115,6 +71,23 @@ jobs: latest: ${{ steps.decide.outputs.latest }} nightly_json: ${{ steps.decide.outputs.nightly_json }} steps: + - uses: actions/checkout@v7 + + - uses: jlt-commons/setup-jolt@v1 + with: + version: ${{ env.TOOLS_JOLT_VERSION }} + + - uses: actions/cache@v6.1.0 + with: + path: ~/.jolt/gitlibs + key: jolt-gitlibs-${{ hashFiles('deps.edn') }} + + # jolt.yaml loads libyaml, which the runner image carries today. Say so + # explicitly so an image change cannot break the tools silently. + - run: sudo apt-get install -y libyaml-0-2 + + # Latest is resolved on every event, a manual dispatch included, because + # the status page shows what latest is whatever was asked for. - name: Work out what to test, and whether to bother id: decide env: @@ -123,162 +96,7 @@ jobs: NIGHTLY_MAX_AGE_HOURS: ${{ vars.NIGHTLY_MAX_AGE_HOURS }} EVENT: ${{ github.event_name }} GH_TOKEN: ${{ github.token }} - run: | - set -euo pipefail - interval="${INTERVAL_HOURS:-0}" - - max_age="${NIGHTLY_MAX_AGE_HOURS:-48}" - nightly_pub="" - nightly="" - nightly_json=null - nightly_note="" - nsha="" - - # Resolved on every event, a manual dispatch included, because the - # status page shows what latest is whatever was asked for. - latest="$(curl -fsSL https://api.github.com/repos/jolt-lang/jolt/releases/latest \ - | sed -n 's/.*"tag_name": *"\([^"]*\)".*/\1/p' | head -1)" - latest="${latest#v}" - [ -n "$latest" ] || { echo "could not resolve jolt's latest release" >&2; exit 1; } - echo "latest=$latest" >> "$GITHUB_OUTPUT" - - if [ -n "$REQUESTED" ]; then - versions="[\"$REQUESTED\"]" - nightly="manual dispatch of $REQUESTED, freshness gate not applied" - echo "manual dispatch, testing $REQUESTED only" - # Asking for the nightly still records which build it was, so the - # status page can show it. Only the freshness and duplicate checks - # are skipped. - if [ "$REQUESTED" = "nightly" ]; then - pub="$(curl -fsSL https://api.github.com/repos/jolt-lang/jolt/releases/tags/vnightly \ - | sed -n 's/.*"published_at": *"\([^"]*\)".*/\1/p' | head -1)" - nsha="$(curl -fsSL https://api.github.com/repos/jolt-lang/jolt/git/refs/tags/vnightly \ - | sed -n 's/.*"sha": *"\([^"]*\)".*/\1/p' | head -1)" - [ -n "$pub" ] && [ -n "$nsha" ] || { echo "could not resolve vnightly" >&2; exit 1; } - nightly_json="$(jq -nc --arg p "$pub" --arg s "$nsha" --arg n "$nightly" \ - '{published_at: $p, sha: $s, note: $n}')" - fi - else - # The release row first, because the nightly block compares against - # it. - set -- "$latest" - - # The nightly is a PRERELEASE, so releases/latest never returns it and - # the two resolutions cannot collide. Read it by tag. - # - # A missing release is not an error here: jolt could stop publishing - # nightlies and the release rows would still be worth running. It is a - # skipped row with a stated reason, like a stale one. - pub="$(curl -fsSL https://api.github.com/repos/jolt-lang/jolt/releases/tags/vnightly \ - | sed -n 's/.*"published_at": *"\([^"]*\)".*/\1/p' | head -1)" - if [ -z "$pub" ]; then - nightly="nightly SKIPPED: no vnightly release found" - else - age=$(( ( $(date -u +%s) - $(date -u -d "$pub" +%s 2>/dev/null || echo 0) ) / 3600 )) - if [ "$age" -gt "$max_age" ]; then - nightly="nightly SKIPPED: published $pub, ${age}h old, limit ${max_age}h. jolt's publish-nightly is gated on its downstream library suites, so a lagging library withholds new builds while the old one stays installable" - else - # Fresh is necessary and NOT sufficient. jolt tags vnightly at - # whatever main was when the nightly job ran, and that is - # regularly the release tag itself: measured 2026-09-02, vnightly - # and v0.8.1 both pointed at 9b768395 (on upstream's line as it - # stood that day; main was force-pushed and both 0.8.x tags moved - # to byte-identical commits on 2026-09-03, which is exactly why - # this compares tags live instead of a recorded SHA), identical, - # while main had already moved 7 commits past it. A row built from the same - # commit as a release row is not a second data point, it is the - # same data point rendered twice, and it reads as coverage. - # - # Lightweight tags on this repo, so object.sha IS the commit and - # one sed suffices. Verified against a real parse of both refs. - nsha="$(curl -fsSL https://api.github.com/repos/jolt-lang/jolt/git/refs/tags/vnightly \ - | sed -n 's/.*"sha": *"\([^"]*\)".*/\1/p' | head -1)" - dupe="" - for v in "$@"; do - vsha="$(curl -fsSL "https://api.github.com/repos/jolt-lang/jolt/git/refs/tags/v$v" \ - | sed -n 's/.*"sha": *"\([^"]*\)".*/\1/p' | head -1)" - [ -n "$nsha" ] && [ "$vsha" = "$nsha" ] && dupe="$v" - done - if [ -n "$dupe" ]; then - nightly="nightly SKIPPED: vnightly is ${nsha:0:8}, the same commit as $dupe, so the row would rebuild what $dupe already covers" - else - nightly_pub="$pub" - nightly="nightly published $pub, ${age}h old, at ${nsha:0:8}" - # The note that reaches status.json must be the same on every - # tick for this nightly, or each tick would commit. No age: - # the page works it out from published_at. - nightly_note="nightly published $pub at ${nsha:0:8}" - fi - fi - fi - - if [ -n "$nightly_pub" ]; then - set -- "$@" "nightly" - nightly_json="$(jq -nc --arg p "$nightly_pub" --arg s "$nsha" --arg n "$nightly_note" \ - '{published_at: $p, sha: $s, note: $n}')" - fi - versions="[$(printf '"%s",' "$@" | sed 's/,$//')]" - echo "testing $versions" - fi - echo "versions=$versions" >> "$GITHUB_OUTPUT" - echo "nightly=$nightly" >> "$GITHUB_OUTPUT" - echo "nightly_json=$nightly_json" >> "$GITHUB_OUTPUT" - echo "$nightly" - - # The cache key IS the change detector. A new jolt release changes the - # version set, which changes the key, which misses the cache. - # - # The nightly needs the published_at folded in, because the literal - # string "nightly" is identical from one day to the next. Without it the - # first green would cache a key that every later run also computes, and - # the nightly row would never run again however far main moved. - key="canary-green-$(printf '%s' "$versions" | tr -d '[]" ' | tr ',' '-')" - [ -n "$nightly_pub" ] && key="$key-$(printf '%s' "$nightly_pub" | tr -cd '0-9')" - echo "key=$key" >> "$GITHUB_OUTPUT" - - if [ "$EVENT" != "schedule" ]; then - echo "proceed=true" >> "$GITHUB_OUTPUT" - echo "reason=manual run, gates skipped" >> "$GITHUB_OUTPUT" - exit 0 - fi - - # Interval 0 means no gate: every tick may run. - if [ "$interval" = "0" ]; then - echo "proceed=true" >> "$GITHUB_OUTPUT" - echo "reason=no interval gate" >> "$GITHUB_OUTPUT" - exit 0 - fi - - # Interval gate, measured from the last canary that actually BUILT - # something, not the last tick. - # - # A gated tick still finishes as a run whose conclusion is "success" - # (plan and status succeeded, the matrix skipped), so counting runs - # would reset the clock every tick and an interval above 1 would never - # come due. The tell is whether a run has any `jolt ` job: - # those exist only when the matrix actually ran. - last="" - for id in $(gh run list --repo "$GITHUB_REPOSITORY" --workflow canary.yml \ - --status completed --limit 12 --json databaseId \ - --jq '.[].databaseId' 2>/dev/null); do - if gh api "repos/$GITHUB_REPOSITORY/actions/runs/$id/jobs" \ - --jq '.jobs[].name' 2>/dev/null | grep -q '^jolt '; then - last="$(gh run view "$id" --repo "$GITHUB_REPOSITORY" \ - --json updatedAt --jq .updatedAt 2>/dev/null || true)" - break - fi - done - if [ -n "$last" ]; then - age=$(( ( $(date -u +%s) - $(date -u -d "$last" +%s 2>/dev/null || echo 0) ) / 3600 )) - if [ "$age" -lt "$interval" ]; then - echo "proceed=false" >> "$GITHUB_OUTPUT" - echo "reason=last run was ${age}h ago, interval is ${interval}h" >> "$GITHUB_OUTPUT" - exit 0 - fi - fi - - echo "proceed=true" >> "$GITHUB_OUTPUT" - echo "reason=due" >> "$GITHUB_OUTPUT" + run: jolt fleet:plan # Change gate. A hit means this exact version set already passed, so # nothing about jolt has moved and there is nothing to learn. @@ -301,18 +119,7 @@ jobs: ALREADY_GREEN: ${{ steps.seen.outputs.cache-hit }} REASON: ${{ steps.decide.outputs.reason }} KEY: ${{ steps.decide.outputs.key }} - run: | - set -euo pipefail - if [ "$INTERVAL_OK" != "true" ]; then - echo "proceed=false" >> "$GITHUB_OUTPUT" - echo "SKIPPING: $REASON" - elif [ "$ALREADY_GREEN" = "true" ]; then - echo "proceed=false" >> "$GITHUB_OUTPUT" - echo "SKIPPING: $KEY already passed, so jolt has not moved" - else - echo "proceed=true" >> "$GITHUB_OUTPUT" - echo "RUNNING: $REASON" - fi + run: jolt fleet:plan --final fleet: name: jolt ${{ matrix.version }} @@ -360,6 +167,7 @@ jobs: # branch. Runs on gated ticks too (no results files then), so the pin column # and the timestamp keep moving. contents: write is granted here and nowhere # else; the App token is only for the collectors' cross-repo reads. + status: needs: [plan, fleet] if: always() && needs.plan.result == 'success' @@ -370,6 +178,19 @@ jobs: steps: - uses: actions/checkout@v7 + - uses: jlt-commons/setup-jolt@v1 + with: + version: ${{ env.TOOLS_JOLT_VERSION }} + + - uses: actions/cache@v6.1.0 + with: + path: ~/.jolt/gitlibs + key: jolt-gitlibs-${{ hashFiles('deps.edn') }} + + # jolt.yaml loads libyaml, which the runner image carries today. Say so + # explicitly so an image change cannot break the tools silently. + - run: sudo apt-get install -y libyaml-0-2 + - name: Mint an installation token id: token uses: actions/create-github-app-token@v3 @@ -395,24 +216,35 @@ jobs: CANARY_RUN: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} run: | set -euo pipefail - # REBUILD is a command string for publish-status.sh to run with sh -c, - # so the quotes are meant literally. - # shellcheck disable=SC2089,SC2090 - REBUILD='bash scripts/refresh-status.sh "$OUT_DIR"' + # fleet:publish refreshes in-process on every attempt (R27), so the + # results files are plain arguments. A gated tick has none. if [ -d results ]; then - while IFS= read -r f; do REBUILD="$REBUILD '$PWD/$f'"; done \ - < <(find results -name results.json | sort) + mapfile -t files < <(find results -name results.json | sort) + else + files=() fi - # shellcheck disable=SC2090 - export REBUILD - echo "REBUILD: $REBUILD" - bash scripts/publish-status.sh "$RUNNER_TEMP/status-out" + jolt fleet:publish "$RUNNER_TEMP/status-out" "${files[@]}" report: needs: [plan, fleet] if: always() && needs.plan.outputs.proceed == 'true' runs-on: ubuntu-latest steps: + - uses: actions/checkout@v7 + + - uses: jlt-commons/setup-jolt@v1 + with: + version: ${{ env.TOOLS_JOLT_VERSION }} + + - uses: actions/cache@v6.1.0 + with: + path: ~/.jolt/gitlibs + key: jolt-gitlibs-${{ hashFiles('deps.edn') }} + + # jolt.yaml loads libyaml, which the runner image carries today. Say so + # explicitly so an image change cannot break the tools silently. + - run: sudo apt-get install -y libyaml-0-2 + - name: Mint an installation token id: token uses: actions/create-github-app-token@v3 @@ -430,6 +262,8 @@ jobs: pattern: results-* path: results + # Opens, comments on or closes the single "canary: jolt breaks the + # fleet" issue. The rules are in src/fleet/canary.clj. - name: Open, update or close the canary issue env: GH_TOKEN: ${{ steps.token.outputs.token }} @@ -437,94 +271,7 @@ jobs: VERSIONS: ${{ needs.plan.outputs.versions }} NIGHTLY: ${{ needs.plan.outputs.nightly }} RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} - DASHBOARD: https://jlt-commons.github.io/fleet/ - run: | - set -euo pipefail - TITLE="canary: jolt breaks the fleet" - existing=$(gh issue list --repo "$GITHUB_REPOSITORY" --state open \ - --search "$TITLE in:title" --limit 1 \ - --json number --jq '.[0].number // ""') - - # Verdict from the merged results: "name (version)" per bad cell. - # fail, mismatch, timed-out and dispatch-failed are findings about - # jolt or the build; infra (jolt not installable, or a dependency - # not downloadable) is not a finding about jolt and is reported - # separately. - files=() - if [ -d results ]; then - while IFS= read -r f; do files+=("$f"); done < <(find results -name results.json | sort) - fi - FAILED="" INFRA="" - if [ "${#files[@]}" -gt 0 ]; then - FAILED=$(jq -rs '[.[] | .requested as $v | .projects[] - | select(.result | IN("fail","mismatch","timed-out","dispatch-failed")) - | "\(.name) (\($v))"] | unique | join(", ")' "${files[@]}") - INFRA=$(jq -rs '[.[] | .requested as $v | .projects[] - | select(.result == "infra") - | "\(.name) (\($v)\(if .failed_step then ", failed step: " + .failed_step else "" end))"] | unique | join(", ")' "${files[@]}") - fi - - # The fleet job failed but no project says why (a leg crashed before - # uploading results): still a failure, never a quiet green. - unclassified="" - if [ -z "$FAILED" ] && [ -z "$INFRA" ] && [ "$RESULT" != "success" ]; then - unclassified=1 - fi - - if [ -z "$FAILED" ] && [ -z "$INFRA" ] && [ -z "$unclassified" ]; then - if [ -n "$existing" ]; then - gh issue comment "$existing" --repo "$GITHUB_REPOSITORY" \ - --body "Recovered. The fleet builds against ${VERSIONS}. ${NIGHTLY}. [Run](${RUN_URL}) Dashboard: ${DASHBOARD}" - gh issue close "$existing" --repo "$GITHUB_REPOSITORY" - echo "closed #$existing" - else - echo "green against ${VERSIONS}, nothing to report" - fi - exit 0 - fi - - # Which matrix legs failed. The job names carry the version, so the - # issue can name it rather than making a reader open the run. - broke=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID/jobs" \ - --jq '[.jobs[] | select(.conclusion=="failure") | .name] | join(", ")' 2>/dev/null || echo "") - - # A failure that is really our own misconfiguration should not be - # filed as a fact about jolt. fanout reports those separately. - if [ -n "$INFRA" ] && [ -z "$FAILED" ]; then - body=$(printf '%s\n' \ - "Infra problems, not findings about jolt: ${INFRA}" \ - "" \ - "A project either could not install jolt (check its \`JOLT_REPO\`," \ - "which should be unset unless deliberately aimed at a fork, since the" \ - "version may not exist in the repository it installs from) or could" \ - "not download a dependency (a package registry problem, often Maven" \ - "Central rate limiting while several projects build at once). The" \ - "failed step in parentheses above shows which." \ - "" \ - "**Versions tested:** ${VERSIONS}" \ - "" \ - "[Run](${RUN_URL}) has the per-project table. Dashboard: ${DASHBOARD}") - else - body=$(printf '%s\n' \ - "The fleet does not build against every jolt version it is meant to." \ - "" \ - "**Versions tested:** ${VERSIONS}" \ - "**Failing:** ${FAILED:-${broke:-see the run}}" \ - "**Nightly:** ${NIGHTLY:-not resolved}" \ - "" \ - "[Run](${RUN_URL}) has a per-project table for each version." \ - "Dashboard: ${DASHBOARD}" \ - "" \ - "This issue closes itself once a later canary passes. Reproduce one" \ - "project by dispatching its own ci.yml with the \`jolt-version\` input.") - fi - - if [ -n "$existing" ]; then - gh issue comment "$existing" --repo "$GITHUB_REPOSITORY" --body "$body" - echo "commented on #$existing" - else - gh issue create --repo "$GITHUB_REPOSITORY" --title "$TITLE" --body "$body" - fi + run: jolt fleet:report results remember: # Only a green run is worth remembering. Saving on failure would mark a diff --git a/deps.edn b/deps.edn index 1496edd..5531d85 100644 --- a/deps.edn +++ b/deps.edn @@ -12,6 +12,7 @@ :tasks {test {:doc "Run every fleet.*-test namespace; exit 1 on any failure or error" :requires ([clojure.test :as t] + [fleet.canary-test] [fleet.cli-test] [fleet.collect-test] [fleet.fanout-test] @@ -20,7 +21,8 @@ [fleet.refresh-test] [fleet.status-test] [fleet.version-test]) - :task (let [{:keys [fail error]} (t/run-tests 'fleet.cli-test + :task (let [{:keys [fail error]} (t/run-tests 'fleet.canary-test + 'fleet.cli-test 'fleet.collect-test 'fleet.fanout-test 'fleet.github-test @@ -30,6 +32,14 @@ 'fleet.version-test)] (when (pos? (+ fail error)) (System/exit 1)))} + fleet:plan {:doc "Canary plan job: decide what to test (env: REQUESTED EVENT INTERVAL_HOURS NIGHTLY_MAX_AGE_HOURS GITHUB_REPOSITORY GH_TOKEN GITHUB_OUTPUT); --final combines the gates (env: INTERVAL_OK ALREADY_GREEN REASON KEY)" + :requires ([fleet.cli :as cli]) + :task (System/exit (cli/plan-main *command-line-args*))} + + fleet:report {:doc "Canary report job: open, update or close the canary issue from results/*/results.json [dir] (env: RESULT VERSIONS NIGHTLY RUN_URL GITHUB_REPOSITORY GITHUB_RUN_ID GH_TOKEN)" + :requires ([fleet.cli :as cli]) + :task (System/exit (cli/report-main *command-line-args*))} + fleet:fanout {:doc "Dispatch every fleet project against a jolt version and wait: [version] (blank = latest release; env: GH_TOKEN, FLEET_JSON)" :requires ([fleet.cli :as cli]) :task (System/exit (cli/fanout-main *command-line-args*))} diff --git a/src/fleet/canary.clj b/src/fleet/canary.clj new file mode 100644 index 0000000..cae10aa --- /dev/null +++ b/src/fleet/canary.clj @@ -0,0 +1,377 @@ +(ns fleet.canary + "The canary workflow's decisions: which jolt versions to test and whether + to bother (the plan job), and whether the fleet is broken and what to tell + the single \"canary: jolt breaks the fleet\" issue (the report job). + + The decisions are pure functions of data. The GitHub reads and writes sit + in gather, last-built-at and report!, which take a fleet.github client. + + Two versions matter: latest, jolt's newest release, and nightly, jolt's + rolling vnightly prerelease. A release is immutable once published, so its + row means what it says. The nightly needs two checks before its row can be + trusted. + + FRESH. jolt's publish-nightly runs only after its downstream library gates, + and it publishes by staging a draft, deleting the old release, then moving + the tag. So a lagging library withholds the NEW artifact while the PREVIOUS + vnightly stays up and installs perfectly. Without a freshness check a + nightly row that goes green cannot tell \"main is healthy\" from \"main + broke four days ago and we keep testing Tuesday's binary\", and a green row + that cannot go red reads as coverage. So the row is skipped when the + artifact is older than the limit (48 hours by default), and a skipped row + says so instead of passing quietly. + + NOT A DUPLICATE. Fresh is necessary and not sufficient. jolt tags vnightly + at whatever main was when the nightly job ran, and that is regularly the + release tag itself (measured 2026-09-02: vnightly and v0.8.1 both pointed + at one commit, three hours old, while main had moved 7 commits past it). + A row built from the same commit as a release row is the same data point + rendered twice. The commits are compared live, by tag, because a recorded + SHA is a label that can be orphaned: jolt force-pushed main on 2026-09-03 + and moved both 0.8.x tags, and `git rev-parse` still answers cheerfully + from a local object store for a commit upstream no longer has. + + TWO GATES keep a 15-minute tick cheap. The interval gate holds a scheduled + tick back until that many hours have passed since a canary last BUILT + something (interval 0 means no gate, and then no lookup is made). The + change gate skips a run when this exact version set already passed. It is + an actions/cache lookup in the workflow, because a task cannot do one, so + plan works out the key and the interval decision, the cache step runs, and + final-decision combines them. A manual dispatch ignores both gates." + (:require [cheshire.core :as json] + [clojure.string :as str])) + +(def title "canary: jolt breaks the fleet") + +(def dashboard "https://jlt-commons.github.io/fleet/") + +(def ^:private jolt-repo "repos/jolt-lang/jolt") + +;; --------------------------------------------------------------------------- +;; Pure: plan + +(defn- epoch-ms [iso] + (try (.toEpochMilli (java.time.Instant/parse iso)) (catch Exception _ nil))) + +(defn- hours-between + "Whole hours from one ISO instant to another, or nil when either does not + parse." + [from to] + (let [a (epoch-ms from) b (epoch-ms to)] + (when (and a b) (quot (- b a) 3600000)))) + +(defn parse-hours + "A whole number of hours from an env value; blank or nil is dflt. Throws + naming the variable when it is not a number." + [text dflt var-name] + (if (str/blank? text) + dflt + (or (parse-long (str/trim text)) + (throw (ex-info (str var-name " is not a whole number of hours: " text) {}))))) + +(defn- short-sha [sha] (subs sha 0 (min 8 (count sha)))) + +(defn- nightly-row + "Decide the automatic nightly row against the release rows already chosen. + Returns {:nightly text :json map-or-nil}. The json note carries no age, so + it is the same on every tick for one nightly and the status build sees no + change between ticks." + [{:keys [nightly-release release-shas versions max-age-hours now]}] + (let [pub (:published-at nightly-release) + sha (or (:sha nightly-release) "")] + (if (str/blank? pub) + {:nightly "nightly SKIPPED: no vnightly release found"} + (let [age (or (hours-between pub now) 0)] + (if (> age max-age-hours) + {:nightly (str "nightly SKIPPED: published " pub ", " age "h old, limit " max-age-hours + "h. jolt's publish-nightly is gated on its downstream library suites, " + "so a lagging library withholds new builds while the old one stays installable")} + (if-let [dupe (when-not (str/blank? sha) + (some #(when (= sha (get release-shas %)) %) versions))] + {:nightly (str "nightly SKIPPED: vnightly is " (short-sha sha) ", the same commit as " + dupe ", so the row would rebuild what " dupe " already covers")} + {:nightly (str "nightly published " pub ", " age "h old, at " (short-sha sha)) + :json {:published_at pub :sha sha + :note (str "nightly published " pub " at " (short-sha sha))}})))))) + +(defn- interval-decision + [{:keys [event interval-hours last-built-at now]}] + (cond + (not= "schedule" event) {:proceed true :reason "manual run, gates skipped"} + (zero? interval-hours) {:proceed true :reason "no interval gate"} + :else + (let [age (when last-built-at (hours-between last-built-at now))] + (if (and age (< age interval-hours)) + {:proceed false :reason (str "last run was " age "h ago, interval is " interval-hours "h")} + {:proceed true :reason "due"})))) + +(defn- versions-key + "The change-gate cache key. A new release changes the version set. The + nightly needs its published_at folded in, because the literal string + \"nightly\" is identical from one day to the next: without it the first + green would cache a key that every later run also computes, and the nightly + row would never run again however far main moved." + [versions nightly-pub] + (str "canary-green-" + (str/join "-" (map #(str/replace % #"[\[\]\" ,]" "") versions)) + (when nightly-pub (str "-" (str/replace nightly-pub #"[^0-9]" ""))))) + +(defn plan + "What to test and whether to bother. + + Takes :requested (the manual input, blank for automatic), :event, + :latest-release (version without v), :nightly-release ({:published-at :sha} + or nil), :release-shas (version -> tag commit), :interval-hours, + :max-age-hours, :last-built-at (ISO or nil) and :now (ISO). + + Returns :versions (vector), :proceed (the interval decision, the change gate + is final-decision's job), :reason, :key, :nightly (text for the report), + :nightly-json (the object status.json records, or nil) and :latest. + + A manual nightly still records which build it was (R23), skipping only the + freshness and duplicate checks, so the status page can show it." + [{:keys [requested latest-release nightly-release] :as in}] + (when (str/blank? latest-release) + (throw (ex-info "could not resolve jolt's latest release" {}))) + (let [{:keys [versions nightly nightly-json nightly-pub]} + (if-not (str/blank? requested) + (let [note (str "manual dispatch of " requested ", freshness gate not applied") + nj (when (= "nightly" requested) + (when (or (str/blank? (:published-at nightly-release)) + (str/blank? (:sha nightly-release))) + (throw (ex-info "could not resolve vnightly" {}))) + {:published_at (:published-at nightly-release) + :sha (:sha nightly-release) + :note note})] + {:versions [requested] :nightly note :nightly-json nj}) + (let [row (nightly-row (assoc in :versions [latest-release]))] + {:versions (cond-> [latest-release] (:json row) (conj "nightly")) + :nightly (:nightly row) + :nightly-json (:json row) + :nightly-pub (when (:json row) (:published_at (:json row)))}))] + (merge {:versions versions :nightly nightly :nightly-json nightly-json + :latest latest-release :key (versions-key versions nightly-pub)} + (interval-decision in)))) + +(defn needs-last-built-at? + "True when plan will read last-built-at: only a scheduled tick under an + interval gate." + [{:keys [event interval-hours]}] + (and (= "schedule" event) (pos? interval-hours))) + +(defn final-decision + "Combine the interval decision (interval-ok, the string \"true\" or not) + with the change gate (already-green, the cache step's cache-hit output, + blank when the step did not run). {:proceed bool :log line}." + [{:keys [interval-ok already-green reason key]}] + (cond + (not= "true" interval-ok) {:proceed false :log (str "SKIPPING: " reason)} + (= "true" already-green) {:proceed false :log (str "SKIPPING: " key " already passed, so jolt has not moved")} + :else {:proceed true :log (str "RUNNING: " reason)})) + +(defn outputs-text + "plan's result as the lines the job writes to $GITHUB_OUTPUT. The keys are + the ones the plan job exposes: versions, proceed, reason, key, nightly, + nightly_json, latest." + [{:keys [versions proceed reason key nightly nightly-json latest]}] + (str "latest=" latest "\n" + "versions=" (json/generate-string versions) "\n" + "nightly=" nightly "\n" + "nightly_json=" (if nightly-json (json/generate-string nightly-json) "null") "\n" + "key=" key "\n" + "proceed=" proceed "\n" + "reason=" reason "\n")) + +;; --------------------------------------------------------------------------- +;; Edges: GitHub reads for plan + +(defn- missing? [e] (= 404 (:status (ex-data e)))) + +(defn- warn [& xs] (binding [*out* *err*] (println (str/join " " xs)))) + +(defn gather + "The GitHub facts plan needs, read through the client. Latest is resolved + on every event, a manual dispatch included, because the status page shows + what latest is whatever was asked for (R14). The nightly is read for an + automatic run and for a manual nightly. A missing vnightly release is not an + error, since jolt could stop publishing nightlies and the release rows would + still be worth running: it comes back as nil and plan skips the row." + [gh requested] + (let [get-json (:get-json gh) + tag (:tag_name (get-json (str jolt-repo "/releases/latest"))) + latest (some-> tag (str/replace-first #"^v" "")) + _ (when (str/blank? latest) + (throw (ex-info "could not resolve jolt's latest release" {}))) + nightly? (or (str/blank? requested) (= "nightly" requested)) + auto? (str/blank? requested) + nightly (when nightly? + (let [pub (try (:published_at (get-json (str jolt-repo "/releases/tags/vnightly"))) + (catch Exception e (when-not (missing? e) (throw e)))) + sha (when pub + (try (get-in (get-json (str jolt-repo "/git/refs/tags/vnightly")) [:object :sha]) + (catch Exception e (when-not (missing? e) (throw e)))))] + (when pub {:published-at pub :sha sha})))] + (cond-> {:latest-release latest} + nightly? (assoc :nightly-release nightly) + auto? (assoc :release-shas + (if (:sha nightly) + {latest (get-in (get-json (str jolt-repo "/git/refs/tags/v" latest)) [:object :sha])} + {}))))) + +(defn last-built-at + "When a canary last BUILT something, or nil. A gated tick still finishes as + a run whose conclusion is success (plan and status succeeded, the matrix + skipped), so counting runs would reset the clock every tick and an interval + above 1 would never come due. The tell is a `jolt ` job, which + exists only when the matrix ran. Looks at the 12 newest completed runs. A + failed lookup is skipped with a warning and, if nothing is found, reads as + due: the safe direction is to run." + [gh repo] + (let [runs (try (:workflow_runs ((:get-json gh) (str "repos/" repo "/actions/workflows/canary.yml/runs?status=completed&per_page=12"))) + (catch Exception e (warn "canary run list failed:" (ex-message e)) nil))] + (some (fn [{:keys [id updated_at]}] + (let [jobs (try (:jobs ((:get-json gh) (str "repos/" repo "/actions/runs/" id "/jobs?per_page=100"))) + (catch Exception e (warn "job list failed for run" id (ex-message e)) nil))] + (when (some #(str/starts-with? (str (:name %)) "jolt ") jobs) + updated_at))) + runs))) + +;; --------------------------------------------------------------------------- +;; Pure: the report + +(def ^:private finding? #{"fail" "mismatch" "timed-out" "dispatch-failed"}) + +(defn- cells + "Sorted, distinct \"name (version)\" strings for projects whose result + satisfies pred. label decorates the version part." + [results pred label] + (->> (for [r results, p (:projects r) :when (pred (:result p))] + (str (:name p) " (" (label (:requested r) p) ")")) + distinct sort vec)) + +(defn verdict + "{:failed [...] :infra [...]} from the merged results. fail, mismatch, + timed-out and dispatch-failed are findings about jolt or the build. infra + (jolt not installable, or a dependency not downloadable) is not a finding + about jolt, so it is reported separately, with each project's failed step." + [results] + {:failed (cells results finding? (fn [v _] v)) + :infra (cells results #{"infra"} + (fn [v p] (str v (when (:failed_step p) (str ", failed step: " (:failed_step p))))))}) + +(defn- lines [& ls] (str/join "\n" ls)) + +(defn issue-body + "What the report job should say, decided from the MERGED results of every + matrix leg (R16), because needs.fleet.outputs.failed holds one leg's value. + + Takes :results (parsed results.json maps), :fleet-result (the fleet job's + result), :versions and :nightly (the plan's texts), :run-url and + :failed-jobs (names of failed jobs, a fallback for the unclassified case). + + Returns :title, :broken? (open or update the issue when true, close it when + false), :infra? (the failures are all infra, R25) and :body. When not + broken the body is the recovery comment. + + The fleet job failing with no project saying why (a leg crashed before + uploading results) is still a failure and never a quiet green." + [{:keys [results fleet-result versions nightly run-url failed-jobs]}] + (let [{:keys [failed infra]} (verdict results) + unclassified? (and (empty? failed) (empty? infra) (not= "success" fleet-result)) + broken? (boolean (or (seq failed) (seq infra) unclassified?)) + infra? (and (seq infra) (empty? failed)) + failed-text (str/join ", " failed) + infra-text (str/join ", " infra)] + {:title title + :broken? broken? + :infra? (boolean infra?) + :body + (cond + (not broken?) + (str "Recovered. The fleet builds against " versions ". " nightly ". [Run](" run-url + ") Dashboard: " dashboard) + + ;; A failure that is really our own misconfiguration or a registry + ;; outage is not filed as a fact about jolt. + infra? + (lines (str "Infra problems, not findings about jolt: " infra-text) + "" + "A project either could not install jolt (check its `JOLT_REPO`," + "which should be unset unless deliberately aimed at a fork, since the" + "version may not exist in the repository it installs from) or could" + "not download a dependency (a package registry problem, often Maven" + "Central rate limiting while several projects build at once). The" + "failed step in parentheses above shows which." + "" + (str "**Versions tested:** " versions) + "" + (str "[Run](" run-url ") has the per-project table. Dashboard: " dashboard)) + + :else + (lines "The fleet does not build against every jolt version it is meant to." + "" + (str "**Versions tested:** " versions) + (str "**Failing:** " (cond (seq failed-text) failed-text + (seq failed-jobs) (str/join ", " failed-jobs) + :else "see the run")) + (str "**Nightly:** " (if (str/blank? nightly) "not resolved" nightly)) + "" + (str "[Run](" run-url ") has a per-project table for each version.") + (str "Dashboard: " dashboard) + "" + "This issue closes itself once a later canary passes. Reproduce one" + "project by dispatching its own ci.yml with the `jolt-version` input."))})) + +;; --------------------------------------------------------------------------- +;; Edge: the issue + +(defn- open-canary-issue + "The number of the open issue with exactly the canary title, or nil. The + issues endpoint lists pull requests too, which are skipped." + [gh repo] + (some (fn [i] (when (and (= title (:title i)) (not (:pull_request i))) (:number i))) + ((:get-paginated gh) (str "repos/" repo "/issues?state=open")))) + +(defn- failed-job-names + "Names of this run's failed jobs, or [] when the lookup fails: the names + only decorate the issue." + [gh repo run-id] + (try (->> ((:get-json gh) (str "repos/" repo "/actions/runs/" run-id "/jobs?per_page=100")) + :jobs (filter #(= "failure" (:conclusion %))) (mapv :name)) + (catch Exception e (warn "job lookup failed:" (ex-message e)) []))) + +(defn report! + "Open, update or close the single canary issue from the merged results. + Green closes an open issue after a recovery comment, and with none open + says nothing. Broken comments on an open issue or opens one. Returns + :nothing, :closed, :opened or :commented. + + opts: :gh (a fleet.github client map), :repo (owner/name), :results, + :fleet-result, :versions, :nightly, :run-url, :run-id." + [{:keys [gh repo results fleet-result versions nightly run-url run-id]}] + (let [existing (open-canary-issue gh repo) + verdict (verdict results) + needs-jobs? (and (empty? (:failed verdict)) (empty? (:infra verdict)) + (not= "success" fleet-result)) + {:keys [broken? body]} + (issue-body {:results results :fleet-result fleet-result :versions versions + :nightly nightly :run-url run-url + :failed-jobs (if needs-jobs? (failed-job-names gh repo run-id) [])}) + comment! #((:post-json gh) (str "repos/" repo "/issues/" existing "/comments") {:body body})] + (cond + (and (not broken?) existing) + (do (comment!) + ((:patch-json gh) (str "repos/" repo "/issues/" existing) {:state "closed"}) + (println (str "closed #" existing)) + :closed) + + (not broken?) + (do (println (str "green against " versions ", nothing to report")) :nothing) + + existing + (do (comment!) (println (str "commented on #" existing)) :commented) + + :else + (let [issue ((:post-json gh) (str "repos/" repo "/issues") {:title title :body body})] + (println (str "opened #" (:number issue))) + :opened)))) diff --git a/src/fleet/cli.clj b/src/fleet/cli.clj index ffcbe83..feb0850 100644 --- a/src/fleet/cli.clj +++ b/src/fleet/cli.clj @@ -3,8 +3,10 @@ arguments (and, where it reads the environment, an env map) and returns an exit code; the task wrapper in deps.edn passes it to System/exit. Failures print one line to stderr, exit 1, and write no files. Usage errors exit 2." - (:require [cheshire.core :as json] + (:require [babashka.fs :as fs] + [cheshire.core :as json] [clojure.string :as str] + [fleet.canary :as canary] [fleet.collect :as collect] [fleet.fanout :as fanout] [fleet.github :as github] @@ -184,3 +186,86 @@ :projects (:projects (load-fleet env)) :gh (gh-of deps) :env (fn [k] (get env k))})))))) + +(defn- append-output! + "Append text to the file GITHUB_OUTPUT names, or print it when unset." + [env text] + (if-let [path (not-empty (get env "GITHUB_OUTPUT"))] + (spit path text :append true) + (print text)) + (flush)) + +(defn- plan! + "The decide step: read GitHub, work out the plan, write the job outputs." + [env deps] + (let [gh (gh-of deps) + requested (or (get env "REQUESTED") "") + interval (canary/parse-hours (get env "INTERVAL_HOURS") 0 "CANARY_INTERVAL_HOURS") + max-age (canary/parse-hours (get env "NIGHTLY_MAX_AGE_HOURS") 48 "NIGHTLY_MAX_AGE_HOURS") + event (get env "EVENT") + repo (get env "GITHUB_REPOSITORY") + in (merge {:requested requested + :event event + :interval-hours interval + :max-age-hours max-age + :now (now-iso)} + (canary/gather gh requested)) + in (cond-> in + (canary/needs-last-built-at? in) (assoc :last-built-at (canary/last-built-at gh repo))) + result (canary/plan in)] + (println (if (str/blank? requested) + (str "testing " (json/generate-string (:versions result))) + (str "manual dispatch, testing " requested " only"))) + (println (:nightly result)) + (append-output! env (canary/outputs-text result)))) + +(defn- final! + "The final-decision step: both gates into the job's `proceed`." + [env] + (let [{:keys [proceed log]} (canary/final-decision {:interval-ok (get env "INTERVAL_OK") + :already-green (get env "ALREADY_GREEN") + :reason (get env "REASON") + :key (get env "KEY")})] + (append-output! env (str "proceed=" proceed "\n")) + (println log))) + +(defn plan-main + "fleet:plan: the canary plan job's decide step. With --final, the step + after the change-gate cache lookup. Env for the decide step: REQUESTED, + EVENT, INTERVAL_HOURS, NIGHTLY_MAX_AGE_HOURS, GITHUB_REPOSITORY, GH_TOKEN, + GITHUB_OUTPUT. Env for --final: INTERVAL_OK, ALREADY_GREEN, REASON, KEY." + ([args] (plan-main args (into {} (System/getenv)) {})) + ([args env deps] + (case (vec args) + [] (guarded "plan" #(plan! env deps)) + ["--final"] (guarded "plan" #(final! env)) + (usage-error "plan [--final]" nil)))) + +(defn- read-results + "Every results.json under dir, parsed. A missing dir is no results." + [dir] + (if (fs/exists? dir) + (mapv #(refresh/read-json-file (str %) false) + (sort (map str (fs/glob dir "**/results.json")))) + [])) + +(defn report-main + "fleet:report [results-dir]: open, update or close the canary issue from the + merged results.json files (default dir: results). Env: RESULT (the fleet + job's result), VERSIONS, NIGHTLY, RUN_URL, GITHUB_REPOSITORY, + GITHUB_RUN_ID, GH_TOKEN." + ([args] (report-main args (into {} (System/getenv)) {})) + ([args env deps] + (if (> (count args) 1) + (usage-error "report [results-dir]" nil) + (if-let [v (require-env env ["GITHUB_REPOSITORY" "VERSIONS" "RUN_URL"])] + (do (err (str "report: " v " is required")) (usage-error "report [results-dir]" nil)) + (guarded "report" + #(canary/report! {:gh (gh-of deps) + :repo (get env "GITHUB_REPOSITORY") + :results (read-results (or (first args) "results")) + :fleet-result (get env "RESULT") + :versions (get env "VERSIONS") + :nightly (get env "NIGHTLY") + :run-url (get env "RUN_URL") + :run-id (get env "GITHUB_RUN_ID")})))))) diff --git a/src/fleet/github.clj b/src/fleet/github.clj index 60d7269..d8340e0 100644 --- a/src/fleet/github.clj +++ b/src/fleet/github.clj @@ -52,19 +52,25 @@ (defn- default-request "No redirects: the client would replay the Authorization header to a - redirect target on any host." + redirect target on any host. A request carries :method (:post or :patch for + the writes, otherwise a GET) and, for the writes, a string :body." [req] - (http/get (:url req) (assoc (dissoc req :url) :follow-redirects false))) + (let [send (case (:method req) :post http/post :patch http/patch http/get)] + (send (:url req) (assoc (dissoc req :url :method) :follow-redirects false)))) (defn- request! - "One GET. Returns the response map, or throws ex-info on a non-2xx status." - [{:keys [token request]} path accept] + "One request, a GET unless method and body are given. Returns the response + map, or throws ex-info on a non-2xx status." + [{:keys [token request]} path accept & [method body]] (let [resp ((or request default-request) - {:url (url-for path) - :throw-exceptions false - :headers (cond-> {"Accept" accept - "X-GitHub-Api-Version" "2022-11-28"} - (seq token) (assoc "Authorization" (str "Bearer " token)))}) + (cond-> {:url (url-for path) + :throw-exceptions false + :headers (cond-> {"Accept" accept + "X-GitHub-Api-Version" "2022-11-28"} + (seq token) (assoc "Authorization" (str "Bearer " token)) + body (assoc "Content-Type" "application/json"))} + method (assoc :method method) + body (assoc :body body))) status (:status resp)] (if (and (integer? status) (<= 200 status 299)) resp @@ -108,9 +114,11 @@ (defn- parse [body] (json/parse-string body true)) (defn client - "A map of fns {:get-json :get-raw :get-paginated :get-redirected-log}, each - taking a path (\"repos/o/r\", \"/repos/o/r\" or a full URL). opts: :token, :request (a fn - from {:url :headers :throw-exceptions} to {:status :headers :body})." + "A map of fns {:get-json :get-raw :get-paginated :get-redirected-log + :post-json :patch-json}, each taking a path (\"repos/o/r\", \"/repos/o/r\" or a full URL). opts: :token, :request (a fn + from {:url :headers :throw-exceptions, plus :method and :body on writes} to + {:status :headers :body}). :post-json and :patch-json take a path and a map + to send as JSON, and return the parsed reply." [opts] {:get-json (fn [path] (parse (:body (request! opts path json-accept)))) :get-raw (fn [path] (:body (request! opts path "application/vnd.github.raw+json"))) @@ -122,7 +130,11 @@ (if-let [nxt (next-link (header (:headers resp) "link"))] (recur nxt acc) acc)))) - :get-redirected-log (fn [path] (redirected-log! opts path))}) + :get-redirected-log (fn [path] (redirected-log! opts path)) + :post-json (fn [path data] + (parse (:body (request! opts path json-accept :post (json/generate-string data))))) + :patch-json (fn [path data] + (parse (:body (request! opts path json-accept :patch (json/generate-string data)))))}) (defn env-client "A client with the token from GH_TOKEN (none when unset)." diff --git a/test/fleet/canary_test.clj b/test/fleet/canary_test.clj new file mode 100644 index 0000000..2d5aa25 --- /dev/null +++ b/test/fleet/canary_test.clj @@ -0,0 +1,388 @@ +(ns fleet.canary-test + (:require [cheshire.core :as json] + [clojure.string :as str] + [clojure.test :refer [deftest is testing]] + [fleet.canary :as canary])) + +;; --------------------------------------------------------------------------- +;; plan + +(def ^:private now "2026-11-20T12:00:00Z") + +(def ^:private fresh-nightly + {:published-at "2026-11-19T21:30:15Z" :sha "dd3c4a4b0000000000000000000000000000aaaa"}) + +(defn- plan [& {:as over}] + (canary/plan (merge {:requested "" :event "schedule" :latest-release "0.8.27" + :nightly-release nil :release-shas {"0.8.27" "9b768395ffff"} + :interval-hours 0 :max-age-hours 48 :last-built-at nil :now now} + over))) + +(deftest new-release-without-a-nightly-tests-latest-only + (let [p (plan)] + (is (= ["0.8.27"] (:versions p))) + (is (= "0.8.27" (:latest p))) + (is (= "nightly SKIPPED: no vnightly release found" (:nightly p))) + (is (nil? (:nightly-json p))) + (is (= "canary-green-0.8.27" (:key p))) + (is (true? (:proceed p))) + (is (= "no interval gate" (:reason p))))) + +(deftest fresh-nightly-joins-the-set-and-its-published-at-joins-the-key + (let [p (plan :nightly-release fresh-nightly)] + (is (= ["0.8.27" "nightly"] (:versions p))) + (is (= "canary-green-0.8.27-nightly-20261119213015" (:key p))) + (is (= "nightly published 2026-11-19T21:30:15Z, 14h old, at dd3c4a4b" (:nightly p))) + (testing "the note that reaches status.json has no age" + (is (= {:published_at "2026-11-19T21:30:15Z" + :sha (:sha fresh-nightly) + :note "nightly published 2026-11-19T21:30:15Z at dd3c4a4b"} + (:nightly-json p)))))) + +(deftest stable-nightly-note-does-not-change-from-tick-to-tick + (is (= (:nightly-json (plan :nightly-release fresh-nightly :now "2026-11-20T01:00:00Z")) + (:nightly-json (plan :nightly-release fresh-nightly :now "2026-11-20T20:59:00Z"))))) + +(deftest a-newer-nightly-changes-the-key + (is (not= (:key (plan :nightly-release fresh-nightly)) + (:key (plan :nightly-release (assoc fresh-nightly :published-at "2026-11-20T03:00:00Z")))))) + +(deftest stale-nightly-is-skipped-with-a-reason + (let [p (plan :nightly-release {:published-at "2026-11-17T00:00:00Z" :sha "aaaaaaaabbbb"})] + (is (= ["0.8.27"] (:versions p))) + (is (nil? (:nightly-json p))) + (is (= "canary-green-0.8.27" (:key p))) + (is (str/starts-with? (:nightly p) + "nightly SKIPPED: published 2026-11-17T00:00:00Z, 84h old, limit 48h. ")))) + +(deftest nightly-at-exactly-the-limit-still-runs + (is (= ["0.8.27" "nightly"] + (:versions (plan :nightly-release {:published-at "2026-11-18T12:00:00Z" :sha "aaaaaaaabbbb"}))))) + +(deftest nightly-on-the-release-commit-is-skipped-as-redundant + (let [p (plan :nightly-release {:published-at "2026-11-19T21:30:15Z" :sha "9b768395ffff"})] + (is (= ["0.8.27"] (:versions p))) + (is (nil? (:nightly-json p))) + (is (= (str "nightly SKIPPED: vnightly is 9b768395, the same commit as 0.8.27, " + "so the row would rebuild what 0.8.27 already covers") + (:nightly p))))) + +(deftest manual-version-tests-only-that-version-and-skips-the-gates + (let [p (plan :requested "0.8.20" :event "workflow_dispatch" :interval-hours 6 + :last-built-at "2026-11-20T11:00:00Z" :nightly-release fresh-nightly)] + (is (= ["0.8.20"] (:versions p))) + (is (= "manual dispatch of 0.8.20, freshness gate not applied" (:nightly p))) + (is (nil? (:nightly-json p))) + (is (= "0.8.27" (:latest p))) + (is (= "canary-green-0.8.20" (:key p))) + (is (true? (:proceed p))) + (is (= "manual run, gates skipped" (:reason p))))) + +(deftest manual-nightly-resolves-the-build-and-skips-freshness + (let [stale {:published-at "2026-11-10T00:00:00Z" :sha "9b768395ffff"} + p (plan :requested "nightly" :event "workflow_dispatch" :nightly-release stale)] + (is (= ["nightly"] (:versions p))) + (is (= {:published_at "2026-11-10T00:00:00Z" :sha "9b768395ffff" + :note "manual dispatch of nightly, freshness gate not applied"} + (:nightly-json p))) + (is (= "canary-green-nightly" (:key p))))) + +(deftest manual-nightly-that-cannot-be-resolved-throws + (doseq [nr [nil {:published-at "2026-11-10T00:00:00Z"} {:sha "abc"}]] + (is (= "could not resolve vnightly" + (ex-message (try (plan :requested "nightly" :event "workflow_dispatch" :nightly-release nr) + nil (catch Exception e e))))))) + +(deftest missing-latest-release-throws + (is (= "could not resolve jolt's latest release" + (ex-message (try (plan :latest-release "") nil (catch Exception e e)))))) + +(deftest interval-gate-holds-a-scheduled-tick-back + (let [p (plan :interval-hours 6 :last-built-at "2026-11-20T09:30:00Z" :nightly-release fresh-nightly)] + (is (false? (:proceed p))) + (is (= "last run was 2h ago, interval is 6h" (:reason p))) + (testing "the version set and key are still worked out for the status job" + (is (= ["0.8.27" "nightly"] (:versions p))) + (is (= "0.8.27" (:latest p))) + (is (some? (:nightly-json p)))))) + +(deftest interval-gate-opens-when-due + (is (= "due" (:reason (plan :interval-hours 6 :last-built-at "2026-11-20T05:59:00Z")))) + (is (true? (:proceed (plan :interval-hours 6 :last-built-at "2026-11-20T05:59:00Z"))))) + +(deftest interval-gate-with-no-earlier-build-is-due + (let [p (plan :interval-hours 6 :last-built-at nil)] + (is (true? (:proceed p))) + (is (= "due" (:reason p))))) + +(deftest interval-zero-never-needs-a-lookup + (is (= "no interval gate" (:reason (plan :interval-hours 0 :last-built-at "2026-11-20T11:59:00Z"))))) + +(deftest interval-only-applies-to-schedule + (is (= "manual run, gates skipped" + (:reason (plan :event "workflow_dispatch" :interval-hours 6 :last-built-at "2026-11-20T11:59:00Z"))))) + +(deftest needs-last-built-at-only-for-a-scheduled-tick-with-an-interval + (is (true? (canary/needs-last-built-at? {:event "schedule" :interval-hours 6}))) + (is (false? (canary/needs-last-built-at? {:event "schedule" :interval-hours 0}))) + (is (false? (canary/needs-last-built-at? {:event "workflow_dispatch" :interval-hours 6})))) + +(deftest parse-hours-reads-blank-as-the-default-and-rejects-junk + (is (= 48 (canary/parse-hours nil 48 "X"))) + (is (= 48 (canary/parse-hours "" 48 "X"))) + (is (= 6 (canary/parse-hours "6" 48 "X"))) + (is (= "X is not a whole number of hours: soon" + (ex-message (try (canary/parse-hours "soon" 48 "X") nil (catch Exception e e)))))) + +;; --------------------------------------------------------------------------- +;; the change gate + +(deftest final-decision-combines-both-gates + (testing "interval says no" + (is (= {:proceed false :log "SKIPPING: last run was 2h ago, interval is 6h"} + (canary/final-decision {:interval-ok "false" :already-green "" :reason "last run was 2h ago, interval is 6h" :key "k"})))) + (testing "cache hit" + (is (= {:proceed false :log "SKIPPING: canary-green-0.8.27 already passed, so jolt has not moved"} + (canary/final-decision {:interval-ok "true" :already-green "true" :reason "due" :key "canary-green-0.8.27"})))) + (testing "cache miss" + (is (= {:proceed true :log "RUNNING: due"} + (canary/final-decision {:interval-ok "true" :already-green "false" :reason "due" :key "k"})))) + (testing "no cache step ran (manual run)" + (is (= {:proceed true :log "RUNNING: manual run, gates skipped"} + (canary/final-decision {:interval-ok "true" :already-green "" :reason "manual run, gates skipped" :key "k"}))))) + +;; --------------------------------------------------------------------------- +;; last-built-at + +(defn- stub-gh + "A client whose :get-json answers from a map of path -> value or Exception." + [answers seen] + {:get-json (fn [path] + (swap! seen conj path) + (let [a (get answers path ::none)] + (cond (= ::none a) (throw (ex-info "nope" {:status 404 :path path})) + (instance? Exception a) (throw a) + :else a)))}) + +(def ^:private runs-path + "repos/o/ci/actions/workflows/canary.yml/runs?status=completed&per_page=12") + +(deftest last-built-at-skips-gated-ticks-and-takes-the-first-run-with-a-jolt-job + (let [seen (atom []) + gh (stub-gh {runs-path {:workflow_runs [{:id 3 :updated_at "2026-11-20T11:00:00Z"} + {:id 2 :updated_at "2026-11-20T08:00:00Z"} + {:id 1 :updated_at "2026-11-20T05:00:00Z"}]} + "repos/o/ci/actions/runs/3/jobs?per_page=100" {:jobs [{:name "plan"} {:name "status"}]} + "repos/o/ci/actions/runs/2/jobs?per_page=100" {:jobs [{:name "plan"} {:name "jolt 0.8.27 / fan-out"}]} + "repos/o/ci/actions/runs/1/jobs?per_page=100" {:jobs [{:name "jolt 0.8.26"}]}} + seen)] + (is (= "2026-11-20T08:00:00Z" (canary/last-built-at gh "o/ci"))) + (is (= [runs-path "repos/o/ci/actions/runs/3/jobs?per_page=100" "repos/o/ci/actions/runs/2/jobs?per_page=100"] + @seen)))) + +(deftest last-built-at-is-nil-when-no-run-built-anything + (let [gh (stub-gh {runs-path {:workflow_runs [{:id 3 :updated_at "x"}]} + "repos/o/ci/actions/runs/3/jobs?per_page=100" {:jobs [{:name "plan"}]}} + (atom []))] + (is (nil? (canary/last-built-at gh "o/ci"))))) + +(deftest last-built-at-ignores-a-job-lookup-that-fails + (let [gh (stub-gh {runs-path {:workflow_runs [{:id 3 :updated_at "A"} {:id 2 :updated_at "B"}]} + "repos/o/ci/actions/runs/3/jobs?per_page=100" (ex-info "502" {:status 502}) + "repos/o/ci/actions/runs/2/jobs?per_page=100" {:jobs [{:name "jolt 1"}]}} + (atom []))] + (is (= "B" (canary/last-built-at gh "o/ci"))))) + +(deftest last-built-at-is-nil-when-the-run-list-fails + (is (nil? (canary/last-built-at (stub-gh {runs-path (ex-info "403" {:status 403})} (atom [])) "o/ci")))) + +;; --------------------------------------------------------------------------- +;; gather + +(deftest gather-reads-latest-always-and-the-nightly-only-when-asked-for + (let [seen (atom []) + base {"repos/jolt-lang/jolt/releases/latest" {:tag_name "v0.8.27"} + "repos/jolt-lang/jolt/releases/tags/vnightly" {:published_at "2026-11-19T21:30:15Z"} + "repos/jolt-lang/jolt/git/refs/tags/vnightly" {:object {:sha "dd3c4a4b00"}} + "repos/jolt-lang/jolt/git/refs/tags/v0.8.27" {:object {:sha "9b768395ff"}}}] + (testing "automatic: everything" + (is (= {:latest-release "0.8.27" + :nightly-release {:published-at "2026-11-19T21:30:15Z" :sha "dd3c4a4b00"} + :release-shas {"0.8.27" "9b768395ff"}} + (canary/gather (stub-gh base seen) "")))) + (testing "manual version: only latest" + (reset! seen []) + (is (= {:latest-release "0.8.27"} (canary/gather (stub-gh base seen) "0.8.20"))) + (is (= ["repos/jolt-lang/jolt/releases/latest"] @seen))) + (testing "manual nightly: latest and the nightly, no release sha" + (is (= {:latest-release "0.8.27" + :nightly-release {:published-at "2026-11-19T21:30:15Z" :sha "dd3c4a4b00"}} + (canary/gather (stub-gh base (atom [])) "nightly")))) + (testing "no vnightly release at all is a skipped row, not an error" + (is (= {:latest-release "0.8.27" :nightly-release nil :release-shas {}} + (canary/gather (stub-gh (dissoc base "repos/jolt-lang/jolt/releases/tags/vnightly") (atom [])) "")))) + (testing "any other failure is an error" + (let [e (try (canary/gather (stub-gh (assoc base "repos/jolt-lang/jolt/releases/tags/vnightly" + (ex-info "boom" {:status 502})) (atom [])) "") + nil (catch Exception e e))] + (is (= 502 (:status (ex-data e)))))))) + +;; --------------------------------------------------------------------------- +;; issue-body + +(defn- res [requested & projects] + {:requested requested + :projects (mapv (fn [[n r step]] (cond-> {:name n :result r} step (assoc :failed_step step))) projects)}) + +(defn- ib [& {:as over}] + (canary/issue-body (merge {:results [(res "0.8.27" ["a" "pass"])] :fleet-result "success" + :versions "[\"0.8.27\"]" :nightly "nightly SKIPPED: stale" + :run-url "https://x/run/9" :failed-jobs []} + over))) + +(deftest all-green-is-recovered + (let [r (ib)] + (is (false? (:broken? r))) + (is (false? (:infra? r))) + (is (= "canary: jolt breaks the fleet" (:title r))) + (is (= (str "Recovered. The fleet builds against [\"0.8.27\"]. nightly SKIPPED: stale. " + "[Run](https://x/run/9) Dashboard: https://jlt-commons.github.io/fleet/") + (:body r))))) + +(deftest not-run-and-pass-do-not-break + (is (false? (:broken? (ib :results [(res "0.8.27" ["a" "pass"] ["b" "not-run"])]))))) + +(deftest a-failing-project-breaks-and-names-itself-and-its-version + (let [r (ib :results [(res "0.8.27" ["glitter" "fail"] ["ebb" "pass"]) + (res "nightly" ["glitter" "fail"] ["raylib-ios" "timed-out"])])] + (is (true? (:broken? r))) + (is (false? (:infra? r))) + (is (str/includes? (:body r) "**Failing:** glitter (0.8.27), glitter (nightly), raylib-ios (nightly)\n")) + (is (str/includes? (:body r) "**Versions tested:** [\"0.8.27\"]\n")) + (is (str/includes? (:body r) "**Nightly:** nightly SKIPPED: stale\n")) + (is (str/includes? (:body r) "[Run](https://x/run/9) has a per-project table for each version.\nDashboard: https://jlt-commons.github.io/fleet/\n")) + (is (str/ends-with? (:body r) "dispatching its own ci.yml with the `jolt-version` input.")))) + +(deftest mismatch-and-dispatch-failed-break-too + (doseq [bad ["mismatch" "dispatch-failed" "timed-out" "fail"]] + (testing bad + (let [r (ib :results [(res "nightly" ["glitter" bad])])] + (is (true? (:broken? r))) + (is (str/includes? (:body r) "**Failing:** glitter (nightly)")))))) + +(deftest infra-alone-uses-the-infra-wording-for-both-causes + (let [r (ib :results [(res "0.8.27" ["glitter" "infra" "Install jolt"] ["raygui-jlt" "infra" "Run clojure -M:test"] ["ebb" "infra"])])] + (is (true? (:broken? r))) + (is (true? (:infra? r))) + (is (str/starts-with? (:body r) (str "Infra problems, not findings about jolt: " + "ebb (0.8.27), glitter (0.8.27, failed step: Install jolt), " + "raygui-jlt (0.8.27, failed step: Run clojure -M:test)\n"))) + (is (str/includes? (:body r) "could not install jolt")) + (is (str/includes? (:body r) "could\nnot download a dependency")) + (is (str/includes? (:body r) "**Versions tested:** [\"0.8.27\"]")) + (is (str/ends-with? (:body r) "has the per-project table. Dashboard: https://jlt-commons.github.io/fleet/")))) + +(deftest infra-plus-a-real-failure-is-reported-as-a-failure + (let [r (ib :results [(res "0.8.27" ["glitter" "fail"] ["ebb" "infra" "Install jolt"])])] + (is (true? (:broken? r))) + (is (false? (:infra? r))) + (is (str/includes? (:body r) "**Failing:** glitter (0.8.27)")))) + +(deftest a-failed-fleet-with-no-results-is-still-broken + (testing "names the failed jobs when it can" + (let [r (ib :results [] :fleet-result "failure" :failed-jobs ["jolt 0.8.27 / fan-out" "x"])] + (is (true? (:broken? r))) + (is (str/includes? (:body r) "**Failing:** jolt 0.8.27 / fan-out, x")))) + (testing "otherwise points at the run" + (is (str/includes? (:body (ib :results [] :fleet-result "cancelled")) "**Failing:** see the run"))) + (testing "a green fleet job with no results is nothing to report" + (is (false? (:broken? (ib :results [] :fleet-result "success")))))) + +(deftest a-green-nightly-note-can-be-blank + (is (str/includes? (:body (ib :results [(res "0.8.27" ["a" "fail"])] :nightly "")) "**Nightly:** not resolved"))) + +;; --------------------------------------------------------------------------- +;; report! + +(defn- recording-gh + "A client over canned issue lists; records writes as [:post path data]." + [issues writes] + {:get-paginated (fn [path] + (is (= "repos/o/ci/issues?state=open" path)) + issues) + :get-json (fn [_] {:jobs []}) + :post-json (fn [path data] (swap! writes conj [:post path data]) {:number 99}) + :patch-json (fn [path data] (swap! writes conj [:patch path data]) {})}) + +(def ^:private open-issue {:number 5 :title "canary: jolt breaks the fleet" :state "open"}) + +(defn- report [issues results & {:as over}] + (let [writes (atom []) + out (canary/report! (merge {:gh (recording-gh issues writes) :repo "o/ci" :results results + :fleet-result "success" :versions "[\"0.8.27\"]" :nightly "n" + :run-url "https://x/run/9" :run-id "9"} + over))] + {:out out :writes @writes})) + +(deftest green-with-nothing-open-does-nothing + (let [{:keys [out writes]} (report [] [(res "0.8.27" ["a" "pass"])])] + (is (= [] writes)) + (is (= :nothing out)))) + +(deftest green-with-an-open-issue-comments-recovered-then-closes + (let [{:keys [out writes]} (report [open-issue] [(res "0.8.27" ["a" "pass"])])] + (is (= :closed out)) + (is (= [:post "repos/o/ci/issues/5/comments"] (take 2 (first writes)))) + (is (str/starts-with? (:body (nth (first writes) 2)) "Recovered.")) + (is (= [:patch "repos/o/ci/issues/5" {:state "closed"}] (second writes))))) + +(deftest broken-with-nothing-open-creates-the-issue + (let [{:keys [out writes]} (report [] [(res "0.8.27" ["a" "fail"])])] + (is (= :opened out)) + (is (= 1 (count writes))) + (is (= [:post "repos/o/ci/issues"] (take 2 (first writes)))) + (is (= "canary: jolt breaks the fleet" (:title (nth (first writes) 2)))))) + +(deftest broken-with-an-open-issue-comments-and-leaves-it-open + (let [{:keys [out writes]} (report [open-issue] [(res "0.8.27" ["a" "fail"])])] + (is (= :commented out)) + (is (= [:post "repos/o/ci/issues/5/comments"] (take 2 (first writes)))) + (is (= 1 (count writes))))) + +(deftest a-pull-request-or-another-title-is-not-the-canary-issue + (let [issues [{:number 1 :title "canary: jolt breaks the fleet" :pull_request {:url "x"}} + {:number 2 :title "something else"} + {:number 3 :title "canary: jolt breaks the fleet today"}] + {:keys [out]} (report issues [(res "0.8.27" ["a" "fail"])])] + (is (= :opened out)))) + +(deftest report-fetches-the-failed-jobs-only-when-it-has-to + (let [calls (atom []) + writes (atom []) + gh (assoc (recording-gh [] writes) + :get-json (fn [p] (swap! calls conj p) + {:jobs [{:name "jolt 0.8.27" :conclusion "failure"} + {:name "plan" :conclusion "success"}]}))] + (canary/report! {:gh gh :repo "o/ci" :results [(res "0.8.27" ["a" "fail"])] :fleet-result "failure" + :versions "v" :nightly "n" :run-url "u" :run-id "9"}) + (is (= [] @calls) "a results-based verdict needs no job lookup") + (canary/report! {:gh gh :repo "o/ci" :results [] :fleet-result "failure" + :versions "v" :nightly "n" :run-url "u" :run-id "9"}) + (is (= ["repos/o/ci/actions/runs/9/jobs?per_page=100"] @calls)) + (is (str/includes? (:body (nth (last @writes) 2)) "**Failing:** jolt 0.8.27\n")))) + +;; --------------------------------------------------------------------------- +;; outputs + +(deftest outputs-text-uses-the-keys-the-plan-job-exposes + (let [p (plan :nightly-release fresh-nightly) + txt (canary/outputs-text p) + kv (into {} (map #(str/split % #"=" 2)) (str/split-lines txt))] + (is (= #{"latest" "versions" "nightly" "nightly_json" "key" "proceed" "reason"} (set (keys kv)))) + (is (= "[\"0.8.27\",\"nightly\"]" (kv "versions"))) + (is (= "true" (kv "proceed"))) + (is (= (:nightly-json p) (json/parse-string (kv "nightly_json") true))) + (is (str/ends-with? txt "\n")))) + +(deftest outputs-text-writes-null-when-there-is-no-nightly + (is (= "null" (get (into {} (map #(str/split % #"=" 2)) (str/split-lines (canary/outputs-text (plan)))) "nightly_json")))) diff --git a/test/fleet/cli_test.clj b/test/fleet/cli_test.clj index bf3a575..47bfa76 100644 --- a/test/fleet/cli_test.clj +++ b/test/fleet/cli_test.clj @@ -159,3 +159,84 @@ "FLEET_JSON" (write! d "fleet.json" "{\"projects\":[],\"excluded\":{}}")} r (run #(cli/refresh-main [(str d "/out")] env {:gh gh}))] (is (= 0 (:rc r))))) + +;; Task 11: fleet:plan and fleet:report. + +(defn- canary-gh + "A client answering the jolt-lang reads, and recording issue writes." + [writes & {:keys [issues] :or {issues []}}] + (let [answers {"repos/jolt-lang/jolt/releases/latest" {:tag_name "v0.8.27"} + "repos/jolt-lang/jolt/releases/tags/vnightly" {:published_at "2026-11-19T21:30:15Z"} + "repos/jolt-lang/jolt/git/refs/tags/vnightly" {:object {:sha "dd3c4a4b00"}} + "repos/jolt-lang/jolt/git/refs/tags/v0.8.27" {:object {:sha "9b768395ff"}}}] + {:get-json (fn [p] (or (get answers p) (throw (ex-info "unexpected" {:path p})))) + :get-paginated (fn [_] issues) + :post-json (fn [p d] (swap! writes conj [:post p d]) {:number 1}) + :patch-json (fn [p d] (swap! writes conj [:patch p d]) {})})) + +(defn- kv [text] (into {} (map #(str/split % #"=" 2)) (str/split-lines text))) + +(deftest plan-writes-the-job-outputs-to-github-output + (let [d (tmp-dir) + out (str d "/out") + r (run #(cli/plan-main [] {"EVENT" "workflow_dispatch" "REQUESTED" "" "GITHUB_OUTPUT" out + "GITHUB_REPOSITORY" "o/ci"} + {:gh (canary-gh (atom []))})) + o (kv (slurp out))] + (is (= 0 (:rc r))) + (is (= "0.8.27" (o "latest"))) + (is (= "true" (o "proceed"))) + (is (= "manual run, gates skipped" (o "reason"))) + (is (= #{"latest" "versions" "nightly" "nightly_json" "key" "proceed" "reason"} (set (keys o)))) + (is (str/starts-with? (o "versions") "[\"0.8.27\"")))) + +(deftest plan-rejects-a-junk-interval-and-writes-nothing + (let [d (tmp-dir) + out (str d "/out") + r (run #(cli/plan-main [] {"EVENT" "schedule" "INTERVAL_HOURS" "soon" "GITHUB_OUTPUT" out} + {:gh (canary-gh (atom []))}))] + (is (= 1 (:rc r))) + (is (str/includes? (:err r) "CANARY_INTERVAL_HOURS is not a whole number")) + (is (not (fs/exists? out))))) + +(deftest plan-final-writes-proceed + (let [d (tmp-dir) + out (str d "/out") + r (run #(cli/plan-main ["--final"] {"INTERVAL_OK" "true" "ALREADY_GREEN" "true" "REASON" "due" + "KEY" "canary-green-0.8.27" "GITHUB_OUTPUT" out} {}))] + (is (= 0 (:rc r))) + (is (= "proceed=false\n" (slurp out))) + (is (str/includes? (:out r) "SKIPPING: canary-green-0.8.27 already passed")))) + +(deftest plan-usage-error + (is (= 2 (:rc (run #(cli/plan-main ["--nope"] {} {})))))) + +(deftest report-reads-every-results-file-and-opens-an-issue-for-a-failure + (let [d (tmp-dir) + _ (fs/create-dirs (str d "/results/results-0.8.27")) + _ (fs/create-dirs (str d "/results/results-nightly")) + _ (spit (str d "/results/results-0.8.27/results.json") + "{\"requested\":\"0.8.27\",\"projects\":[{\"name\":\"a\",\"result\":\"pass\"}]}") + _ (spit (str d "/results/results-nightly/results.json") + "{\"requested\":\"nightly\",\"projects\":[{\"name\":\"a\",\"result\":\"fail\"}]}") + writes (atom []) + r (run #(cli/report-main [(str d "/results")] + {"GITHUB_REPOSITORY" "o/ci" "VERSIONS" "[\"0.8.27\",\"nightly\"]" + "RUN_URL" "https://x/run/1" "RESULT" "failure" "GITHUB_RUN_ID" "1"} + {:gh (canary-gh writes)}))] + (is (= 0 (:rc r))) + (is (= 1 (count @writes))) + (is (str/includes? (:body (nth (first @writes) 2)) "**Failing:** a (nightly)")))) + +(deftest report-with-no-results-dir-and-a-green-fleet-does-nothing + (let [writes (atom []) + r (run #(cli/report-main [(str (tmp-dir) "/results")] + {"GITHUB_REPOSITORY" "o/ci" "VERSIONS" "[]" "RUN_URL" "u" "RESULT" "success"} + {:gh (canary-gh writes)}))] + (is (= 0 (:rc r))) + (is (= [] @writes)))) + +(deftest report-needs-its-environment + (let [r (run #(cli/report-main [] {} {}))] + (is (= 2 (:rc r))) + (is (str/includes? (:err r) "GITHUB_REPOSITORY is required")))) diff --git a/test/fleet/github_test.clj b/test/fleet/github_test.clj index ee24a20..c0d3895 100644 --- a/test/fleet/github_test.clj +++ b/test/fleet/github_test.clj @@ -1,5 +1,6 @@ (ns fleet.github-test - (:require [clojure.string :as str] + (:require [cheshire.core :as json] + [clojure.string :as str] [clojure.test :refer [deftest is testing]] [fleet.github :as gh])) @@ -176,3 +177,47 @@ blob {:status 403 :headers {} :body "expired"}} (atom []))}) e (try ((:get-redirected-log c) "l") nil (catch Exception e e))] (is (= 403 (gh/status-of e))))) + +;; Task 11: POST and PATCH for the canary issue, under the same host guard. + +(deftest post-json-sends-method-json-body-and-auth-and-parses-the-reply + (let [seen (atom []) + c (gh/client {:token "tok" + :request (stub {"https://api.github.com/repos/o/r/issues" + {:status 201 :headers {} :body "{\"number\":7}"}} + seen)})] + (is (= {:number 7} ((:post-json c) "repos/o/r/issues" {:title "t" :body "b\nline"}))) + (let [req (first @seen)] + (is (= :post (:method req))) + (is (= {:title "t" :body "b\nline"} (json/parse-string (:body req) true))) + (is (= "Bearer tok" (get-in req [:headers "Authorization"]))) + (is (= "application/json" (get-in req [:headers "Content-Type"]))) + (is (= false (:throw-exceptions req)))))) + +(deftest patch-json-sends-patch + (let [seen (atom []) + c (gh/client {:request (stub {"https://api.github.com/repos/o/r/issues/7" + {:status 200 :headers {} :body "{\"state\":\"closed\"}"}} + seen)})] + (is (= {:state "closed"} ((:patch-json c) "repos/o/r/issues/7" {:state "closed"}))) + (is (= :patch (:method (first @seen)))))) + +(deftest writes-throw-ex-info-with-status-on-non-2xx + (let [c (gh/client {:request (stub {"https://api.github.com/x" {:status 403 :headers {} :body "no"}} (atom []))})] + (doseq [f [:post-json :patch-json]] + (is (= 403 (gh/status-of (try ((f c) "x" {}) nil (catch Exception e e)))))))) + +(deftest writes-refuse-a-foreign-host-and-send-nothing + (let [seen (atom []) + c (gh/client {:token "tok" :request (stub {} seen)})] + (doseq [f [:post-json :patch-json] + url ["https://evil.example/repos/o/r/issues" "https://api.github.com.evil.example/x"]] + (is (foreign-host? (try ((f c) url {}) nil (catch Exception e e))))) + (is (= [] @seen)))) + +(deftest reads-still-carry-no-method-or-body + (let [seen (atom []) + c (gh/client {:request (stub {"https://api.github.com/a" {:status 200 :headers {} :body "{}"}} seen)})] + ((:get-json c) "a") + (is (nil? (:body (first @seen)))) + (is (contains? #{nil :get} (:method (first @seen)))))) From 1e4d1c0ec7aa41d2605c47dce2b37877d4e8027d Mon Sep 17 00:00:00 2001 From: burinc Date: Fri, 20 Nov 2026 15:34:15 +1100 Subject: [PATCH 22/31] fleet: drop the bash tooling now that jolt runs it --- .github/workflows/test.yml | 8 -- scripts/build-status.sh | 125 ---------------------- scripts/collect-own-pin.sh | 68 ------------ scripts/collect-uncovered.sh | 52 --------- scripts/lib/version.sh | 106 ------------------- scripts/publish-status.sh | 75 ------------- scripts/refresh-status.sh | 31 ------ src/fleet/cli.clj | 2 +- test/build-status.bats | 199 ----------------------------------- test/collect.bats | 107 ------------------- test/fleet/collect_test.clj | 7 +- test/fleet/publish_test.clj | 2 +- test/fleet/refresh_test.clj | 2 +- test/fleet/status_test.clj | 6 +- test/publish-status.bats | 112 -------------------- test/refresh-status.bats | 47 --------- test/version.bats | 69 ------------ 17 files changed, 9 insertions(+), 1009 deletions(-) delete mode 100755 scripts/build-status.sh delete mode 100755 scripts/collect-own-pin.sh delete mode 100755 scripts/collect-uncovered.sh delete mode 100644 scripts/lib/version.sh delete mode 100755 scripts/publish-status.sh delete mode 100755 scripts/refresh-status.sh delete mode 100644 test/build-status.bats delete mode 100644 test/collect.bats delete mode 100644 test/publish-status.bats delete mode 100644 test/refresh-status.bats delete mode 100644 test/version.bats diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index b5e9736..43e4ad2 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -16,14 +16,6 @@ env: TOOLS_JOLT_VERSION: ${{ vars.TOOLS_JOLT_VERSION || '0.8.27' }} jobs: - test: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v7 - - run: sudo apt-get install -y bats - - run: bats test/ - - run: shellcheck -x scripts/lib/*.sh scripts/build-status.sh scripts/collect-own-pin.sh scripts/collect-uncovered.sh scripts/publish-status.sh scripts/refresh-status.sh - jolt: runs-on: ubuntu-latest steps: diff --git a/scripts/build-status.sh b/scripts/build-status.sh deleted file mode 100755 index fd58de8..0000000 --- a/scripts/build-status.sh +++ /dev/null @@ -1,125 +0,0 @@ -#!/usr/bin/env bash -# Pure merge: fan-out results + own-pin + uncovered + previous status/history -# -> new status.json and history.json. No network, no git. -set -euo pipefail - -usage() { - echo "usage: build-status.sh --prev-status F --prev-history F --own-pin F --uncovered F" >&2 - echo " --latest VERSION --nightly-json JSON|null --canary-run URL --now ISO --out-dir D [results.json ...]" >&2 - exit 2 -} - -prev_status="" prev_history="" own_pin="" uncovered="" latest="" nightly="" canary="" now="" out="" -nightly_set=0 -while [ $# -gt 0 ]; do - case "$1" in - --prev-status) [ $# -ge 2 ] || usage; prev_status=$2; shift 2 ;; - --prev-history) [ $# -ge 2 ] || usage; prev_history=$2; shift 2 ;; - --own-pin) [ $# -ge 2 ] || usage; own_pin=$2; shift 2 ;; - --uncovered) [ $# -ge 2 ] || usage; uncovered=$2; shift 2 ;; - --latest) [ $# -ge 2 ] || usage; latest=$2; shift 2 ;; - --nightly-json) [ $# -ge 2 ] || usage; nightly=$2; nightly_set=1; shift 2 ;; - --canary-run) [ $# -ge 2 ] || usage; canary=$2; shift 2 ;; - --now) [ $# -ge 2 ] || usage; now=$2; shift 2 ;; - --out-dir) [ $# -ge 2 ] || usage; out=$2; shift 2 ;; - --) shift; break ;; - -*) usage ;; - *) break ;; - esac -done -results=("$@") -[ -n "$own_pin" ] && [ -n "$uncovered" ] && [ -n "$latest" ] && [ "$nightly_set" -eq 1 ] \ - && [ -n "$canary" ] && [ -n "$now" ] && [ -n "$out" ] || usage - -latest=${latest#v} -mkdir -p "$out" -tmp=$(mktemp -d "$out/.build-status.XXXXXX") -trap 'rm -rf "$tmp"' EXIT - -# A missing previous file counts as empty (null). -slurp_or_null() { if [ -n "$1" ] && [ -f "$1" ]; then cp "$1" "$2"; else echo null > "$2"; fi; } -slurp_or_null "$prev_status" "$tmp/prev-status.json" -slurp_or_null "$prev_history" "$tmp/prev-history.json" - -if [ ${#results[@]} -gt 0 ]; then - jq -s '.' "${results[@]}" > "$tmp/results.json" -else - echo '[]' > "$tmp/results.json" -fi - -jq -n \ - --slurpfile prev "$tmp/prev-status.json" \ - --slurpfile prevh "$tmp/prev-history.json" \ - --slurpfile files "$tmp/results.json" \ - --slurpfile own "$own_pin" \ - --slurpfile unc "$uncovered" \ - --arg latest "$latest" \ - --argjson nj "$nightly" \ - --arg canary "$canary" \ - --arg now "$now" ' - def strip: if type == "string" then sub("^v"; "") else . end; - def valid: ["pass","fail","infra","timed-out","dispatch-failed","mismatch","not-run"]; - def notrun: {result: "not-run"}; - def cell($f): { - result: .result, version: ($f.requested | strip), installed: (.installed // null), - run_url: (.run_url // null), finished_at: (.finished_at // null), - failed_step: (.failed_step // null)}; - def column($f): - if $f.requested == "nightly" then "nightly" - elif ($f.requested | strip) == $latest then "latest" - else "adhoc" end; - - ($prev[0]) as $ps | ($prevh[0]) as $ph | $files[0] as $fs | $own[0] as $op | $unc[0] as $un - | (($op | type) == "array" and all($op[]; (.name | type) == "string" and (.pin | type) == "string") - or error("malformed own-pin")) as $_ - | (($un | type) == "array" or error("malformed uncovered")) as $_ - | (($ps == null or ($ps | type) == "object") or error("malformed prev status")) as $_ - | (($ph == null or ($ph | type) == "object") or error("malformed prev history")) as $_ - | (all($fs[]; type == "object" and (.requested | type) == "string" and (.projects | type) == "array" - and all(.projects[]; (.name | type) == "string" and (.result as $r | valid | any(. == $r)))) - or error("malformed results")) as $_ - - # results this run, in file order - | [ $fs[] as $f | $f.projects[] | {name, col: column($f), cell: cell($f)} ] as $res - - | (if $ps == null then false else ($ps.jolt.latest.version // null) != $latest end) as $latest_stale - | (if $nj == null then false else ($ps.jolt.nightly.sha // null) != $nj.sha end) as $nightly_stale - | ((($ps.projects // []) | map({key: .name, value: .cells}) | from_entries)) as $pc - | ($res | map(select(.col != "adhoc")) | reduce .[] as $e ({}; .[$e.name + "/" + $e.col] = $e.cell)) as $new - - | def pick($n; $c; $stale): - $new[$n + "/" + $c] - // (if $stale then notrun else (($pc[$n] // {})[$c] // notrun) end); - - [ $op[] | . as $p - | {name: $p.name, pin: $p.pin, - cells: { - pin: {result: $p.result, version: $p.pin, installed: null, - run_url: ($p.run_url // null), finished_at: ($p.finished_at // null), - failed_step: ($p.failed_step // null)}, - latest: pick($p.name; "latest"; $latest_stale), - nightly: pick($p.name; "nightly"; $nightly_stale)}} ] as $projects - - | ($projects | map(select(.cells | [.[] | .result | . != "pass" and . != "not-run"] | any)) | map(.name)) as $bad - | ($projects | sort_by([(.name as $n | if $bad | any(. == $n) then 0 else 1 end), .name])) as $sorted - - # history: results this run, then the pin cell when its run is new - | ($res + [ $projects[] | . as $p | {name: $p.name, col: "pin", cell: $p.cells.pin} - | select(((($ph.projects // {})[.name].pin // [])[0].run_url // "__none__") != (.cell.run_url // "__none__") - or ((($ph.projects // {})[.name].pin // []) | length) == 0) ]) as $entries - | ($entries | reduce .[] as $e ($ph.projects // {}; - if $e.cell.run_url != null and ((.[$e.name][$e.col] // []) | any(.run_url == $e.cell.run_url)) - then . - else .[$e.name][$e.col] = ([$e.cell] + (.[$e.name][$e.col] // []))[0:30] end) - | map_values({pin: [], latest: [], nightly: [], adhoc: []} + .)) as $hist - - | {status: {schema: 1, generated_at: $now, canary_run: $canary, - jolt: {latest: {version: $latest}, nightly: ($nj // $ps.jolt.nightly // null)}, - projects: $sorted, uncovered: $un}, - history: {schema: 1, projects: $hist}} -' > "$tmp/both.json" - -jq '.status' "$tmp/both.json" > "$tmp/status.json" -jq '.history' "$tmp/both.json" > "$tmp/history.json" -mv "$tmp/status.json" "$out/status.json" -mv "$tmp/history.json" "$out/history.json" diff --git a/scripts/collect-own-pin.sh b/scripts/collect-own-pin.sh deleted file mode 100755 index ac192da..0000000 --- a/scripts/collect-own-pin.sh +++ /dev/null @@ -1,68 +0,0 @@ -#!/usr/bin/env bash -# For each fleet project: its latest completed push CI run on the default -# branch, plus the pin parsed from ci.yml. Prints own-pin.json on stdout. -# GH is the command used for every call (default: gh), split on spaces. -set -euo pipefail - -root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) -# shellcheck source=scripts/lib/version.sh -source "$root/scripts/lib/version.sh" -read -r -a GHC <<< "${GH:-gh}" -fleet=${FLEET_JSON:-$root/fleet.json} -org=jlt-commons -tmp=$(mktemp -d) -trap 'rm -rf "$tmp"' EXIT - -warn() { echo "collect-own-pin: $*" >&2; } - -# emit -emit() { - jq -n --arg name "$1" --arg pin "$2" --arg result "$3" --arg url "$4" \ - --arg at "$5" --arg step "$6" ' - def nz: if . == "" then null else . end; - {name: $name, pin: ($pin|nz), result: $result, run_url: ($url|nz), - finished_at: ($at|nz), failed_step: ($step|nz)}' -} - -collect() { - local p=$1 branch pin="" runs conc result url at id step="" ci="$tmp/ci.yml" - branch=$("${GHC[@]}" api "repos/$org/$p" --jq .default_branch 2>"$tmp/err") || { - warn "$p: could not read repository: $(tail -n1 "$tmp/err")" - emit "$p" "" not-run "" "" ""; return - } - if "${GHC[@]}" api -H 'Accept: application/vnd.github.raw' \ - "repos/$org/$p/contents/.github/workflows/ci.yml" >"$ci" 2>"$tmp/err"; then - pin=$(parse_pin "$ci") || pin="" - else - warn "$p: could not read ci.yml: $(tail -n1 "$tmp/err")" - fi - runs=$("${GHC[@]}" run list --repo "$org/$p" --workflow ci.yml --branch "$branch" \ - --event push --status completed --limit 1 \ - --json conclusion,url,updatedAt,databaseId 2>"$tmp/err") || { - warn "$p: could not list runs: $(tail -n1 "$tmp/err")" - emit "$p" "$pin" not-run "" "" ""; return - } - if [ "$(jq length <<<"$runs")" -eq 0 ]; then - emit "$p" "$pin" not-run "" "" ""; return - fi - conc=$(jq -r '.[0].conclusion // "none"' <<<"$runs") - case "$conc" in - success) result=pass ;; - failure) result=fail ;; - timed_out) result=timed-out ;; - *) result=not-run ;; - esac - url=$(jq -r '.[0].url // ""' <<<"$runs") - at=$(jq -r '.[0].updatedAt // ""' <<<"$runs") - if [ "$result" = fail ]; then - id=$(jq -r '.[0].databaseId' <<<"$runs") - step=$("${GHC[@]}" run view "$id" --repo "$org/$p" --json jobs \ - --jq '[.jobs[] | select(.conclusion=="failure") | .steps[]? | select(.conclusion=="failure") | .name] | first // ""' \ - 2>"$tmp/err") || { warn "$p: could not read jobs: $(tail -n1 "$tmp/err")"; step=""; } - fi - emit "$p" "$pin" "$result" "$url" "$at" "$step" -} - -while IFS= read -r p; do - collect "$p" -done < <(jq -r '.projects[]' "$fleet") | jq -s . diff --git a/scripts/collect-uncovered.sh b/scripts/collect-uncovered.sh deleted file mode 100755 index 05b1a3d..0000000 --- a/scripts/collect-uncovered.sh +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env bash -# Public, non-archived org repos that the fleet does not cover, each with a -# reason. Prints uncovered.json on stdout. -# GH is the command used for every call (default: gh), split on spaces. -set -euo pipefail - -root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) -# shellcheck source=scripts/lib/version.sh -source "$root/scripts/lib/version.sh" -read -r -a GHC <<< "${GH:-gh}" -fleet=${FLEET_JSON:-$root/fleet.json} -org=jlt-commons -tmp=$(mktemp -d) -trap 'rm -rf "$tmp"' EXIT - -command -v yq >/dev/null 2>&1 || { echo "collect-uncovered: yq is required but not on PATH" >&2; exit 1; } - -warn() { echo "collect-uncovered: $*" >&2; } - -reason_for() { - local out p=$1 in_fleet=0 excluded has_ci=0 has_input=0 ci="$tmp/ci.yml" - if jq -e --arg p "$p" '.projects | index($p)' "$fleet" >/dev/null; then in_fleet=1; fi - excluded=$(jq -r --arg p "$p" '.excluded[$p] // ""' "$fleet") - if [ "$in_fleet" = 0 ] && [ -z "$excluded" ]; then - if "${GHC[@]}" api -H 'Accept: application/vnd.github.raw' \ - "repos/$org/$p/contents/.github/workflows/ci.yml" >"$ci" 2>"$tmp/err"; then - has_ci=1 - # YAML 1.1 readers may turn the "on" key into boolean true. - if ! out=$(yq '(.on // .true) | select(tag == "!!map") | (.workflow_dispatch.inputs // {}) | has("jolt-version")' "$ci" 2>"$tmp/err"); then - warn "$p: could not parse ci.yml: $(tail -n1 "$tmp/err")" - printf 'could not read repository\n'; return - fi - [ "$out" = true ] && has_input=1 - elif grep -qE '\(HTTP 404\)[[:space:]]*$' "$tmp/err"; then - has_ci=0 - else - warn "$p: could not read repository: $(tail -n1 "$tmp/err")" - printf 'could not read repository\n'; return - fi - fi - uncovered_reason "$p" "$has_ci" "$has_input" "$in_fleet" "$excluded" -} - -names=$("${GHC[@]}" api --paginate "orgs/$org/repos?type=public&per_page=100" \ - --jq '.[] | select((.archived|not) and (.private|not)) | .name') - -while IFS= read -r p; do - [ -n "$p" ] || continue - r=$(reason_for "$p") - [ -n "$r" ] || continue - jq -n --arg name "$p" --arg reason "$r" '{name: $name, reason: $reason}' -done <<<"$names" | jq -s . diff --git a/scripts/lib/version.sh b/scripts/lib/version.sh deleted file mode 100644 index 8dedf13..0000000 --- a/scripts/lib/version.sh +++ /dev/null @@ -1,106 +0,0 @@ -#!/usr/bin/env bash -# Pure helpers for the fleet dashboard. Sourced, so no `set -e` here. - -# installed_version -# Prints the version from the first "jolt v[-N-g]" line (after the -# Actions timestamp), without the leading v. Exits 1 when there is none. -installed_version() { - local line re='^([0-9T:.-]+Z )?jolt v([0-9]+\.[0-9]+\.[0-9]+(-[0-9]+-g[0-9a-f]+)?)$' - while IFS= read -r line || [ -n "$line" ]; do - line=${line%$'\r'} - if [[ $line =~ $re ]]; then - printf '%s\n' "${BASH_REMATCH[2]}" - return 0 - fi - done < "$1" - return 1 -} - -# version_matches [nightly_sha] -version_matches() { - local requested=$1 installed=$2 sha=${3:-} re='-g([0-9a-f]+)$' - if [ "$requested" = "nightly" ]; then - [ -n "$sha" ] || return 1 - [[ $installed =~ $re ]] || return 1 - [[ $sha == "${BASH_REMATCH[1]}"* ]] - return - fi - [ "${requested#v}" = "$installed" ] -} - -# pick_installed ... -# Prints the first installed version (across the logs, in order) that matches -# the request and exits 0. If none match, prints the first version found and -# exits 1. If no log has a version, prints nothing and exits 1. -pick_installed() { - local requested=$1 sha=$2 f v first="" - shift 2 - for f in "$@"; do - v=$(installed_version "$f") || continue - [ -n "$first" ] || first=$v - if version_matches "$requested" "$v" "$sha"; then - printf '%s\n' "$v" - return 0 - fi - done - [ -n "$first" ] && printf '%s\n' "$first" - return 1 -} - -# parse_pin -# Prints the literal version from the first JOLT_VERSION: key line, without v. -# Exits 1 when the file or key is missing or the pin is not a literal version. -parse_pin() { - local line v ws='[[:space:]]*' - v="v?([0-9]+\\.[0-9]+\\.[0-9]+)" - local re="^${ws}JOLT_VERSION:${ws}(\\\$\\{\\{${ws}inputs\\.jolt-version${ws}\\|\\|${ws}'${v}'${ws}\\}\\}|\"${v}\"|'${v}'|${v})${ws}\$" - [ -r "$1" ] || return 1 - line=$(grep -m1 -E '^[[:space:]]*JOLT_VERSION:' "$1") || return 1 - line=${line%% \#*} - [[ $line =~ $re ]] || return 1 - # Exactly one of the four alternatives matched, so one version group is set. - printf '%s\n' "${BASH_REMATCH[2]}${BASH_REMATCH[3]}${BASH_REMATCH[4]}${BASH_REMATCH[5]}" -} - -# uncovered_reason -uncovered_reason() { - local has_ci=$2 has_input=$3 in_fleet=$4 excluded=${5:-} - [ "$in_fleet" = "1" ] && return 0 - if [ -n "$excluded" ]; then - printf 'excluded: %s\n' "$excluded" - elif [ "$has_ci" = "0" ]; then - printf 'no ci.yml\n' - elif [ "$has_input" = "0" ]; then - printf 'ci.yml has no jolt-version input\n' - else - printf 'ready, not yet in fleet.json\n' - fi -} - -# download_failure ... -# Exits 0 only when EVERY given log shows a dependency download failure (a -# package registry refusing or lacking an artifact) inside its failed step. -# The failed step is the text from the last "##[group]Run " line before the -# log's first "##[error]" line, up to that error line. A log with no -# "##[error]" line, an unreadable log, or no logs at all is not a match. -# Prints nothing. Pass exactly the failed jobs' logs, so one real break among -# them keeps the whole run a failure. -download_failure() { - [ "$#" -gt 0 ] || return 1 - local f section - for f in "$@"; do - [ -r "$f" ] || return 1 - section=$(awk ' - $2 == "##[group]Run" { buf = $0; next } - $2 ~ /^##\[error\]/ { print buf; exit } - { buf = buf "\n" $0 } - ' "$f") - [ -n "$section" ] || return 1 - printf '%s\n' "$section" | grep -qF \ - -e 'status code: 429' \ - -e 'Too Many Requests' \ - -e 'Could not transfer artifact' \ - -e 'Could not find artifact' \ - -e 'Failed to read artifact descriptor' || return 1 - done -} diff --git a/scripts/publish-status.sh b/scripts/publish-status.sh deleted file mode 100755 index d7d4c2c..0000000 --- a/scripts/publish-status.sh +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/env bash -# Commit status.json and history.json to the orphan `status` branch of origin. -# -# usage: REBUILD='' publish-status.sh -# -# Run inside a checkout whose origin it can push to. REBUILD runs on every -# attempt, the first included, with PREV_DIR (the freshly fetched status-branch -# files, which may be absent) and OUT_DIR () in its environment, and -# must write OUT_DIR/status.json and OUT_DIR/history.json. Per attempt: fetch, -# worktree at the branch tip, REBUILD, compare, commit, push. A rejected push -# means someone else published meanwhile, so the next attempt rebuilds on top -# of their result. Three attempts, then non-zero. -# -# "Unchanged" ignores generated_at and canary_run in status.json (both change -# every tick) and is byte-exact for history.json. -set -euo pipefail - -[ $# -eq 1 ] || { echo "usage: REBUILD=... publish-status.sh " >&2; exit 2; } -[ -n "${REBUILD:-}" ] || { echo "publish-status: REBUILD is required" >&2; exit 2; } -out=$1 -mkdir -p "$out" -out=$(cd "$out" && pwd) - -tmp=$(mktemp -d) -wt="$tmp/wt" -trap 'git worktree remove --force "$wt" 2>/dev/null || true; git worktree prune; rm -rf "$tmp"' EXIT - -norm() { jq -S 'del(.generated_at, .canary_run)' "$1"; } -bot=(-c user.name="github-actions[bot]" -c user.email="41898282+github-actions[bot]@users.noreply.github.com") - -for attempt in 1 2 3; do - rm -rf "$tmp/prev"; mkdir -p "$tmp/prev" - git worktree remove --force "$wt" 2>/dev/null || true - rm -rf "$wt" - - rc=0 - git ls-remote --exit-code --heads origin status >/dev/null 2>&1 || rc=$? - case "$rc" in - 0) - git fetch --quiet origin +refs/heads/status:refs/remotes/origin/status - git worktree add --quiet --detach "$wt" refs/remotes/origin/status - for f in status.json history.json; do - [ -f "$wt/$f" ] && cp "$wt/$f" "$tmp/prev/$f" - done - ;; - 2) - git worktree add --quiet --detach "$wt" HEAD - git -C "$wt" checkout --quiet --orphan status - git -C "$wt" rm -rfq . - ;; - *) echo "publish-status: cannot reach origin (ls-remote exit $rc)" >&2; exit 1 ;; - esac - - PREV_DIR="$tmp/prev" OUT_DIR="$out" sh -c "$REBUILD" - [ -f "$out/status.json" ] && [ -f "$out/history.json" ] \ - || { echo "publish-status: REBUILD did not write both files in $out" >&2; exit 1; } - - if [ -f "$wt/status.json" ] && [ -f "$wt/history.json" ] \ - && cmp -s "$out/history.json" "$wt/history.json" \ - && [ "$(norm "$out/status.json")" = "$(norm "$wt/status.json")" ]; then - echo "status: unchanged" - exit 0 - fi - - cp "$out/status.json" "$out/history.json" "$wt/" - git -C "$wt" add status.json history.json - git -C "$wt" "${bot[@]}" commit --quiet -m "status: update fleet status" - if git -C "$wt" push --quiet origin HEAD:refs/heads/status; then - echo "status: published (attempt $attempt)" - exit 0 - fi - echo "publish-status: push rejected on attempt $attempt, retrying" >&2 -done -echo "publish-status: gave up after 3 rejected pushes" >&2 -exit 1 diff --git a/scripts/refresh-status.sh b/scripts/refresh-status.sh deleted file mode 100755 index bbd309d..0000000 --- a/scripts/refresh-status.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/usr/bin/env bash -# Collect and build the fleet status files; publish-status.sh calls this as its -# REBUILD command, and so does the ad-hoc publish job in fanout.yml. -# -# usage: refresh-status.sh [results.json ...] -# env: LATEST jolt's latest release (a leading v is fine) -# NIGHTLY_JSON compact {"published_at","sha","note"} or the literal null -# CANARY_RUN URL of the run that is publishing -# PREV_DIR directory holding the previous status.json/history.json -# (may be absent or empty); set by publish-status.sh -# GH_TOKEN, GH, FLEET_JSON as for the collectors -set -euo pipefail - -[ $# -ge 1 ] || { echo "usage: refresh-status.sh [results.json ...]" >&2; exit 2; } -for v in LATEST NIGHTLY_JSON CANARY_RUN; do - [ -n "${!v:-}" ] || { echo "refresh-status: $v is required" >&2; exit 2; } -done -out=$1; shift -root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) -prev=${PREV_DIR:-/nonexistent} -tmp=$(mktemp -d) -trap 'rm -rf "$tmp"' EXIT - -"$root/scripts/collect-own-pin.sh" > "$tmp/own-pin.json" -"$root/scripts/collect-uncovered.sh" > "$tmp/uncovered.json" - -"$root/scripts/build-status.sh" \ - --prev-status "$prev/status.json" --prev-history "$prev/history.json" \ - --own-pin "$tmp/own-pin.json" --uncovered "$tmp/uncovered.json" \ - --latest "$LATEST" --nightly-json "$NIGHTLY_JSON" --canary-run "$CANARY_RUN" \ - --now "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --out-dir "$out" "$@" diff --git a/src/fleet/cli.clj b/src/fleet/cli.clj index feb0850..fed72dc 100644 --- a/src/fleet/cli.clj +++ b/src/fleet/cli.clj @@ -86,7 +86,7 @@ :else (recur (next args) opts (conj results (first args)))))) (defn status-main - "fleet:status: the pure merge, with build-status.sh's flags." + "fleet:status: the pure merge, with its own flags." [args] (let [{:keys [opts results error]} (parse-status-args args) missing (remove opts [:own-pin :uncovered :latest :nightly-json :canary-run :now :out-dir])] diff --git a/test/build-status.bats b/test/build-status.bats deleted file mode 100644 index f5d81d3..0000000 --- a/test/build-status.bats +++ /dev/null @@ -1,199 +0,0 @@ -setup() { - F="$BATS_TEST_DIRNAME/fixtures/status" - S="$BATS_TEST_DIRNAME/../scripts/build-status.sh" - OUT="$BATS_TEST_TMPDIR/out" - NJ='{"published_at":"2026-11-20T01:00:00Z","sha":"f4e82fc8eac874cae1658b7976518253027c4f6a","note":"n"}' -} - -# run_bs [extra args] -- results files: uses fixtures for own-pin/uncovered; prev files via PS/PH -run_bs() { - local nj=${NJ_ARG-$NJ} latest=${LATEST:-0.8.27} - run "$S" --prev-status "${PS:-/nonexistent}" --prev-history "${PH:-/nonexistent}" \ - --own-pin "${OP:-$F/own-pin.json}" --uncovered "$F/uncovered.json" \ - --latest "$latest" --nightly-json "$nj" --canary-run https://example/run/1 \ - --now 2026-11-20T04:00:00Z --out-dir "$OUT" "$@" -} -st() { jq -c "$1" "$OUT/status.json"; } -hi() { jq -c "$1" "$OUT/history.json"; } - -@test "first run with no prev files" { - run_bs "$F/results-latest.json" - [ "$status" -eq 0 ] - [ "$(st '.schema')" = 1 ] - [ "$(st '.projects|map(.name)|sort')" = '["ebb","glitter","raygui-jlt"]' ] - [ "$(st '.projects[]|select(.name=="raygui-jlt").cells.latest')" = '{"result":"not-run"}' ] - [ "$(st '.projects[]|select(.name=="raygui-jlt").cells.nightly')" = '{"result":"not-run"}' ] - [ "$(st '.uncovered')" = '[{"name":"duratom","reason":"ci.yml has no jolt-version input"}]' ] - [ "$(st '.generated_at')" = '"2026-11-20T04:00:00Z"' ] - [ "$(hi '.schema')" = 1 ] - [ "$(hi '.projects.glitter.latest|length')" = 1 ] - [ "$(hi '.projects.ebb.latest|length')" = 1 ] - [ "$(hi '.projects.glitter.pin|length')" = 1 ] -} - -@test "pin cell comes from own-pin with installed null" { - run_bs - [ "$(st '.projects[]|select(.name=="glitter").cells.pin|[.result,.version,.installed]')" = '["pass","0.8.24",null]' ] -} - -@test "latest result lands in latest column" { - run_bs "$F/results-latest.json" - [ "$(st '.projects[]|select(.name=="glitter").cells.latest|[.result,.version,.installed]')" = '["pass","0.8.27","0.8.27"]' ] - [ "$(st '.jolt.latest')" = '{"version":"0.8.27"}' ] -} - -@test "v prefix on requested is stripped" { - jq '.requested="v0.8.27"' "$F/results-latest.json" > "$BATS_TEST_TMPDIR/r.json" - run_bs "$BATS_TEST_TMPDIR/r.json" - [ "$(st '.projects[]|select(.name=="glitter").cells.latest.version')" = '"0.8.27"' ] -} - -@test "nightly result lands in nightly column" { - run_bs "$F/results-nightly.json" - [ "$(st '.projects[]|select(.name=="glitter").cells.nightly|[.result,.version,.installed]')" = '["pass","nightly","0.8.27-376-gf4e82fc8"]' ] - [ "$(st '.jolt.nightly.sha')" = '"f4e82fc8eac874cae1658b7976518253027c4f6a"' ] -} - -@test "adhoc result only in history" { - PS="$F/prev-status.json" PH="$F/prev-history.json" run_bs "$F/results-adhoc.json" - [ "$status" -eq 0 ] - [ "$(st '.projects[]|select(.name=="glitter").cells.latest.run_url')" = '"https://github.com/jlt-commons/glitter/actions/runs/42"' ] - [ "$(hi '.projects.glitter.adhoc|length')" = 1 ] - [ "$(hi '.projects.glitter.adhoc[0].version')" = '"0.8.25"' ] - [ "$(hi '.projects.glitter.latest|length')" = 0 ] -} - -@test "results for a project outside own-pin go to history, not the grid" { - jq '.projects[0].name="gone"' "$F/results-latest.json" > "$BATS_TEST_TMPDIR/r.json" - run_bs "$BATS_TEST_TMPDIR/r.json" - [ "$(st '.projects|map(.name)|index("gone")')" = null ] - [ "$(hi '.projects.gone.latest|length')" = 1 ] -} - -@test "carry over with only own-pin input" { - NJ_ARG='{"published_at":"x","sha":"aaaa1111","note":"n"}' PS="$F/prev-status.json" PH="$F/prev-history.json" run_bs - [ "$status" -eq 0 ] - [ "$(st '.projects[]|select(.name=="ebb").cells.latest')" = "$(jq -c '.projects[]|select(.name=="ebb").cells.latest' "$F/prev-status.json")" ] - [ "$(st '.projects[]|select(.name=="glitter").cells.nightly')" = "$(jq -c '.projects[]|select(.name=="glitter").cells.nightly' "$F/prev-status.json")" ] - # raygui-jlt had no prior cells - [ "$(st '.projects[]|select(.name=="raygui-jlt").cells.latest')" = '{"result":"not-run"}' ] -} - -@test "new latest version invalidates carried latest cells" { - NJ_ARG='{"published_at":"x","sha":"aaaa1111","note":"n"}' PS="$F/prev-status.json" PH="$F/prev-history.json" LATEST=0.8.28 run_bs - [ "$(st '.projects[]|select(.name=="ebb").cells.latest')" = '{"result":"not-run"}' ] - [ "$(st '.projects[]|select(.name=="glitter").cells.latest')" = '{"result":"not-run"}' ] - # nightly unaffected - [ "$(st '.projects[]|select(.name=="glitter").cells.nightly.result')" = '"pass"' ] -} - -@test "new nightly sha invalidates carried nightly cells" { - PS="$F/prev-status.json" PH="$F/prev-history.json" run_bs - [ "$(st '.projects[]|select(.name=="glitter").cells.nightly.result')" = '"not-run"' ] - [ "$(st '.projects[]|select(.name=="glitter").cells.latest.result')" = '"pass"' ] -} - -@test "null nightly-json with no previous status gives null jolt.nightly" { - NJ_ARG=null run_bs - [ "$status" -eq 0 ] - [ "$(st '.jolt.nightly')" = null ] -} - -@test "same nightly sha keeps carried nightly cells" { - NJ_ARG='{"published_at":"x","sha":"aaaa1111","note":"n"}' PS="$F/prev-status.json" run_bs - [ "$(st '.projects[]|select(.name=="glitter").cells.nightly.result')" = '"pass"' ] -} - -@test "null nightly-json keeps previous nightly cells and previous jolt.nightly" { - NJ_ARG=null PS="$F/prev-status.json" run_bs - [ "$status" -eq 0 ] - [ "$(st '.jolt.nightly')" = "$(jq -c '.jolt.nightly' "$F/prev-status.json")" ] - [ "$(st '.projects[]|select(.name=="glitter").cells.nightly.result')" = '"pass"' ] -} - -@test "pin history appended only when run_url is new" { - PS="$F/prev-status.json" PH="$F/prev-history.json" run_bs - # glitter's own-pin run_url equals the newest pin history entry - [ "$(hi '.projects.glitter.pin|length')" = 1 ] - # ebb has no pin history yet - [ "$(hi '.projects.ebb.pin|length')" = 1 ] - # second tick over the first one's output adds nothing - cp "$OUT/history.json" "$BATS_TEST_TMPDIR/h2.json" - PS="$OUT/status.json" PH="$BATS_TEST_TMPDIR/h2.json" run_bs - [ "$(hi '.projects.ebb.pin|length')" = 1 ] - [ "$(hi '.projects["raygui-jlt"].pin|length')" = 1 ] -} - -@test "pin history grows when the pin run changes" { - PS="$F/prev-status.json" PH="$F/prev-history.json" run_bs - jq '.[0].run_url="https://github.com/jlt-commons/glitter/actions/runs/99"' "$F/own-pin.json" > "$BATS_TEST_TMPDIR/op.json" - cp "$OUT/history.json" "$BATS_TEST_TMPDIR/h2.json" - OP="$BATS_TEST_TMPDIR/op.json" PH="$BATS_TEST_TMPDIR/h2.json" run_bs - [ "$(hi '.projects.glitter.pin|length')" = 2 ] - [ "$(hi '.projects.glitter.pin[0].run_url')" = '"https://github.com/jlt-commons/glitter/actions/runs/99"' ] -} - -@test "history capped at 30, newest first" { - jq '.projects.glitter.latest = [range(0;30) | {result:"pass",version:"0.8.26",installed:null,run_url:("old/"+tostring),finished_at:null,failed_step:null}]' \ - "$F/prev-history.json" > "$BATS_TEST_TMPDIR/h.json" - PH="$BATS_TEST_TMPDIR/h.json" run_bs "$F/results-latest.json" - [ "$(hi '.projects.glitter.latest|length')" = 30 ] - [ "$(hi '.projects.glitter.latest[0].run_url')" = '"https://github.com/jlt-commons/glitter/actions/runs/11"' ] - [ "$(hi '.projects.glitter.latest[29].run_url')" = '"old/28"' ] -} - -@test "failing first, then by name" { - # raygui-jlt has a failing own-pin cell - run_bs - [ "$(st '.projects|map(.name)')" = '["raygui-jlt","ebb","glitter"]' ] -} - -@test "mismatch cell sorts before passing ones" { - jq '.[2].result="pass"' "$F/own-pin.json" > "$BATS_TEST_TMPDIR/op.json" - OP="$BATS_TEST_TMPDIR/op.json" run_bs "$F/results-nightly.json" - [ "$(st '.projects|map(.name)')" = '["raygui-jlt","ebb","glitter"]' ] -} - -@test "malformed results: non-zero exit and no files written" { - echo '{"requested":"0.8.27","projects":"nope"}' > "$BATS_TEST_TMPDIR/bad.json" - run_bs "$BATS_TEST_TMPDIR/bad.json" - [ "$status" -ne 0 ] - [ ! -e "$OUT/status.json" ] - [ ! -e "$OUT/history.json" ] -} - -@test "unknown result value is rejected" { - jq '.projects[0].result="weird"' "$F/results-latest.json" > "$BATS_TEST_TMPDIR/bad.json" - run_bs "$BATS_TEST_TMPDIR/bad.json" - [ "$status" -ne 0 ] - [ ! -e "$OUT/status.json" ] -} - -@test "unparseable results file: non-zero exit" { - echo '{not json' > "$BATS_TEST_TMPDIR/bad.json" - run_bs "$BATS_TEST_TMPDIR/bad.json" - [ "$status" -ne 0 ] - [ ! -e "$OUT/status.json" ] -} - -@test "--latest with a v prefix matches results and prev" { - NJ_ARG='{"published_at":"x","sha":"aaaa1111","note":"n"}' PS="$F/prev-status.json" LATEST=v0.8.27 run_bs "$F/results-latest.json" - [ "$status" -eq 0 ] - [ "$(st '.jolt.latest.version')" = '"0.8.27"' ] - [ "$(st '.projects[]|select(.name=="glitter").cells.latest.run_url')" = '"https://github.com/jlt-commons/glitter/actions/runs/11"' ] - # no stale reset for a project the results file lacks - [ "$(st '.projects[]|select(.name=="raygui-jlt").cells.latest.result')" = '"not-run"' ] - NJ_ARG='{"published_at":"x","sha":"aaaa1111","note":"n"}' PS="$F/prev-status.json" LATEST=v0.8.27 run_bs - [ "$(st '.projects[]|select(.name=="ebb").cells.latest.result')" = '"fail"' ] -} - -@test "reprocessing the same results does not duplicate history" { - run_bs "$F/results-latest.json" "$F/results-nightly.json" "$F/results-adhoc.json" - cp "$OUT/status.json" "$BATS_TEST_TMPDIR/s1.json"; cp "$OUT/history.json" "$BATS_TEST_TMPDIR/h1.json" - PS="$BATS_TEST_TMPDIR/s1.json" PH="$BATS_TEST_TMPDIR/h1.json" run_bs "$F/results-latest.json" "$F/results-nightly.json" "$F/results-adhoc.json" - [ "$status" -eq 0 ] - [ "$(jq -c . "$OUT/history.json")" = "$(jq -c . "$BATS_TEST_TMPDIR/h1.json")" ] - [ "$(hi '.projects.glitter.adhoc|length')" = 1 ] - [ "$(hi '.projects.glitter.latest|length')" = 1 ] - [ "$(hi '.projects.glitter.nightly|length')" = 1 ] -} diff --git a/test/collect.bats b/test/collect.bats deleted file mode 100644 index b0d3403..0000000 --- a/test/collect.bats +++ /dev/null @@ -1,107 +0,0 @@ -setup() { - ROOT="$BATS_TEST_DIRNAME/.." - cat > "$BATS_TMPDIR/gh-stub" <<'S' -#!/usr/bin/env bash -# Serves canned files from test/fixtures/gh by argument pattern; honours --jq. -D="$FIXTURE_DIR"; a=" $* "; jqf=""; prev="" -for x in "$@"; do [ "$prev" = "--jq" ] && jqf=$x; prev=$x; done -out() { if [ -n "$jqf" ]; then jq -r "$jqf" "$1"; else cat "$1"; fi; } -fail() { echo "gh: stub has no fixture for:$a (HTTP 404)" >&2; exit 1; } -case "$a" in - *"orgs/jlt-commons/repos"*) out "$D/org-repos.json" ;; - *"repos/jlt-commons/ratelimited/contents/"*) echo "API rate limit exceeded for installation ID 4040404 (HTTP 403)" >&2; exit 1 ;; - *"repos/jlt-commons/brokenrepo/contents/"*) echo "HTTP 500" >&2; exit 1 ;; - *"repos/jlt-commons/"*"/contents/.github/workflows/ci.yml"*) - p=${a#*repos/jlt-commons/}; p=${p%%/*}; [ -f "$D/$p.ci.yml" ] || fail; cat "$D/$p.ci.yml" ;; - " api repos/jlt-commons/"*" --jq .default_branch "|*"api repos/jlt-commons/"*"--jq .default_branch"*) - p=${a#*repos/jlt-commons/}; p=${p%% *}; [ -f "$D/$p.branch" ] || fail; cat "$D/$p.branch" ;; - *"run list --repo jlt-commons/"*) - p=${a#*--repo jlt-commons/}; p=${p%% *}; [ -f "$D/$p.runs.json" ] || fail - case "$a" in *"--branch trunk"*) [ "$p" = glitter-gl ] || fail ;; esac - out "$D/$p.runs.json" ;; - *"run view "*"--repo jlt-commons/"*) - p=${a#*--repo jlt-commons/}; p=${p%% *}; [ -f "$D/$p.jobs.json" ] || fail; out "$D/$p.jobs.json" ;; - *) fail ;; -esac -S - chmod +x "$BATS_TMPDIR/gh-stub" - export GH="$BATS_TMPDIR/gh-stub" FIXTURE_DIR="$ROOT/test/fixtures/gh" - cat > "$BATS_TMPDIR/fleet.json" <<'F' -{"projects":["glitter","glitter-gl","glitter-uikit","ghost"],"excluded":{"jolt-lsp":"releases jolt-lsp","secretrepo":"private"}} -F - export FLEET_JSON="$BATS_TMPDIR/fleet.json" -} - -own() { bash "$ROOT/scripts/collect-own-pin.sh" 2>"$BATS_TMPDIR/err"; } -unc() { bash "$ROOT/scripts/collect-uncovered.sh" 2>"$BATS_TMPDIR/err"; } - -@test "own-pin: one entry per fleet project" { - run own; [ "$status" -eq 0 ] - [ "$(jq length <<<"$output")" -eq 4 ] - [ "$(jq -r '[.[].name]|join(",")' <<<"$output")" = "glitter,glitter-gl,glitter-uikit,ghost" ] -} -@test "own-pin: pass run with literal pin" { - run own - jq -e '.[0] | .pin==null and .result=="pass" and .run_url=="https://github.com/jlt-commons/glitter/actions/runs/1" and .finished_at=="2026-11-19T10:00:00Z" and .failed_step==null' <<<"$output" -} -@test "own-pin: default branch is used, failed run names the failed step, pin parsed" { - run own - jq -e '.[1] | .pin=="0.8.24" and .result=="fail" and .failed_step=="Run tests"' <<<"$output" -} -@test "own-pin: no push run yet is not-run, non-literal pin is null" { - run own - jq -e '.[2] | .result=="not-run" and .pin==null and .run_url==null and .finished_at==null' <<<"$output" -} -@test "own-pin: a repo whose API fails is not-run, warns, and does not abort" { - run own - jq -e '.[3] | .name=="ghost" and .result=="not-run" and .pin==null' <<<"$output" - grep -q 'ghost' "$BATS_TMPDIR/err" -} -@test "own-pin: conclusion mapping" { - for c in success:pass failure:fail timed_out:timed-out cancelled:not-run skipped:not-run neutral:not-run null:not-run; do - echo "[{\"conclusion\":${c%%:*},\"url\":\"u\",\"updatedAt\":\"t\",\"databaseId\":1}]" | sed 's/:\([a-z_]*\),/:"\1",/; s/:"null"/:null/' > "$BATS_TMPDIR/runs.json" - cp "$BATS_TMPDIR/runs.json" "$FIXTURE_DIR/zz.runs.json"; echo main > "$FIXTURE_DIR/zz.branch" - echo '{"projects":["zz"],"excluded":{}}' > "$FLEET_JSON" - run own; [ "$(jq -r '.[0].result' <<<"$output")" = "${c##*:}" ] || { echo "$c -> $output"; rm -f "$FIXTURE_DIR"/zz.*; return 1; } - rm -f "$FIXTURE_DIR"/zz.* - done -} -@test "own-pin: GH may be several words" { - export GH="env X=1 $BATS_TMPDIR/gh-stub" - run own; [ "$(jq length <<<"$output")" -eq 4 ] -} - -@test "uncovered: reasons per repo, fleet members and archived/private skipped" { - run unc; [ "$status" -eq 0 ] - [ "$(jq -r '.[]|select(.name=="jolt-lsp").reason' <<<"$output")" = "excluded: releases jolt-lsp" ] - [ "$(jq -r '.[]|select(.name=="nociyml").reason' <<<"$output")" = "no ci.yml" ] - [ "$(jq -r '.[]|select(.name=="noinput").reason' <<<"$output")" = "ci.yml has no jolt-version input" ] - [ "$(jq -r '.[]|select(.name=="readyrepo").reason' <<<"$output")" = "ready, not yet in fleet.json" ] - [ "$(jq '[.[]|select(.name=="glitter")]|length' <<<"$output")" -eq 0 ] - [ "$(jq '[.[]|select(.name=="oldrepo" or .name=="secretrepo")]|length' <<<"$output")" -eq 0 ] -} -@test "uncovered: a repo that cannot be read gets a reason and a warning" { - run unc - [ "$(jq -r '.[]|select(.name=="brokenrepo").reason' <<<"$output")" = "could not read repository" ] - grep -q brokenrepo "$BATS_TMPDIR/err" -} -@test "uncovered: on key parsed as boolean true still finds the input" { - echo '{"projects":[],"excluded":{}}' > "$FLEET_JSON" - run unc - [ "$(jq -r '.[]|select(.name=="glitter").reason' <<<"$output")" = "ready, not yet in fleet.json" ] -} -@test "uncovered: a 403 whose text contains 404 is not treated as a missing ci.yml" { - run unc - [ "$(jq -r '.[]|select(.name=="ratelimited").reason' <<<"$output")" = "could not read repository" ] - grep -q ratelimited "$BATS_TMPDIR/err" -} -@test "uncovered: unparsable ci.yml is could not read repository, with a warning" { - run unc - [ "$(jq -r '.[]|select(.name=="badyaml").reason' <<<"$output")" = "could not read repository" ] - grep -q badyaml "$BATS_TMPDIR/err" -} -@test "uncovered: missing yq fails loudly" { - mkdir -p "$BATS_TMPDIR/nobin"; for t in bash jq mktemp rm dirname cat grep tail env; do ln -sf "$(command -v $t)" "$BATS_TMPDIR/nobin/$t"; done - PATH="$BATS_TMPDIR/nobin" run bash "$ROOT/scripts/collect-uncovered.sh" - [ "$status" -ne 0 ]; [[ "$output" == *yq* ]] -} diff --git a/test/fleet/collect_test.clj b/test/fleet/collect_test.clj index 3d192cd..5cb0e8e 100644 --- a/test/fleet/collect_test.clj +++ b/test/fleet/collect_test.clj @@ -1,5 +1,5 @@ (ns fleet.collect-test - "Ports test/collect.bats. gh is a map of stub fns over a data 'world' read + "The collectors. gh is a map of stub fns over a data 'world' read from test/fixtures/gh, so no network is touched." (:require [cheshire.core :as json] [clojure.string :as str] @@ -170,9 +170,8 @@ (is (str/includes? err "badyaml")))) (deftest uncovered-transport-failure-is-could-not-read-not-no-ci-yml - ;; Replaces "missing yq fails loudly": jolt parses YAML in-process, so there - ;; is no external tool to miss. The matching risk is a transport error (no - ;; :status) being mistaken for an explicit 404. + ;; jolt parses YAML in-process, so there is no external tool to miss. The + ;; risk is a transport error (no :status) being mistaken for an explicit 404. (let [w (assoc-in (world) [:ci "readyrepo"] (ex-info "connection refused" {})) [rows _err] (warnings-of #(unc* w))] (is (= "could not read repository" (:reason (by-name rows "readyrepo")))))) diff --git a/test/fleet/publish_test.clj b/test/fleet/publish_test.clj index e61562e..55a1d07 100644 --- a/test/fleet/publish_test.clj +++ b/test/fleet/publish_test.clj @@ -1,5 +1,5 @@ (ns fleet.publish-test - "Ports test/publish-status.bats: a local bare repo stands in for origin, and + "Publishing to the status branch: a local bare repo stands in for origin, and rebuild is a function (the in-process REBUILD)." (:require [babashka.fs :as fs] [cheshire.core :as json] diff --git a/test/fleet/refresh_test.clj b/test/fleet/refresh_test.clj index 9cb4f1c..44f3bff 100644 --- a/test/fleet/refresh_test.clj +++ b/test/fleet/refresh_test.clj @@ -1,5 +1,5 @@ (ns fleet.refresh-test - "Ports test/refresh-status.bats. The collectors are thunks returning the + "Refresh. The collectors are thunks returning the status fixtures, so nothing touches the network." (:require [babashka.fs :as fs] [cheshire.core :as json] diff --git a/test/fleet/status_test.clj b/test/fleet/status_test.clj index bd58da3..f89ff26 100644 --- a/test/fleet/status_test.clj +++ b/test/fleet/status_test.clj @@ -18,7 +18,7 @@ (def ^:private nj-aaaa {:published_at "x" :sha "aaaa1111" :note "n"}) (defn- run-bs - "build with the bats defaults. Opts override: :ps :ph :op :latest :nj + "build with the default inputs. Opts override: :ps :ph :op :latest :nj (use ::none for a nil nightly)." [{:keys [ps ph op latest nightly] :or {latest "0.8.27" nightly nj}} & results] (status/build {:prev-status ps @@ -168,8 +168,8 @@ (is (thrown? Exception (run-bs {} (assoc-in (fx "results-latest.json") [:projects 0 :result] "weird"))))) -;; The bats case "unparseable results file" is the file-reading edge. Here it -;; is the shape a failed parse gives the pure function: not a map. +;; An unparseable results file is the file-reading edge. Here it is the +;; shape a failed parse gives the pure function: not a map. (deftest unparseable-results-input-is-rejected (is (thrown? Exception (run-bs {} nil))) (is (thrown? Exception (run-bs {} "{not json")))) diff --git a/test/publish-status.bats b/test/publish-status.bats deleted file mode 100644 index 3cd0be9..0000000 --- a/test/publish-status.bats +++ /dev/null @@ -1,112 +0,0 @@ -setup() { - ROOT="$BATS_TEST_DIRNAME/.." - T=$(mktemp -d "$BATS_TMPDIR/pub.XXXXXX") - git init -q --bare "$T/origin.git" - git init -q -b main "$T/work" - git -C "$T/work" config user.email t@example.com - git -C "$T/work" config user.name t - git -C "$T/work" remote add origin "$T/origin.git" - echo x > "$T/work/README" - git -C "$T/work" add README - git -C "$T/work" commit -q -m init - git -C "$T/work" push -q origin main - export T - # Default REBUILD: write fixed files regardless of PREV_DIR. - cat > "$T/rebuild-fixed.sh" <<'R' -#!/usr/bin/env bash -mkdir -p "$OUT_DIR" -echo "{\"schema\":1,\"generated_at\":\"$(date +%s%N)\",\"canary_run\":\"run-$(date +%s%N)\",\"projects\":[\"a\"]}" > "$OUT_DIR/status.json" -echo '{"schema":1,"adhoc":[]}' > "$OUT_DIR/history.json" -R - chmod +x "$T/rebuild-fixed.sh" -} - -pub() { (cd "$T/work" && REBUILD="$1" bash "$ROOT/scripts/publish-status.sh" "$T/out"); } -remote_show() { git -C "$T/origin.git" show "status:$1"; } - -@test "creates the branch on first publish" { - run pub "$T/rebuild-fixed.sh" - [ "$status" -eq 0 ] - [ "$(git -C "$T/origin.git" rev-list --count status)" -eq 1 ] - [ "$(remote_show status.json | jq '.projects|length')" -eq 1 ] - [ "$(remote_show history.json | jq .schema)" -eq 1 ] - # orphan: no README from main - run git -C "$T/origin.git" show status:README - [ "$status" -ne 0 ] - [ "$(git -C "$T/origin.git" log -1 --format=%an status)" = "github-actions[bot]" ] -} - -@test "no commit when only generated_at and canary_run changed" { - pub "$T/rebuild-fixed.sh" - before=$(git -C "$T/origin.git" rev-parse status) - run pub "$T/rebuild-fixed.sh" - [ "$status" -eq 0 ] - [[ "$output" == *"status: unchanged"* ]] - [ "$(git -C "$T/origin.git" rev-parse status)" = "$before" ] -} - -@test "commits when history.json changes" { - pub "$T/rebuild-fixed.sh" - before=$(git -C "$T/origin.git" rev-parse status) - cat > "$T/rebuild-hist.sh" <<'R' -#!/usr/bin/env bash -echo '{"schema":1,"projects":["a"]}' > "$OUT_DIR/status.json" -echo '{"schema":1,"adhoc":[1]}' > "$OUT_DIR/history.json" -R - run pub "bash $T/rebuild-hist.sh" - [ "$status" -eq 0 ] - [ "$(git -C "$T/origin.git" rev-parse status)" != "$before" ] - [ "$(remote_show history.json | jq '.adhoc|length')" -eq 1 ] -} - -@test "retries after a concurrent push and keeps both results" { - pub "$T/rebuild-fixed.sh" - # REBUILD adds its own project to whatever PREV_DIR holds. On the first - # attempt it also pushes a competing commit (project "theirs") after the - # fetch, so our push is rejected and attempt 2 must rebuild on top of it. - cat > "$T/rebuild-merge.sh" <<'R' -#!/usr/bin/env bash -set -e -n=$(cat "$T/attempts" 2>/dev/null || echo 0); n=$((n+1)); echo "$n" > "$T/attempts" -if [ "$n" -eq 1 ]; then - c=$(mktemp -d "$T/rival.XXXXXX") - git clone -q --branch status "$T/origin.git" "$c" - jq '.projects += ["theirs"]' "$c/status.json" > "$c/s" && mv "$c/s" "$c/status.json" - git -C "$c" -c user.email=r@example.com -c user.name=rival commit -q -am rival - git -C "$c" push -q origin status -fi -mkdir -p "$OUT_DIR" -jq '.projects += ["ours"]' "$PREV_DIR/status.json" > "$OUT_DIR/status.json" -cp "$PREV_DIR/history.json" "$OUT_DIR/history.json" -R - run pub "bash $T/rebuild-merge.sh" - [ "$status" -eq 0 ] - [ "$(cat "$T/attempts")" -eq 2 ] - [ "$(remote_show status.json | jq -c '.projects|sort')" = '["a","ours","theirs"]' ] -} - -@test "gives up after 3 rejections with non-zero exit" { - pub "$T/rebuild-fixed.sh" - cat > "$T/rebuild-lose.sh" <<'R' -#!/usr/bin/env bash -set -e -n=$(cat "$T/attempts" 2>/dev/null || echo 0); n=$((n+1)); echo "$n" > "$T/attempts" -c=$(mktemp -d "$T/rival.XXXXXX") -git clone -q --branch status "$T/origin.git" "$c" -echo "{\"schema\":1,\"projects\":[\"rival$n\"]}" > "$c/status.json" -git -C "$c" -c user.email=r@example.com -c user.name=rival commit -q -am "rival $n" -git -C "$c" push -q origin status -mkdir -p "$OUT_DIR" -echo "{\"schema\":1,\"projects\":[\"ours$n\"]}" > "$OUT_DIR/status.json" -echo '{"schema":1}' > "$OUT_DIR/history.json" -R - run pub "bash $T/rebuild-lose.sh" - [ "$status" -ne 0 ] - [ "$(cat "$T/attempts")" -eq 3 ] -} - -@test "fails without REBUILD" { - run bash -c "cd '$T/work' && env -u REBUILD bash '$ROOT/scripts/publish-status.sh' '$T/out'" - [ "$status" -ne 0 ] - [[ "$output" == *"REBUILD"* ]] -} diff --git a/test/refresh-status.bats b/test/refresh-status.bats deleted file mode 100644 index 239a032..0000000 --- a/test/refresh-status.bats +++ /dev/null @@ -1,47 +0,0 @@ -setup() { - ROOT="$BATS_TEST_DIRNAME/.." - F="$ROOT/test/fixtures/status" - # Copy the scripts so the network collectors can be replaced by stubs that - # print fixtures; refresh-status.sh finds its siblings relative to itself. - S="$BATS_TEST_TMPDIR/ci" - mkdir -p "$S" - cp -R "$ROOT/scripts" "$S/scripts" - printf '#!/usr/bin/env bash\ncat %q\n' "$F/own-pin.json" > "$S/scripts/collect-own-pin.sh" - printf '#!/usr/bin/env bash\ncat %q\n' "$F/uncovered.json" > "$S/scripts/collect-uncovered.sh" -} - -@test "refresh-status writes status.json and history.json from collectors and results" { - export LATEST=0.8.27 NIGHTLY_JSON=null CANARY_RUN=https://example/run/1 - PREV_DIR="$BATS_TEST_TMPDIR/none" run bash "$S/scripts/refresh-status.sh" "$BATS_TEST_TMPDIR/out" "$F/results-latest.json" - [ "$status" -eq 0 ] - [ "$(jq .schema "$BATS_TEST_TMPDIR/out/status.json")" -eq 1 ] - [ "$(jq -c '.projects|map(.name)|sort' "$BATS_TEST_TMPDIR/out/status.json")" = '["ebb","glitter","raygui-jlt"]' ] - [ "$(jq .schema "$BATS_TEST_TMPDIR/out/history.json")" -eq 1 ] -} - -@test "refresh-status needs LATEST" { - run env -u LATEST NIGHTLY_JSON=null CANARY_RUN=x bash "$S/scripts/refresh-status.sh" "$BATS_TEST_TMPDIR/out" - [ "$status" -ne 0 ] - [[ "$output" == *"LATEST"* ]] -} - -@test "two publishes whose only differences are the clock and canary_run make one commit" { - T="$BATS_TEST_TMPDIR/pub"; mkdir -p "$T" - git init -q --bare "$T/origin.git" - git init -q -b main "$T/work" - git -C "$T/work" config user.email t@example.com; git -C "$T/work" config user.name t - git -C "$T/work" remote add origin "$T/origin.git" - echo x > "$T/work/README"; git -C "$T/work" add README; git -C "$T/work" commit -q -m init - git -C "$T/work" push -q origin main - export LATEST=0.8.27 - # The stable note the canary plan job now emits: no age in it. - export NIGHTLY_JSON='{"published_at":"2026-11-20T01:00:00Z","sha":"f4e82fc8eac874cae1658b7976518253027c4f6a","note":"nightly published 2026-11-20T01:00:00Z at f4e82fc8"}' - export REBUILD="bash $S/scripts/refresh-status.sh \"\$OUT_DIR\" $F/results-latest.json" - cd "$T/work" - CANARY_RUN=https://example/run/1 bash "$S/scripts/publish-status.sh" "$T/out1" - sleep 1 - CANARY_RUN=https://example/run/2 run bash "$S/scripts/publish-status.sh" "$T/out2" - [ "$status" -eq 0 ] - [[ "$output" == *"status: unchanged"* ]] - [ "$(git -C "$T/origin.git" rev-list --count status)" -eq 1 ] -} diff --git a/test/version.bats b/test/version.bats deleted file mode 100644 index 917616d..0000000 --- a/test/version.bats +++ /dev/null @@ -1,69 +0,0 @@ -setup() { source "$BATS_TEST_DIRNAME/../scripts/lib/version.sh"; F="$BATS_TEST_DIRNAME/fixtures"; } - -@test "release log" { run installed_version "$F/log-release.txt"; [ "$output" = "0.8.24" ]; } -@test "nightly log" { run installed_version "$F/log-nightly.txt"; [ "$output" = "0.8.27-241-gdd3c4a4b" ]; } -@test "no version line" { printf 'Successfully installed jolt vnightly to /x\n' > "$BATS_TMPDIR/l"; run installed_version "$BATS_TMPDIR/l"; [ "$status" -eq 1 ]; [ -z "$output" ]; } -@test "v prefix requested" { run version_matches v0.8.24 0.8.24; [ "$status" -eq 0 ]; } -@test "release mismatch" { run version_matches 0.8.27 0.8.24; [ "$status" -eq 1 ]; } -@test "nightly sha match" { run version_matches nightly 0.8.27-241-gdd3c4a4b dd3c4a4b0123456789abcdef0123456789abcdef; [ "$status" -eq 0 ]; } -@test "nightly stale sha" { run version_matches nightly 0.8.27-241-gdd3c4a4b 98e5ef990000000000000000000000000000000a; [ "$status" -eq 1 ]; } -@test "nightly no sha" { run version_matches nightly 0.8.27-241-gdd3c4a4b; [ "$status" -eq 1 ]; } -@test "nightly got a release" { run version_matches nightly 0.8.27 dd3c4a4b00; [ "$status" -eq 1 ]; } - -pin() { printf '%s\n' "$1" > "$BATS_TMPDIR/ci.yml"; run parse_pin "$BATS_TMPDIR/ci.yml"; } - -@test "pin: input with default" { pin " JOLT_VERSION: \${{ inputs.jolt-version || '0.8.24' }}"; [ "$status" -eq 0 ]; [ "$output" = "0.8.24" ]; } -@test "pin: input with v default" { pin " JOLT_VERSION: \${{ inputs.jolt-version || 'v0.8.24' }}"; [ "$status" -eq 0 ]; [ "$output" = "0.8.24" ]; } -@test "pin: quoted literal" { pin ' JOLT_VERSION: "0.8.24"'; [ "$status" -eq 0 ]; [ "$output" = "0.8.24" ]; } -@test "pin: needs output is not literal" { pin " JOLT_VERSION: \${{ needs.jolt-version.outputs.version }}"; [ "$status" -eq 1 ]; [ -z "$output" ]; } -@test "pin: comment mentions are skipped" { - printf '# JOLT_VERSION: 9.9.9 is old\nenv:\n JOLT_VERSION: "0.8.24"\n' > "$BATS_TMPDIR/ci.yml" - run parse_pin "$BATS_TMPDIR/ci.yml"; [ "$status" -eq 0 ]; [ "$output" = "0.8.24" ] -} -@test "pin: no key at all" { printf 'name: x\n' > "$BATS_TMPDIR/ci.yml"; run parse_pin "$BATS_TMPDIR/ci.yml"; [ "$status" -eq 1 ]; [ -z "$output" ]; } -@test "pin: missing file" { run parse_pin "$BATS_TMPDIR/nope.yml"; [ "$status" -eq 1 ]; } - -@test "uncovered: in fleet prints nothing" { run uncovered_reason glitter 1 1 1 ""; [ "$status" -eq 0 ]; [ -z "$output" ]; } -@test "uncovered: in fleet beats excluded" { run uncovered_reason glitter 0 0 1 "why"; [ -z "$output" ]; } -@test "uncovered: excluded" { run uncovered_reason jolt-lsp 1 0 0 "needs input"; [ "$output" = "excluded: needs input" ]; } -@test "uncovered: excluded beats no ci" { run uncovered_reason x 0 0 0 "private demo"; [ "$output" = "excluded: private demo" ]; } -@test "uncovered: no ci.yml" { run uncovered_reason x 0 0 0 ""; [ "$output" = "no ci.yml" ]; } -@test "uncovered: no input" { run uncovered_reason x 1 0 0 ""; [ "$output" = "ci.yml has no jolt-version input" ]; } -@test "uncovered: ready" { run uncovered_reason x 1 1 0 ""; [ "$output" = "ready, not yet in fleet.json" ]; } - -@test "pin: non-literal with quoted version in a trailing comment" { - pin " JOLT_VERSION: \${{ needs.x.outputs.v }} # was '0.8.24'"; [ "$status" -eq 1 ]; [ -z "$output" ] -} -@test "pin: literal followed by a comment" { pin ' JOLT_VERSION: "0.8.24" # pinned'; [ "$status" -eq 0 ]; [ "$output" = "0.8.24" ]; } -@test "pin: bare literal" { pin ' JOLT_VERSION: v0.8.24'; [ "$status" -eq 0 ]; [ "$output" = "0.8.24" ]; } - -@test "installed: CRLF line" { - printf '2026-11-18T03:48:27.0669741Z jolt v0.8.27-241-gdd3c4a4b\r\n' > "$BATS_TMPDIR/crlf" - run installed_version "$BATS_TMPDIR/crlf"; [ "$status" -eq 0 ]; [ "$output" = "0.8.27-241-gdd3c4a4b" ] -} -@test "installed: 20000-line log, version last" { - { yes '2026-11-18T03:48:27.0000000Z some build output line with jolt in it' | head -n 20000 - printf '2026-11-18T03:48:28.0000000Z jolt v0.8.24\n'; } > "$BATS_TMPDIR/big" - run installed_version "$BATS_TMPDIR/big"; [ "$status" -eq 0 ]; [ "$output" = "0.8.24" ] -} - -logs2() { printf '2026-11-19T01:02:03.0000000Z jolt v%s\n' "$1" > "$BATS_TMPDIR/a.log"; printf '2026-11-19T01:02:04.0000000Z jolt v%s\n' "$2" > "$BATS_TMPDIR/b.log"; } - -@test "pick: matching second log" { logs2 0.7.29 0.8.27; run pick_installed 0.8.27 "" "$BATS_TMPDIR/a.log" "$BATS_TMPDIR/b.log"; [ "$status" -eq 0 ]; [ "$output" = "0.8.27" ]; } -@test "pick: none match reports first" { logs2 0.7.29 0.8.27; run pick_installed 0.8.26 "" "$BATS_TMPDIR/a.log" "$BATS_TMPDIR/b.log"; [ "$status" -eq 1 ]; [ "$output" = "0.7.29" ]; } -@test "pick: nightly sha in second log" { logs2 0.7.29 0.8.27-241-gdd3c4a4b; run pick_installed nightly dd3c4a4b0123456789abcdef0123456789abcdef "$BATS_TMPDIR/a.log" "$BATS_TMPDIR/b.log"; [ "$status" -eq 0 ]; [ "$output" = "0.8.27-241-gdd3c4a4b" ]; } -@test "pick: no versions" { printf 'nothing\n' > "$BATS_TMPDIR/a.log"; run pick_installed 0.8.27 "" "$BATS_TMPDIR/a.log"; [ "$status" -eq 1 ]; [ -z "$output" ]; } - -@test "download_failure: maven 429" { run download_failure "$F/log-maven-429.txt"; [ "$status" -eq 0 ]; [ -z "$output" ]; } -@test "download_failure: maven absent" { run download_failure "$F/log-maven-absent.txt"; [ "$status" -eq 0 ]; } -@test "download_failure: test failure" { run download_failure "$F/log-test-failure.txt"; [ "$status" -eq 1 ]; [ -z "$output" ]; } -@test "download_failure: no args" { run download_failure; [ "$status" -eq 1 ]; } - -@test "download_failure: earlier step printed 429, failed step is a test" { run download_failure "$F/log-early-429.txt"; [ "$status" -eq 1 ]; } -@test "download_failure: one deps log and one test log is not infra" { run download_failure "$F/log-maven-429.txt" "$F/log-test-failure.txt"; [ "$status" -eq 1 ]; } -@test "download_failure: both deps logs" { run download_failure "$F/log-maven-429.txt" "$F/log-maven-absent.txt"; [ "$status" -eq 0 ]; } -@test "download_failure: no ##[error] line" { run download_failure "$F/log-no-error.txt"; [ "$status" -eq 1 ]; } -@test "download_failure: Classpath lookup failed alone is not enough" { - printf '%s\n' '2026-11-20T01:00:00.0000000Z ##[group]Run x' '2026-11-20T01:00:01.0000000Z [ERROR] Classpath lookup failed' '2026-11-20T01:00:02.0000000Z ##[error]Process completed with exit code 1.' > "$BATS_TMPDIR/cp.txt" - run download_failure "$BATS_TMPDIR/cp.txt"; [ "$status" -eq 1 ] -} From 7abb26325bb857be1f0b587428c2a95e71abad3d Mon Sep 17 00:00:00 2001 From: burinc Date: Fri, 20 Nov 2026 15:41:21 +1100 Subject: [PATCH 23/31] canary: gated ticks do not reset the interval, junk vars warn, unresolved nightly tag skips the row --- src/fleet/canary.clj | 20 +++++++++++++++----- src/fleet/cli.clj | 17 +++++++++++++++-- test/fleet/canary_test.clj | 36 ++++++++++++++++++++++++++++++++---- test/fleet/cli_test.clj | 35 ++++++++++++++++++++++++++--------- 4 files changed, 88 insertions(+), 20 deletions(-) diff --git a/src/fleet/canary.clj b/src/fleet/canary.clj index cae10aa..bcc3e46 100644 --- a/src/fleet/canary.clj +++ b/src/fleet/canary.clj @@ -79,15 +79,22 @@ [{:keys [nightly-release release-shas versions max-age-hours now]}] (let [pub (:published-at nightly-release) sha (or (:sha nightly-release) "")] - (if (str/blank? pub) + (cond + (str/blank? pub) {:nightly "nightly SKIPPED: no vnightly release found"} + + ;; The release exists but its tag does not resolve (R30). A row with no + ;; commit cannot be checked against the releases, so it is not run. + (str/blank? sha) + {:nightly "nightly SKIPPED: could not resolve the vnightly tag"} + + :else (let [age (or (hours-between pub now) 0)] (if (> age max-age-hours) {:nightly (str "nightly SKIPPED: published " pub ", " age "h old, limit " max-age-hours "h. jolt's publish-nightly is gated on its downstream library suites, " "so a lagging library withholds new builds while the old one stays installable")} - (if-let [dupe (when-not (str/blank? sha) - (some #(when (= sha (get release-shas %)) %) versions))] + (if-let [dupe (some #(when (= sha (get release-shas %)) %) versions)] {:nightly (str "nightly SKIPPED: vnightly is " (short-sha sha) ", the same commit as " dupe ", so the row would rebuild what " dupe " already covers")} {:nightly (str "nightly published " pub ", " age "h old, at " (short-sha sha)) @@ -223,7 +230,8 @@ a run whose conclusion is success (plan and status succeeded, the matrix skipped), so counting runs would reset the clock every tick and an interval above 1 would never come due. The tell is a `jolt ` job, which - exists only when the matrix ran. Looks at the 12 newest completed runs. A + exists only when the matrix ran, and a gated tick lists that job as + skipped, so a job counts only if it is not skipped (R28). Looks at the 12 newest completed runs. A failed lookup is skipped with a warning and, if nothing is found, reads as due: the safe direction is to run." [gh repo] @@ -232,7 +240,9 @@ (some (fn [{:keys [id updated_at]}] (let [jobs (try (:jobs ((:get-json gh) (str "repos/" repo "/actions/runs/" id "/jobs?per_page=100"))) (catch Exception e (warn "job list failed for run" id (ex-message e)) nil))] - (when (some #(str/starts-with? (str (:name %)) "jolt ") jobs) + (when (some #(and (str/starts-with? (str (:name %)) "jolt ") + (not= "skipped" (:conclusion %))) + jobs) updated_at))) runs))) diff --git a/src/fleet/cli.clj b/src/fleet/cli.clj index fed72dc..456e0d5 100644 --- a/src/fleet/cli.clj +++ b/src/fleet/cli.clj @@ -195,14 +195,27 @@ (print text)) (flush)) +(defn- hours-or-default + "canary/parse-hours, but a bad value prints a ::warning:: naming the + variable and falls back to dflt (R29): a typo in a repo variable must not + stop the plan, and with it the status job, on every event." + [text dflt var-name] + (try (canary/parse-hours text dflt var-name) + (catch Exception e + (println (str "::warning::" (ex-message e) ", using " dflt)) + dflt))) + (defn- plan! "The decide step: read GitHub, work out the plan, write the job outputs." [env deps] (let [gh (gh-of deps) requested (or (get env "REQUESTED") "") - interval (canary/parse-hours (get env "INTERVAL_HOURS") 0 "CANARY_INTERVAL_HOURS") - max-age (canary/parse-hours (get env "NIGHTLY_MAX_AGE_HOURS") 48 "NIGHTLY_MAX_AGE_HOURS") event (get env "EVENT") + ;; Only a scheduled tick reads the interval at all. + interval (if (= "schedule" event) + (hours-or-default (get env "INTERVAL_HOURS") 0 "CANARY_INTERVAL_HOURS") + 0) + max-age (hours-or-default (get env "NIGHTLY_MAX_AGE_HOURS") 48 "NIGHTLY_MAX_AGE_HOURS") repo (get env "GITHUB_REPOSITORY") in (merge {:requested requested :event event diff --git a/test/fleet/canary_test.clj b/test/fleet/canary_test.clj index 2d5aa25..5e997c4 100644 --- a/test/fleet/canary_test.clj +++ b/test/fleet/canary_test.clj @@ -55,6 +55,14 @@ (is (str/starts-with? (:nightly p) "nightly SKIPPED: published 2026-11-17T00:00:00Z, 84h old, limit 48h. ")))) +(deftest nightly-with-an-unresolved-tag-is-skipped + (doseq [sha [nil "" " "]] + (let [p (plan :nightly-release {:published-at "2026-11-19T21:30:15Z" :sha sha})] + (is (= ["0.8.27"] (:versions p))) + (is (nil? (:nightly-json p))) + (is (= "nightly SKIPPED: could not resolve the vnightly tag" (:nightly p))) + (is (= "canary-green-0.8.27" (:key p)))))) + (deftest nightly-at-exactly-the-limit-still-runs (is (= ["0.8.27" "nightly"] (:versions (plan :nightly-release {:published-at "2026-11-18T12:00:00Z" :sha "aaaaaaaabbbb"}))))) @@ -172,14 +180,34 @@ gh (stub-gh {runs-path {:workflow_runs [{:id 3 :updated_at "2026-11-20T11:00:00Z"} {:id 2 :updated_at "2026-11-20T08:00:00Z"} {:id 1 :updated_at "2026-11-20T05:00:00Z"}]} - "repos/o/ci/actions/runs/3/jobs?per_page=100" {:jobs [{:name "plan"} {:name "status"}]} - "repos/o/ci/actions/runs/2/jobs?per_page=100" {:jobs [{:name "plan"} {:name "jolt 0.8.27 / fan-out"}]} - "repos/o/ci/actions/runs/1/jobs?per_page=100" {:jobs [{:name "jolt 0.8.26"}]}} + "repos/o/ci/actions/runs/3/jobs?per_page=100" {:jobs [{:name "plan" :conclusion "success"} + {:name "jolt ${{ matrix.version }}" :conclusion "skipped"} + {:name "status" :conclusion "success"}]} + "repos/o/ci/actions/runs/2/jobs?per_page=100" {:jobs [{:name "plan"} {:name "jolt 0.8.27 / fan-out" :conclusion "success"}]} + "repos/o/ci/actions/runs/1/jobs?per_page=100" {:jobs [{:name "jolt 0.8.26" :conclusion "success"}]}} seen)] (is (= "2026-11-20T08:00:00Z" (canary/last-built-at gh "o/ci"))) (is (= [runs-path "repos/o/ci/actions/runs/3/jobs?per_page=100" "repos/o/ci/actions/runs/2/jobs?per_page=100"] @seen)))) +;; R28: a gated tick lists its matrix job, skipped, under the literal name +;; "jolt ${{ matrix.version }}". It must not reset the interval clock. +(deftest a-gated-tick-does-not-reset-the-interval-clock + (let [gh (stub-gh {runs-path {:workflow_runs [{:id 3 :updated_at "2026-11-20T11:45:00Z"} + {:id 2 :updated_at "2026-11-20T09:00:00Z"}]} + "repos/o/ci/actions/runs/3/jobs?per_page=100" + {:jobs [{:name "plan" :conclusion "success"} + {:name "jolt ${{ matrix.version }}" :conclusion "skipped"} + {:name "status" :conclusion "success"}]} + "repos/o/ci/actions/runs/2/jobs?per_page=100" + {:jobs [{:name "jolt 0.8.27 / fan-out" :conclusion "success"}]}} + (atom [])) + last (canary/last-built-at gh "o/ci") + p (plan :interval-hours 2 :last-built-at last)] + (is (= "2026-11-20T09:00:00Z" last)) + (is (true? (:proceed p))) + (is (= "due" (:reason p))))) + (deftest last-built-at-is-nil-when-no-run-built-anything (let [gh (stub-gh {runs-path {:workflow_runs [{:id 3 :updated_at "x"}]} "repos/o/ci/actions/runs/3/jobs?per_page=100" {:jobs [{:name "plan"}]}} @@ -189,7 +217,7 @@ (deftest last-built-at-ignores-a-job-lookup-that-fails (let [gh (stub-gh {runs-path {:workflow_runs [{:id 3 :updated_at "A"} {:id 2 :updated_at "B"}]} "repos/o/ci/actions/runs/3/jobs?per_page=100" (ex-info "502" {:status 502}) - "repos/o/ci/actions/runs/2/jobs?per_page=100" {:jobs [{:name "jolt 1"}]}} + "repos/o/ci/actions/runs/2/jobs?per_page=100" {:jobs [{:name "jolt 1" :conclusion "failure"}]}} (atom []))] (is (= "B" (canary/last-built-at gh "o/ci"))))) diff --git a/test/fleet/cli_test.clj b/test/fleet/cli_test.clj index 47bfa76..5bac6a3 100644 --- a/test/fleet/cli_test.clj +++ b/test/fleet/cli_test.clj @@ -190,15 +190,6 @@ (is (= #{"latest" "versions" "nightly" "nightly_json" "key" "proceed" "reason"} (set (keys o)))) (is (str/starts-with? (o "versions") "[\"0.8.27\"")))) -(deftest plan-rejects-a-junk-interval-and-writes-nothing - (let [d (tmp-dir) - out (str d "/out") - r (run #(cli/plan-main [] {"EVENT" "schedule" "INTERVAL_HOURS" "soon" "GITHUB_OUTPUT" out} - {:gh (canary-gh (atom []))}))] - (is (= 1 (:rc r))) - (is (str/includes? (:err r) "CANARY_INTERVAL_HOURS is not a whole number")) - (is (not (fs/exists? out))))) - (deftest plan-final-writes-proceed (let [d (tmp-dir) out (str d "/out") @@ -240,3 +231,29 @@ (let [r (run #(cli/report-main [] {} {}))] (is (= 2 (:rc r))) (is (str/includes? (:err r) "GITHUB_REPOSITORY is required")))) + +;; R29: a junk variable warns and falls back, never stops the plan. + +(defn- plan-out [env] + (let [d (tmp-dir) out (str d "/out") + r (run #(cli/plan-main [] (assoc env "GITHUB_OUTPUT" out "GITHUB_REPOSITORY" "o/ci") + {:gh (canary-gh (atom []))}))] + (assoc r :o (when (fs/exists? out) (kv (slurp out)))))) + +(deftest plan-manual-dispatch-ignores-a-junk-interval + (let [r (plan-out {"EVENT" "workflow_dispatch" "INTERVAL_HOURS" "soon"})] + (is (= 0 (:rc r))) + (is (= "true" (get-in r [:o "proceed"]))) + (is (not (str/includes? (:out r) "::warning::"))))) + +(deftest plan-schedule-with-a-junk-interval-warns-and-uses-zero + (let [r (plan-out {"EVENT" "schedule" "INTERVAL_HOURS" "soon"})] + (is (= 0 (:rc r))) + (is (str/includes? (:out r) "::warning::CANARY_INTERVAL_HOURS is not a whole number of hours: soon, using 0")) + (is (= "no interval gate" (get-in r [:o "reason"]))))) + +(deftest plan-junk-max-age-warns-and-uses-48 + (let [r (plan-out {"EVENT" "workflow_dispatch" "NIGHTLY_MAX_AGE_HOURS" "x"})] + (is (= 0 (:rc r))) + (is (str/includes? (:out r) "::warning::NIGHTLY_MAX_AGE_HOURS is not a whole number of hours: x, using 48")) + (is (= "true" (get-in r [:o "proceed"]))))) From 598cb0e6c535dff2ad9f2917dab4c6321afb87d4 Mon Sep 17 00:00:00 2001 From: burinc Date: Fri, 20 Nov 2026 15:43:20 +1100 Subject: [PATCH 24/31] fleet: add ensemble, ebb, docs-engine, raylib-jolt-demo, raylib-ios-demo --- fleet.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fleet.json b/fleet.json index 9bc8d25..ec7df7c 100644 --- a/fleet.json +++ b/fleet.json @@ -1,4 +1,4 @@ -{"projects": ["glitter", "glitter-gl", "glitter-uikit", "raygui-jlt", "raylib-jlt", "raylib-ios", "raylib-android"], +{"projects": ["glitter", "glitter-gl", "glitter-uikit", "raygui-jlt", "raylib-jlt", "raylib-ios", "raylib-android", "ensemble", "ebb", "docs-engine", "raylib-jolt-demo", "raylib-ios-demo"], "excluded": {"jolt-lsp": "its dispatch input releases jolt-lsp; needs a jolt-version input first", "ci-builds": "this repository", "demo-repository": "private demo"}} From f8da95201a0a828db5aecfa13edd654b9595a119 Mon Sep 17 00:00:00 2001 From: burinc Date: Fri, 20 Nov 2026 16:28:47 +1100 Subject: [PATCH 25/31] canary: retry backoff for a known-bad version set, dispatch-failed reads as infra, demos excluded until the App is installed - fleet.json: raylib-jolt-demo and raylib-ios-demo move to excluded (R34) - plan outputs tried_key (canary-tried--), a second lookup-only cache restore gates a scheduled tick, and a run whose fleet result is not success saves the key (R35) - the issue groups dispatch-failed with infra (R36) - bad hour variables warn by name without echoing the value (M1, part) --- .github/workflows/canary.yml | 39 +++++++++++++++++- fleet.json | 6 ++- src/fleet/canary.clj | 77 +++++++++++++++++++++++++----------- src/fleet/cli.clj | 10 ++++- test/fleet/canary_test.clj | 48 ++++++++++++++++++++-- test/fleet/cli_test.clj | 25 ++++++++++-- 6 files changed, 172 insertions(+), 33 deletions(-) diff --git a/.github/workflows/canary.yml b/.github/workflows/canary.yml index d31cc04..daf0c6e 100644 --- a/.github/workflows/canary.yml +++ b/.github/workflows/canary.yml @@ -27,6 +27,9 @@ name: canary # vars.CANARY_INTERVAL_HOURS (default 0, no interval gate) holds a scheduled # tick back. The cron itself cannot be a variable, GitHub requires a literal. # vars.NIGHTLY_MAX_AGE_HOURS (default 48) is the nightly freshness limit. +# vars.CANARY_RETRY_HOURS (default 6) sizes the retry window: a version set +# that did not pass is tried once per window, and a new version set is tried at +# once. # A manual dispatch ignores both gates. That is the point of a manual dispatch. # --------------------------------------------------------------------------- @@ -67,6 +70,7 @@ jobs: proceed: ${{ steps.final.outputs.proceed }} reason: ${{ steps.decide.outputs.reason }} key: ${{ steps.decide.outputs.key }} + tried_key: ${{ steps.decide.outputs.tried_key }} nightly: ${{ steps.decide.outputs.nightly }} latest: ${{ steps.decide.outputs.latest }} nightly_json: ${{ steps.decide.outputs.nightly_json }} @@ -93,6 +97,7 @@ jobs: env: REQUESTED: ${{ inputs.jolt-version }} INTERVAL_HOURS: ${{ vars.CANARY_INTERVAL_HOURS }} + RETRY_HOURS: ${{ vars.CANARY_RETRY_HOURS }} NIGHTLY_MAX_AGE_HOURS: ${{ vars.NIGHTLY_MAX_AGE_HOURS }} EVENT: ${{ github.event_name }} GH_TOKEN: ${{ github.token }} @@ -109,7 +114,21 @@ jobs: key: ${{ steps.decide.outputs.key }} lookup-only: true - # Both gates land here. A step cannot rewrite an earlier step's output, + # Retry backoff (R35). A run that did not pass saves this key, which + # holds the version set and the current window (epoch hours div + # vars.CANARY_RETRY_HOURS, default 6). A hit means this exact set was + # already tried in this window, so a known-bad set is retried once per + # window while a new version set has a new key and runs on the next tick. + - name: Have we already tried this version set in this window? + id: tried + if: steps.decide.outputs.proceed == 'true' && github.event_name == 'schedule' + uses: actions/cache/restore@v6.1.0 + with: + path: .canary-state + key: ${{ steps.decide.outputs.tried_key }} + lookup-only: true + + # The gates land here. A step cannot rewrite an earlier step's output, # so the job's `proceed` reads THIS step and not `decide`, which knows # only about the interval. - name: Final decision @@ -117,6 +136,7 @@ jobs: env: INTERVAL_OK: ${{ steps.decide.outputs.proceed }} ALREADY_GREEN: ${{ steps.seen.outputs.cache-hit }} + ALREADY_TRIED: ${{ steps.tried.outputs.cache-hit }} REASON: ${{ steps.decide.outputs.reason }} KEY: ${{ steps.decide.outputs.key }} run: jolt fleet:plan --final @@ -285,3 +305,20 @@ jobs: with: path: .canary-state key: ${{ needs.plan.outputs.key }} + + # Retry backoff (R35). A fleet result that is not success marks this version + # set as tried for the current window, so the next ticks skip it instead of + # dispatching every project every 15 minutes. Same dummy-file trick as + # `remember`: the cache action needs a path that exists. !cancelled() so a + # failed fleet job does not skip this job, while a cancelled workflow still + # does. + remember-tried: + needs: [plan, fleet] + if: ${{ !cancelled() && needs.plan.outputs.proceed == 'true' && needs.fleet.result != 'success' }} + runs-on: ubuntu-latest + steps: + - run: mkdir -p .canary-state && date -u +%FT%TZ > .canary-state/tried-at + - uses: actions/cache/save@v6.1.0 + with: + path: .canary-state + key: ${{ needs.plan.outputs.tried_key }} diff --git a/fleet.json b/fleet.json index ec7df7c..6f0fe00 100644 --- a/fleet.json +++ b/fleet.json @@ -1,4 +1,6 @@ -{"projects": ["glitter", "glitter-gl", "glitter-uikit", "raygui-jlt", "raylib-jlt", "raylib-ios", "raylib-android", "ensemble", "ebb", "docs-engine", "raylib-jolt-demo", "raylib-ios-demo"], +{"projects": ["glitter", "glitter-gl", "glitter-uikit", "raygui-jlt", "raylib-jlt", "raylib-ios", "raylib-android", "ensemble", "ebb", "docs-engine"], "excluded": {"jolt-lsp": "its dispatch input releases jolt-lsp; needs a jolt-version input first", "ci-builds": "this repository", - "demo-repository": "private demo"}} + "demo-repository": "private demo", + "raylib-jolt-demo": "waiting on the jlt-commons-ci App installation", + "raylib-ios-demo": "waiting on the jlt-commons-ci App installation"}} diff --git a/src/fleet/canary.clj b/src/fleet/canary.clj index bcc3e46..2f295a7 100644 --- a/src/fleet/canary.clj +++ b/src/fleet/canary.clj @@ -67,7 +67,7 @@ (if (str/blank? text) dflt (or (parse-long (str/trim text)) - (throw (ex-info (str var-name " is not a whole number of hours: " text) {}))))) + (throw (ex-info (str var-name " is not a whole number of hours") {}))))) (defn- short-sha [sha] (subs sha 0 (min 8 (count sha)))) @@ -112,17 +112,32 @@ {:proceed false :reason (str "last run was " age "h ago, interval is " interval-hours "h")} {:proceed true :reason "due"})))) -(defn- versions-key - "The change-gate cache key. A new release changes the version set. The +(defn- versions-part + "The version set as a cache-key fragment. A new release changes it. The nightly needs its published_at folded in, because the literal string \"nightly\" is identical from one day to the next: without it the first green would cache a key that every later run also computes, and the nightly row would never run again however far main moved." [versions nightly-pub] - (str "canary-green-" - (str/join "-" (map #(str/replace % #"[\[\]\" ,]" "") versions)) + (str (str/join "-" (map #(str/replace % #"[\[\]\" ,]" "") versions)) (when nightly-pub (str "-" (str/replace nightly-pub #"[^0-9]" ""))))) +(defn- versions-key + "The change-gate cache key, saved only by a green run." + [versions nightly-pub] + (str "canary-green-" (versions-part versions nightly-pub))) + +(def default-retry-hours 6) + +(defn tried-key + "The retry-backoff cache key (R35), saved by a run that did not pass: the + version set plus the current window, epoch hours div retry-hours. A known-bad + version set is retried once per window, while a NEW version set has a new key + and is tried on the very next tick. retry-hours below 1 counts as 1." + [versions nightly-pub now retry-hours] + (let [window (quot (quot (or (epoch-ms now) 0) 3600000) (max 1 retry-hours))] + (str "canary-tried-" (versions-part versions nightly-pub) "-" window))) + (defn plan "What to test and whether to bother. @@ -131,8 +146,11 @@ or nil), :release-shas (version -> tag commit), :interval-hours, :max-age-hours, :last-built-at (ISO or nil) and :now (ISO). + :retry-hours (default 6) sizes the retry-backoff window. + Returns :versions (vector), :proceed (the interval decision, the change gate - is final-decision's job), :reason, :key, :nightly (text for the report), + is final-decision's job), :reason, :key, :tried-key (the retry-backoff cache + key), :nightly (text for the report), :nightly-json (the object status.json records, or nil) and :latest. A manual nightly still records which build it was (R23), skipping only the @@ -157,7 +175,9 @@ :nightly-json (:json row) :nightly-pub (when (:json row) (:published_at (:json row)))}))] (merge {:versions versions :nightly nightly :nightly-json nightly-json - :latest latest-release :key (versions-key versions nightly-pub)} + :latest latest-release :key (versions-key versions nightly-pub) + :tried-key (tried-key versions nightly-pub (:now in) + (or (:retry-hours in) default-retry-hours))} (interval-decision in)))) (defn needs-last-built-at? @@ -168,24 +188,28 @@ (defn final-decision "Combine the interval decision (interval-ok, the string \"true\" or not) - with the change gate (already-green, the cache step's cache-hit output, - blank when the step did not run). {:proceed bool :log line}." - [{:keys [interval-ok already-green reason key]}] + with the two cache gates (already-green and already-tried, the cache steps' + cache-hit outputs, blank when the step did not run). A hit on the tried key + means a non-passing run of this version set already happened in the current + retry window (R35). {:proceed bool :log line}." + [{:keys [interval-ok already-green already-tried reason key]}] (cond (not= "true" interval-ok) {:proceed false :log (str "SKIPPING: " reason)} (= "true" already-green) {:proceed false :log (str "SKIPPING: " key " already passed, so jolt has not moved")} + (= "true" already-tried) {:proceed false :log "SKIPPING: already tried in this window"} :else {:proceed true :log (str "RUNNING: " reason)})) (defn outputs-text "plan's result as the lines the job writes to $GITHUB_OUTPUT. The keys are - the ones the plan job exposes: versions, proceed, reason, key, nightly, - nightly_json, latest." - [{:keys [versions proceed reason key nightly nightly-json latest]}] + the ones the plan job exposes: versions, proceed, reason, key, tried_key, + nightly, nightly_json, latest." + [{:keys [versions proceed reason key tried-key nightly nightly-json latest]}] (str "latest=" latest "\n" "versions=" (json/generate-string versions) "\n" "nightly=" nightly "\n" "nightly_json=" (if nightly-json (json/generate-string nightly-json) "null") "\n" "key=" key "\n" + "tried_key=" tried-key "\n" "proceed=" proceed "\n" "reason=" reason "\n")) @@ -249,7 +273,12 @@ ;; --------------------------------------------------------------------------- ;; Pure: the report -(def ^:private finding? #{"fail" "mismatch" "timed-out" "dispatch-failed"}) +(def ^:private finding? #{"fail" "mismatch" "timed-out"}) + +;; R36: a dispatch that never started says nothing about jolt. It is our App or +;; configuration, so the issue groups it with infra. The result value on the +;; status page stays dispatch-failed. +(def ^:private infra-result? #{"infra" "dispatch-failed"}) (defn- cells "Sorted, distinct \"name (version)\" strings for projects whose result @@ -260,13 +289,15 @@ distinct sort vec)) (defn verdict - "{:failed [...] :infra [...]} from the merged results. fail, mismatch, - timed-out and dispatch-failed are findings about jolt or the build. infra - (jolt not installable, or a dependency not downloadable) is not a finding - about jolt, so it is reported separately, with each project's failed step." + "{:failed [...] :infra [...]} from the merged results. fail, mismatch and + timed-out are findings about jolt or the build. infra (jolt not installable, + or a dependency not downloadable) and dispatch-failed (the run never + started) are not findings about jolt, so they are reported separately, with + each project's failed step (for a dispatch failure, the first line gh + printed)." [results] {:failed (cells results finding? (fn [v _] v)) - :infra (cells results #{"infra"} + :infra (cells results infra-result? (fn [v p] (str v (when (:failed_step p) (str ", failed step: " (:failed_step p))))))}) (defn- lines [& ls] (str/join "\n" ls)) @@ -308,10 +339,12 @@ "" "A project either could not install jolt (check its `JOLT_REPO`," "which should be unset unless deliberately aimed at a fork, since the" - "version may not exist in the repository it installs from) or could" + "version may not exist in the repository it installs from), could" "not download a dependency (a package registry problem, often Maven" - "Central rate limiting while several projects build at once). The" - "failed step in parentheses above shows which." + "Central rate limiting while several projects build at once), or" + "could not be dispatched (the jlt-commons-ci App lacks access to the" + "repository, or GitHub refused the dispatch). The failed step in" + "parentheses above shows which." "" (str "**Versions tested:** " versions) "" diff --git a/src/fleet/cli.clj b/src/fleet/cli.clj index 456e0d5..4a0eadf 100644 --- a/src/fleet/cli.clj +++ b/src/fleet/cli.clj @@ -215,11 +215,15 @@ interval (if (= "schedule" event) (hours-or-default (get env "INTERVAL_HOURS") 0 "CANARY_INTERVAL_HOURS") 0) + retry (if (= "schedule" event) + (hours-or-default (get env "RETRY_HOURS") canary/default-retry-hours "CANARY_RETRY_HOURS") + canary/default-retry-hours) max-age (hours-or-default (get env "NIGHTLY_MAX_AGE_HOURS") 48 "NIGHTLY_MAX_AGE_HOURS") repo (get env "GITHUB_REPOSITORY") in (merge {:requested requested :event event :interval-hours interval + :retry-hours retry :max-age-hours max-age :now (now-iso)} (canary/gather gh requested)) @@ -237,6 +241,7 @@ [env] (let [{:keys [proceed log]} (canary/final-decision {:interval-ok (get env "INTERVAL_OK") :already-green (get env "ALREADY_GREEN") + :already-tried (get env "ALREADY_TRIED") :reason (get env "REASON") :key (get env "KEY")})] (append-output! env (str "proceed=" proceed "\n")) @@ -245,8 +250,9 @@ (defn plan-main "fleet:plan: the canary plan job's decide step. With --final, the step after the change-gate cache lookup. Env for the decide step: REQUESTED, - EVENT, INTERVAL_HOURS, NIGHTLY_MAX_AGE_HOURS, GITHUB_REPOSITORY, GH_TOKEN, - GITHUB_OUTPUT. Env for --final: INTERVAL_OK, ALREADY_GREEN, REASON, KEY." + EVENT, INTERVAL_HOURS, RETRY_HOURS, NIGHTLY_MAX_AGE_HOURS, + GITHUB_REPOSITORY, GH_TOKEN, GITHUB_OUTPUT. Env for --final: INTERVAL_OK, + ALREADY_GREEN, ALREADY_TRIED, REASON, KEY." ([args] (plan-main args (into {} (System/getenv)) {})) ([args env deps] (case (vec args) diff --git a/test/fleet/canary_test.clj b/test/fleet/canary_test.clj index 5e997c4..fcb2cc0 100644 --- a/test/fleet/canary_test.clj +++ b/test/fleet/canary_test.clj @@ -139,12 +139,32 @@ (is (= 48 (canary/parse-hours nil 48 "X"))) (is (= 48 (canary/parse-hours "" 48 "X"))) (is (= 6 (canary/parse-hours "6" 48 "X"))) - (is (= "X is not a whole number of hours: soon" + (is (= "X is not a whole number of hours" (ex-message (try (canary/parse-hours "soon" 48 "X") nil (catch Exception e e)))))) ;; --------------------------------------------------------------------------- ;; the change gate +(deftest tried-key-is-stable_inside_a_window_and_moves_with_the_window + (let [k (fn [& {:as over}] (:tried-key (plan over)))] + (testing "same window, same key" + (is (= (k :now "2026-11-20T12:00:00Z" :retry-hours 6) + (k :now "2026-11-20T17:59:59Z" :retry-hours 6)))) + (testing "next window, new key" + (is (not= (k :now "2026-11-20T17:59:59Z" :retry-hours 6) + (k :now "2026-11-20T18:00:00Z" :retry-hours 6)))) + (testing "shape: versions part of the green key plus epoch-hours div retry-hours" + ;; 2026-11-20T12:00:00Z is 498660 epoch hours (measured), 498660 div 6 = 83110 + (is (= "canary-tried-0.8.27-83110" (k :now "2026-11-20T12:00:00Z" :retry-hours 6)))) + (testing "a nightly's published_at and a new release both change it" + (is (= "canary-tried-0.8.27-nightly-20261119213015-83110" + (:tried-key (plan :nightly-release fresh-nightly :retry-hours 6)))) + (is (not= (k :retry-hours 6) (k :retry-hours 6 :latest-release "0.8.28" + :release-shas {"0.8.28" "aa"})))) + (testing "retry-hours defaults to 6 and never divides by zero" + (is (= (k :retry-hours 6) (k))) + (is (= (k :retry-hours 1) (k :retry-hours 0)))))) + (deftest final-decision-combines-both-gates (testing "interval says no" (is (= {:proceed false :log "SKIPPING: last run was 2h ago, interval is 6h"} @@ -155,6 +175,15 @@ (testing "cache miss" (is (= {:proceed true :log "RUNNING: due"} (canary/final-decision {:interval-ok "true" :already-green "false" :reason "due" :key "k"})))) + (testing "already tried in this window gates like a green hit" + (is (= {:proceed false :log "SKIPPING: already tried in this window"} + (canary/final-decision {:interval-ok "true" :already-green "false" :already-tried "true" :reason "due" :key "k"})))) + (testing "a tried-cache miss runs" + (is (= {:proceed true :log "RUNNING: due"} + (canary/final-decision {:interval-ok "true" :already-green "false" :already-tried "false" :reason "due" :key "k"})))) + (testing "green hit wins the wording over tried" + (is (= {:proceed false :log "SKIPPING: k already passed, so jolt has not moved"} + (canary/final-decision {:interval-ok "true" :already-green "true" :already-tried "true" :reason "due" :key "k"})))) (testing "no cache step ran (manual run)" (is (= {:proceed true :log "RUNNING: manual run, gates skipped"} (canary/final-decision {:interval-ok "true" :already-green "" :reason "manual run, gates skipped" :key "k"}))))) @@ -292,7 +321,7 @@ (is (str/ends-with? (:body r) "dispatching its own ci.yml with the `jolt-version` input.")))) (deftest mismatch-and-dispatch-failed-break-too - (doseq [bad ["mismatch" "dispatch-failed" "timed-out" "fail"]] + (doseq [bad ["mismatch" "timed-out" "fail"]] (testing bad (let [r (ib :results [(res "nightly" ["glitter" bad])])] (is (true? (:broken? r))) @@ -310,6 +339,19 @@ (is (str/includes? (:body r) "**Versions tested:** [\"0.8.27\"]")) (is (str/ends-with? (:body r) "has the per-project table. Dashboard: https://jlt-commons.github.io/fleet/")))) +(deftest r36-dispatch-failed-is-grouped-with-infra-for-the-issue + (testing "alone: infra wording, naming the project and gh's line, not a jolt finding" + (let [r (ib :results [(res "0.8.27" ["raylib-ios-demo" "dispatch-failed" "HTTP 404: Not Found"])])] + (is (true? (:broken? r))) + (is (true? (:infra? r))) + (is (str/starts-with? (:body r) "Infra problems, not findings about jolt: raylib-ios-demo (0.8.27, failed step: HTTP 404: Not Found)\n")) + (is (str/includes? (:body r) "could not be dispatched")) + (is (not (str/includes? (:body r) "**Failing:**"))))) + (testing "beside a real failure it is reported as a failure, as other infra is" + (let [r (ib :results [(res "0.8.27" ["glitter" "fail"] ["x" "dispatch-failed"])])] + (is (false? (:infra? r))) + (is (str/includes? (:body r) "**Failing:** glitter (0.8.27)\n"))))) + (deftest infra-plus-a-real-failure-is-reported-as-a-failure (let [r (ib :results [(res "0.8.27" ["glitter" "fail"] ["ebb" "infra" "Install jolt"])])] (is (true? (:broken? r))) @@ -406,7 +448,7 @@ (let [p (plan :nightly-release fresh-nightly) txt (canary/outputs-text p) kv (into {} (map #(str/split % #"=" 2)) (str/split-lines txt))] - (is (= #{"latest" "versions" "nightly" "nightly_json" "key" "proceed" "reason"} (set (keys kv)))) + (is (= #{"latest" "versions" "nightly" "nightly_json" "key" "tried_key" "proceed" "reason"} (set (keys kv)))) (is (= "[\"0.8.27\",\"nightly\"]" (kv "versions"))) (is (= "true" (kv "proceed"))) (is (= (:nightly-json p) (json/parse-string (kv "nightly_json") true))) diff --git a/test/fleet/cli_test.clj b/test/fleet/cli_test.clj index 5bac6a3..a8b2813 100644 --- a/test/fleet/cli_test.clj +++ b/test/fleet/cli_test.clj @@ -187,7 +187,7 @@ (is (= "0.8.27" (o "latest"))) (is (= "true" (o "proceed"))) (is (= "manual run, gates skipped" (o "reason"))) - (is (= #{"latest" "versions" "nightly" "nightly_json" "key" "proceed" "reason"} (set (keys o)))) + (is (= #{"latest" "versions" "nightly" "nightly_json" "key" "tried_key" "proceed" "reason"} (set (keys o)))) (is (str/starts-with? (o "versions") "[\"0.8.27\"")))) (deftest plan-final-writes-proceed @@ -199,6 +199,15 @@ (is (= "proceed=false\n" (slurp out))) (is (str/includes? (:out r) "SKIPPING: canary-green-0.8.27 already passed")))) +(deftest plan-final-an-already-tried-hit-gates-the-tick + (let [d (tmp-dir) + out (str d "/out") + r (run #(cli/plan-main ["--final"] {"INTERVAL_OK" "true" "ALREADY_GREEN" "false" "ALREADY_TRIED" "true" + "REASON" "due" "KEY" "k" "GITHUB_OUTPUT" out} {}))] + (is (= 0 (:rc r))) + (is (= "proceed=false\n" (slurp out))) + (is (str/includes? (:out r) "SKIPPING: already tried in this window")))) + (deftest plan-usage-error (is (= 2 (:rc (run #(cli/plan-main ["--nope"] {} {})))))) @@ -249,11 +258,21 @@ (deftest plan-schedule-with-a-junk-interval-warns-and-uses-zero (let [r (plan-out {"EVENT" "schedule" "INTERVAL_HOURS" "soon"})] (is (= 0 (:rc r))) - (is (str/includes? (:out r) "::warning::CANARY_INTERVAL_HOURS is not a whole number of hours: soon, using 0")) + (is (str/includes? (:out r) "::warning::CANARY_INTERVAL_HOURS is not a whole number of hours, using 0")) + (is (not (str/includes? (:out r) "soon"))) (is (= "no interval gate" (get-in r [:o "reason"]))))) +(deftest plan-schedule-writes-a-tried-key-with-the-retry-window + (let [r (plan-out {"EVENT" "schedule" "RETRY_HOURS" "3"})] + (is (re-matches #"canary-tried-0\.8\.27-nightly-\d+-\d+" (get-in r [:o "tried_key"]))) + (is (= 0 (:rc r)))) + (testing "junk warns without echoing the value, and falls back to 6" + (let [r (plan-out {"EVENT" "schedule" "RETRY_HOURS" "soon"})] + (is (str/includes? (:out r) "::warning::CANARY_RETRY_HOURS is not a whole number of hours, using 6")) + (is (not (str/includes? (:out r) "soon")))))) + (deftest plan-junk-max-age-warns-and-uses-48 (let [r (plan-out {"EVENT" "workflow_dispatch" "NIGHTLY_MAX_AGE_HOURS" "x"})] (is (= 0 (:rc r))) - (is (str/includes? (:out r) "::warning::NIGHTLY_MAX_AGE_HOURS is not a whole number of hours: x, using 48")) + (is (str/includes? (:out r) "::warning::NIGHTLY_MAX_AGE_HOURS is not a whole number of hours, using 48")) (is (= "true" (get-in r [:o "proceed"]))))) From 36c4bfa92de844dbc82745afe01a8e1a85481b8b Mon Sep 17 00:00:00 2001 From: burinc Date: Fri, 20 Nov 2026 16:31:22 +1100 Subject: [PATCH 26/31] fanout: unreadable logs are infra, cancelled runs are not-run, the poll ends on a wall-clock deadline, a dispatch failure says why - I1: a green run's job logs are read twice, then infra (could not read logs) instead of mismatch - I2/R37: cancelled, startup_failure and action_required map to not-run with the conclusion as detail; a manual fan-out queues in the canary concurrency group - I5: poll until 45 minutes after dispatch by the injected now, then mark the rest timed-out - I8/R33: first line of gh's output is logged indented and kept as failed_step, token blanked --- .github/workflows/fanout.yml | 9 +++ src/fleet/fanout.clj | 144 ++++++++++++++++++++++++---------- test/fleet/fanout_test.clj | 147 +++++++++++++++++++++++++++++++---- 3 files changed, 246 insertions(+), 54 deletions(-) diff --git a/.github/workflows/fanout.yml b/.github/workflows/fanout.yml index 5310b8f..99209f7 100644 --- a/.github/workflows/fanout.yml +++ b/.github/workflows/fanout.yml @@ -60,6 +60,15 @@ jobs: name: fan-out runs-on: ubuntu-latest timeout-minutes: 60 + # A manual fan-out queues behind a running canary instead of racing it: two + # dispatches of one project's ci.yml at once cancel each other when its + # own concurrency group cancels in progress (R37). It joins the canary's + # group only when run on its own. Called by the canary (github.workflow is + # then `canary`), the caller already holds that group, so the job takes a + # group of its own, which is unique per run and never waits. + concurrency: + group: ${{ github.workflow == 'fan-out' && 'canary' || format('fanout-called-{0}', github.run_id) }} + cancel-in-progress: false outputs: failed: ${{ steps.run.outputs.failed }} infra: ${{ steps.run.outputs.infra }} diff --git a/src/fleet/fanout.clj b/src/fleet/fanout.clj index 8211bea..55ac80b 100644 --- a/src/fleet/fanout.clj +++ b/src/fleet/fanout.clj @@ -33,16 +33,19 @@ - mismatch: the run succeeded but no job's `jolt --version` is the requested one (nightly republished between resolve and install, or a project ignoring the input). Never reported as pass. - - infra: a failed run whose cause is not jolt. Two causes. Either the - install-jolt step failed (measured 2026-09-02: JOLT_REPO was left - pointing at a fork that publishes only nightlies, so asking for 0.8.0 - gave curl 404 and two scheduled canaries called the fleet broken), or - every failed job's failed step shows a dependency download failure - (R21/R24, Maven Central 429s and missing artifacts). The failed step is - recorded for both (R25). + - infra: a run whose cause is not jolt. Three causes. The install-jolt step + failed (JOLT_REPO left pointing at a fork that publishes only nightlies + makes a requested release a curl 404), or every failed job's failed step + shows a dependency download failure (R21/R24, Maven Central 429s and + missing artifacts), or a green run's logs could not be read after two + tries, so which jolt it ran is unknown (I1). The failed step is recorded + for each (R25). - fail: any other non-success conclusion. timed-out and dispatch-failed - come from this loop, not from GitHub. - - not-run: GitHub concluded `skipped` (R5). + come from this loop, not from GitHub. A dispatch-failed row carries the + first line gh printed as its failed step (R33). + - not-run: GitHub concluded `skipped` (R5), or the run was `cancelled`, + never started (`startup_failure`) or waited on a person + (`action_required`), none of which says anything about jolt (R37). IO sits behind injected fns, so a test drives a whole fan-out with no network and no sleeping: gh (the fleet.github client map), sh, env, sleep @@ -58,7 +61,7 @@ (def ^:private jolt-repo "repos/jolt-lang/jolt") -(def ^:private poll-tries 150) +(def ^:private poll-window-ms (* 45 60 1000)) (def ^:private poll-interval-ms 20000) ;; --------------------------------------------------------------------------- @@ -80,24 +83,46 @@ (every? some? texts) (version/download-failure? texts))))) +(def ^:private unreadable-logs "could not read logs") + (defn classify "One finished run to {:result :installed :failed-step :cause :detail}. conclusion is GitHub's. jobs are the run's job maps ({:id :conclusion :steps [{:name :conclusion}]}). logs maps job id to log text, nil for a log - that could not be fetched. :cause is :install or :deps for infra, else - nil. :detail is the conclusion, kept for the table's FAIL (x) text." + that could not be fetched. :cause is :install, :deps or :logs for infra, + else nil. :detail is the conclusion, kept for the table's FAIL (x) text. + + A success whose logs show no matching jolt is a mismatch only when every + log was read. With an unreadable log it is infra (:logs), step \"could not + read logs\". + + cancelled, startup_failure and action_required are not-run: the project's + build never gave an answer, which is not a failure of jolt." [{:keys [requested nightly-sha conclusion jobs logs]}] (let [base {:installed nil :failed-step nil :cause nil :detail conclusion}] (case conclusion "success" - (let [{:keys [installed match?]} - (version/pick-installed requested nightly-sha - (keep #(get logs (:id %)) jobs))] - (assoc base :result (if match? "pass" "mismatch") :installed installed)) + (let [texts (map #(get logs (:id %)) jobs) + {:keys [installed match?]} + (version/pick-installed requested nightly-sha (remove nil? texts))] + (cond + match? (assoc base :result "pass" :installed installed) + + ;; No job showed the requested version, and a log we could not read + ;; may have been the one that did. That is no evidence of a wrong + ;; jolt, so it is not reported as one (I1). + (or (empty? jobs) (some nil? texts)) + (assoc base :result "infra" :cause :logs :failed-step unreadable-logs) + + :else (assoc base :result "mismatch" :installed installed))) "skipped" (assoc base :result "not-run") + ;; Nothing ran to completion, so nothing is known about jolt (I2, R37). + ;; detail keeps the conclusion for the table. + ("cancelled" "startup_failure" "action_required") (assoc base :result "not-run") + "failure" (let [steps (failed-steps jobs) cause (cond @@ -115,29 +140,33 @@ (defn- icon [{:keys [result cause detail installed]}] (case result "pass" "pass" - "not-run" "skipped" + "not-run" (if (contains? #{"cancelled" "startup_failure" "action_required"} detail) + (str "not run (" detail ")") + "skipped") "mismatch" (str "**WRONG JOLT** (ran " (or installed "no version found") ")") - "infra" (if (= :deps cause) - "**could not download dependencies**" + "infra" (case cause + :deps "**could not download dependencies**" + :logs "**could not read the run's logs**" "**could not install jolt**") (str "**FAIL** (" detail ")"))) (defn- split-names "Project names by outcome, in fleet order: {:failed :infra :nodeps - :mismatch :noinstall}. failed holds mismatches too, as the table always - did." + :nologs :mismatch :noinstall}. failed holds mismatches too, as the table + always did." [projects] (let [names (fn [pred] (mapv :name (filter pred projects)))] {:mismatch (names #(= "mismatch" (:result %))) :failed (names #(contains? #{"mismatch" "fail" "timed-out" "dispatch-failed"} (:result %))) :infra (names #(= "infra" (:result %))) :nodeps (names #(and (= "infra" (:result %)) (= :deps (:cause %)))) - :noinstall (names #(and (= "infra" (:result %)) (not= :deps (:cause %))))})) + :nologs (names #(and (= "infra" (:result %)) (= :logs (:cause %)))) + :noinstall (names #(and (= "infra" (:result %)) (not (#{:deps :logs} (:cause %)))))})) (defn summary-md "The step summary: a row per project, then a line per kind of trouble." [{:keys [version projects]}] - (let [{:keys [mismatch failed infra nodeps noinstall]} (split-names projects) + (let [{:keys [mismatch failed infra nodeps nologs noinstall]} (split-names projects) lines (concat [(str "## jolt `" version "` across " org) "" "| project | result | run |" "|---|---|---|"] @@ -159,6 +188,11 @@ "" "That is a package-registry problem, often Maven Central rate" "limiting while several projects build at once, not a fact about jolt."]) + (when (seq nologs) + [(str "**Could not read the logs of a green run for:** " (joined nologs)) + "" + "The run succeeded but its logs could not be fetched twice, so which" + "jolt it ran is unknown. That is a GitHub API problem, not a fact about jolt."]) ;; Counted from the projects rather than written out, so the number ;; cannot go stale beside the list it counts. (when (and (empty? failed) (empty? infra)) @@ -231,9 +265,21 @@ (defn- run-url [project id] (str "https://github.com/" org "/" project "/actions/runs/" id)) +(defn- first-line + "The first non-blank line of gh's stdout and stderr, trimmed and capped at + 200 characters, with the token blanked out should it ever appear. Printed + and recorded as the row's failed step so a dispatch failure explains itself + (R33). gh does not print its token; this guards the day it does." + [text token] + (let [line (or (->> (str/split-lines (or text "")) (map str/trim) (remove str/blank?) first) + "gh printed nothing") + line (if (seq token) (str/replace line token "***") line)] + (subs line 0 (min 200 (count line))))) + (defn- dispatch-all! - "Dispatch ci.yml in each project. Returns {project {:run-id :need-id? :detail}} - where :detail \"dispatch-failed\" marks a failed dispatch." + "Dispatch ci.yml in each project. Returns {project {:run-id :need-id? :detail + :failed-step}} where :detail \"dispatch-failed\" marks a failed dispatch and + :failed-step is the first line gh printed." [{:keys [sh token]} version projects] (log (str "::group::dispatch jolt " version)) (let [res (reduce @@ -253,8 +299,11 @@ ", falling back to newest-run matching. That is unreliable when fan-outs overlap.") (log (str " dispatched " pr ", run id unknown")) (assoc acc pr {:need-id? true})))) - (do (log (str " FAILED to dispatch " pr)) - (assoc acc pr {:detail "dispatch-failed"}))))) + (let [line (first-line (str out err) token)] + ;; Indented, so gh's text can never open a workflow command. + (log (str " FAILED to dispatch " pr)) + (log (str " " line)) + (assoc acc pr {:detail "dispatch-failed" :failed-step line}))))) {} projects)] (log "::endgroup::") res)) @@ -312,31 +361,44 @@ (warn (str "could not list the jobs of " pr " run " id ": " (explain e))) []))) +(defn- fetch-log-twice + "A job's log, read again once when the first read fails (I1)." + [gh pr job-id] + (or (fetch-log gh pr job-id) (fetch-log gh pr job-id))) + (defn- finish "Read the finished run's jobs and the logs the verdict needs, then classify. Logs are fetched only here, for completed runs: the failed jobs' for a failure (install and download failures live there), every job's for a - success (to read the `jolt --version` line)." + success (to read the `jolt --version` line, each read retried once)." [{:keys [gh now requested nightly-sha]} pr id conclusion] (let [jobs (run-jobs gh pr id) want (case conclusion "success" jobs "failure" (filter #(= "failure" (:conclusion %)) jobs) []) - logs (into {} (map (fn [j] [(:id j) (fetch-log gh pr (:id j))])) want) + fetch (if (= "success" conclusion) fetch-log-twice fetch-log) + logs (into {} (map (fn [j] [(:id j) (fetch gh pr (:id j))])) want) c (classify {:requested requested :nightly-sha nightly-sha :conclusion conclusion :jobs jobs :logs logs})] (assoc c :finished-at (now)))) +(defn- now-ms + "The injected clock as epoch milliseconds." + [now] + (.toEpochMilli (java.time.Instant/parse (now)))) + (defn- poll! - "Wait for every dispatched run to complete. Returns {project verdict}, polling in - fleet order. A - transport error while polling is just 'not yet'. Projects still running - after the last try are timed-out." - [{:keys [gh sleep] :as ctx} projects runs] + "Wait for every dispatched run to complete, in fleet order, until ctx's + :deadline (epoch ms, 45 minutes after dispatch, measured with the injected + now, so a slow poll pass costs time and not iterations). Returns {project + verdict}. A transport error while polling is just 'not yet'. Projects still + running at the deadline have no verdict and the caller marks them + timed-out. Every run is polled at least once." + [{:keys [gh sleep now deadline] :as ctx} projects runs] (log "::group::wait for completion") - (let [out (loop [i 0 pending (filterv runs projects) done {}] - (if (or (empty? pending) (>= i poll-tries)) + (let [out (loop [pending (filterv runs projects) done {}] + (if (empty? pending) done (let [step (reduce (fn [{:keys [pending done]} pr] @@ -355,8 +417,10 @@ {:pending pending :done (assoc done pr v)}) {:pending (conj pending pr) :done done}))) {:pending [] :done done} pending)] - (when (seq (:pending step)) (sleep poll-interval-ms)) - (recur (inc i) (:pending step) (:done step)))))] + (if (or (empty? (:pending step)) (>= (now-ms now) deadline)) + (:done step) + (do (sleep poll-interval-ms) + (recur (:pending step) (:done step)))))))] (log "::endgroup::") out)) @@ -383,6 +447,7 @@ _ (when sha (log "vnightly is" sha)) ctx {:gh gh :sh sh :sleep sleep :now now :token (env "GH_TOKEN") :requested requested :nightly-sha sha} + ctx (assoc ctx :deadline (+ (now-ms now) poll-window-ms)) dispatched (identify-fallback! ctx (dispatch-all! ctx requested projects)) verdicts (poll! ctx projects (into {} (filter (comp :run-id val)) dispatched)) rows (mapv (fn [pr] @@ -394,7 +459,8 @@ :cause nil :finished-at nil} (cond v v - (:detail d) {:result (or (:result d) (:detail d)) :detail (:detail d)} + (:detail d) {:result (or (:result d) (:detail d)) :detail (:detail d) + :failed-step (:failed-step d)} :else {:result "timed-out" :detail "timed-out"})))) projects) {:keys [failed infra]} (split-names rows) diff --git a/test/fleet/fanout_test.clj b/test/fleet/fanout_test.clj index 5cdcf74..17583ca 100644 --- a/test/fleet/fanout_test.clj +++ b/test/fleet/fanout_test.clj @@ -42,12 +42,29 @@ :jobs [(job 1 "success")] :logs {1 (jolt-log "0.7.29")}}) [:result :installed])))) -(deftest a-green-run-with-no-version-line-is-mismatch +(deftest a-green-run-with-readable-logs-and-no-version-line-is-mismatch (is (= {:result "mismatch" :installed nil} (select-keys (fanout/classify {:requested "0.8.27" :conclusion "success" - :jobs [(job 1 "success")] :logs {1 nil}}) + :jobs [(job 1 "success")] :logs {1 "no version here\n"}}) [:result :installed])))) +(deftest i1-a-green-run-whose-logs-cannot-be-read-is-infra-never-mismatch + (testing "nil logs" + (is (= {:result "infra" :cause :logs :failed-step "could not read logs" :installed nil} + (select-keys (fanout/classify {:requested "0.8.27" :conclusion "success" + :jobs [(job 1 "success")] :logs {1 nil}}) + [:result :cause :failed-step :installed])))) + (testing "one job unreadable and the other on the wrong jolt: the unreadable one may have matched" + (is (= "infra" (:result (fanout/classify {:requested "0.8.27" :conclusion "success" + :jobs [(job 1 "success") (job 2 "success")] + :logs {1 nil 2 (jolt-log "0.7.29")}}))))) + (testing "one job unreadable but another matches (R4): pass" + (is (= "pass" (:result (fanout/classify {:requested "0.8.27" :conclusion "success" + :jobs [(job 1 "success") (job 2 "success")] + :logs {1 nil 2 (jolt-log "0.8.27")}}))))) + (testing "no jobs listed at all" + (is (= "infra" (:result (fanout/classify {:requested "0.8.27" :conclusion "success" :jobs [] :logs {}})))))) + (deftest nightly-needs-the-vnightly-sha-prefix (let [base {:requested "nightly" :conclusion "success" :jobs [(job 1 "success")] :logs {1 nightly-log}}] (is (= {:result "pass" :installed "0.8.27-241-gdd3c4a4b"} @@ -109,9 +126,16 @@ 2 (fixture "log-test-failure.txt")}}) [:result :cause :failed-step])))) +(deftest r37-cancelled-startup-failure-and-action-required-are-not-run + (doseq [c ["cancelled" "startup_failure" "action_required"]] + (testing c + (is (= {:result "not-run" :failed-step nil :detail c} + (select-keys (fanout/classify {:requested "0.8.27" :conclusion c :jobs [] :logs {}}) + [:result :failed-step :detail])))))) + (deftest other-conclusions-are-fail-without-a-step - (is (= {:result "fail" :failed-step nil :detail "cancelled"} - (select-keys (fanout/classify {:requested "0.8.27" :conclusion "cancelled" :jobs [] :logs {}}) + (is (= {:result "fail" :failed-step nil :detail "timed_out"} + (select-keys (fanout/classify {:requested "0.8.27" :conclusion "timed_out" :jobs [] :logs {}}) [:result :failed-step :detail])))) ;; --------------------------------------------------------------------------- @@ -150,6 +174,17 @@ (is (str/includes? md "package-registry problem")) (is (not (str/includes? md "All "))))) +(deftest summary-says-why-a-run-did-not-answer + (let [md (fanout/summary-md + {:version "0.8.27" + :projects [(row "c" "not-run" :detail "cancelled") + (row "l" "infra" :cause :logs)]})] + (is (str/includes? md "| `c` | not run (cancelled) |")) + (is (str/includes? md "| `l` | **could not read the run's logs** |")) + (is (str/includes? md "**Could not read the logs of a green run for:** l\n")) + (is (not (str/includes? md "Could not install"))) + (is (not (str/includes? md "Broken by jolt"))))) + (deftest summary-mismatch-without-a-version (is (str/includes? (fanout/summary-md {:version "1" :projects [(row "m" "mismatch")]}) "**WRONG JOLT** (ran no version found)"))) @@ -198,8 +233,8 @@ :sleep (fn [ms] (swap! sleeps conj ms)) :now (constantly "2026-11-20T03:00:00Z")})) -(defn- env-for [dir] - (let [m {"GH_TOKEN" "tok" "RUNNER_TEMP" dir +(defn- env-for [dir & [token]] + (let [m {"GH_TOKEN" (or token "tok") "RUNNER_TEMP" dir "GITHUB_STEP_SUMMARY" (str dir "/summary.md") "GITHUB_OUTPUT" (str dir "/output.txt") "GITHUB_SERVER_URL" "https://github.com" "GITHUB_REPOSITORY" "jlt-commons/ci-builds" "GITHUB_RUN_ID" "999"}] @@ -207,13 +242,13 @@ (defn- tmp [] (str (fs/create-temp-dir))) -(defn- run-fake [world version] +(defn- run-fake [world version & {:keys [token]}] (let [dir (tmp) out (java.io.StringWriter.) err (java.io.StringWriter.) rc (binding [*out* out *err* err] (fanout/run! (assoc (select-keys world [:gh :sh :sleep :now]) - :version version :projects ["alpha" "beta"] :env (env-for dir))))] + :version version :projects ["alpha" "beta"] :env (env-for dir token))))] {:rc rc :dir dir :stdout (str out) :stderr (str err) :results (json/parse-string (slurp (str dir "/fanout-results/results.json")) true) :summary (slurp (str dir "/summary.md")) @@ -287,19 +322,48 @@ r (run-fake w "0.8.27") b (second (:projects (:results r)))] (is (= 1 (:rc r))) - (is (= {:result "dispatch-failed" :run_url nil :finished_at nil} (select-keys b [:result :run_url :finished_at]))) + (is (= {:result "dispatch-failed" :run_url nil :finished_at nil :failed_step "HTTP 422"} + (select-keys b [:result :run_url :finished_at :failed_step]))) + (is (str/includes? (:stdout r) "\n HTTP 422\n")) (is (not-any? #(and (= :get (first %)) (str/includes? (second %) "beta")) @(:calls w))))) -(deftest run-gives-up-after-150-polls-as-timed-out - (let [w (fake-world {:runs {"alpha" [{:status "in_progress"}] "beta" [ok-run]} - :jobs {"beta" [(job 2 "success")]} - :logs {2 (jolt-log "0.8.27")}}) +(defn- with-clock + "The world with a fake clock that only sleep advances, so a test can watch + the wall-clock deadline pass without waiting. Returns [world clock-atom]." + [w] + (let [t (atom (.toEpochMilli (java.time.Instant/parse "2026-11-20T03:00:00Z")))] + [(assoc w + :sleep (fn [ms] (swap! (:sleeps w) conj ms) (swap! t + ms)) + :now (fn [] (str (java.time.Instant/ofEpochMilli @t)))) + t])) + +(deftest i5-run-gives-up-45-minutes-after-dispatch-and-marks-the-rest-timed-out + (let [[w t] (with-clock (fake-world {:runs {"alpha" [{:status "in_progress"}] "beta" [ok-run]} + :jobs {"beta" [(job 2 "success")]} + :logs {2 (jolt-log "0.8.27")}})) r (run-fake w "0.8.27")] (is (= 1 (:rc r))) - (is (= 150 (count @(:sleeps w)))) - (is (= ["timed-out" "pass"] (mapv :result (:projects (:results r))))) + (testing "20s sleeps until 45 minutes have passed: 2700s / 20s" + (is (= 135 (count @(:sleeps w)))) + (is (= (* 45 60 1000) (- @t (.toEpochMilli (java.time.Instant/parse "2026-11-20T03:00:00Z")))))) + (testing "what finished is written, the rest is timed-out" + (is (= ["timed-out" "pass"] (mapv :result (:projects (:results r)))))) (is (str/includes? (:summary r) "| `alpha` | **FAIL** (timed-out) |")))) +(deftest i5-a-slow-poll-pass-costs-time-not-iterations + (testing "each pass takes 10 minutes of wall clock (a slow log read), so the deadline is hit after 5 passes" + (let [[w t] (with-clock (fake-world {:runs {"alpha" [{:status "in_progress"}] "beta" [ok-run]} + :jobs {"beta" [(job 2 "success")]} + :logs {2 (jolt-log "0.8.27")}})) + w (update w :gh assoc :get-json + (let [base (:get-json (:gh w))] + (fn [path] + (when (str/includes? path "/alpha/actions/runs/101") (swap! t + (* 10 60 1000))) + (base path)))) + r (run-fake w "0.8.27")] + (is (= 4 (count @(:sleeps w)))) + (is (= ["timed-out" "pass"] (mapv :result (:projects (:results r)))))))) + (deftest run-without-a-printed-url-warns-and-takes-the-newest-dispatch-run (let [w (fake-world {:print-url? false :runs {"alpha" [ok-run] "beta" [ok-run]} @@ -391,3 +455,56 @@ :jobs [{:id 1 :conclusion "failure" :steps 42} {:id 2 :conclusion "failure" :steps [{:conclusion "failure"}]}] :logs {1 "x" 2 "x"}}))))) + +(deftest i1-a-log-that-fails_once_is_read_again_and_the_run_passes + (let [w (fake-world {:runs {"alpha" [ok-run] "beta" [ok-run]} + :jobs {"alpha" [(job 1 "success")] "beta" [(job 2 "success")]} + :logs {1 (jolt-log "0.8.27") 2 (jolt-log "0.8.27")}}) + fails (atom 0) + w (update w :gh assoc :get-redirected-log + (let [base (:get-redirected-log (:gh w))] + (fn [path] + (if (and (str/includes? path "/jobs/1/") (< @fails 1)) + (do (swap! fails inc) (throw (ex-info "flaky" {:status 502}))) + (base path))))) + r (run-fake w "0.8.27")] + (is (= 0 (:rc r))) + (is (= ["pass" "pass"] (mapv :result (:projects (:results r))))) + (is (= 1 @fails)))) + +(deftest i1-a-log-that-stays-unreadable-is-infra-not-mismatch + (let [w (fake-world {:runs {"alpha" [ok-run] "beta" [ok-run]} + :jobs {"alpha" [(job 1 "success")] "beta" [(job 2 "success")]} + :logs {1 :fail 2 (jolt-log "0.8.27")}}) + r (run-fake w "0.8.27") + a (first (:projects (:results r)))] + (is (= 1 (:rc r))) + (is (= {:result "infra" :failed_step "could not read logs"} (select-keys a [:result :failed_step]))) + (testing "the read was tried twice" + (is (= 2 (count (filter #(= [:log "repos/jlt-commons/alpha/actions/jobs/1/logs"] %) @(:calls w)))))) + (is (str/includes? (:output r) "failed=\ninfra=alpha\n")))) + +(deftest r33-a-dispatch-error-line-is-printed-indented-and-never-leaks-the-token + (let [token "ghs_s3cr3tT0ken" + w (fake-world {:dispatch {"beta" :fail} + :runs {"alpha" [ok-run]} + :jobs {"alpha" [(job 1 "success")]} + :logs {1 (jolt-log "0.8.27")}}) + ;; gh does not print its token, but a hostile first line that starts + ;; with a workflow command and echoes it must still do neither. + w (assoc w :sh (let [base (:sh w)] + (fn [args env] + (if (str/includes? (nth args 5) "beta") + {:exit 1 :out "" + :err (str "::set-output name=x::y token " (get env "GH_TOKEN") "\nsecond line\n")} + (base args env))))) + r (run-fake w "0.8.27" :token token) + b (second (:projects (:results r)))] + (testing "indented two spaces, so it cannot start a workflow command" + (is (some #(= " ::set-output name=x::y token ***" %) (str/split-lines (:stdout r)))) + (is (not-any? #(str/starts-with? % "::set-output") (str/split-lines (:stdout r))))) + (testing "first line only, in the row" + (is (= "::set-output name=x::y token ***" (:failed_step b)))) + (testing "the token is nowhere in the output" + (doseq [text [(:stdout r) (:stderr r) (:summary r) (:output r) (json/generate-string (:results r))]] + (is (not (str/includes? text token))))))) From b97fb2198a131589ce8e9ec9ecbab1b7341c1bc2 Mon Sep 17 00:00:00 2001 From: burinc Date: Fri, 20 Nov 2026 16:34:37 +1100 Subject: [PATCH 27/31] status: an unreadable read keeps the previous cell and reason, and a 6h heartbeat keeps generated_at moving - I3/R38: collectors mark unreadable rows; build carries the previous pin cell and pin with no history entry, and uncovered rows keep their previous reason; pass, outage, pass, pass leaves no bogus not-run in the pin history - I4/R39: an unchanged status is still published once the previous generated_at is 6h old; canary.yml comment corrected --- .github/workflows/canary.yml | 8 +++-- src/fleet/collect.clj | 28 ++++++++++++---- src/fleet/status.clj | 64 ++++++++++++++++++++++++++++-------- test/fleet/collect_test.clj | 21 ++++++++++-- test/fleet/publish_test.clj | 41 ++++++++++++++++++----- test/fleet/status_test.clj | 64 ++++++++++++++++++++++++++++++++++-- 6 files changed, 191 insertions(+), 35 deletions(-) diff --git a/.github/workflows/canary.yml b/.github/workflows/canary.yml index daf0c6e..4615a22 100644 --- a/.github/workflows/canary.yml +++ b/.github/workflows/canary.yml @@ -21,8 +21,12 @@ name: canary # # Every run also ends with the `status` job, which merges the results into # status.json and history.json on the `status` branch. The fleet page reads -# those two files. A gated tick still runs it, so the pin column and the -# dashboard's timestamp keep moving while jolt stands still. +# those two files. A gated tick still runs it, so the pin column keeps up with +# each project's own CI while jolt stands still. Publishing commits only when +# the content changed, or when the last commit is 6 or more hours old (a +# heartbeat, about 4 commits a day), so the dashboard's generated_at moves at +# least that often and its 12 hour staleness banner fires only when the canary +# has really stopped. # # vars.CANARY_INTERVAL_HOURS (default 0, no interval gate) holds a scheduled # tick back. The cron itself cannot be a variable, GitHub requires a literal. diff --git a/src/fleet/collect.clj b/src/fleet/collect.clj index 7af3c48..3800bcc 100644 --- a/src/fleet/collect.clj +++ b/src/fleet/collect.clj @@ -3,7 +3,9 @@ pin, and the org repos the fleet does not cover. gh is a map of the fleet.github fns ({:get-json :get-raw :get-paginated}), so tests stub it. Any failure to read one repo degrades that repo's row and warns on stderr; - it never aborts the collection." + it never aborts the collection. A row whose read failed carries + :unreadable true (R38), which tells the status build to keep that project's + previous cell or reason instead of recording the outage as a result." (:require [clojure.string :as str] [fleet.version :as version] [jolt.yaml :as yaml])) @@ -24,6 +26,12 @@ (defn- run-row [name pin result run-url at step] {:name name :pin pin :result result :run_url run-url :finished_at at :failed_step step}) +(defn- unreadable-row + "A row for a project whose run could not be read: not-run, and marked so the + build does not mistake the outage for a result." + [name pin] + (assoc (run-row name pin "not-run" nil nil nil) :unreadable true)) + (defn- conclusion->result [conclusion] (case conclusion "success" "pass" @@ -50,7 +58,7 @@ (warn "collect-own-pin" p "could not read repository:" (explain e)) nil))] (if-not branch - (run-row p nil "not-run" nil nil nil) + (unreadable-row p nil) (let [pin (try (version/parse-pin ((:get-raw gh) (ci-path p))) (catch Exception e (warn "collect-own-pin" p "could not read ci.yml:" (explain e)) @@ -64,7 +72,7 @@ (warn "collect-own-pin" p "could not list runs:" (explain e)) ::failed))] (cond - (= ::failed runs) (run-row p pin "not-run" nil nil nil) + (= ::failed runs) (unreadable-row p pin) (empty? runs) (run-row p pin "not-run" nil nil nil) :else (let [r (first runs) @@ -89,7 +97,10 @@ (def ^:private unreadable "could not read repository") -(defn- reason-for [gh fleet p] +(defn- reason-for + "The uncovered reason for repo p, nil when it is covered. A string, or the + keyword ::unreadable when the repository could not be read at all (R38)." + [gh fleet p] (let [in-fleet? (boolean (some #{p} (:projects fleet))) excluded (get (:excluded fleet) (keyword p))] (if (or in-fleet? (seq excluded)) @@ -101,7 +112,7 @@ (do (warn "collect-uncovered" p unreadable ":" (explain e)) {:error true}))))] (cond - (:error ci) unreadable + (:error ci) ::unreadable (:missing ci) (version/uncovered-reason {:has-ci? false}) :else (try (version/uncovered-reason {:has-ci? true :has-input? (has-input? (yaml/load (:text ci)))}) @@ -111,11 +122,14 @@ (defn uncovered "Public, non-archived org repos the fleet does not cover, each with a - reason: [{:name :reason}]." + reason: [{:name :reason}]. A repo that could not be read has the reason + \"could not read repository\" and :unreadable true (R38)." [gh fleet] (->> ((:get-paginated gh) (str "orgs/" org "/repos?type=public")) (filter #(and (not (:archived %)) (not (:private %)))) (keep (fn [{:keys [name]}] (when-let [r (reason-for gh fleet name)] - {:name name :reason r}))) + (if (= ::unreadable r) + {:name name :reason unreadable :unreadable true} + {:name name :reason r})))) vec)) diff --git a/src/fleet/status.clj b/src/fleet/status.clj index 410ba94..035f92d 100644 --- a/src/fleet/status.clj +++ b/src/fleet/status.clj @@ -68,7 +68,12 @@ "Merge into {:status m :history m}. Keys of the input map: :prev-status, :prev-history (nil when absent), :own-pin, :uncovered, :latest, :nightly (a map, or nil to keep the previous one, R22), :canary-run, :now, :results - (a seq of fan-out results maps). Throws ex-info on malformed input." + (a seq of fan-out results maps). Throws ex-info on malformed input. + + An own-pin row marked :unreadable (R38) could not be read this time. The + project keeps its previous pin cell and pin, and the outage adds no pin + history entry, so a GitHub blip never shows as a not-run result. The same + goes for an uncovered row marked :unreadable: it keeps its previous reason." [{:keys [prev-status prev-history own-pin uncovered latest nightly canary-run now results] :as in}] (validate! in) @@ -83,6 +88,10 @@ nightly-stale? (and (some? nightly) (not= (get-in prev-status [:jolt :nightly :sha]) (:sha nightly))) prev-cells (into {} (map (juxt :name :cells)) (:projects prev-status)) + prev-pins (into {} (map (juxt :name :pin)) (:projects prev-status)) + prev-reasons (into {} (map (juxt :name :reason)) (:uncovered prev-status)) + carry-pin? (fn [p] (and (:unreadable p) (contains? prev-cells (:name p)) + (get-in prev-cells [(:name p) :pin]))) fresh (reduce (fn [m {:keys [name col cell]}] (if (= col :adhoc) m (assoc m [name col] cell))) {} res) @@ -91,23 +100,26 @@ (if stale? (not-run) (or (get-in prev-cells [n c]) (not-run))))) projects (vec (for [p own-pin] {:name (:name p) - :pin (:pin p) - :cells {:pin {:result (:result p) - :version (:pin p) - :installed nil - :run_url (:run_url p) - :finished_at (:finished_at p) - :failed_step (:failed_step p)} + :pin (if (carry-pin? p) (get prev-pins (:name p)) (:pin p)) + :cells {:pin (or (carry-pin? p) + {:result (:result p) + :version (:pin p) + :installed nil + :run_url (:run_url p) + :finished_at (:finished_at p) + :failed_step (:failed_step p)}) :latest (pick (:name p) :latest latest-stale?) :nightly (pick (:name p) :nightly nightly-stale?)}})) sorted (vec (sort-by (fn [p] [(if (bad? p) 0 1) (:name p)]) projects)) prev-hist (:projects prev-history) + unreadable (into #{} (comp (filter :unreadable) (map :name)) own-pin) pin-entries (for [p projects :let [pin-hist (get-in prev-hist [(keyword (:name p)) :pin]) cell (get-in p [:cells :pin])] - :when (or (not= (or (:run_url (first pin-hist)) "__none__") - (or (:run_url cell) "__none__")) - (empty? pin-hist))] + :when (and (not (contains? unreadable (:name p))) + (or (not= (or (:run_url (first pin-hist)) "__none__") + (or (:run_url cell) "__none__")) + (empty? pin-hist)))] {:name (:name p) :col :pin :cell cell}) hist (reduce add-entry (or prev-hist {}) (concat res pin-entries)) hist (into {} (map (fn [[k v]] @@ -119,12 +131,36 @@ :jolt {:latest {:version latest} :nightly (or nightly (get-in prev-status [:jolt :nightly]))} :projects sorted - :uncovered (vec uncovered)} + :uncovered (mapv (fn [u] + {:name (:name u) + :reason (if (and (:unreadable u) (contains? prev-reasons (:name u))) + (get prev-reasons (:name u)) + (:reason u))}) + uncovered)} :history {:schema 1 :projects hist}})) +(def heartbeat-hours + "R39: a status whose content has not moved is still published once its + previous generated_at is this old." + 6) + +(defn- heartbeat-due? + "True when old-status was generated heartbeat-hours or more before + new-status. Unparseable timestamps are due: publishing is the safe side." + [old-status new-status] + (let [ms (fn [s] (try (.toEpochMilli (java.time.Instant/parse (:generated_at s))) + (catch Exception _ nil))) + a (ms old-status) + b (ms new-status)] + (or (nil? a) (nil? b) (>= (- b a) (* heartbeat-hours 3600 1000))))) + (defn unchanged? "R12: two statuses are the same when they differ only in generated_at and - canary_run." + canary_run, unless the old one is heartbeat-hours or more older than the new + one (R39). The heartbeat keeps generated_at moving, about 4 commits a day, + so the page's 12 hour staleness banner fires only when the canary has + really stopped." [old-status new-status] (let [norm #(dissoc % :generated_at :canary_run)] - (= (norm old-status) (norm new-status)))) + (and (= (norm old-status) (norm new-status)) + (not (heartbeat-due? old-status new-status))))) diff --git a/test/fleet/collect_test.clj b/test/fleet/collect_test.clj index 5cb0e8e..90a166d 100644 --- a/test/fleet/collect_test.clj +++ b/test/fleet/collect_test.clj @@ -107,11 +107,24 @@ (deftest own-pin-failing-api-is-not-run-warns-and-does-not-abort (let [[rows err] (warnings-of #(own* (world)))] (is (= {:name "ghost" :pin nil :result "not-run" - :run_url nil :finished_at nil :failed_step nil} + :run_url nil :finished_at nil :failed_step nil :unreadable true} (by-name rows "ghost"))) (is (str/includes? err "ghost")) (is (= 4 (count rows))))) +(deftest r38-own-pin-marks-only-reads-that-failed-as-unreadable + (testing "a project with no completed push run is a real not-run" + (is (not (:unreadable (by-name (own (world)) "glitter-uikit"))))) + (testing "a failing run list is unreadable and keeps the pin it did read" + (let [w (-> (world) + (assoc-in [:branch "zz"] "main") + (assoc-in [:ci "zz"] "name: ci\nenv:\n JOLT_VERSION: \"0.8.24\"\n")) + row (by-name (own w {:projects ["zz"] :excluded {}}) "zz")] + (is (true? (:unreadable row))) + (is (= "not-run" (:result row))))) + (testing "a readable row carries no marker" + (is (not (contains? (by-name (own (world)) "glitter") :unreadable))))) + (deftest own-pin-conclusion-mapping (doseq [[conclusion result] [["success" "pass"] ["failure" "fail"] ["timed_out" "timed-out"] ["cancelled" "not-run"] ["skipped" "not-run"] @@ -135,7 +148,7 @@ :else (throw (not-found path))))) [rows err] (warnings-of #(collect/own-pin gh {:projects ["glitter-gl"] :excluded {}}))] (is (= [{:name "glitter-gl" :pin "0.8.24" :result "not-run" - :run_url nil :finished_at nil :failed_step nil}] + :run_url nil :finished_at nil :failed_step nil :unreadable true}] rows)) (is (str/includes? err "glitter-gl")))) @@ -153,6 +166,10 @@ (deftest uncovered-unreadable-repo-gets-a-reason-and-a-warning (let [[rows err] (warnings-of #(unc* (world)))] (is (= "could not read repository" (:reason (by-name rows "brokenrepo")))) + (is (true? (:unreadable (by-name rows "brokenrepo")))) + (is (true? (:unreadable (by-name rows "ratelimited")))) + (testing "an unparsable ci.yml is a content problem, not an outage" + (is (not (:unreadable (by-name rows "badyaml"))))) (is (str/includes? err "brokenrepo")))) (deftest uncovered-on-key-parsed-as-boolean-true-still-finds-the-input diff --git a/test/fleet/publish_test.clj b/test/fleet/publish_test.clj index 55a1d07..722cede 100644 --- a/test/fleet/publish_test.clj +++ b/test/fleet/publish_test.clj @@ -4,7 +4,7 @@ (:require [babashka.fs :as fs] [cheshire.core :as json] [clojure.string :as str] - [clojure.test :refer [deftest is]] + [clojure.test :refer [deftest is testing]] [fleet.publish :as publish])) (defn- git @@ -37,14 +37,22 @@ (defn- write-json! [path m] (spit path (json/generate-string m))) +(defn- rebuild-at + "A rebuild that writes the same content each time except generated_at (the + given ISO instant) and canary_run." + [generated-at] + (fn [{:keys [out-dir]}] + (fs/create-dirs out-dir) + (write-json! (str out-dir "/status.json") + {:schema 1 :generated_at generated-at :canary_run (str "run-" (System/nanoTime)) + :projects ["a"]}) + (write-json! (str out-dir "/history.json") {:schema 1 :adhoc []}))) + (defn- rebuild-fixed - "Writes the same content each time except generated_at and canary_run." - [{:keys [out-dir]}] - (fs/create-dirs out-dir) - (write-json! (str out-dir "/status.json") - {:schema 1 :generated_at (str (System/nanoTime)) :canary_run (str "run-" (System/nanoTime)) - :projects ["a"]}) - (write-json! (str out-dir "/history.json") {:schema 1 :adhoc []})) + "Same content each time, generated_at is the current instant (seconds + apart, well inside the heartbeat)." + [dirs] + ((rebuild-at (str (java.time.Instant/now))) dirs)) (defn- pub [{:keys [work out]} rebuild] (publish/publish! {:repo-dir work :out-dir out :rebuild rebuild :sh publish/sh})) @@ -73,6 +81,23 @@ (is (= :unchanged (:result res))) (is (= before (remote-head r))))) +(deftest r39-heartbeat-publishes-an-unchanged-status-once-it-is-6h-old + (testing "5h59m59s later: still unchanged" + (let [r (repo) + _ (pub r (rebuild-at "2026-11-20T00:00:00Z")) + before (remote-head r) + res (pub r (rebuild-at "2026-11-20T05:59:59Z"))] + (is (= :unchanged (:result res))) + (is (= before (remote-head r))))) + (testing "exactly 6h later: a commit that only moves generated_at" + (let [r (repo) + _ (pub r (rebuild-at "2026-11-20T00:00:00Z")) + before (remote-head r) + res (pub r (rebuild-at "2026-11-20T06:00:00Z"))] + (is (= :published (:result res))) + (is (not= before (remote-head r))) + (is (= "2026-11-20T06:00:00Z" (:generated_at (remote-show r "status.json"))))))) + (deftest commits-when-history-changes (let [r (repo) _ (pub r rebuild-fixed) diff --git a/test/fleet/status_test.clj b/test/fleet/status_test.clj index f89ff26..404ed6b 100644 --- a/test/fleet/status_test.clj +++ b/test/fleet/status_test.clj @@ -1,6 +1,6 @@ (ns fleet.status-test (:require [cheshire.core :as json] - [clojure.test :refer [deftest is]] + [clojure.test :refer [deftest is testing]] [fleet.status :as status])) (defn- fx @@ -194,11 +194,71 @@ (deftest unchanged-ignores-generated-at-and-canary-run (let [s (:status (run-bs {}))] - (is (true? (status/unchanged? s (assoc s :generated_at "2030-01-01T00:00:00Z" + (is (true? (status/unchanged? s (assoc s :generated_at "2026-11-20T05:00:00Z" :canary_run "https://example/run/2")))) (is (false? (status/unchanged? s (assoc-in s [:jolt :latest :version] "0.8.28")))) (is (false? (status/unchanged? s (assoc s :uncovered [])))))) +(deftest r39-heartbeat-both-sides-of-6h + ;; run-bs generates at 2026-11-20T04:00:00Z + (let [s (:status (run-bs {})) + at (fn [t] (assoc s :generated_at t))] + (is (true? (status/unchanged? s (at "2026-11-20T09:59:59Z")))) + (is (false? (status/unchanged? s (at "2026-11-20T10:00:00Z")))) + (is (false? (status/unchanged? s (at "2026-11-21T04:00:00Z")))) + (testing "an unparseable timestamp publishes" + (is (false? (status/unchanged? (assoc s :generated_at "soon") s)))))) + +(defn- own-row [pin result url & {:as more}] + (merge {:name "glitter" :pin pin :result result :run_url url :finished_at nil :failed_step nil} more)) + +(defn- seq-build + "Feed builds one after another, each from the previous output. rows: one + own-pin row vector per build." + [rows] + (reduce (fn [{:keys [status history]} op] + (status/build {:prev-status status :prev-history history :own-pin op + :uncovered [] :latest "0.8.27" :nightly nil + :canary-run "r" :now "2026-11-20T04:00:00Z" :results []})) + {} rows)) + +(deftest r38-outage-recovery-keeps-the-pin-cell-and-adds-no-bogus-history + (let [pass1 (own-row "0.8.24" "pass" "https://r/1") + outage (own-row nil "not-run" nil :unreadable true) + pass2 (own-row "0.8.24" "pass" "https://r/2") + step (fn [rows] (let [o (seq-build rows)] + {:cell (get-in o [:status :projects 0 :cells :pin]) + :pin (get-in o [:status :projects 0 :pin]) + :hist (mapv :result (get-in o [:history :projects :glitter :pin])) + :urls (mapv :run_url (get-in o [:history :projects :glitter :pin]))})) + after-outage (step [[pass1] [outage]])] + (testing "during the outage the previous pin cell and pin stay" + (is (= "pass" (:result (:cell after-outage)))) + (is (= "https://r/1" (:run_url (:cell after-outage)))) + (is (= "0.8.24" (:pin after-outage))) + (is (= ["https://r/1"] (:urls after-outage)))) + (testing "pass, outage, pass, pass: history is the two passes only" + (let [o (step [[pass1] [outage] [pass2] [pass2]])] + (is (= ["https://r/2" "https://r/1"] (:urls o))) + (is (= ["pass" "pass"] (:hist o))) + (is (= "https://r/2" (:run_url (:cell o)))))) + (testing "an outage on the very first build has nothing to carry and no history" + (let [o (step [[outage]])] + (is (= [] (:hist o))))))) + +(deftest r38-an-unreadable-uncovered-row-keeps-its-previous-reason + (let [prev (assoc (:status (run-bs {})) :uncovered [{:name "duratom" :reason "ci.yml has no jolt-version input"} + {:name "other" :reason "ready, not yet in fleet.json"}]) + out (status/build {:prev-status prev :prev-history nil :own-pin (fx "own-pin.json") + :uncovered [{:name "duratom" :reason "could not read repository" :unreadable true} + {:name "other" :reason "ready, not yet in fleet.json"} + {:name "newrepo" :reason "could not read repository" :unreadable true}] + :latest "0.8.27" :nightly nil :canary-run "r" :now "2026-11-20T04:00:00Z" :results []})] + (is (= [{:name "duratom" :reason "ci.yml has no jolt-version input"} + {:name "other" :reason "ready, not yet in fleet.json"} + {:name "newrepo" :reason "could not read repository"}] + (get-in out [:status :uncovered]))))) + (deftest nil-pin-is-accepted-and-the-project-still-appears ;; R26: a project with a non-literal JOLT_VERSION has pin nil. It must not ;; stop the whole dashboard from updating. From 6484977df468cd5dd319288fd3e9ffbea9c408bc Mon Sep 17 00:00:00 2001 From: burinc Date: Fri, 20 Nov 2026 16:35:30 +1100 Subject: [PATCH 28/31] workflows: report is skipped on cancel, artifact downloads cannot stop a publish, tokens are scoped, libyaml is installed only when missing - I6: report runs on !cancelled() and a proceed plan - I7: continue-on-error on the three download-artifact steps - M2: no issues: write at workflow level; the report token mints permission-issues write (plus actions read for the job names), the status and publish-adhoc tokens contents and actions read; input names read from actions/create-github-app-token v3 action.yml - M4: dpkg -s libyaml-0-2 check with apt-get update in every job that runs jolt, test.yml included --- .github/workflows/canary.yml | 28 +++++++++++++++++++++++----- .github/workflows/fanout.yml | 12 ++++++++++-- .github/workflows/test.yml | 4 ++++ 3 files changed, 37 insertions(+), 7 deletions(-) diff --git a/.github/workflows/canary.yml b/.github/workflows/canary.yml index 4615a22..58936a9 100644 --- a/.github/workflows/canary.yml +++ b/.github/workflows/canary.yml @@ -49,9 +49,10 @@ on: required: false default: "" +# Read only. The report job's App token carries issues: write, and the status +# job's own block adds contents: write, so nothing else holds either. permissions: contents: read - issues: write actions: read env: @@ -92,7 +93,8 @@ jobs: # jolt.yaml loads libyaml, which the runner image carries today. Say so # explicitly so an image change cannot break the tools silently. - - run: sudo apt-get install -y libyaml-0-2 + - run: | + dpkg -s libyaml-0-2 >/dev/null 2>&1 || { sudo apt-get update && sudo apt-get install -y libyaml-0-2; } # Latest is resolved on every event, a manual dispatch included, because # the status page shows what latest is whatever was asked for. @@ -213,7 +215,8 @@ jobs: # jolt.yaml loads libyaml, which the runner image carries today. Say so # explicitly so an image change cannot break the tools silently. - - run: sudo apt-get install -y libyaml-0-2 + - run: | + dpkg -s libyaml-0-2 >/dev/null 2>&1 || { sudo apt-get update && sudo apt-get install -y libyaml-0-2; } - name: Mint an installation token id: token @@ -222,12 +225,18 @@ jobs: client-id: ${{ secrets.APP_CLIENT_ID }} private-key: ${{ secrets.APP_PRIVATE_KEY }} owner: jlt-commons + # Cross-repo reads only: each project's ci.yml, runs and jobs. + permission-contents: read + permission-actions: read # Reusable-workflow artifacts belong to this (the caller's) run. A gated # tick has none, so the step is skipped there rather than trusting the # action to treat "no match" as success; the script copes with no results. - uses: actions/download-artifact@v8 if: needs.fleet.result != 'skipped' + # An artifact that cannot be fetched leaves its project out of this + # run's results. It must not stop the status or the issue. + continue-on-error: true with: pattern: results-* path: results @@ -251,7 +260,8 @@ jobs: report: needs: [plan, fleet] - if: always() && needs.plan.outputs.proceed == 'true' + # !cancelled() and not always(): a cancelled run must not open an issue. + if: ${{ !cancelled() && needs.plan.outputs.proceed == 'true' }} runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 @@ -267,7 +277,8 @@ jobs: # jolt.yaml loads libyaml, which the runner image carries today. Say so # explicitly so an image change cannot break the tools silently. - - run: sudo apt-get install -y libyaml-0-2 + - run: | + dpkg -s libyaml-0-2 >/dev/null 2>&1 || { sudo apt-get update && sudo apt-get install -y libyaml-0-2; } - name: Mint an installation token id: token @@ -277,11 +288,18 @@ jobs: private-key: ${{ secrets.APP_PRIVATE_KEY }} owner: jlt-commons repositories: ci-builds + # Opens, comments on and closes the canary issue, and reads this run's + # job names for the issue text. + permission-issues: write + permission-actions: read # needs.fleet.outputs.failed holds one matrix leg's value, so the verdict # is read from every leg's results file instead. - uses: actions/download-artifact@v8 if: needs.fleet.result != 'skipped' + # An artifact that cannot be fetched leaves its project out of this + # run's results. It must not stop the status or the issue. + continue-on-error: true with: pattern: results-* path: results diff --git a/.github/workflows/fanout.yml b/.github/workflows/fanout.yml index 99209f7..184757f 100644 --- a/.github/workflows/fanout.yml +++ b/.github/workflows/fanout.yml @@ -92,7 +92,8 @@ jobs: # jolt.yaml loads libyaml, which the runner image carries today. Say so # explicitly so an image change cannot break the tools silently. - - run: sudo apt-get install -y libyaml-0-2 + - run: | + dpkg -s libyaml-0-2 >/dev/null 2>&1 || { sudo apt-get update && sudo apt-get install -y libyaml-0-2; } # Mints a token scoped to the App's seven repositories, valid one hour. # Never a PAT: a PAT would act as whoever created it, and any collaborator @@ -146,7 +147,8 @@ jobs: path: ~/.jolt/gitlibs key: jolt-gitlibs-${{ hashFiles('deps.edn') }} - - run: sudo apt-get install -y libyaml-0-2 + - run: | + dpkg -s libyaml-0-2 >/dev/null 2>&1 || { sudo apt-get update && sudo apt-get install -y libyaml-0-2; } - name: Mint an installation token id: token @@ -155,8 +157,14 @@ jobs: client-id: ${{ secrets.APP_CLIENT_ID }} private-key: ${{ secrets.APP_PRIVATE_KEY }} owner: jlt-commons + # Cross-repo reads only: each project's ci.yml, runs and jobs. + permission-contents: read + permission-actions: read - uses: actions/download-artifact@v8 + # An artifact that cannot be fetched leaves its project out of the + # results. It must not stop the publish. + continue-on-error: true with: pattern: results-* path: results diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 43e4ad2..e145ac1 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -27,4 +27,8 @@ jobs: with: path: ~/.jolt/gitlibs key: jolt-gitlibs-${{ hashFiles('deps.edn') }} + # jolt.yaml loads libyaml. Install it when the runner image lacks it, so + # an image change cannot turn this red for a reason unrelated to the tree. + - run: | + dpkg -s libyaml-0-2 >/dev/null 2>&1 || { sudo apt-get update && sudo apt-get install -y libyaml-0-2; } - run: jolt test From 6b8eb8367e52c922a8cc6f9d1b1e89862650e257 Mon Sep 17 00:00:00 2001 From: burinc Date: Fri, 20 Nov 2026 16:37:13 +1100 Subject: [PATCH 29/31] docs: comments and docstrings describe current behaviour, not incidents or counts - M6: no 'seven repositories' or 'five build environments'; incident history rewritten as the rule it justifies (run ids kept where they justify one); 'our own misconfiguration' is neutral; the doubled publish-status: prefix is gone - the matrix comment no longer says cancelled reads as a failure (R37) --- .github/workflows/canary.yml | 30 ++++++++++-------------------- .github/workflows/fanout.yml | 26 ++++++++++++++------------ src/fleet/canary.clj | 17 ++++++++--------- src/fleet/fanout.clj | 31 ++++++++++++++++--------------- src/fleet/publish.clj | 8 ++++---- test/fleet/publish_test.clj | 6 ++++++ 6 files changed, 58 insertions(+), 60 deletions(-) diff --git a/.github/workflows/canary.yml b/.github/workflows/canary.yml index 58936a9..51ae8a2 100644 --- a/.github/workflows/canary.yml +++ b/.github/workflows/canary.yml @@ -154,26 +154,16 @@ jobs: strategy: fail-fast: false # ONE version at a time. Each leg's fan-out dispatches every project's - # own ci.yml on `main`, and with both legs in flight together - # that is two near-simultaneous workflow_dispatch calls - # against the SAME project on the SAME ref. raylib-ios's concurrency - # group cancels unconditionally (`cancel-in-progress: true`, no ref - # guard), so its earlier dispatches die within a couple of seconds of - # the next one starting - reproduced 2026-09-05, run 33999584713: - # raylib-ios cancelled (not failed) in both the nightly and 0.8.1 legs, - # created and cancelled a mere 2-3s apart. glitter-gl's own dispatch - # was cancelled the same run despite ITS concurrency group being - # ref-guarded false on main, same instant cancellation pattern (2s), - # so something outside any one project's own workflow file also - # collides two of these together, not only raylib-ios's config. - # Either way, `fanout.yml` treats a "cancelled" conclusion the same as - # a genuine build failure and reports "jolt breaks the fleet" (issue - # #5) for a version nothing actually failed against - every leg that - # finished normally that run was green. max-parallel: 1 removes the - # race outright: legs run one after another, so no project is ever - # dispatched twice at once. Costs wall-clock (up to ~2x on a run that - # tests both rows), not correctness, and the concurrency group keeps - # overlapping ticks from stacking up. + # own ci.yml on `main`, and two legs in flight together would dispatch + # the SAME project on the SAME ref twice within seconds. A project whose + # concurrency group cancels in progress (raylib-ios does, with no ref + # guard) then loses the earlier run: in run 33999584713 it was cancelled + # in both the nightly and 0.8.1 legs, 2-3s after being created. + # max-parallel: 1 runs the legs one after another, so no project is + # dispatched twice at once. It costs wall-clock (up to ~2x on a run that + # tests both rows) and nothing else. The concurrency group keeps + # overlapping ticks from stacking up, and a run that is cancelled anyway + # reads not-run in fan-out, never fail (R37). max-parallel: 1 matrix: version: ${{ fromJSON(needs.plan.outputs.versions) }} diff --git a/.github/workflows/fanout.yml b/.github/workflows/fanout.yml index 184757f..21c4e4f 100644 --- a/.github/workflows/fanout.yml +++ b/.github/workflows/fanout.yml @@ -8,21 +8,22 @@ name: fan-out # how to build it (raygui needs raylib natives, glitter-uikit needs AppKit and # GTK4, glitter-gl needs a GL context under Xvfb, raylib-ios runs its pure # scenes under jolt on Linux because its real target is a phone), and every one -# of them -# accepts a `jolt-version` dispatch input that overrides its pinned +# of them accepts a `jolt-version` dispatch input that overrides its pinned # JOLT_VERSION for a single run. So this workflow dispatches those and collects -# the answers. Reimplementing five build environments here would rot, and would -# test something other than what a contributor actually hits. +# the answers. Reimplementing every project's build environment here would +# rot, and would test something other than what a contributor actually hits. # # Auth is the jlt-commons-ci GitHub App rather than a PAT, so a run is # attributed to the App and not to whoever pressed the button, and the token it -# mints lives for an hour and reaches exactly seven repositories. +# mints lives for an hour and reaches only the repositories the App is +# installed on. # -# Why this exists: jolt v0.8.0 published 2026-09-01 and reversed -# jolt.ffi/write's last two arguments (jolt-lang/jolt#802). Both spellings are -# plain integers, so a mismatch writes to the wrong address and reports -# nothing. Finding that out one repository at a time, days apart, is the thing -# this workflow is meant to replace. +# Why this exists: a jolt release can change an API without any error. v0.8.0 +# reversed jolt.ffi/write's last two arguments (jolt-lang/jolt#802), and both +# spellings are plain integers, so a mismatch writes to the wrong address and +# reports nothing. One run over the whole fleet shows that on the day it +# happens, not one repository at a time days later. The loop and its rules are +# in src/fleet/fanout.clj. # --------------------------------------------------------------------------- on: @@ -43,7 +44,7 @@ on: description: "Space-separated projects that did not pass" value: ${{ jobs.fanout.outputs.failed }} infra: - description: "Space-separated projects whose jolt could not be installed at all" + description: "Space-separated projects whose failure is not about jolt (install, dependency download, unreadable logs)" value: ${{ jobs.fanout.outputs.infra }} version: description: "The jolt version actually tested" @@ -95,7 +96,8 @@ jobs: - run: | dpkg -s libyaml-0-2 >/dev/null 2>&1 || { sudo apt-get update && sudo apt-get install -y libyaml-0-2; } - # Mints a token scoped to the App's seven repositories, valid one hour. + # Mints a token scoped to the repositories the App is installed on, valid + # one hour. # Never a PAT: a PAT would act as whoever created it, and any collaborator # able to run this workflow would be borrowing that identity. - name: Mint an installation token diff --git a/src/fleet/canary.clj b/src/fleet/canary.clj index 2f295a7..9904a26 100644 --- a/src/fleet/canary.clj +++ b/src/fleet/canary.clj @@ -23,13 +23,12 @@ NOT A DUPLICATE. Fresh is necessary and not sufficient. jolt tags vnightly at whatever main was when the nightly job ran, and that is regularly the - release tag itself (measured 2026-09-02: vnightly and v0.8.1 both pointed - at one commit, three hours old, while main had moved 7 commits past it). - A row built from the same commit as a release row is the same data point - rendered twice. The commits are compared live, by tag, because a recorded - SHA is a label that can be orphaned: jolt force-pushed main on 2026-09-03 - and moved both 0.8.x tags, and `git rev-parse` still answers cheerfully - from a local object store for a commit upstream no longer has. + release tag's own commit, even when main has moved on since. A row built + from the same commit as a release row is the same data point rendered + twice. The commits are compared live, by tag, because a recorded SHA is a + label that can be orphaned: after a force-push of main that moves the tags, + `git rev-parse` still answers from a local object store for a commit + upstream no longer has. TWO GATES keep a 15-minute tick cheap. The interval gate holds a scheduled tick back until that many hours have passed since a canary last BUILT @@ -332,8 +331,8 @@ (str "Recovered. The fleet builds against " versions ". " nightly ". [Run](" run-url ") Dashboard: " dashboard) - ;; A failure that is really our own misconfiguration or a registry - ;; outage is not filed as a fact about jolt. + ;; A failure caused by the environment (the install source, a package + ;; registry, dispatch access) is not filed as a fact about jolt. infra? (lines (str "Infra problems, not findings about jolt: " infra-text) "" diff --git a/src/fleet/fanout.clj b/src/fleet/fanout.clj index 55ac80b..aaa9d6a 100644 --- a/src/fleet/fanout.clj +++ b/src/fleet/fanout.clj @@ -8,24 +8,25 @@ its pure scenes under jolt on Linux because its real target is a phone), and every one of them accepts a `jolt-version` dispatch input that overrides its pinned JOLT_VERSION for a single run. So this dispatches those and - collects the answers. Reimplementing five build environments here would - rot, and would test something other than what a contributor actually hits. + collects the answers. Reimplementing every project's build environment + here would rot, and would test something other than what a contributor + actually hits. - Why it exists: jolt v0.8.0 reversed jolt.ffi/write's last two arguments - (jolt-lang/jolt#802). Both spellings are plain integers, so a mismatch - writes to the wrong address and reports nothing. Finding that out one - repository at a time, days apart, is what this replaces. + Why it exists: a jolt release can change an API without any error. v0.8.0 + reversed jolt.ffi/write's last two arguments (jolt-lang/jolt#802), and both + spellings are plain integers, so a mismatch writes to the wrong address and + reports nothing. One run over the whole fleet shows that on the day it + happens, not one repository at a time days later. Run ids come from gh's own output. `gh workflow run` prints the URL of the - run it created, so the id is READ from that. The guess this replaced was - \"the newest workflow_dispatch run above a baseline recorded before - dispatching\", a positive control that always returns a plausible id. It - failed for real: canary run 33682325150 ran two fan-out legs at once, 0.8.0 - and 0.8.1, and BOTH claimed glitter run 33682354193, though gh had printed - 33682349678 to the 0.8.1 leg. The 0.8.1 row reported a result for a build - of 0.8.0. Reading gh's output holds however many fan-outs overlap. Only an - older gh that prints no URL falls back to the newest workflow_dispatch run, - with a ::warning:: saying the attribution is a guess. + run it created, so the id is READ from that. Guessing \"the newest + workflow_dispatch run above a baseline recorded before dispatching\" always + returns a plausible id, so it cannot tell when it is wrong: in canary run + 33682325150 two overlapping fan-out legs both claimed glitter run + 33682354193, and the 0.8.1 row reported a build of 0.8.0. Reading gh's + output holds however many fan-outs overlap. Only an older gh that prints no + URL falls back to the newest workflow_dispatch run, with a ::warning:: + saying the attribution is a guess. Result classes, all per project: - pass: the run succeeded and a job installed the requested jolt (R4: ANY diff --git a/src/fleet/publish.clj b/src/fleet/publish.clj index 630e649..64cfdb2 100644 --- a/src/fleet/publish.clj +++ b/src/fleet/publish.clj @@ -48,7 +48,7 @@ 2 (do (git! sh repo-dir "worktree" "add" "--quiet" "--detach" wt "HEAD") (git! sh wt "checkout" "--quiet" "--orphan" "status") (git! sh wt "rm" "-rfq" ".")) - (throw (ex-info (str "publish-status: cannot reach origin (ls-remote exit " rc ")") + (throw (ex-info (str "cannot reach origin (ls-remote exit " rc ")") {:exit rc}))))) (defn- unchanged? @@ -72,7 +72,7 @@ (open-worktree! sh repo-dir wt prev) (rebuild {:prev-dir prev :out-dir out}) (when-not (and (fs/exists? (str out "/status.json")) (fs/exists? (str out "/history.json"))) - (throw (ex-info (str "publish-status: rebuild did not write both files in " out) {}))) + (throw (ex-info (str "rebuild did not write both files in " out) {}))) (if (unchanged? out wt) :unchanged (do (fs/copy (str out "/status.json") (str wt "/status.json") {:replace-existing true}) @@ -99,7 +99,7 @@ :attempt n} or {:result :unchanged}; throws after 3 rejected pushes." [{:keys [out-dir rebuild] :as opts}] (when-not rebuild - (throw (ex-info "publish-status: rebuild is required" {}))) + (throw (ex-info "rebuild is required" {}))) (fs/create-dirs out-dir) (let [out (str (fs/canonicalize out-dir)) tmp (str (fs/create-temp-dir))] @@ -111,6 +111,6 @@ (= :published r) {:result :published :attempt n} (< n attempts) (do (warn (str "push rejected on attempt " n ", retrying")) (recur (inc n))) - :else (throw (ex-info (str "publish-status: gave up after " attempts " rejected pushes") + :else (throw (ex-info (str "gave up after " attempts " rejected pushes") {:attempts attempts}))))) (finally (fs/delete-tree tmp))))) diff --git a/test/fleet/publish_test.clj b/test/fleet/publish_test.clj index 722cede..b81c9ce 100644 --- a/test/fleet/publish_test.clj +++ b/test/fleet/publish_test.clj @@ -162,3 +162,9 @@ (let [r (repo)] (pub r rebuild-fixed) (is (= 1 (count (str/split-lines (git (:work r) "worktree" "list"))))))) + +(deftest errors-carry-no-prefix-of-their-own + ;; The CLI adds `publish-status:`; a second one in the message read as a stutter. + (let [e (try (publish/publish! {:out-dir (str (fs/create-temp-dir))}) nil + (catch Exception e e))] + (is (= "rebuild is required" (ex-message e))))) From 4e5cb485f6bf0bb83adbc3daa13a7f90f78eaaff Mon Sep 17 00:00:00 2001 From: burinc Date: Fri, 20 Nov 2026 17:00:56 +1100 Subject: [PATCH 30/31] fanout: untested and undispatched projects are could-not-run, never a pass or a recovery - R40: a cancelled, startup_failure or action_required run stays not-run (detail kept in results.json) but joins the infra output, exits 1, is never counted in 'All N projects build', and the canary report treats it as infra - R41: the dispatch error line is logged as ' gh: ' since the runner trims leading whitespace before parsing commands - R42: dispatch-failed and untested rows get their own 'Could not run' summary line and a 'could not run (detail)' icon instead of 'Broken by jolt' --- src/fleet/canary.clj | 19 +++++++++++---- src/fleet/fanout.clj | 46 ++++++++++++++++++++++++++---------- test/fleet/canary_test.clj | 15 ++++++++++++ test/fleet/fanout_test.clj | 48 ++++++++++++++++++++++++++++++-------- 4 files changed, 101 insertions(+), 27 deletions(-) diff --git a/src/fleet/canary.clj b/src/fleet/canary.clj index 9904a26..faa9273 100644 --- a/src/fleet/canary.clj +++ b/src/fleet/canary.clj @@ -272,18 +272,27 @@ ;; --------------------------------------------------------------------------- ;; Pure: the report -(def ^:private finding? #{"fail" "mismatch" "timed-out"}) +(def ^:private finding-result? #{"fail" "mismatch" "timed-out"}) +(defn- finding? [p] (finding-result? (:result p))) ;; R36: a dispatch that never started says nothing about jolt. It is our App or ;; configuration, so the issue groups it with infra. The result value on the ;; status page stays dispatch-failed. (def ^:private infra-result? #{"infra" "dispatch-failed"}) +;; R40: a run that was cancelled, never started or waited on a person is +;; not-run with the conclusion as its detail. It tested nothing, so it is +;; neither a recovery nor a jolt finding: infra. +(defn- infra? [p] + (or (infra-result? (:result p)) + (and (= "not-run" (:result p)) + (contains? #{"cancelled" "startup_failure" "action_required"} (:detail p))))) + (defn- cells "Sorted, distinct \"name (version)\" strings for projects whose result satisfies pred. label decorates the version part." [results pred label] - (->> (for [r results, p (:projects r) :when (pred (:result p))] + (->> (for [r results, p (:projects r) :when (pred p)] (str (:name p) " (" (label (:requested r) p) ")")) distinct sort vec)) @@ -296,7 +305,7 @@ printed)." [results] {:failed (cells results finding? (fn [v _] v)) - :infra (cells results infra-result? + :infra (cells results infra? (fn [v p] (str v (when (:failed_step p) (str ", failed step: " (:failed_step p))))))}) (defn- lines [& ls] (str/join "\n" ls)) @@ -342,8 +351,8 @@ "not download a dependency (a package registry problem, often Maven" "Central rate limiting while several projects build at once), or" "could not be dispatched (the jlt-commons-ci App lacks access to the" - "repository, or GitHub refused the dispatch). The failed step in" - "parentheses above shows which." + "repository, or GitHub refused the dispatch), or its run was cancelled before it" + "answered. The failed step in parentheses above shows which." "" (str "**Versions tested:** " versions) "" diff --git a/src/fleet/fanout.clj b/src/fleet/fanout.clj index aaa9d6a..b48861f 100644 --- a/src/fleet/fanout.clj +++ b/src/fleet/fanout.clj @@ -138,12 +138,24 @@ (defn- joined [names] (str/join " " names)) -(defn- icon [{:keys [result cause detail installed]}] +(def ^:private untested-details #{"cancelled" "startup_failure" "action_required"}) + +(defn- untested? + "R40: a not-run row whose run was cancelled, never started or waited on a + person. Nothing was learned, so it is not a pass and not a recovery." + [{:keys [result detail]}] + (and (= "not-run" result) (contains? untested-details detail))) + +(defn- could-not-run? + "R42: the project gave no answer for a reason that is not a jolt result." + [{:keys [result] :as row}] + (or (= "dispatch-failed" result) (untested? row))) + +(defn- icon [{:keys [result cause detail installed] :as row}] (case result "pass" "pass" - "not-run" (if (contains? #{"cancelled" "startup_failure" "action_required"} detail) - (str "not run (" detail ")") - "skipped") + "not-run" (if (untested? row) (str "could not run (" detail ")") "skipped") + "dispatch-failed" (str "could not run (" detail ")") "mismatch" (str "**WRONG JOLT** (ran " (or installed "no version found") ")") "infra" (case cause :deps "**could not download dependencies**" @@ -152,14 +164,17 @@ (str "**FAIL** (" detail ")"))) (defn- split-names - "Project names by outcome, in fleet order: {:failed :infra :nodeps + "Project names by outcome, in fleet order: {:failed :infra :couldnt :nodeps :nologs :mismatch :noinstall}. failed holds mismatches too, as the table - always did." + always did. infra also holds the could-not-run rows (dispatch-failed and + untested, R40/R42), which is how they reach the exit code, the infra + output and the canary report." [projects] (let [names (fn [pred] (mapv :name (filter pred projects)))] {:mismatch (names #(= "mismatch" (:result %))) - :failed (names #(contains? #{"mismatch" "fail" "timed-out" "dispatch-failed"} (:result %))) - :infra (names #(= "infra" (:result %))) + :failed (names #(contains? #{"mismatch" "fail" "timed-out"} (:result %))) + :infra (names #(or (= "infra" (:result %)) (could-not-run? %))) + :couldnt (names could-not-run?) :nodeps (names #(and (= "infra" (:result %)) (= :deps (:cause %)))) :nologs (names #(and (= "infra" (:result %)) (= :logs (:cause %)))) :noinstall (names #(and (= "infra" (:result %)) (not (#{:deps :logs} (:cause %)))))})) @@ -167,7 +182,7 @@ (defn summary-md "The step summary: a row per project, then a line per kind of trouble." [{:keys [version projects]}] - (let [{:keys [mismatch failed infra nodeps nologs noinstall]} (split-names projects) + (let [{:keys [mismatch failed infra couldnt nodeps nologs noinstall]} (split-names projects) lines (concat [(str "## jolt `" version "` across " org) "" "| project | result | run |" "|---|---|---|"] @@ -177,6 +192,11 @@ [""] (when (seq mismatch) [(str "**Ran on the wrong jolt:** " (joined mismatch))]) (when (seq failed) [(str "**Broken by jolt `" version "`:** " (joined failed))]) + (when (seq couldnt) + [(str "**Could not run:** " (joined couldnt)) + "" + "These projects gave no answer because the run never started, was cancelled or" + "waited on a person. That says nothing about jolt, and they are not counted as passing."]) (when (seq noinstall) [(str "**Could not install jolt `" version "` for:** " (joined noinstall)) "" @@ -213,7 +233,8 @@ :installed (:installed pr) :run_url (:run-url pr) :finished_at (:finished-at pr) - :failed_step (:failed-step pr)}) + :failed_step (:failed-step pr) + :detail (:detail pr)}) projects)}) ;; --------------------------------------------------------------------------- @@ -301,9 +322,10 @@ (log (str " dispatched " pr ", run id unknown")) (assoc acc pr {:need-id? true})))) (let [line (first-line (str out err) token)] - ;; Indented, so gh's text can never open a workflow command. (log (str " FAILED to dispatch " pr)) - (log (str " " line)) + ;; Indented AND prefixed: the runner trims leading + ;; whitespace before looking for a `::` command (R41). + (log (str " gh: " line)) (assoc acc pr {:detail "dispatch-failed" :failed-step line}))))) {} projects)] (log "::endgroup::") diff --git a/test/fleet/canary_test.clj b/test/fleet/canary_test.clj index fcb2cc0..1442720 100644 --- a/test/fleet/canary_test.clj +++ b/test/fleet/canary_test.clj @@ -352,6 +352,21 @@ (is (false? (:infra? r))) (is (str/includes? (:body r) "**Failing:** glitter (0.8.27)\n"))))) +(defn- res-detail [requested name result detail] + {:requested requested :projects [{:name name :result result :detail detail}]}) + +(deftest r40-an-untested-project-is-infra-never-recovered + (doseq [c ["cancelled" "startup_failure" "action_required"]] + (testing c + (let [r (ib :results [(res "0.8.27" ["a" "pass"]) (res-detail "0.8.27" "b" "not-run" c)] + :fleet-result "failure")] + (is (true? (:broken? r))) + (is (true? (:infra? r))) + (is (str/starts-with? (:body r) "Infra problems, not findings about jolt: b (0.8.27)")) + (is (not (str/includes? (:body r) "Recovered")))))) + (testing "a plain skipped not-run still does not break" + (is (false? (:broken? (ib :results [(res-detail "0.8.27" "b" "not-run" "skipped")])))))) + (deftest infra-plus-a-real-failure-is-reported-as-a-failure (let [r (ib :results [(res "0.8.27" ["glitter" "fail"] ["ebb" "infra" "Install jolt"])])] (is (true? (:broken? r))) diff --git a/test/fleet/fanout_test.clj b/test/fleet/fanout_test.clj index 17583ca..07732e4 100644 --- a/test/fleet/fanout_test.clj +++ b/test/fleet/fanout_test.clj @@ -179,7 +179,9 @@ {:version "0.8.27" :projects [(row "c" "not-run" :detail "cancelled") (row "l" "infra" :cause :logs)]})] - (is (str/includes? md "| `c` | not run (cancelled) |")) + (is (str/includes? md "| `c` | could not run (cancelled) |")) + (is (str/includes? md "**Could not run:** c\n")) + (is (not (str/includes? md "All "))) (is (str/includes? md "| `l` | **could not read the run's logs** |")) (is (str/includes? md "**Could not read the logs of a green run for:** l\n")) (is (not (str/includes? md "Could not install"))) @@ -277,10 +279,10 @@ :run_url "https://github.com/jlt-commons/ci-builds/actions/runs/999" :projects [{:name "alpha" :result "pass" :installed "0.8.27" :run_url "https://github.com/jlt-commons/alpha/actions/runs/101" - :finished_at "2026-11-20T03:00:00Z" :failed_step nil} + :finished_at "2026-11-20T03:00:00Z" :failed_step nil :detail "success"} {:name "beta" :result "pass" :installed "0.8.27" :run_url "https://github.com/jlt-commons/beta/actions/runs/202" - :finished_at "2026-11-20T03:00:00Z" :failed_step nil}]} + :finished_at "2026-11-20T03:00:00Z" :failed_step nil :detail "success"}]} (:results r)))) (is (str/includes? (:summary r) "All 2 projects build against jolt `0.8.27`.")) (is (= (str "results_dir=" (:dir r) "/fanout-results\nartifact=results-0.8.27\nversion=0.8.27\nfailed=\ninfra=\n") @@ -324,7 +326,7 @@ (is (= 1 (:rc r))) (is (= {:result "dispatch-failed" :run_url nil :finished_at nil :failed_step "HTTP 422"} (select-keys b [:result :run_url :finished_at :failed_step]))) - (is (str/includes? (:stdout r) "\n HTTP 422\n")) + (is (str/includes? (:stdout r) "\n gh: HTTP 422\n")) (is (not-any? #(and (= :get (first %)) (str/includes? (second %) "beta")) @(:calls w))))) (defn- with-clock @@ -412,9 +414,11 @@ a (first (:projects (:results r)))] (is (= 1 (:rc r))) (is (= {:result "dispatch-failed" :run_url nil} (select-keys a [:result :run_url]))) - (is (str/includes? (:output r) "failed=alpha\n")) - (is (str/includes? (:summary r) "| `alpha` | **FAIL** (no-run-appeared) | - |")) - (is (str/includes? (:summary r) "**Broken by jolt `0.8.27`:** alpha")) + (is (str/includes? (:output r) "failed=\ninfra=alpha\n")) + (is (str/includes? (:summary r) "| `alpha` | could not run (no-run-appeared) | - |")) + (is (str/includes? (:summary r) "**Could not run:** alpha\n")) + (is (str/includes? (:summary r) "says nothing about jolt")) + (is (not (str/includes? (:summary r) "Broken by jolt"))) (is (not (str/includes? (:summary r) "All "))))) (deftest run-one-malformed-project-is-fail-and_does_not_drop_the_others @@ -500,11 +504,35 @@ (base args env))))) r (run-fake w "0.8.27" :token token) b (second (:projects (:results r)))] - (testing "indented two spaces, so it cannot start a workflow command" - (is (some #(= " ::set-output name=x::y token ***" %) (str/split-lines (:stdout r)))) - (is (not-any? #(str/starts-with? % "::set-output") (str/split-lines (:stdout r))))) + (testing "R41: the runner trims leading whitespace, so the line is prefixed, not just indented" + (is (some #(= " gh: ::set-output name=x::y token ***" %) (str/split-lines (:stdout r)))) + (is (not-any? #(str/starts-with? (str/trim %) "::set-output") (str/split-lines (:stdout r)))) + (testing "the only `::` lines are the loop's own group markers" + (is (every? #(re-matches #"::(group|endgroup)::.*" %) + (filter #(str/starts-with? (str/trim %) "::") (str/split-lines (:stdout r))))))) (testing "first line only, in the row" (is (= "::set-output name=x::y token ***" (:failed_step b)))) (testing "the token is nowhere in the output" (doseq [text [(:stdout r) (:stderr r) (:summary r) (:output r) (json/generate-string (:results r))]] (is (not (str/includes? text token))))))) + +(deftest r40-a-cancelled-project-is-untested-so-the-run-fails-and-never_reads_as_all_pass + (let [w (fake-world {:runs {"alpha" [{:status "completed" :conclusion "cancelled"}] "beta" [ok-run]} + :jobs {"beta" [(job 2 "success")]} + :logs {2 (jolt-log "0.8.27")}}) + r (run-fake w "0.8.27") + a (first (:projects (:results r)))] + (is (= 1 (:rc r))) + (is (= {:result "not-run" :detail "cancelled"} (select-keys a [:result :detail]))) + (is (str/includes? (:output r) "failed=\ninfra=alpha\n")) + (is (not (str/includes? (:summary r) "All "))) + (is (str/includes? (:summary r) "**Could not run:** alpha\n")) + (is (str/includes? (:summary r) "| `alpha` | could not run (cancelled) |")) + (is (str/includes? (:stderr r) "infra: alpha")))) + +(deftest r40-a-plain-skipped-run-is-still-not-run-and-passes + (let [w (fake-world {:runs {"alpha" [{:status "completed" :conclusion "skipped"}] "beta" [ok-run]} + :jobs {"beta" [(job 2 "success")]} + :logs {2 (jolt-log "0.8.27")}}) + r (run-fake w "0.8.27")] + (is (= 0 (:rc r))))) From 51e2c8e91a25b306390dabaac8f4d97739fc16b5 Mon Sep 17 00:00:00 2001 From: burinc Date: Fri, 20 Nov 2026 17:05:08 +1100 Subject: [PATCH 31/31] docs: the fleet dashboard, the jolt tooling and the 15-minute canary --- README.md | 369 +++++++++++++++++++++++++++++++----------------------- 1 file changed, 212 insertions(+), 157 deletions(-) diff --git a/README.md b/README.md index 58f1402..25356d7 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,8 @@ # ci-builds Fleet CI for [jlt-commons](https://github.com/jlt-commons): build every project -against one jolt version and report the result in a single table. +against the jolt versions that matter, and show the result on one dashboard at +. ## Why @@ -19,147 +20,192 @@ floating to `latest` at the time and silently moved onto it. ## What it does -`fan-out` does not build anything itself. Every project's own `ci.yml` already -knows how to build it, and each accepts a `jolt-version` dispatch input that -overrides its pinned `JOLT_VERSION` for a single run. So `fan-out` dispatches -those five workflows, waits, and renders the answers: - -``` -## jolt `0.8.0` across jlt-commons - -| project | result | run | -|-----------------|--------|--------| -| `glitter` | pass | [run] | -| `glitter-gl` | pass | [run] | -| `glitter-uikit` | pass | [run] | -| `raygui-jlt` | pass | [run] | -| `raylib-jlt` | pass | [run] | -| `raylib-ios` | pass | [run] | - -All 6 projects build against jolt `0.8.0`. -``` +Nothing here builds a project. Every project's own `ci.yml` already knows how +to build it, and each accepts a `jolt-version` dispatch input that overrides its +pinned `JOLT_VERSION` for a single run. `fan-out` dispatches those workflows +with the version under test, waits for them, and works out one result per +project. `canary` runs `fan-out` on a schedule against the versions worth +watching, writes the results to the dashboard's data and keeps one issue open +while jolt breaks something. Reusing each project's real gate matters. `raygui-jlt` needs raylib natives, `glitter-uikit` needs AppKit and GTK4, `glitter-gl` needs a GL context under Xvfb. `raylib-ios` is the odd one: its real target is a phone, which no runner can be, so what it contributes here is its pure scene namespaces run under jolt -on Linux. That still catches a jolt divergence, which is what this is for. - -### Adding a project to the fan-out - -Two steps, and the second is not in this repository. - -1. Add it to `PROJECTS` in `.github/workflows/fanout.yml`, and give the project - a `ci.yml` that takes a `jolt-version` input and actually builds or tests - under jolt. A project whose CI never touches jolt will report a green here - that means nothing, which is worse than being absent. -2. **Add the repository to the `jlt-commons-ci` GitHub App installation.** The - App is scoped to selected repositories, and the token the fan-out mints - reaches only those. A project in `PROJECTS` but outside the installation - fails at dispatch with a 404 that reads like a missing workflow. This is a - settings change, at - `https://github.com/organizations/jlt-commons/settings/installations`, and no - API call in this repository can do it. A central rebuild of all that would rot, and would test something other -than what a contributor hits. - -`canary` runs `fan-out` against the jolt versions this fleet cares about, opens -an issue when they break and closes it when a later run passes, so an open -canary issue means "broken right now" rather than "broke once". Two versions: - -| | | -|---|---| -| pinned | what the projects pin today, `vars.JOLT_PIN`, default `0.8.1` | -| latest | jolt's newest published release | +on Linux. That still catches a jolt divergence, which is what this is for. A +central rebuild of all that would rot, and would test something other than what +a contributor hits. + +The tools are plain Clojure in `src/fleet/`, run by jolt as `jolt `. The +only shell script left is `scripts/setup-app.sh`. The project list is +`fleet.json`: a `projects` array, plus an `excluded` map of repositories that +are deliberately not in it, each with its reason. + +### fan-out -They are the same while the fleet is current, and the run collapses to one -build. They diverge the moment jolt ships a release nobody has adopted, which -is the window worth watching. +`fan-out` takes one version, blank meaning jolt's latest release. It dispatches +every project's `ci.yml` with `-f jolt-version=X`, polls until each run ends, +and then checks which jolt each run really used. That check reads the +`jolt --version` line in each job's log. A release must match the version +asked for. A nightly reports a version like `0.8.27-241-gdd3c4a4b`, and its +`-g` commit must be a prefix of the `vnightly` tag's commit. A run that went +green on some other jolt is a mismatch, never a pass. -It ticks hourly and two gates decide whether a tick does anything: +Each project ends in one of these: -- **interval** — `vars.CANARY_INTERVAL_HOURS`, default `1`. A cron cannot be a - variable, GitHub requires a literal, so the schedule ticks hourly and this - decides how often a tick is allowed to do work. Measured from the last run - that actually built something, since a gated tick still finishes as a - successful run and would otherwise reset the clock every hour. -- **change** — a version set that already passed is not retested. Held in the - Actions cache, so there is nothing to commit back and no extra permission. +| result | meaning | +|---|---| +| pass | the run succeeded and a job installed the requested jolt | +| fail | the run failed for any other reason, and the failed step is recorded | +| infra | not about jolt: jolt could not be installed, a dependency could not be downloaded, or a green run's logs could not be read | +| timed-out | the run did not finish before the deadline | +| dispatch-failed | GitHub refused the dispatch, and the first line of its error is kept | +| mismatch | the run succeeded but never ran the requested jolt | +| not-run | GitHub skipped the run, or it was cancelled, never started or waited on a person | + +Polling stops at a 45-minute wall-clock deadline. The results go up as a +`results-` artifact. A manual run of the `fan-out` workflow also adds +its result to the dashboard's history through `publish-adhoc`, and leaves the +grid's nightly cells alone. + +Dispatch-failed, cancelled and unreadable runs say nothing about jolt, so they +count as "could not run" and never as a pass or a recovery. + +### canary + +`canary` ticks every 15 minutes, at minutes 7, 22, 37 and 52. The odd minutes +keep it away from the quarter hours, where GitHub's scheduler is busiest and +most likely to delay or drop a run. Each tick works out a version set, which is +jolt's latest release plus the nightly when the nightly qualifies: + +- The nightly is jolt's rolling `vnightly` prerelease, published since + [jolt-lang/jolt#824](https://github.com/jolt-lang/jolt/pull/824). It is + dropped when it is older than `vars.NIGHTLY_MAX_AGE_HOURS` (default `48`), + because jolt publishes it only after its own downstream-library checks pass. + A lagging library withholds the new artifact while the previous `vnightly` + stays up and installs perfectly, so a green nightly row could mean "main is + healthy" or "main broke on Tuesday and this is Tuesday's binary". +- It is also dropped when it is the same commit as the release. jolt tags + `vnightly` at whatever main was when the job ran, which is often the release + tag itself, and one build should not show up as two answers. The canary + compares the tags' commits at run time. + +What each project pins is not a row. It is read from the project's own latest +push run on its default branch and shown as the "Own pin" column. + +Three gates decide whether a tick tests anything: + +- The interval: `vars.CANARY_INTERVAL_HOURS`, default `0`, which means no gate. + A cron cannot be a variable, since GitHub requires a literal, so the schedule + ticks and this decides how often a tick may do work. It is measured from the + last run that built something. +- The green cache: a version set that already passed is not retested. The + Actions cache holds it, so nothing is committed back. The nightly's + `published_at` is part of the key. The literal string `nightly` is the same + today as yesterday, so without it the first green would cache a key every + later run recomputes. +- The retry backoff: a set that did not pass is tried once per window, + `vars.CANARY_RETRY_HOURS` (default `6`). A new version set has a new key and + runs on the next tick, while a known-bad one does not dispatch every project + every 15 minutes. + +A manual dispatch skips all three. + +The legs run one version at a time. Each leg dispatches every project's `ci.yml` +on its default branch, and two legs in flight together would dispatch the same +project twice within seconds, which cancels the earlier run in any project whose +concurrency group cancels in progress. + +Two more things happen on every tick, including a gated one. The `status` job +merges the results into the dashboard's data, so the pin column keeps up with +each project's own CI while jolt stands still. It commits only when the content +changed or the last commit is 6 hours old, a heartbeat of about 4 commits a day +that keeps `generated_at` moving, so the dashboard's staleness banner fires only +when the canary has really stopped. The `report` job opens, updates or closes the +single issue titled "canary: jolt breaks the fleet". It opens when a project +fails, mismatches or times out on a version, and closes itself with a recovery +comment once a later run passes, so an open issue means "broken right now" and +not "broke once". When every problem is infra, the issue says so and names the +failed step. Infra covers jolt that could not be installed, a dependency that +could not be downloaded, a run that could not start (dispatch failed or +cancelled) and logs that could not be read. None of those is a finding about +jolt. + +The tools run on their own jolt, `vars.TOOLS_JOLT_VERSION` (default `0.8.27`), +pinned in the workflows and never the jolt under test. A release published +overnight must not change the thing that measures releases. + +## Dashboard + + has one row per project and three +columns: + +| column | what it shows | +|---|---| +| Own pin | the project's latest push run on its default branch, with the version its `ci.yml` pins | +| Latest release | the project built against jolt's newest release | +| Nightly | the project built against `vnightly`, when the canary tested one | + +A cell is one of the results in the fan-out table, shown as "pass", "fail at +", "could not run: infra", "timed out", "dispatch failed", "ran on the +wrong jolt" or "not tested yet". Each links to its run, and a row expands to the +last runs in each column, ad-hoc fan-outs included. The header says which +release is latest, which nightly commit was tested and how old it is, and when +the data was generated. After 12 hours without an update the page warns that the +canary may have stopped. Below the grid, "Not in the fleet yet" lists the +organization's repositories that no run covers, each with a reason: excluded, +no `ci.yml`, no `jolt-version` input, or ready but not yet in `fleet.json`. + +The data lives on this repository's orphan `status` branch as `status.json` and +`history.json`, both schema 1. The page fetches them from +`https://raw.githubusercontent.com/jlt-commons/ci-builds/status/status.json` and +`.../history.json`. That host sends `Access-Control-Allow-Origin: *` and caches +for 300 seconds, so the page can lag the branch by up to five minutes. The page +source is in +[jlt-commons.github.io](https://github.com/jlt-commons/jlt-commons.github.io), +not here. -A manual dispatch ignores both. +## Using it -**Both rows are releases, and jolt's `main` is testable too.** This section -used to say testing an unreleased jolt would mean building it from source -against Chez on two operating systems. That stopped being true on 2026-09-02, -when [jolt-lang/jolt#824](https://github.com/jolt-lang/jolt/pull/824) merged and -jolt began publishing a rolling `vnightly` prerelease from main. Every project -already takes a `jolt-version` input, so: +To try a candidate jolt across everything, go to Actions, then fan-out, then Run +workflow, and give it a version (blank means jolt's latest release, `nightly` means +`vnightly`). Nothing is committed to any project. Each one builds at its own +HEAD with the version you named, and the result goes into the dashboard's +history. ``` gh workflow run fanout.yml --repo jlt-commons/ci-builds -f jolt-version=nightly ``` -is the whole thing, no code anywhere. Run [33691047983](https://github.com/jlt-commons/ci-builds/actions/runs/33691047983) -did exactly that and all five passed. +To try one project, dispatch that project's own `ci.yml` with the +`jolt-version` input. It is the same mechanism for one repository. -`nightly` is now a third row in the canary matrix, behind a freshness check -that is the reason the row can be trusted: +To run the canary now, dispatch `canary`, optionally with a version. A manual +dispatch skips the gates. -| | | -|---|---| -| pinned | what the projects pin today, `vars.JOLT_PIN`, default `0.8.1` | -| latest | jolt's newest published release | -| nightly | jolt's `vnightly` prerelease, when it is fresh enough | - -jolt publishes the nightly by staging a draft, deleting the old release, then -moving the tag, and only after its own downstream-library gates pass. So a -lagging library withholds the new artifact while the previous `vnightly` stays -up and installs perfectly. jolt's very first nightly run published nothing at -all for exactly that reason, with three library suites failing on main against -the `:jolt/provides` change that v0.8.1 later announced. - -Left alone, a green `nightly` row could not distinguish "main is healthy" from -"main broke on Tuesday and we are still testing Tuesday's binary". So the canary -reads the release's `published_at`, skips the row when the artifact is older -than `vars.NIGHTLY_MAX_AGE_HOURS` (default `48`), and stamps the age on every -result. A skipped row says so in the run log and in the issue body. It never -passes quietly. - -Fresh is not sufficient on its own. jolt tags `vnightly` at whatever main was -when the nightly job ran, and that is often the release tag itself. On -2026-09-02 `vnightly` and `v0.8.1` both pointed at `9b768395`, identical and -three hours old, while main had already moved 7 commits past both. That SHA -named upstream's line as it stood that day. jolt force-pushed main on -2026-09-03 and moved both `0.8.x` tags to byte-identical commits, so it no -longer resolves there, which is the reason the canary compares tags at run time -rather than trusting an id written down earlier. A row like -that is fresh, green, and tells you nothing the release row did not already say. -So the canary compares the nightly's commit against the release rows' commits -and skips it as redundant when they match, rather than rendering one build as -two answers. - -The `published_at` also goes into the change-gate cache key. The literal string -`nightly` is the same today as yesterday, so without it the first green would -cache a key every later run recomputes, and the nightly row would never run -again however far main moved. - -The two release rows need none of this, because a published release is -immutable once it exists. - -## Using it - -**Try a candidate jolt across everything.** Actions → fan-out → Run workflow, -and give it a version (blank means jolt's latest release). Nothing is -committed anywhere; each project builds at its own HEAD with the version you -named. - -**Try one project.** Dispatch that project's own `ci.yml` with the -`jolt-version` input. Same mechanism, one repository. - -**Adopt a new jolt.** Run `fan-out` against it, then, when green, move each +To adopt a new jolt, run `fan-out` against it, then, when green, move each project's `JOLT_VERSION` pin in one reviewed commit per repository. Moving a -pin IS the cutover commit for a breaking jolt change, which is the point of +pin is the cutover commit for a breaking jolt change, which is the point of pinning rather than floating. +## Adding a project + +1. Give its `ci.yml` a `workflow_dispatch` input named `jolt-version` and a + workflow-level `JOLT_VERSION` pin that reads it (see below). A project whose + CI never touches jolt would report a green here that means nothing, which is + worse than being absent. +2. Add the repository to the jlt-commons-ci App installation. The App is scoped + to selected repositories, and the token the fan-out mints reaches only + those. A project outside the installation fails at dispatch with a 404 that + reads like a missing workflow. This is a settings change, at + `https://github.com/organizations/jlt-commons/settings/installations`, and + no API call in this repository can do it. +3. Add its name to `projects` in `fleet.json`. +4. Run one fan-out and confirm the project dispatches and reports. + +Until step 3, the dashboard lists the repository under "Not in the fleet yet" +with the reason it is not covered. + ## The pin convention Every project carries a workflow-level pin: @@ -194,7 +240,7 @@ state the requirement for consumers. See Runs authenticate as the **jlt-commons-ci** GitHub App, not a personal access token. The App is owned by the organization, mints a token that lives one hour -and reaches exactly six repositories, and is what lets someone trigger a fleet +and reaches only the repositories the App is installed on, and is what lets someone trigger a fleet build without borrowing another person's identity. A PAT would attribute every dispatched run to whoever created it and would die with their access. @@ -203,51 +249,60 @@ than organization secrets because this is a free organization, where org secrets cover public repositories only, and because the credential's blast radius should be the one repository that needs it. -## Setting the App up again - -`scripts/setup-app.sh` walks the whole thing: create the App, set its -permissions, install it, store the credentials in `pass`, create this -repository, and set its secrets. It is the script that actually created the -current setup, corrected afterwards for two things it got wrong the first time. +## Working on it ``` -bash scripts/setup-app.sh +jolt test # run the suite, exit 1 on any failure +jolt tasks # list every task with its doc +jolt nrepl-server # a REPL for editors, writes .nrepl-port ``` -It is idempotent enough to re-run: stage 1 asks whether the App already exists -and skips creation if so, and stage 5 detects this repository and moves on. You -would need it to rotate the private key, to rebuild the App after an uninstall, -or to set the same thing up for another organization. - -Two things it records that are easy to get wrong: - -- The workflows authenticate with the App's **Client ID**, not its App ID. - `create-github-app-token@v3` deprecates the `app-id` input, so a setup that - only captures the App ID produces credentials the workflows cannot use. -- `pass` **auto-commits** every entry it writes but never pushes. The - credentials are not backed up until `git -C ~/dev/b12n-pass push`. - -## Adding a project +The tasks are in `deps.edn`: `test`, and the `fleet:` tools the workflows call +(`fleet:own-pin`, `fleet:uncovered`, `fleet:status`, `fleet:refresh`, +`fleet:publish`, `fleet:fanout`, `fleet:plan`, `fleet:report`). The prefix keeps +them clear of jolt's own subcommands. Code is in `src/fleet/` and tests in +`test/fleet/`. The ones that touch GitHub take `GH_TOKEN` from the environment, +and the network sits behind injected functions, so the suite runs offline. -1. Give it a `workflow_dispatch` input named `jolt-version` and a - workflow-level `JOLT_VERSION` pin that reads it. -2. Add the repository to the jlt-commons-ci App installation. -3. Add its name to `PROJECTS` in `.github/workflows/fanout.yml`. +Two jolts are involved. The tools run on the tool jolt, pinned as +`TOOLS_JOLT_VERSION` in each workflow, with `vars.TOOLS_JOLT_VERSION` as an +override. The jolt under test is only ever a `jolt-version` input to a project's +`ci.yml`. Locally, whatever `jolt` is on your path runs the tools, so a new +release can change the tools' behavior on your machine before it does in CI. ## Known gaps -- **The canary polls rather than being told.** A `repository_dispatch` from - `jolt-lang/jolt` on release would be the better signal, but jolt is a - different organization where we are read-only, so that change is not ours to - make. Worth asking about. -- **`glitter-gl` has a shim a single pin cannot fully exercise.** +- The cron runs less often than it says. GitHub ran the old hourly cron + only 3 to 4 times a day between 2026-11-10 and 2026-11-19. That is why the + canary ticks every 15 minutes, and the real rate under the new schedule is + still unmeasured. Check it a week after this merges, from the run history of + `canary`, and move the schedule again if ticks still go missing. +- The canary polls rather than being told. Jolt publishes a release every + few days, plus a nightly, and a poll notices within a tick or two at best. A + `repository_dispatch` step in jolt's release workflow would make it + immediate. That is a request to jolt's maintainer, since jolt is a different + organization where we are read-only. +- Two demos are excluded. `raylib-jolt-demo` and `raylib-ios-demo` wait on + the jlt-commons-ci App installation, because until they are installed they + fail at dispatch and would open a false issue. They show under "Not in the + fleet yet". `fleet.json` lists the other exclusions. +- A repository without a `jolt-version` input cannot join. It is listed as + "Not in the fleet yet" until its `ci.yml` takes one. +- A stale nightly drops the nightly row. Past 48 hours the canary stops + testing it, which also means an open issue about a nightly failure can close + as recovered while the project is still broken on main. +- A permanently unreadable project keeps its last cell. When a collector + cannot read a project, the dashboard keeps the previous cell and reason and + warns on stderr, with no age limit, so the page can show an old good result + for a project whose runs have become unreadable. +- `glitter-gl` has a shim a single pin cannot fully exercise. `glitter-gl.ffi-compat` resolves `ffi/write`'s argument order at load and has two branches; a run pinned to one jolt only ever takes one of them. A two-entry matrix over an old and a new jolt would cover both. -- **`PROJECTS` is a hardcoded list**, so a new repository is invisible until - someone edits the workflow. Deliberate for now: discovery by topic or by - listing the App's installation would be quieter but would also silently - change what the canary covers. +- `fleet.json` is a hardcoded list, so a new repository is invisible to the + fan-out until someone edits it. The dashboard still lists it under "Not in the + fleet yet". Discovery by topic or by the App's installation would be quieter + but would also silently change what the canary covers. ## Licence