diff --git a/.github/workflows/canary.yml b/.github/workflows/canary.yml index 929f1ee..51ae8a2 100644 --- a/.github/workflows/canary.yml +++ b/.github/workflows/canary.yml @@ -4,92 +4,68 @@ 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 # -# 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. +# 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`. # -# 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`. +# 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. # -# 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 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. -# -# TWO GATES, so an hourly 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. -# 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. +# 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 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. +# 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. # --------------------------------------------------------------------------- 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: "" +# 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: + # 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). +concurrency: + group: canary + cancel-in-progress: false + jobs: plan: name: plan @@ -99,142 +75,39 @@ 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 }} 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: | + 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. - 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 }} + RETRY_HOURS: ${{ vars.CANARY_RETRY_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}" - - max_age="${NIGHTLY_MAX_AGE_HOURS:-48}" - nightly_pub="" - nightly="" - - 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 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}" - fi - fi - fi - - [ -n "$nightly_pub" ] && set -- "$@" "nightly" - versions="[$(printf '"%s",' "$@" | sed 's/,$//')]" - echo "testing $versions" - fi - echo "versions=$versions" >> "$GITHUB_OUTPUT" - echo "nightly=$nightly" >> "$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 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 - # 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. @@ -247,7 +120,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 @@ -255,20 +142,10 @@ 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: | - 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 }} @@ -277,39 +154,122 @@ 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 - # 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 ~3x on a run that - # tests all three rows), not correctness, and an hourly cron has the - # room. + # 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) }} + # 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 + + - 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: | + 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 + uses: actions/create-github-app-token@v3 + with: + 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 + + - 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 + # 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 + mapfile -t files < <(find results -name results.json | sort) + else + files=() + fi + jolt fleet:publish "$RUNNER_TEMP/status-out" "${files[@]}" + 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 + + - 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: | + 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 uses: actions/create-github-app-token@v3 @@ -318,74 +278,32 @@ 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 + + # 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 }} 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 }} - 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 // ""') - - if [ "$RESULT" = "success" ]; then - if [ -n "$existing" ]; then - gh issue comment "$existing" --repo "$GITHUB_REPOSITORY" \ - --body "Recovered. The fleet builds against ${VERSIONS}. ${NIGHTLY}. [Run](${RUN_URL})" - 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' \ - "jolt could not be INSTALLED for: ${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." \ - "" \ - "**Versions tested:** ${VERSIONS}" \ - "" \ - "[Run](${RUN_URL}) has the per-project table.") - 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}" \ - "**Nightly:** ${NIGHTLY:-not resolved}" \ - "" \ - "[Run](${RUN_URL}) has a per-project table for each version." \ - "" \ - "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 @@ -399,3 +317,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/.github/workflows/fanout.yml b/.github/workflows/fanout.yml index 939024f..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" @@ -52,18 +53,51 @@ on: permissions: contents: read +env: + TOOLS_JOLT_VERSION: ${{ vars.TOOLS_JOLT_VERSION || '0.8.27' }} + jobs: fanout: 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 }} - version: ${{ steps.version.outputs.version }} + version: ${{ steps.run.outputs.version }} steps: - # Mints a token scoped to the App's seven repositories, valid one hour. + # 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: | + 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 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 @@ -74,195 +108,81 @@ 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 - PROJECTS="glitter glitter-gl glitter-uikit raygui-jlt raylib-jlt raylib-ios raylib-android" - declare -A RUN CONC URL - # 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="" + 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" - # `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::" + - name: Upload results.json + if: always() + uses: actions/upload-artifact@v7 + with: + 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 - # 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 + # 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 - 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 - CONC[$p]="$cc" - echo " $p: $cc" - 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::" + - 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') }} - # Render the table this workflow exists to produce. - failed="" - infra="" - { - 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" ;; - toolchain-unavailable) - icon="**could not install jolt**"; infra="$infra $p" ;; - *) icon="**FAIL** ($c)"; failed="$failed $p" ;; - esac - link="-" - [ -n "${URL[$p]:-}" ] && link="[run](${URL[$p]})" - echo "| \`$p\` | $icon | $link |" >> "$GITHUB_STEP_SUMMARY" - done - failed="${failed# }" - infra="${infra# }" - { - echo - [ -n "$failed" ] && echo "**Broken by jolt \`$VERSION\`:** $failed" - if [ -n "$infra" ]; then - echo "**Could not install jolt \`$VERSION\` for:** $infra" - 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 - # 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" + - run: | + dpkg -s libyaml-0-2 >/dev/null 2>&1 || { sudo apt-get update && sudo apt-get install -y libyaml-0-2; } - echo "failed=$failed" >> "$GITHUB_OUTPUT" - echo "infra=$infra" >> "$GITHUB_OUTPUT" - [ -z "$failed$infra" ] || { echo "failing: ${failed:-none} infra: ${infra:-none}" >&2; exit 1; } + - 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 + # 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 + + - 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 + # fleet:publish refreshes in-process on every attempt (R27), so the + # results files are plain arguments. + if [ -d results ]; then + mapfile -t files < <(find results -name results.json | sort) + else + files=() + fi + jolt fleet:publish "$RUNNER_TEMP/status-out" "${files[@]}" diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..e145ac1 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,34 @@ +name: test + +on: + push: + # The status branch holds data files only. + 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: + 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') }} + # 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 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d337e6d --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.jolt/ 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 diff --git a/deps.edn b/deps.edn new file mode 100644 index 0000000..5531d85 --- /dev/null +++ b/deps.edn @@ -0,0 +1,65 @@ +;; 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.canary-test] + [fleet.cli-test] + [fleet.collect-test] + [fleet.fanout-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.canary-test + 'fleet.cli-test + 'fleet.collect-test + 'fleet.fanout-test + 'fleet.github-test + 'fleet.publish-test + 'fleet.refresh-test + 'fleet.status-test + '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*))} + + 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/fleet.json b/fleet.json new file mode 100644 index 0000000..6f0fe00 --- /dev/null +++ b/fleet.json @@ -0,0 +1,6 @@ +{"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", + "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 new file mode 100644 index 0000000..faa9273 --- /dev/null +++ b/src/fleet/canary.clj @@ -0,0 +1,428 @@ +(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'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 + 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") {}))))) + +(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) "")] + (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 (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-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 (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. + + 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). + + :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, :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 + 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) + :tried-key (tried-key versions nightly-pub (:now in) + (or (:retry-hours in) default-retry-hours))} + (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 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, 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")) + +;; --------------------------------------------------------------------------- +;; 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, 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] + (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 #(and (str/starts-with? (str (:name %)) "jolt ") + (not= "skipped" (:conclusion %))) + jobs) + updated_at))) + runs))) + +;; --------------------------------------------------------------------------- +;; Pure: the report + +(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 p)] + (str (:name p) " (" (label (:requested r) p) ")")) + distinct sort vec)) + +(defn verdict + "{: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? + (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 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) + "" + "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), could" + "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), or its run was cancelled before it" + "answered. 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 new file mode 100644 index 0000000..4a0eadf --- /dev/null +++ b/src/fleet/cli.clj @@ -0,0 +1,290 @@ +(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 [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] + [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 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])] + (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 (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) + :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: 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 ["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 ["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) ")"))))))))) + +(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))})))))) + +(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- 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") "") + 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) + 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)) + 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") + :already-tried (get env "ALREADY_TRIED") + :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, 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) + [] (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/collect.clj b/src/fleet/collect.clj new file mode 100644 index 0000000..3800bcc --- /dev/null +++ b/src/fleet/collect.clj @@ -0,0 +1,135 @@ +(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. 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])) + +(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- 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" + "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 + (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)) + 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) (unreadable-row p pin) + (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 + "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)) + (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}]. 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)] + (if (= ::unreadable r) + {:name name :reason unreadable :unreadable true} + {:name name :reason r})))) + vec)) diff --git a/src/fleet/fanout.clj b/src/fleet/fanout.clj new file mode 100644 index 0000000..b48861f --- /dev/null +++ b/src/fleet/fanout.clj @@ -0,0 +1,512 @@ +(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 every project's build environment + here would rot, and would test something other than what a contributor + actually hits. + + 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. 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 + 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 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. 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 + 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-window-ms (* 45 60 1000)) +(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 (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 + 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))))) + +(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, :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 [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 + (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)) + +(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 (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**" + :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 :couldnt :nodeps + :nologs :mismatch :noinstall}. failed holds mismatches too, as the table + 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"} (: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 %)))))})) + +(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 couldnt nodeps nologs 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 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)) + "" + "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."]) + (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)) + [(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) + :detail (:detail 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- 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 + :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 + (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})))) + (let [line (first-line (str out err) token)] + (log (str " FAILED to dispatch " pr)) + ;; 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::") + 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" :result "dispatch-failed"})))) + 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- 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, 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) + []) + 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, 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 [pending (filterv runs projects) done {}] + (if (empty? pending) + 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 (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)}) + {:pending (conj pending pr) :done done}))) + {:pending [] :done done} pending)] + (if (or (empty? (:pending step)) (>= (now-ms now) deadline)) + (:done step) + (do (sleep poll-interval-ms) + (recur (: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} + 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] + (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 (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) + 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 new file mode 100644 index 0000000..d8340e0 --- /dev/null +++ b/src/fleet/github.clj @@ -0,0 +1,147 @@ +(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- 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 #"^[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 + "No redirects: the client would replay the Authorization header to a + 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] + (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 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) + (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 + (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 :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"))) + :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)))) + :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)." + [] + (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/publish.clj b/src/fleet/publish.clj new file mode 100644 index 0000000..64cfdb2 --- /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 "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 "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 "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 "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/src/fleet/status.clj b/src/fleet/status.clj new file mode 100644 index 0000000..035f92d --- /dev/null +++ b/src/fleet/status.clj @@ -0,0 +1,166 @@ +(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 %)) (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" {})) + (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. + + 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) + (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)) + 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) + 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 (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 (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]] + [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 (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, 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)] + (and (= (norm old-status) (norm new-status)) + (not (heartbeat-due? old-status 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/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/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..bb870a6 --- /dev/null +++ b/test/fixtures/gh/org-repos.json @@ -0,0 +1,10 @@ +[{"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":"ratelimited","archived":false,"private":false}, + {"name":"badyaml","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: {} 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 new file mode 100644 index 0000000..c30c04d --- /dev/null +++ b/test/fixtures/log-maven-429.txt @@ -0,0 +1,5 @@ +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) +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..c67788f --- /dev/null +++ b/test/fixtures/log-maven-absent.txt @@ -0,0 +1,5 @@ +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 +2026-11-20T01:45:11.0000000Z ##[error]Process completed with exit code 1. 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-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-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/fixtures/log-test-failure.txt b/test/fixtures/log-test-failure.txt new file mode 100644 index 0000000..35b3a0c --- /dev/null +++ b/test/fixtures/log-test-failure.txt @@ -0,0 +1,6 @@ +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] +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/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"}] diff --git a/test/fleet/canary_test.clj b/test/fleet/canary_test.clj new file mode 100644 index 0000000..1442720 --- /dev/null +++ b/test/fleet/canary_test.clj @@ -0,0 +1,473 @@ +(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-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"}))))) + +(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" + (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"} + (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 "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"}))))) + +;; --------------------------------------------------------------------------- +;; 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" :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"}]}} + (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" :conclusion "failure"}]}} + (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" "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 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"))))) + +(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))) + (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" "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))) + (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 new file mode 100644 index 0000000..a8b2813 --- /dev/null +++ b/test/fleet/cli_test.clj @@ -0,0 +1,278 @@ +(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"))))))) + +(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")))) + +(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))))) + +;; 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" "tried_key" "proceed" "reason"} (set (keys o)))) + (is (str/starts-with? (o "versions") "[\"0.8.27\"")))) + +(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-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"] {} {})))))) + +(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")))) + +;; 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, 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, using 48")) + (is (= "true" (get-in r [:o "proceed"]))))) diff --git a/test/fleet/collect_test.clj b/test/fleet/collect_test.clj new file mode 100644 index 0000000..90a166d --- /dev/null +++ b/test/fleet/collect_test.clj @@ -0,0 +1,194 @@ +(ns fleet.collect-test + "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] + [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 :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"] + ["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 :unreadable true}] + 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 (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 + (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 + ;; 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/fanout_test.clj b/test/fleet/fanout_test.clj new file mode 100644 index 0000000..07732e4 --- /dev/null +++ b/test/fleet/fanout_test.clj @@ -0,0 +1,538 @@ +(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-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 "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"} + (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 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 "timed_out"} + (select-keys (fanout/classify {:requested "0.8.27" :conclusion "timed_out" :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-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` | 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"))) + (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)"))) + +;; --------------------------------------------------------------------------- +;; 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 & [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"}] + #(get m %))) + +(defn- tmp [] (str (fs/create-temp-dir))) + +(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 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")) + :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 :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 :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") + (: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 :failed_step "HTTP 422"} + (select-keys b [:result :run_url :finished_at :failed_step]))) + (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 + "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))) + (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]} + :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))))) + +(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=\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 + (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"}}))))) + +(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 "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))))) diff --git a/test/fleet/github_test.clj b/test/fleet/github_test.clj new file mode 100644 index 0000000..c0d3895 --- /dev/null +++ b/test/fleet/github_test.clj @@ -0,0 +1,223 @@ +(ns fleet.github-test + (:require [cheshire.core :as json] + [clojure.string :as str] + [clojure.test :refer [deftest is testing]] + [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))))) + +;; 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))))))) + +(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))))) + +;; 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)))))) diff --git a/test/fleet/publish_test.clj b/test/fleet/publish_test.clj new file mode 100644 index 0000000..b81c9ce --- /dev/null +++ b/test/fleet/publish_test.clj @@ -0,0 +1,170 @@ +(ns fleet.publish-test + "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] + [clojure.string :as str] + [clojure.test :refer [deftest is testing]] + [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-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 + "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})) + +(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 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) + 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"))))))) + +(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))))) diff --git a/test/fleet/refresh_test.clj b/test/fleet/refresh_test.clj new file mode 100644 index 0000000..44f3bff --- /dev/null +++ b/test/fleet/refresh_test.clj @@ -0,0 +1,74 @@ +(ns fleet.refresh-test + "Refresh. 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-canary-run + (let [out (str (tmp-dir) "/out") + err (StringWriter.) + rc (binding [*err* err] + (cli/refresh-main [out] {"NIGHTLY_JSON" "null"} {}))] + (is (= 2 rc)) + (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 + (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")))))) diff --git a/test/fleet/status_test.clj b/test/fleet/status_test.clj new file mode 100644 index 0000000..404ed6b --- /dev/null +++ b/test/fleet/status_test.clj @@ -0,0 +1,273 @@ +(ns fleet.status-test + (:require [cheshire.core :as json] + [clojure.test :refer [deftest is testing]] + [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 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 + :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"))))) + +;; 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")))) + +(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 "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. + (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))))))) 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]))))