From 7a07c404de2a5e35bb6291858e8b0d16632e6bcc Mon Sep 17 00:00:00 2001 From: Svilen Stefanov Date: Thu, 3 Dec 2026 15:35:05 +0100 Subject: [PATCH 1/3] fix: save the base as soon as it is built, explain refused pushes, and stop early on a spent quota - Review uploads the base right after generating it, before the head analysis, so a head that fails or times out no longer discards it. - Sync publishes the analyzed commit's base whatever the delivery did; the baseline-commit copy still needs a delivered commit. - A push refused by branch protection or a ruleset (GH006/GH013) fails with the branch and the fix. - A spent hosted quota or OpenRouter key limit stops the run before checkout and install, with the reason in the review comment or sync summary. - README workflow examples use timeout-minutes: 180. Co-Authored-By: Claude Opus 5.5 --- README.md | 8 +- action.yml | 97 +++++++------ docs/COMMIT_STRATEGY.md | 23 ++- scripts/action/codeboarding-baseline.sh | 10 +- scripts/action/configure-auth.sh | 7 +- scripts/action/deliver-sync.sh | 27 ++-- scripts/action/quota_check.py | 82 +++++++++++ scripts/action/sync-generate-baseline.sh | 2 + tests/test_action_state.py | 24 ++++ tests/test_action_sync.py | 39 +++++- tests/test_baseline_branch.py | 9 +- tests/test_quota_check.py | 169 +++++++++++++++++++++++ 12 files changed, 426 insertions(+), 71 deletions(-) create mode 100755 scripts/action/quota_check.py create mode 100644 tests/test_quota_check.py diff --git a/README.md b/README.md index 7f220267..8a51ffeb 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,7 @@ jobs: startsWith(github.event.comment.body, '/codeboarding') && contains(fromJSON('["OWNER","MEMBER","COLLABORATOR"]'), github.event.comment.author_association)) runs-on: ubuntu-latest - timeout-minutes: 60 + timeout-minutes: 180 permissions: contents: read actions: read # download the analysis an earlier run published @@ -60,7 +60,7 @@ jobs: sync: if: github.event_name == 'push' runs-on: ubuntu-latest - timeout-minutes: 60 + timeout-minutes: 180 permissions: contents: write actions: read # catch up from an analysis a review saved @@ -72,6 +72,8 @@ jobs: llm: hosted ``` +A first analysis of a large repository, around a million lines, can take over an hour, hence `timeout-minutes: 180`; GitHub bills the minutes used, not the limit. + Both jobs use the default `codeboarding_analysis_location`, so review always reads the analysis where sync saves it. If you set it, set it in both jobs. Keep both jobs in this one file: a repository running CodeBoarding from more than one workflow file is an [older setup](#moving-an-existing-setup), which the CodeBoarding dashboard flags and offers to fold into one. ## Review pull requests @@ -380,7 +382,7 @@ Off by default. With `problem_history: 'true'` on the sync job, every sync (a pu sync: if: github.event_name == 'push' runs-on: ubuntu-latest - timeout-minutes: 60 + timeout-minutes: 180 permissions: contents: write # also writes codeboarding/briefing actions: read # also reads merged pull requests' review artifacts diff --git a/action.yml b/action.yml index cbd98187..aecfeecb 100644 --- a/action.yml +++ b/action.yml @@ -392,6 +392,22 @@ runs: fi exit 1 + - name: Configure analysis authentication + if: steps.guard.outputs.skip != 'true' + shell: bash + env: + ACTION_PATH: ${{ github.action_path }} + run: "$GITHUB_ACTION_PATH/scripts/action/configure-auth.sh" + + # Before the checkout and the engine install, like the credential check. A spent + # quota otherwise shows at the first model call, after the static analysis, which on + # a large repository is most of an hour in. + - name: Check LLM quota + id: quota + if: steps.guard.outputs.skip != 'true' + shell: bash + run: python3 "$GITHUB_ACTION_PATH/scripts/action/quota_check.py" + # Before the checkout and the engine install, like the credential check: a sync # that could not save its result fails in seconds, not after a full analysis. - name: Check analysis branch @@ -455,13 +471,6 @@ runs: exit 1 } - - name: Configure analysis authentication - if: steps.guard.outputs.skip != 'true' - shell: bash - env: - ACTION_PATH: ${{ github.action_path }} - run: "$GITHUB_ACTION_PATH/scripts/action/configure-auth.sh" - - name: Resolve analysis cache keys id: state if: steps.guard.outputs.skip != 'true' @@ -553,15 +562,15 @@ runs: run: "$GITHUB_ACTION_PATH/scripts/action/deliver-sync.sh" # Named for the commit pull requests branch from, so a review that forks there - # finds this graph and skips analyzing the base entirely. Published under both - # the analyzed commit and the baseline commit written on top, because a pull - # request opened either side of that commit has a different merge base. - - name: Publish baseline analysis - if: steps.guard.outputs.skip != 'true' && steps.guard.outputs.mode == 'sync' && steps.sync_commit.outputs.baseline_sha != '' && steps.state.outputs.cfg_hash != '' && github.server_url == 'https://github.com' + # finds this graph and skips analyzing the base entirely. Published whatever the + # delivery did: a refused push must not throw away an hour of analysis, and the + # next sync or review catches up from this artifact instead of starting over. + - name: Publish baseline analysis for the analyzed commit + if: "!cancelled() && steps.guard.outputs.skip != 'true' && steps.guard.outputs.mode == 'sync' && steps.sync_analyze.outcome == 'success' && steps.state.outputs.cfg_hash != '' && github.server_url == 'https://github.com'" continue-on-error: true uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: - name: codeboarding-base-${{ steps.state.outputs.cfg_hash }}-${{ steps.sync_commit.outputs.baseline_sha }} + name: codeboarding-base-${{ steps.state.outputs.cfg_hash }}-${{ steps.sync_analyze.outputs.analyzed_sha }} path: ${{ runner.temp }}/cb-state/${{ github.action }}/out/base # Longer than a review's 14 days on purpose, and the margin is the whole # point: correctness comes from the renewal check, which republishes any @@ -572,12 +581,14 @@ runs: retention-days: 30 if-no-files-found: ignore - - name: Publish baseline analysis for the analyzed commit - if: steps.guard.outputs.skip != 'true' && steps.guard.outputs.mode == 'sync' && steps.sync_commit.outputs.analyzed_sha != '' && steps.sync_commit.outputs.analyzed_sha != steps.sync_commit.outputs.baseline_sha && steps.state.outputs.cfg_hash != '' && github.server_url == 'https://github.com' + # Also under the baseline commit written on top, which only exists once delivered: + # a pull request opened either side of that commit has a different merge base. + - name: Publish baseline analysis + if: steps.guard.outputs.skip != 'true' && steps.guard.outputs.mode == 'sync' && steps.sync_commit.outputs.baseline_sha != '' && steps.sync_commit.outputs.baseline_sha != steps.sync_analyze.outputs.analyzed_sha && steps.state.outputs.cfg_hash != '' && github.server_url == 'https://github.com' continue-on-error: true uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: - name: codeboarding-base-${{ steps.state.outputs.cfg_hash }}-${{ steps.sync_commit.outputs.analyzed_sha }} + name: codeboarding-base-${{ steps.state.outputs.cfg_hash }}-${{ steps.sync_commit.outputs.baseline_sha }} path: ${{ runner.temp }}/cb-state/${{ github.action }}/out/base # Longer than a review's 14 days on purpose, and the margin is the whole # point: correctness comes from the renewal check, which republishes any @@ -614,7 +625,7 @@ runs: FILES: ${{ steps.sync_commit.outputs.files_written }} SAVED_TO: ${{ steps.guard.outputs.analysis_branch || steps.guard.outputs.synced_branch }} # A failed sync has no pull request to comment on; the summary is where it says why. - FAILURE_REASON: ${{ steps.guard.outputs.failure_reason || steps.analysis_check.outputs.failure_reason || steps.state.outputs.failure_reason || steps.sync_analyze.outputs.failure_reason || steps.sync_commit.outputs.failure_reason }} + FAILURE_REASON: ${{ steps.guard.outputs.failure_reason || steps.analysis_check.outputs.failure_reason || steps.quota.outputs.failure_reason || steps.state.outputs.failure_reason || steps.sync_analyze.outputs.failure_reason || steps.sync_commit.outputs.failure_reason }} run: "$GITHUB_ACTION_PATH/scripts/action/sync-summary.sh" - name: Generate review baseline @@ -650,6 +661,29 @@ runs: KEEP_AUTH: 'true' run: '"$GITHUB_ACTION_PATH/scripts/action/with-auth.sh" "$GITHUB_ACTION_PATH/scripts/action/review-generate-baseline.sh"' + # Published as soon as it exists, ahead of the head analysis: a base built from + # scratch can take most of the job's time, and a run that then fails or times + # out on the head must not leave the next review to build it again. + # Only a trusted run publishes a base graph: it is named for a commit, so + # every pull request forking there would read it, and a fork's analysis must + # never be what they read. + - name: Publish base analysis + id: publish_base + if: steps.guard.outputs.skip != 'true' && steps.guard.outputs.mode == 'review' && steps.review_baseline.outputs.publish_base == 'true' && steps.guard.outputs.is_fork != 'true' && steps.state.outputs.base_name != '' && github.server_url == 'https://github.com' + continue-on-error: true + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: ${{ steps.state.outputs.base_name }} + path: ${{ runner.temp }}/cb-state/${{ github.action }}/out/base + # Longer than a review's 14 days on purpose, and the margin is the whole + # point: correctness comes from the renewal check, which republishes any + # base with less than a review's lifetime left, while this surplus + # decides how often that fires. Equal lifetimes renew on every run and + # publish a base per run rather than per merge base — more storage, not + # less. 30 leaves a 16-day reuse window. + retention-days: 30 + if-no-files-found: ignore + - name: Analyze pull request id: review_analyze if: steps.guard.outputs.skip != 'true' && steps.guard.outputs.mode == 'review' @@ -687,26 +721,6 @@ runs: retention-days: ${{ inputs.warmstart_retention_days }} if-no-files-found: ignore - # Only a trusted run publishes a base graph: it is named for a commit, so - # every pull request forking there would read it, and a fork's analysis must - # never be what they read. - - name: Publish base analysis - id: publish_base - if: steps.guard.outputs.skip != 'true' && steps.guard.outputs.mode == 'review' && steps.review_baseline.outputs.publish_base == 'true' && steps.guard.outputs.is_fork != 'true' && steps.state.outputs.base_name != '' && github.server_url == 'https://github.com' - continue-on-error: true - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 - with: - name: ${{ steps.state.outputs.base_name }} - path: ${{ runner.temp }}/cb-state/${{ github.action }}/out/base - # Longer than a review's 14 days on purpose, and the margin is the whole - # point: correctness comes from the renewal check, which republishes any - # base with less than a review's lifetime left, while this surplus - # decides how often that fires. Equal lifetimes renew on every run and - # publish a base per run rather than per merge base — more storage, not - # less. 30 leaves a 16-day reuse window. - retention-days: 30 - if-no-files-found: ignore - - name: Render review diagram id: review_render if: steps.guard.outputs.skip != 'true' && steps.guard.outputs.mode == 'review' @@ -973,10 +987,11 @@ runs: if-no-files-found: error retention-days: 14 - # The head and preview steps remove the credentials themselves; this covers a run that - # failed before them, and a setup PR's run, which keeps them for its previews. + # The analysis steps remove the credentials themselves; this covers a run that + # failed before them (they are configured ahead of the checkout), and a setup PR's + # run, which keeps them for its previews. - name: Remove analysis credentials - if: always() && steps.guard.outputs.skip != 'true' && steps.guard.outputs.mode == 'review' + if: always() && steps.guard.outputs.skip != 'true' shell: bash run: '"$GITHUB_ACTION_PATH/scripts/action/clear-auth.sh"' @@ -1008,6 +1023,6 @@ runs: message: | ### CodeBoarding review · failed - ${{ steps.review_baseline.outputs.failure_reason || steps.review_analyze.outputs.failure_reason }} + ${{ steps.quota.outputs.failure_reason || steps.review_baseline.outputs.failure_reason || steps.review_analyze.outputs.failure_reason }} See the [workflow logs](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}). diff --git a/docs/COMMIT_STRATEGY.md b/docs/COMMIT_STRATEGY.md index 9e80f7e6..7f4720df 100644 --- a/docs/COMMIT_STRATEGY.md +++ b/docs/COMMIT_STRATEGY.md @@ -38,7 +38,11 @@ pays for them. Health configuration stays, because a run seeded from a bundle reads it. The base graph is published only by the run that *computed* it, so it is written -about once per merge base rather than once per run — with two exceptions. A +about once per merge base rather than once per run. It is published as soon as it +exists, before the head is analyzed: building a base from scratch can take most of +a job's time limit, and a run that then fails or times out on the head still saves +it, so the next review starts from it instead of building it again. There are two +exceptions to "once per merge base". A review artifact references a base by id for its whole retention, so a base about to expire inside that window is republished rather than left dangling under a review that outlives it. And when no artifact holds the base at all, because the @@ -75,8 +79,11 @@ never fires. | `analysed_files_changed` | string | analysed files whose content hash differs between base and head; `unknown` when the analyses cannot say | | `pr_number`, `mode`, `seed_source`, `chain_depth` | string | provenance; nothing rendering a diagram needs them. `mode` is the head's engine mode | -**A sync run** publishes the base graph under both the commit it analyzed and the -baseline commit it writes on top, because a pull request opened either side of +**A sync run** publishes the base graph under the commit it analyzed as soon as +the analysis succeeds, whether or not delivering it does: a push the remote +refuses must not throw the analysis away, and the next sync or review catches up +from the artifact. When delivery writes a baseline commit on top (`in_place`), it +is published under that commit too, because a pull request opened either side of that commit has a different merge base. ## Retention is what costs @@ -195,9 +202,11 @@ a code branch that happens to be named `codeboarding/baseline` fails, before any during the analysis, the result is still saved for the commit it analyzed: entries are keyed by commit, and a branch that merges faster than sync runs would otherwise never be saved. Only an analysis of an older commit than the tip's is -dropped, so the tip stays the latest diagram. If another sync moved the baseline branch, it builds on that tip once. A push the -remote refuses while the tip did not move is a branch rule, and the run fails -saying so. +dropped, so the tip stays the latest diagram. If another sync moved the baseline branch, it builds on that tip once. A push GitHub +refuses with a branch rule error (`GH006` for branch protection, `GH013` for a +ruleset) fails the run naming the bypass to add; any other refusal while the tip +did not move fails it asking to check the token. Either way the analysis is +already published as an artifact. The tip is compared just before the push, not in the same transaction: if a sync of a newer commit lands in that window, the push is no longer a fast-forward and @@ -234,7 +243,7 @@ from a same-repository pull request branch, can still push to the branch and pla the pickle sync loads. Creation is covered too, so the bypass actor must be the identity sync pushes as -before the first sync, or that sync fails on the rule. Rulesets on a private repository need a paid GitHub plan +before the first sync, or that sync fails on the rule, saying which bypass to add. Rulesets on a private repository need a paid GitHub plan (Pro, Team or Enterprise); on Free they apply to public repositories only. ## Trust boundary diff --git a/scripts/action/codeboarding-baseline.sh b/scripts/action/codeboarding-baseline.sh index be19508d..c7be901b 100644 --- a/scripts/action/codeboarding-baseline.sh +++ b/scripts/action/codeboarding-baseline.sh @@ -105,7 +105,7 @@ from_codeboarding_baseline() { # Saves the analysis installed by install-sync.sh as one fast-forward commit on # BASELINE_BRANCH, never writing to the synced branch. Called by deliver-sync.sh, -# whose REMOTE, BASE_SHA and emit_result it uses; always exits. +# whose REMOTE, BASE_SHA, emit_result and refused_by_rule it uses; always exits. save_to_codeboarding_baseline() { local branch="$BASELINE_BRANCH" tree="$RUNNER_TEMP/codeboarding-baseline-tree" local index="$RUNNER_TEMP/codeboarding-baseline-index" git_dir files new_tree tip tip_source parent commit now @@ -171,13 +171,17 @@ CodeBoarding-Config: $CFG_HASH") commit="$(git commit-tree "$new_tree" ${parent[@]+"${parent[@]}"} \ -m "chore(codeboarding): diagram of $SYNCED_BRANCH @${BASE_SHA:0:7}" "${trailers[@]}")" # Never forced: the parent is the tip just read, so this only ever fast-forwards. - if git push -q "$REMOTE" "$commit:refs/heads/$branch"; then + if pushed="$(git push -q "$REMOTE" "$commit:refs/heads/$branch" 2>&1)"; then emit_result "$files" true "$BASE_SHA" exit 0 fi + echo "$pushed" >&2 + if refused_by_rule "$pushed"; then + baseline_fail "GitHub refused the push to $branch because a ruleset or branch protection covers it. Add the identity sync pushes as (GitHub Actions for the default token, or the CodeBoarding app) as a bypass actor for $branch: https://github.com/CodeBoarding/CodeBoarding-action/blob/main/docs/COMMIT_STRATEGY.md#the-baseline-branch" + fi now="$(git ls-remote "$REMOTE" "refs/heads/$branch" | awk '{print $1; exit}')" if [ "$now" = "$tip" ]; then - baseline_fail "GitHub refused the push to $branch, most likely because a branch rule protects it. Add the identity sync pushes with (the CodeBoarding app, or GitHub Actions for the default token) as a bypass actor for $branch in the repository's rulesets, and check that github_token may push to it." + baseline_fail "GitHub refused the push to $branch. Check that github_token may push to it and that no branch rule covers it." fi done emit_result "$files" false "$BASE_SHA" diff --git a/scripts/action/configure-auth.sh b/scripts/action/configure-auth.sh index 6abcc9da..3ca9425d 100755 --- a/scripts/action/configure-auth.sh +++ b/scripts/action/configure-auth.sh @@ -1,9 +1,10 @@ #!/usr/bin/env bash # Starts the hosted credential relay when the resolved plan calls for it. # -# The plan itself was decided by verify-credentials.sh before the checkout; this step only -# does the part that needs the engine's Python present. A direct-provider run has -# nothing to do here: its key never leaves the runner. +# The plan itself was decided by verify-credentials.sh; this step starts the relay that +# plan calls for. The relay is stdlib-only, so it runs before the checkout and the +# engine install, and the quota check after it can stop the run in seconds. A +# direct-provider run has nothing to do here: its key never leaves the runner. set -euo pipefail AUTH_DIR="${RUNNER_TEMP}/codeboarding-auth" HOSTED_PROXY_URL="https://auduihjmm4b735zci7vyabuikq0hppqn.lambda-url.us-east-1.on.aws" diff --git a/scripts/action/deliver-sync.sh b/scripts/action/deliver-sync.sh index 98100a35..141e17d6 100755 --- a/scripts/action/deliver-sync.sh +++ b/scripts/action/deliver-sync.sh @@ -19,16 +19,19 @@ chmod 700 "$ASKPASS" export GIT_ASKPASS="$ASKPASS" GIT_TERMINAL_PROMPT=0 trap 'rm -f "$ASKPASS"' EXIT # A pull request's merge base is whichever commit its author branched from, and -# this run's analysis is valid for two of them: the commit it analyzed, and the -# baseline commit it writes on top, which differs only in .codeboarding files -# that the fingerprint ignores. Publishing both means a pull request opened -# either side of a sync commit still gets an exact hit. +# this run's analysis is valid for two of them: the commit it analyzed, published +# whether or not delivery succeeds, and baseline_sha, the baseline commit written +# on top, which differs only in .codeboarding files that the fingerprint ignores. +# Publishing both means a pull request opened either side of a sync commit still +# gets an exact hit. emit_result() { - printf 'files_written=%s\ncommitted=%s\nbaseline_sha=%s\nanalyzed_sha=%s\n' \ - "$1" "$2" "$3" "$BASE_SHA" >> "$GITHUB_OUTPUT" + printf 'files_written=%s\ncommitted=%s\nbaseline_sha=%s\n' "$1" "$2" "$3" >> "$GITHUB_OUTPUT" } +# GitHub's refusal when a branch rule covers the branch: GH006 is classic branch +# protection, GH013 a ruleset. +refused_by_rule() { grep -qiE 'protected branch|GH006|GH013|rule violation' <<< "$1"; } classify_push_failure() { - local expected="$1" branch="$2" current + local expected="$1" branch="$2" pushed="$3" current current="$(git ls-remote "$REMOTE" "refs/heads/$branch" | awk '{print $1; exit}')" [ "$current" != "$(git rev-parse HEAD)" ] || return 0 if [ "$current" != "$expected" ]; then @@ -36,6 +39,9 @@ classify_push_failure() { echo "::notice::A newer run updated $branch; leaving it untouched." exit 0 fi + if refused_by_rule "$pushed"; then + baseline_fail "$branch is protected, so sync cannot commit the analysis to it. Remove \`codeboarding_analysis_location: in_place\` (or \`sync_strategy: push\`) from both CodeBoarding jobs, and sync saves it to \`codeboarding/baseline\`, a branch of its own: https://github.com/CodeBoarding/CodeBoarding-action#keep-the-baseline-current" + fi baseline_fail "Could not push the CodeBoarding baseline to $branch." } @@ -84,7 +90,8 @@ fi git commit -m 'chore(codeboarding): sync analysis baseline' >/dev/null -if ! git push "$REMOTE" "HEAD:refs/heads/$SYNCED_BRANCH"; then - classify_push_failure "$BASE_SHA" "$SYNCED_BRANCH" -fi +push_status=0 +pushed="$(git push "$REMOTE" "HEAD:refs/heads/$SYNCED_BRANCH" 2>&1)" || push_status=$? +echo "$pushed" >&2 +[ "$push_status" = 0 ] || classify_push_failure "$BASE_SHA" "$SYNCED_BRANCH" "$pushed" emit_result "$files_written" true "$(git rev-parse HEAD)" diff --git a/scripts/action/quota_check.py b/scripts/action/quota_check.py new file mode 100755 index 00000000..03d00d39 --- /dev/null +++ b/scripts/action/quota_check.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python3 +"""Stops a run whose LLM can no longer be called, before any analysis starts. + +A spent quota otherwise shows at the first model call, after the static analysis. +Only a definite "spent" stops the run: a check that cannot reach a verdict leaves the +analysis to try, as every run did before this existed. +""" + +from __future__ import annotations + +import json +import os +import sys +from pathlib import Path +from urllib.error import HTTPError +from urllib.request import Request, urlopen + +DOCS = "https://github.com/CodeBoarding/CodeBoarding-action#authentication-and-providers" +OPENROUTER_KEY_URL = "https://openrouter.ai/api/v1/key" + +HOSTED_SPENT = ( + "This account's free CodeBoarding quota is used up for the week, so no analysis ran; it resets weekly. " + f"Wait for the reset, or switch to `llm: license` or your own provider key ([how]({DOCS}))." +) +KEY_SPENT = ( + "The key in `openrouter_api_key` has reached its OpenRouter spending limit, so no analysis ran. " + "Raise the key's limit on openrouter.ai, or use another key." +) + + +def _get(url: str, headers: dict[str, str] | None = None) -> tuple[int, bytes]: + try: + with urlopen(Request(url, headers=headers or {}), timeout=30) as response: # nosec B310 - fixed URLs + return response.status, response.read() + except HTTPError as response: + return response.code, response.read() + + +def verdict(auth_dir: Path) -> str | None: + """The reason the run cannot call its LLM, or None when it can or that is unknown.""" + tier = (auth_dir / "tier").read_text(encoding="utf-8").strip() + env = auth_dir / "env" + if tier in ("hosted", "license"): + # Through the relay, which signs the request as this run. The proxy checks the + # quota on every request before forwarding it; one without a body runs no model + # and is not metered, so asking costs nothing. Paid licences always pass. + status, _ = _get((env / "OPENROUTER_BASE_URL").read_text(encoding="utf-8").rstrip("/") + "/models") + if status == 402: + return HOSTED_SPENT + if status != 200: + print(f"::notice::Could not check the CodeBoarding quota (HTTP {status}); analyzing anyway.") + return None + if (auth_dir / "provider-name").read_text(encoding="utf-8").strip() != "openrouter": + return None + key = (env / "OPENROUTER_API_KEY").read_text(encoding="utf-8").strip() + status, body = _get(OPENROUTER_KEY_URL, {"Authorization": f"Bearer {key}"}) + if status != 200: + print(f"::notice::Could not check the OpenRouter key's limit (HTTP {status}); analyzing anyway.") + return None + # null means the key has no limit. + remaining = json.loads(body).get("data", {}).get("limit_remaining") + if isinstance(remaining, (int, float)) and not isinstance(remaining, bool) and remaining <= 0: + return KEY_SPENT + return None + + +def main() -> int: + try: + reason = verdict(Path(os.environ["RUNNER_TEMP"]) / "codeboarding-auth") + except Exception as exc: # best effort: never the reason a run fails + print(f"::notice::Could not check the LLM quota ({type(exc).__name__}); analyzing anyway.") + return 0 + if reason is None: + return 0 + print(f"::error title=CodeBoarding LLM quota::{reason}") + with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as output: + output.write(f"failure_reason={reason}\n") + return 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/action/sync-generate-baseline.sh b/scripts/action/sync-generate-baseline.sh index 88daf726..58c1e8a8 100755 --- a/scripts/action/sync-generate-baseline.sh +++ b/scripts/action/sync-generate-baseline.sh @@ -37,4 +37,6 @@ stage "$state" base { echo "$result" echo "analysis_dir=$state" + # The base is published under this commit whatever the delivery does. + echo "analyzed_sha=$head_sha" } >> "$GITHUB_OUTPUT" diff --git a/tests/test_action_state.py b/tests/test_action_state.py index 0a02ea46..4e532703 100644 --- a/tests/test_action_state.py +++ b/tests/test_action_state.py @@ -1040,6 +1040,30 @@ def test_the_renewal_threshold_matches_the_review_retention(self) -> None: review = next(s for s in self._uploads() if "review_artifact.outputs.artifact_dir" in s.get("path", "")) self.assertIn(f"'{review['retention-days']}'", renew) + def test_the_review_base_is_published_before_the_head_is_analyzed(self) -> None: + # A base built from scratch can take most of the job's time limit; a head + # analysis that then fails or times out must not take it down with it. + names = [s["name"] for s in self._steps()] + self.assertLess(names.index("Generate review baseline"), names.index("Publish base analysis")) + self.assertLess(names.index("Publish base analysis"), names.index("Analyze pull request")) + + def test_sync_publishes_its_analysis_whatever_the_delivery_did(self) -> None: + # A refused push used to throw away a finished analysis, so the next run + # analyzed everything again. + name = "Publish baseline analysis for the analyzed commit" + names = [s["name"] for s in self._steps()] + step = next(s for s in self._uploads() if s["name"] == name) + self.assertGreater(names.index(name), names.index("Deliver baseline")) + self.assertIn("!cancelled()", step["if"]) + self.assertIn("steps.sync_analyze.outcome == 'success'", step["if"]) + self.assertNotIn("sync_commit", step["if"]) + text = (ROOT / "action.yml").read_text(encoding="utf-8") + block = text[text.index(f"- name: {name}") :] + self.assertIn( + "codeboarding-base-${{ steps.state.outputs.cfg_hash }}-${{ steps.sync_analyze.outputs.analyzed_sha }}", + block[: block.index("\n\n")], + ) + def test_the_reusable_analysis_honours_the_configured_retention(self) -> None: warmstart = [s for s in self._uploads() if "warmstart" in s.get("path", "")] self.assertTrue(warmstart, "no warm-start publication step found") diff --git a/tests/test_action_sync.py b/tests/test_action_sync.py index 30ed2462..681afbf6 100644 --- a/tests/test_action_sync.py +++ b/tests/test_action_sync.py @@ -415,5 +415,40 @@ def test_it_publishes_the_analysis_under_both_commits(self) -> None: # written on top, which differs only in files the fingerprint ignores. # A pull request branched either side of that commit must hit the cache. self.assertEqual(values["baseline_sha"], baseline_sha) - self.assertEqual(values["analyzed_sha"], self.analyzed_sha) - self.assertNotEqual(values["baseline_sha"], values["analyzed_sha"]) + self.assertNotEqual(values["baseline_sha"], self.analyzed_sha) + + def test_a_protected_branch_says_to_save_the_analysis_elsewhere(self) -> None: + hook = self.remote / "hooks" / "pre-receive" + hook.write_text( + '#!/bin/sh\necho "error: GH006: Protected branch update failed for refs/heads/main." >&2\nexit 1\n', + encoding="utf-8", + ) + hook.chmod(0o755) + output = self.root / "github-output" + result = subprocess.run( + [str(ROOT / "scripts" / "action" / "deliver-sync.sh")], + env={ + "PATH": os.environ["PATH"], + "PYTHONPATH": str(self.core), + "ACTION_PATH": str(ROOT), + "ANALYSIS_DIR": str(self.analysis), + "CHECKOUT_DIR": str(self.checkout), + "GITHUB_OUTPUT": str(output), + "RUNNER_TEMP": str(self.root), + "GITHUB_SERVER_URL": str(self.root), + "GITHUB_TOKEN": "unused", + "REPOSITORY": "owner/repo", + "SYNCED_BRANCH": "main", + }, + capture_output=True, + text=True, + check=False, + ) + + self.assertNotEqual(result.returncode, 0) + values = dict(line.split("=", 1) for line in output.read_text(encoding="utf-8").splitlines() if "=" in line) + reason = values["failure_reason"] + self.assertIn("main is protected", reason) + self.assertIn("codeboarding_analysis_location: in_place", reason) + self.assertIn("#keep-the-baseline-current", reason) + self.assertIn(f"::error::{reason}", result.stdout) diff --git a/tests/test_baseline_branch.py b/tests/test_baseline_branch.py index eebc855b..b9d5e8ed 100644 --- a/tests/test_baseline_branch.py +++ b/tests/test_baseline_branch.py @@ -165,11 +165,14 @@ def test_a_push_refused_by_a_branch_rule_says_how_to_fix_it(self) -> None: ) hook.chmod(0o755) - result, _values = self._deliver(expect_ok=False) + result, values = self._deliver(expect_ok=False) self.assertNotEqual(result.returncode, 0) self.assertIn(f"GitHub refused the push to {BRANCH}", result.stdout) self.assertIn("bypass actor", result.stdout) + # The sync summary repeats it, so it says why without opening the log. + self.assertIn("a ruleset or branch protection covers it", values["failure_reason"]) + self.assertIn("COMMIT_STRATEGY.md#the-baseline-branch", values["failure_reason"]) def _check(self, synced: str) -> subprocess.CompletedProcess: (self.root / "check-output").write_text("", encoding="utf-8") @@ -477,9 +480,11 @@ def test_the_branch_outranks_a_baseline_committed_at_the_merge_base(self) -> Non self.assertNotEqual(base["components"], ["stale"]) def test_sync_continues_from_the_branch_tip(self) -> None: - self._analyze(ANALYSIS_KIND="sync") + values = self._analyze(ANALYSIS_KIND="sync") self.assertEqual(self._modes(), ["incremental"]) + # Named before delivery, so the analysis is published even when delivery fails. + self.assertEqual(values["analyzed_sha"], git(self.checkout, "rev-parse", "HEAD")) def test_sync_replaces_the_committed_state_with_the_branch_tip(self) -> None: # Switching from push: the checkout still holds the old committed baseline. diff --git a/tests/test_quota_check.py b/tests/test_quota_check.py new file mode 100644 index 00000000..22ecf572 --- /dev/null +++ b/tests/test_quota_check.py @@ -0,0 +1,169 @@ +"""The quota check stops a run whose LLM cannot be called, and nothing else.""" + +from __future__ import annotations + +import json +import os +import subprocess +import tempfile +import threading +import unittest +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +SCRIPT = ROOT / "scripts" / "action" / "quota_check.py" + + +class _Upstream: + """Answers every request with one status and body, and records what was asked.""" + + def __init__(self, status: int, body: bytes) -> None: + requests: list[tuple[str, str, str]] = [] + + class Handler(BaseHTTPRequestHandler): + def do_GET(self) -> None: # noqa: N802 + requests.append((self.path, self.headers.get("Authorization", ""), self.headers.get("Content-Length"))) + self.send_response(status) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *_args: object) -> None: + return + + self.requests = requests + self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + threading.Thread(target=self.server.serve_forever, daemon=True).start() + self.url = f"http://127.0.0.1:{self.server.server_port}" + + def close(self) -> None: + self.server.shutdown() + self.server.server_close() + + +class QuotaCheckTests(unittest.TestCase): + def setUp(self) -> None: + temp_dir = tempfile.TemporaryDirectory() + self.addCleanup(temp_dir.cleanup) + self.root = Path(temp_dir.name) + self.auth = self.root / "codeboarding-auth" + (self.auth / "env").mkdir(parents=True) + + def _plan(self, tier: str, provider: str, **env: str) -> None: + (self.auth / "tier").write_text(tier) + (self.auth / "provider-name").write_text(provider) + for name, value in env.items(): + (self.auth / "env" / name).write_text(value) + + def _upstream(self, status: int, body: object = b"") -> _Upstream: + upstream = _Upstream(status, body if isinstance(body, bytes) else json.dumps(body).encode()) + self.addCleanup(upstream.close) + return upstream + + def _check(self, **env: str) -> tuple[subprocess.CompletedProcess, str]: + output = self.root / "github-output" + output.write_text("") + result = subprocess.run( + ["python3", str(SCRIPT)], + env={"PATH": os.environ["PATH"], "RUNNER_TEMP": str(self.root), "GITHUB_OUTPUT": str(output), **env}, + capture_output=True, + text=True, + check=False, + ) + return result, output.read_text() + + def test_a_spent_hosted_quota_stops_the_run_with_the_reason(self) -> None: + proxy = self._upstream(402, {"error": {"message": "Resource exhausted: token limit reached"}}) + self._plan("hosted", "openrouter", OPENROUTER_BASE_URL=proxy.url) + + result, output = self._check() + + self.assertEqual(result.returncode, 1) + self.assertIn("failure_reason=This account's free CodeBoarding quota is used up", output) + self.assertIn("::error title=CodeBoarding LLM quota::", result.stdout) + # Asked through the relay, which signs it; no body, so the proxy runs no model. + self.assertEqual([path for path, _auth, _length in proxy.requests], ["/models"]) + self.assertIn(proxy.requests[0][2], (None, "0")) + + def test_a_hosted_quota_with_room_lets_the_run_go_on(self) -> None: + proxy = self._upstream(200, {"data": []}) + self._plan("license", "openrouter", OPENROUTER_BASE_URL=proxy.url) + + result, output = self._check() + + self.assertEqual(result.returncode, 0, result.stdout) + self.assertEqual(output, "") + + def test_any_other_answer_is_no_reason_to_stop(self) -> None: + for status in (401, 500, 502): + with self.subTest(status=status): + proxy = self._upstream(status, {"error": {"message": "no"}}) + self._plan("hosted", "openrouter", OPENROUTER_BASE_URL=proxy.url) + + result, output = self._check() + + self.assertEqual(result.returncode, 0, result.stdout) + self.assertEqual(output, "") + self.assertIn("::notice::", result.stdout) + + def test_an_unreachable_proxy_is_no_reason_to_stop(self) -> None: + proxy = self._upstream(200) + url = proxy.url + proxy.close() + self._plan("hosted", "openrouter", OPENROUTER_BASE_URL=url) + + result, output = self._check() + + self.assertEqual(result.returncode, 0, result.stdout) + self.assertEqual(output, "") + self.assertIn("::notice::", result.stdout) + + def test_a_direct_provider_other_than_openrouter_is_not_asked(self) -> None: + self._plan("byok", "anthropic", ANTHROPIC_API_KEY="sk-ant") + + result, output = self._check() + + self.assertEqual(result.returncode, 0, result.stdout) + self.assertEqual(output, "") + + +class OpenRouterKeyTests(unittest.TestCase): + """The key's own limit, read in-process so the URL can point at a local server.""" + + def setUp(self) -> None: + import importlib.util + + spec = importlib.util.spec_from_file_location("quota_check", SCRIPT) + assert spec and spec.loader + self.module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(self.module) + temp_dir = tempfile.TemporaryDirectory() + self.addCleanup(temp_dir.cleanup) + self.auth = Path(temp_dir.name) + (self.auth / "env").mkdir() + (self.auth / "tier").write_text("byok") + (self.auth / "provider-name").write_text("openrouter") + (self.auth / "env" / "OPENROUTER_API_KEY").write_text("sk-or-user") + + def _verdict(self, data: dict) -> tuple[str | None, list]: + upstream = _Upstream(200, json.dumps({"data": data}).encode()) + self.addCleanup(upstream.close) + self.module.OPENROUTER_KEY_URL = f"{upstream.url}/api/v1/key" + return self.module.verdict(self.auth), upstream.requests + + def test_a_key_at_its_limit_stops_the_run(self) -> None: + reason, requests = self._verdict({"limit": 5, "limit_remaining": 0}) + + self.assertEqual(reason, self.module.KEY_SPENT) + self.assertEqual(requests[0][:2], ("/api/v1/key", "Bearer sk-or-user")) + + def test_a_key_with_room_or_no_limit_lets_the_run_go_on(self) -> None: + for remaining in (3.5, None): + with self.subTest(limit_remaining=remaining): + reason, _requests = self._verdict({"limit_remaining": remaining}) + self.assertIsNone(reason) + + +if __name__ == "__main__": + unittest.main() From 1322f4bb60b757b40e5fb3faa53b6a1ffca9c702 Mon Sep 17 00:00:00 2001 From: Svilen Stefanov Date: Thu, 3 Dec 2026 15:50:34 +0100 Subject: [PATCH 2/3] =?UTF-8?q?fix:=20address=20review=20=E2=80=94=20quota?= =?UTF-8?q?=20message,=20non-default=20branch=20advice,=20simpler=20output?= =?UTF-8?q?s?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - The quota message matches Core's and links to pricing; it no longer tells a license user to switch to a license. - "Remove in_place" is advised only for the default branch; any other branch gets the bypass-actor fix. - baseline_sha is set only when in_place writes a commit, so its publish step needs one plain condition. - refused_by_rule lives next to baseline_fail; clearer names, shorter comments, shared test helpers. Co-Authored-By: Claude Opus 5.5 --- action.yml | 24 ++++----- docs/COMMIT_STRATEGY.md | 18 +++---- scripts/action/codeboarding-baseline.sh | 24 +++++---- scripts/action/configure-auth.sh | 5 +- scripts/action/deliver-sync.sh | 37 +++++++------- scripts/action/quota_check.py | 25 +++++----- tests/test_action_sync.py | 66 ++++++++++++------------- tests/test_baseline_branch.py | 2 +- tests/test_quota_check.py | 41 ++++++++------- 9 files changed, 120 insertions(+), 122 deletions(-) diff --git a/action.yml b/action.yml index aecfeecb..782acbcd 100644 --- a/action.yml +++ b/action.yml @@ -399,17 +399,14 @@ runs: ACTION_PATH: ${{ github.action_path }} run: "$GITHUB_ACTION_PATH/scripts/action/configure-auth.sh" - # Before the checkout and the engine install, like the credential check. A spent - # quota otherwise shows at the first model call, after the static analysis, which on - # a large repository is most of an hour in. + # A spent quota stops the run here, in seconds, not at the first model call. - name: Check LLM quota id: quota if: steps.guard.outputs.skip != 'true' shell: bash run: python3 "$GITHUB_ACTION_PATH/scripts/action/quota_check.py" - # Before the checkout and the engine install, like the credential check: a sync - # that could not save its result fails in seconds, not after a full analysis. + # A sync that could not save its result fails here, in seconds, not after a full analysis. - name: Check analysis branch id: analysis_check if: steps.guard.outputs.skip != 'true' && steps.guard.outputs.mode == 'sync' @@ -552,6 +549,7 @@ runs: ANALYSIS_DIR: ${{ steps.sync_analyze.outputs.analysis_dir }} CHECKOUT_DIR: ${{ github.workspace }}/.codeboarding-target SYNCED_BRANCH: ${{ steps.guard.outputs.synced_branch }} + DEFAULT_BRANCH: ${{ github.event.repository.default_branch }} BASELINE_BRANCH: ${{ steps.guard.outputs.analysis_branch }} ENGINE_VERSION: ${{ steps.state.outputs.engine_version }} # Recorded with each baseline-branch commit, so a reader can tell which configuration made it. @@ -563,8 +561,7 @@ runs: # Named for the commit pull requests branch from, so a review that forks there # finds this graph and skips analyzing the base entirely. Published whatever the - # delivery did: a refused push must not throw away an hour of analysis, and the - # next sync or review catches up from this artifact instead of starting over. + # delivery did, so a refused push does not throw the analysis away. - name: Publish baseline analysis for the analyzed commit if: "!cancelled() && steps.guard.outputs.skip != 'true' && steps.guard.outputs.mode == 'sync' && steps.sync_analyze.outcome == 'success' && steps.state.outputs.cfg_hash != '' && github.server_url == 'https://github.com'" continue-on-error: true @@ -581,10 +578,10 @@ runs: retention-days: 30 if-no-files-found: ignore - # Also under the baseline commit written on top, which only exists once delivered: - # a pull request opened either side of that commit has a different merge base. - - name: Publish baseline analysis - if: steps.guard.outputs.skip != 'true' && steps.guard.outputs.mode == 'sync' && steps.sync_commit.outputs.baseline_sha != '' && steps.sync_commit.outputs.baseline_sha != steps.sync_analyze.outputs.analyzed_sha && steps.state.outputs.cfg_hash != '' && github.server_url == 'https://github.com' + # Also under the commit in_place writes on top of the analyzed one: a pull request + # opened either side of that commit has a different merge base. + - name: Publish baseline analysis for the baseline commit + if: steps.guard.outputs.skip != 'true' && steps.guard.outputs.mode == 'sync' && steps.sync_commit.outputs.baseline_sha != '' && steps.state.outputs.cfg_hash != '' && github.server_url == 'https://github.com' continue-on-error: true uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: @@ -661,9 +658,8 @@ runs: KEEP_AUTH: 'true' run: '"$GITHUB_ACTION_PATH/scripts/action/with-auth.sh" "$GITHUB_ACTION_PATH/scripts/action/review-generate-baseline.sh"' - # Published as soon as it exists, ahead of the head analysis: a base built from - # scratch can take most of the job's time, and a run that then fails or times - # out on the head must not leave the next review to build it again. + # Published before the head is analyzed, so a run that then fails or times out + # does not leave the next review to build the base again. # Only a trusted run publishes a base graph: it is named for a commit, so # every pull request forking there would read it, and a fork's analysis must # never be what they read. diff --git a/docs/COMMIT_STRATEGY.md b/docs/COMMIT_STRATEGY.md index 7f4720df..bd52f897 100644 --- a/docs/COMMIT_STRATEGY.md +++ b/docs/COMMIT_STRATEGY.md @@ -42,10 +42,9 @@ about once per merge base rather than once per run. It is published as soon as i exists, before the head is analyzed: building a base from scratch can take most of a job's time limit, and a run that then fails or times out on the head still saves it, so the next review starts from it instead of building it again. There are two -exceptions to "once per merge base". A -review artifact references a base by id for its whole retention, so a base about -to expire inside that window is republished rather than left dangling under a -review that outlives it. And when no artifact holds the base at all, because the +exceptions to "once per merge base". A review artifact references a base by id +for its whole retention, so a base about to expire inside that window is +republished rather than left dangling under a review that outlives it. And when no artifact holds the base at all, because the upload failed or because a fork review publishes nothing, the review artifact carries the graph inline and leaves `base_artifact` empty: a reader should prefer an inline `base_analysis.json` and fall back to the named artifact — ten runs on one pull request @@ -79,10 +78,9 @@ never fires. | `analysed_files_changed` | string | analysed files whose content hash differs between base and head; `unknown` when the analyses cannot say | | `pr_number`, `mode`, `seed_source`, `chain_depth` | string | provenance; nothing rendering a diagram needs them. `mode` is the head's engine mode | -**A sync run** publishes the base graph under the commit it analyzed as soon as -the analysis succeeds, whether or not delivering it does: a push the remote -refuses must not throw the analysis away, and the next sync or review catches up -from the artifact. When delivery writes a baseline commit on top (`in_place`), it +**A sync run** publishes the base graph under the commit it analyzed whether or +not delivering it succeeds, so a push the remote refuses does not throw the +analysis away: the next sync or review catches up from the artifact. When delivery writes a baseline commit on top (`in_place`), it is published under that commit too, because a pull request opened either side of that commit has a different merge base. @@ -205,8 +203,8 @@ otherwise never be saved. Only an analysis of an older commit than the tip's is dropped, so the tip stays the latest diagram. If another sync moved the baseline branch, it builds on that tip once. A push GitHub refuses with a branch rule error (`GH006` for branch protection, `GH013` for a ruleset) fails the run naming the bypass to add; any other refusal while the tip -did not move fails it asking to check the token. Either way the analysis is -already published as an artifact. +did not move fails it asking to check the token. On github.com the analysis is +still published as an artifact. The tip is compared just before the push, not in the same transaction: if a sync of a newer commit lands in that window, the push is no longer a fast-forward and diff --git a/scripts/action/codeboarding-baseline.sh b/scripts/action/codeboarding-baseline.sh index c7be901b..fdea894c 100644 --- a/scripts/action/codeboarding-baseline.sh +++ b/scripts/action/codeboarding-baseline.sh @@ -16,6 +16,10 @@ baseline_fail() { exit 1 } +# True when git push output $1 is GitHub refusing a branch rule: GH006 is classic +# branch protection, GH013 a ruleset. +refused_by_rule() { grep -qiE 'protected branch|GH006|GH013|rule violation' <<< "$1"; } + # Returns 0 when branch $2 (BASELINE_BRANCH by default) exists in repository $1 and # 2 when it does not. Any other failure is retried once, so one network blip does # not fail the run. @@ -105,10 +109,10 @@ from_codeboarding_baseline() { # Saves the analysis installed by install-sync.sh as one fast-forward commit on # BASELINE_BRANCH, never writing to the synced branch. Called by deliver-sync.sh, -# whose REMOTE, BASE_SHA, emit_result and refused_by_rule it uses; always exits. +# whose REMOTE, BASE_SHA and emit_result it uses; always exits. save_to_codeboarding_baseline() { local branch="$BASELINE_BRANCH" tree="$RUNNER_TEMP/codeboarding-baseline-tree" - local index="$RUNNER_TEMP/codeboarding-baseline-index" git_dir files new_tree tip tip_source parent commit now + local index="$RUNNER_TEMP/codeboarding-baseline-index" git_dir files new_tree tip tip_source parent commit push_output now git_dir="$(git rev-parse --absolute-git-dir)" rm -rf "$tree" "$index" mkdir -p "$tree" @@ -154,7 +158,7 @@ CodeBoarding-Config: $CFG_HASH") parent=(-p "$tip") if [ "$tip_source" = "$BASE_SHA" ] && git diff --quiet -I '"generated_at"' -I '"timestamp"' "$tip" "$new_tree"; then - emit_result "$files" false "$BASE_SHA" + emit_result "$files" false echo "::notice::$branch already holds this analysis of $SYNCED_BRANCH @${BASE_SHA:0:7}." exit 0 fi @@ -162,7 +166,7 @@ CodeBoarding-Config: $CFG_HASH") if [ "$tip_source" != "$BASE_SHA" ]; then git fetch -q --depth="$(( CATCHUP_BOUND + 1 ))" "$REMOTE" "$SYNCED_BRANCH" if git merge-base --is-ancestor "$BASE_SHA" "$tip_source" 2>/dev/null; then - emit_result "$files" false "$BASE_SHA" + emit_result "$files" false echo "::notice::$branch already holds the analysis of a newer commit, ${tip_source:0:7}; leaving it." exit 0 fi @@ -171,20 +175,20 @@ CodeBoarding-Config: $CFG_HASH") commit="$(git commit-tree "$new_tree" ${parent[@]+"${parent[@]}"} \ -m "chore(codeboarding): diagram of $SYNCED_BRANCH @${BASE_SHA:0:7}" "${trailers[@]}")" # Never forced: the parent is the tip just read, so this only ever fast-forwards. - if pushed="$(git push -q "$REMOTE" "$commit:refs/heads/$branch" 2>&1)"; then - emit_result "$files" true "$BASE_SHA" + if push_output="$(git push -q "$REMOTE" "$commit:refs/heads/$branch" 2>&1)"; then + emit_result "$files" true exit 0 fi - echo "$pushed" >&2 - if refused_by_rule "$pushed"; then - baseline_fail "GitHub refused the push to $branch because a ruleset or branch protection covers it. Add the identity sync pushes as (GitHub Actions for the default token, or the CodeBoarding app) as a bypass actor for $branch: https://github.com/CodeBoarding/CodeBoarding-action/blob/main/docs/COMMIT_STRATEGY.md#the-baseline-branch" + echo "$push_output" >&2 + if refused_by_rule "$push_output"; then + baseline_fail "GitHub refused the push to $branch: a ruleset or branch protection covers it. Add GitHub Actions (or the CodeBoarding app, if github_token is its token) as a bypass actor: https://github.com/CodeBoarding/CodeBoarding-action/blob/main/docs/COMMIT_STRATEGY.md#the-baseline-branch" fi now="$(git ls-remote "$REMOTE" "refs/heads/$branch" | awk '{print $1; exit}')" if [ "$now" = "$tip" ]; then baseline_fail "GitHub refused the push to $branch. Check that github_token may push to it and that no branch rule covers it." fi done - emit_result "$files" false "$BASE_SHA" + emit_result "$files" false echo "::notice::Another sync keeps updating $branch; leaving it to that run." exit 0 } diff --git a/scripts/action/configure-auth.sh b/scripts/action/configure-auth.sh index 3ca9425d..93136ff7 100755 --- a/scripts/action/configure-auth.sh +++ b/scripts/action/configure-auth.sh @@ -1,9 +1,8 @@ #!/usr/bin/env bash # Starts the hosted credential relay when the resolved plan calls for it. # -# The plan itself was decided by verify-credentials.sh; this step starts the relay that -# plan calls for. The relay is stdlib-only, so it runs before the checkout and the -# engine install, and the quota check after it can stop the run in seconds. A +# The plan was decided by verify-credentials.sh. The relay is stdlib-only, so it starts +# before the checkout and the engine install, in time for the quota check. A # direct-provider run has nothing to do here: its key never leaves the runner. set -euo pipefail AUTH_DIR="${RUNNER_TEMP}/codeboarding-auth" diff --git a/scripts/action/deliver-sync.sh b/scripts/action/deliver-sync.sh index 141e17d6..56e57e6b 100755 --- a/scripts/action/deliver-sync.sh +++ b/scripts/action/deliver-sync.sh @@ -18,29 +18,28 @@ SH chmod 700 "$ASKPASS" export GIT_ASKPASS="$ASKPASS" GIT_TERMINAL_PROMPT=0 trap 'rm -f "$ASKPASS"' EXIT -# A pull request's merge base is whichever commit its author branched from, and -# this run's analysis is valid for two of them: the commit it analyzed, published -# whether or not delivery succeeds, and baseline_sha, the baseline commit written -# on top, which differs only in .codeboarding files that the fingerprint ignores. -# Publishing both means a pull request opened either side of a sync commit still -# gets an exact hit. +# baseline_sha is the commit written on top of the analyzed one, set only when +# in_place writes one. It differs only in .codeboarding files the fingerprint +# ignores, so the analysis is published under it too: a pull request opened +# either side of it still gets an exact hit. emit_result() { - printf 'files_written=%s\ncommitted=%s\nbaseline_sha=%s\n' "$1" "$2" "$3" >> "$GITHUB_OUTPUT" + printf 'files_written=%s\ncommitted=%s\nbaseline_sha=%s\n' "$1" "$2" "${3:-}" >> "$GITHUB_OUTPUT" } -# GitHub's refusal when a branch rule covers the branch: GH006 is classic branch -# protection, GH013 a ruleset. -refused_by_rule() { grep -qiE 'protected branch|GH006|GH013|rule violation' <<< "$1"; } classify_push_failure() { - local expected="$1" branch="$2" pushed="$3" current + local expected="$1" branch="$2" push_output="$3" current current="$(git ls-remote "$REMOTE" "refs/heads/$branch" | awk '{print $1; exit}')" [ "$current" != "$(git rev-parse HEAD)" ] || return 0 if [ "$current" != "$expected" ]; then - emit_result "$files_written" false "$BASE_SHA" + emit_result "$files_written" false echo "::notice::A newer run updated $branch; leaving it untouched." exit 0 fi - if refused_by_rule "$pushed"; then - baseline_fail "$branch is protected, so sync cannot commit the analysis to it. Remove \`codeboarding_analysis_location: in_place\` (or \`sync_strategy: push\`) from both CodeBoarding jobs, and sync saves it to \`codeboarding/baseline\`, a branch of its own: https://github.com/CodeBoarding/CodeBoarding-action#keep-the-baseline-current" + if refused_by_rule "$push_output"; then + # Only the default branch's analysis can live on codeboarding/baseline. + if [ "$branch" = "${DEFAULT_BRANCH:-}" ]; then + baseline_fail "GitHub refused the push to $branch: a ruleset or branch protection covers it. Remove \`codeboarding_analysis_location: in_place\` from both CodeBoarding jobs, and sync saves the analysis to \`codeboarding/baseline\`, a branch of its own: https://github.com/CodeBoarding/CodeBoarding-action#keep-the-baseline-current" + fi + baseline_fail "GitHub refused the push to $branch: a ruleset or branch protection covers it. Add GitHub Actions (or the CodeBoarding app, if github_token is its token) as a bypass actor: https://github.com/CodeBoarding/CodeBoarding-action#keep-the-analysis-on-the-code-branch" fi baseline_fail "Could not push the CodeBoarding baseline to $branch." } @@ -73,7 +72,7 @@ files_written="$(find "$CHECKOUT_DIR/.codeboarding" -maxdepth 1 -type f \ git fetch "$REMOTE" "$SYNCED_BRANCH" remote_sha="$(git rev-parse FETCH_HEAD)" if [ "$remote_sha" != "$BASE_SHA" ]; then - emit_result "$files_written" false "$BASE_SHA" + emit_result "$files_written" false echo "::notice::$SYNCED_BRANCH advanced during analysis; a newer run should update its baseline." exit 0 fi @@ -83,7 +82,7 @@ fi # every run. Dropping either filter turns every sync into a commit. if git diff --cached --quiet || git diff --cached --quiet -I '"generated_at"' -I '"timestamp"'; then git reset -q - emit_result "$files_written" false "$BASE_SHA" + emit_result "$files_written" false echo "::notice::The CodeBoarding baseline is unchanged." exit 0 fi @@ -91,7 +90,7 @@ fi git commit -m 'chore(codeboarding): sync analysis baseline' >/dev/null push_status=0 -pushed="$(git push "$REMOTE" "HEAD:refs/heads/$SYNCED_BRANCH" 2>&1)" || push_status=$? -echo "$pushed" >&2 -[ "$push_status" = 0 ] || classify_push_failure "$BASE_SHA" "$SYNCED_BRANCH" "$pushed" +push_output="$(git push "$REMOTE" "HEAD:refs/heads/$SYNCED_BRANCH" 2>&1)" || push_status=$? +echo "$push_output" >&2 +[ "$push_status" = 0 ] || classify_push_failure "$BASE_SHA" "$SYNCED_BRANCH" "$push_output" emit_result "$files_written" true "$(git rev-parse HEAD)" diff --git a/scripts/action/quota_check.py b/scripts/action/quota_check.py index 03d00d39..e8da065f 100755 --- a/scripts/action/quota_check.py +++ b/scripts/action/quota_check.py @@ -2,8 +2,7 @@ """Stops a run whose LLM can no longer be called, before any analysis starts. A spent quota otherwise shows at the first model call, after the static analysis. -Only a definite "spent" stops the run: a check that cannot reach a verdict leaves the -analysis to try, as every run did before this existed. +Only a definite "spent" stops the run; any other answer lets the analysis try. """ from __future__ import annotations @@ -15,12 +14,11 @@ from urllib.error import HTTPError from urllib.request import Request, urlopen -DOCS = "https://github.com/CodeBoarding/CodeBoarding-action#authentication-and-providers" OPENROUTER_KEY_URL = "https://openrouter.ai/api/v1/key" HOSTED_SPENT = ( - "This account's free CodeBoarding quota is used up for the week, so no analysis ran; it resets weekly. " - f"Wait for the reset, or switch to `llm: license` or your own provider key ([how]({DOCS}))." + "Your CodeBoarding quota is used up, so no analysis ran. " + "Buy a license at https://codeboarding.org/pricing, or wait for the weekly reset." ) KEY_SPENT = ( "The key in `openrouter_api_key` has reached its OpenRouter spending limit, so no analysis ran. " @@ -32,8 +30,8 @@ def _get(url: str, headers: dict[str, str] | None = None) -> tuple[int, bytes]: try: with urlopen(Request(url, headers=headers or {}), timeout=30) as response: # nosec B310 - fixed URLs return response.status, response.read() - except HTTPError as response: - return response.code, response.read() + except HTTPError as error: + return error.code, error.read() def verdict(auth_dir: Path) -> str | None: @@ -41,9 +39,8 @@ def verdict(auth_dir: Path) -> str | None: tier = (auth_dir / "tier").read_text(encoding="utf-8").strip() env = auth_dir / "env" if tier in ("hosted", "license"): - # Through the relay, which signs the request as this run. The proxy checks the - # quota on every request before forwarding it; one without a body runs no model - # and is not metered, so asking costs nothing. Paid licences always pass. + # Asked through the relay, which signs the request as this run. The proxy checks + # the quota before forwarding; a request without a body runs no model and costs nothing. status, _ = _get((env / "OPENROUTER_BASE_URL").read_text(encoding="utf-8").rstrip("/") + "/models") if status == 402: return HOSTED_SPENT @@ -57,9 +54,9 @@ def verdict(auth_dir: Path) -> str | None: if status != 200: print(f"::notice::Could not check the OpenRouter key's limit (HTTP {status}); analyzing anyway.") return None - # null means the key has no limit. remaining = json.loads(body).get("data", {}).get("limit_remaining") - if isinstance(remaining, (int, float)) and not isinstance(remaining, bool) and remaining <= 0: + # None means the key has no limit. + if remaining is not None and remaining <= 0: return KEY_SPENT return None @@ -67,8 +64,8 @@ def verdict(auth_dir: Path) -> str | None: def main() -> int: try: reason = verdict(Path(os.environ["RUNNER_TEMP"]) / "codeboarding-auth") - except Exception as exc: # best effort: never the reason a run fails - print(f"::notice::Could not check the LLM quota ({type(exc).__name__}); analyzing anyway.") + except Exception as error: # best effort: never the reason a run fails + print(f"::notice::Could not check the LLM quota ({type(error).__name__}); analyzing anyway.") return 0 if reason is None: return 0 diff --git a/tests/test_action_sync.py b/tests/test_action_sync.py index 681afbf6..ae992700 100644 --- a/tests/test_action_sync.py +++ b/tests/test_action_sync.py @@ -385,8 +385,9 @@ def tearDown(self) -> None: def _git(self, cwd: Path, *args: str) -> str: return subprocess.run(["git", *args], cwd=str(cwd), capture_output=True, text=True, check=True).stdout.strip() - def test_it_publishes_the_analysis_under_both_commits(self) -> None: + def _deliver(self, **env: str) -> tuple[subprocess.CompletedProcess, dict[str, str]]: output = self.root / "github-output" + output.write_text("", encoding="utf-8") result = subprocess.run( [str(ROOT / "scripts" / "action" / "deliver-sync.sh")], env={ @@ -401,54 +402,51 @@ def test_it_publishes_the_analysis_under_both_commits(self) -> None: "GITHUB_TOKEN": "unused", "REPOSITORY": "owner/repo", "SYNCED_BRANCH": "main", + **env, }, capture_output=True, text=True, check=False, ) - self.assertEqual(result.returncode, 0, result.stderr or result.stdout) - values = dict(line.split("=", 1) for line in output.read_text(encoding="utf-8").splitlines() if "=" in line) - self.assertEqual(values["committed"], "true") - baseline_sha = self._git(self.checkout, "rev-parse", "HEAD") - # The analysis describes the tree it ran on and the baseline commit - # written on top, which differs only in files the fingerprint ignores. - # A pull request branched either side of that commit must hit the cache. - self.assertEqual(values["baseline_sha"], baseline_sha) - self.assertNotEqual(values["baseline_sha"], self.analyzed_sha) + return result, values - def test_a_protected_branch_says_to_save_the_analysis_elsewhere(self) -> None: + def _protect_main(self) -> None: hook = self.remote / "hooks" / "pre-receive" hook.write_text( '#!/bin/sh\necho "error: GH006: Protected branch update failed for refs/heads/main." >&2\nexit 1\n', encoding="utf-8", ) hook.chmod(0o755) - output = self.root / "github-output" - result = subprocess.run( - [str(ROOT / "scripts" / "action" / "deliver-sync.sh")], - env={ - "PATH": os.environ["PATH"], - "PYTHONPATH": str(self.core), - "ACTION_PATH": str(ROOT), - "ANALYSIS_DIR": str(self.analysis), - "CHECKOUT_DIR": str(self.checkout), - "GITHUB_OUTPUT": str(output), - "RUNNER_TEMP": str(self.root), - "GITHUB_SERVER_URL": str(self.root), - "GITHUB_TOKEN": "unused", - "REPOSITORY": "owner/repo", - "SYNCED_BRANCH": "main", - }, - capture_output=True, - text=True, - check=False, - ) + + def test_it_publishes_the_analysis_under_both_commits(self) -> None: + result, values = self._deliver() + + self.assertEqual(result.returncode, 0, result.stderr or result.stdout) + self.assertEqual(values["committed"], "true") + # The analysis describes the tree it ran on and the baseline commit + # written on top, which differs only in files the fingerprint ignores. + # A pull request branched either side of that commit must hit the cache. + self.assertEqual(values["baseline_sha"], self._git(self.checkout, "rev-parse", "HEAD")) + self.assertNotEqual(values["baseline_sha"], self.analyzed_sha) + + def test_a_protected_default_branch_says_to_save_the_analysis_elsewhere(self) -> None: + self._protect_main() + + result, values = self._deliver(DEFAULT_BRANCH="main") self.assertNotEqual(result.returncode, 0) - values = dict(line.split("=", 1) for line in output.read_text(encoding="utf-8").splitlines() if "=" in line) reason = values["failure_reason"] - self.assertIn("main is protected", reason) - self.assertIn("codeboarding_analysis_location: in_place", reason) + self.assertIn("Remove `codeboarding_analysis_location: in_place`", reason) self.assertIn("#keep-the-baseline-current", reason) self.assertIn(f"::error::{reason}", result.stdout) + + def test_a_protected_branch_other_than_the_default_names_the_bypass(self) -> None: + # codeboarding/baseline holds only the default branch's analysis, so moving there fails too. + self._protect_main() + + result, values = self._deliver(DEFAULT_BRANCH="trunk") + + self.assertNotEqual(result.returncode, 0) + self.assertIn("bypass actor", values["failure_reason"]) + self.assertNotIn("codeboarding_analysis_location", values["failure_reason"]) diff --git a/tests/test_baseline_branch.py b/tests/test_baseline_branch.py index b9d5e8ed..60f6b77b 100644 --- a/tests/test_baseline_branch.py +++ b/tests/test_baseline_branch.py @@ -105,7 +105,7 @@ def test_the_first_sync_creates_an_orphan_branch_with_its_provenance(self) -> No (only,) = self._branch_log() self.assertEqual(only.split(), [git(self.remote, "rev-parse", BRANCH)], "the branch must have no parent") self.assertEqual(values["committed"], "true") - self.assertEqual(values["baseline_sha"], main_before, "artifacts are named for the analysed commit") + self.assertEqual(values["baseline_sha"], "", "nothing is written on main to publish under") files = set(git(self.remote, "ls-tree", "-r", "--name-only", BRANCH).splitlines()) self.assertEqual( files, diff --git a/tests/test_quota_check.py b/tests/test_quota_check.py index 22ecf572..4ec5437e 100644 --- a/tests/test_quota_check.py +++ b/tests/test_quota_check.py @@ -2,6 +2,7 @@ from __future__ import annotations +import importlib.util import json import os import subprocess @@ -19,11 +20,17 @@ class _Upstream: """Answers every request with one status and body, and records what was asked.""" def __init__(self, status: int, body: bytes) -> None: - requests: list[tuple[str, str, str]] = [] + requests: list[dict[str, str | None]] = [] class Handler(BaseHTTPRequestHandler): def do_GET(self) -> None: # noqa: N802 - requests.append((self.path, self.headers.get("Authorization", ""), self.headers.get("Content-Length"))) + requests.append( + { + "path": self.path, + "authorization": self.headers.get("Authorization"), + "content_length": self.headers.get("Content-Length"), + } + ) self.send_response(status) self.send_header("Content-Length", str(len(body))) self.end_headers() @@ -61,12 +68,12 @@ def _upstream(self, status: int, body: object = b"") -> _Upstream: self.addCleanup(upstream.close) return upstream - def _check(self, **env: str) -> tuple[subprocess.CompletedProcess, str]: + def _check(self) -> tuple[subprocess.CompletedProcess, str]: output = self.root / "github-output" output.write_text("") result = subprocess.run( ["python3", str(SCRIPT)], - env={"PATH": os.environ["PATH"], "RUNNER_TEMP": str(self.root), "GITHUB_OUTPUT": str(output), **env}, + env={"PATH": os.environ["PATH"], "RUNNER_TEMP": str(self.root), "GITHUB_OUTPUT": str(output)}, capture_output=True, text=True, check=False, @@ -80,11 +87,12 @@ def test_a_spent_hosted_quota_stops_the_run_with_the_reason(self) -> None: result, output = self._check() self.assertEqual(result.returncode, 1) - self.assertIn("failure_reason=This account's free CodeBoarding quota is used up", output) + self.assertIn("failure_reason=Your CodeBoarding quota is used up", output) + self.assertIn("https://codeboarding.org/pricing", output) self.assertIn("::error title=CodeBoarding LLM quota::", result.stdout) - # Asked through the relay, which signs it; no body, so the proxy runs no model. - self.assertEqual([path for path, _auth, _length in proxy.requests], ["/models"]) - self.assertIn(proxy.requests[0][2], (None, "0")) + # No body, so the proxy runs no model. + self.assertEqual([request["path"] for request in proxy.requests], ["/models"]) + self.assertIn(proxy.requests[0]["content_length"], (None, "0")) def test_a_hosted_quota_with_room_lets_the_run_go_on(self) -> None: proxy = self._upstream(200, {"data": []}) @@ -132,12 +140,10 @@ class OpenRouterKeyTests(unittest.TestCase): """The key's own limit, read in-process so the URL can point at a local server.""" def setUp(self) -> None: - import importlib.util - - spec = importlib.util.spec_from_file_location("quota_check", SCRIPT) - assert spec and spec.loader - self.module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(self.module) + module_spec = importlib.util.spec_from_file_location("quota_check", SCRIPT) + assert module_spec and module_spec.loader + self.module = importlib.util.module_from_spec(module_spec) + module_spec.loader.exec_module(self.module) temp_dir = tempfile.TemporaryDirectory() self.addCleanup(temp_dir.cleanup) self.auth = Path(temp_dir.name) @@ -146,8 +152,8 @@ def setUp(self) -> None: (self.auth / "provider-name").write_text("openrouter") (self.auth / "env" / "OPENROUTER_API_KEY").write_text("sk-or-user") - def _verdict(self, data: dict) -> tuple[str | None, list]: - upstream = _Upstream(200, json.dumps({"data": data}).encode()) + def _verdict(self, key_data: dict) -> tuple[str | None, list[dict[str, str | None]]]: + upstream = _Upstream(200, json.dumps({"data": key_data}).encode()) self.addCleanup(upstream.close) self.module.OPENROUTER_KEY_URL = f"{upstream.url}/api/v1/key" return self.module.verdict(self.auth), upstream.requests @@ -156,7 +162,8 @@ def test_a_key_at_its_limit_stops_the_run(self) -> None: reason, requests = self._verdict({"limit": 5, "limit_remaining": 0}) self.assertEqual(reason, self.module.KEY_SPENT) - self.assertEqual(requests[0][:2], ("/api/v1/key", "Bearer sk-or-user")) + self.assertEqual(requests[0]["path"], "/api/v1/key") + self.assertEqual(requests[0]["authorization"], "Bearer sk-or-user") def test_a_key_with_room_or_no_limit_lets_the_run_go_on(self) -> None: for remaining in (3.5, None): From 07c63d21475a1e85c4414cd680a5219fd266aeea Mon Sep 17 00:00:00 2001 From: Svilen Stefanov Date: Sun, 6 Dec 2026 00:05:28 +0100 Subject: [PATCH 3/3] refactor: move the early quota check out of this PR Review asked for quota handling in one place: Core's LLMQuotaError already tells the user's CodeBoarding quota apart from the hosted provider running out, and the Action shows its message. The early check moves to Core, so the Action gets it without its own request or copy of the message. Authentication is configured where it was before, and credentials are cleared in review mode only, as on main. Co-Authored-By: Claude Opus 5.5 --- action.yml | 35 +++--- scripts/action/configure-auth.sh | 6 +- scripts/action/quota_check.py | 79 -------------- tests/test_quota_check.py | 176 ------------------------------- 4 files changed, 17 insertions(+), 279 deletions(-) delete mode 100755 scripts/action/quota_check.py delete mode 100644 tests/test_quota_check.py diff --git a/action.yml b/action.yml index 782acbcd..9a1db454 100644 --- a/action.yml +++ b/action.yml @@ -392,21 +392,8 @@ runs: fi exit 1 - - name: Configure analysis authentication - if: steps.guard.outputs.skip != 'true' - shell: bash - env: - ACTION_PATH: ${{ github.action_path }} - run: "$GITHUB_ACTION_PATH/scripts/action/configure-auth.sh" - - # A spent quota stops the run here, in seconds, not at the first model call. - - name: Check LLM quota - id: quota - if: steps.guard.outputs.skip != 'true' - shell: bash - run: python3 "$GITHUB_ACTION_PATH/scripts/action/quota_check.py" - - # A sync that could not save its result fails here, in seconds, not after a full analysis. + # Before the checkout and the engine install, like the credential check: a sync + # that could not save its result fails in seconds, not after a full analysis. - name: Check analysis branch id: analysis_check if: steps.guard.outputs.skip != 'true' && steps.guard.outputs.mode == 'sync' @@ -468,6 +455,13 @@ runs: exit 1 } + - name: Configure analysis authentication + if: steps.guard.outputs.skip != 'true' + shell: bash + env: + ACTION_PATH: ${{ github.action_path }} + run: "$GITHUB_ACTION_PATH/scripts/action/configure-auth.sh" + - name: Resolve analysis cache keys id: state if: steps.guard.outputs.skip != 'true' @@ -622,7 +616,7 @@ runs: FILES: ${{ steps.sync_commit.outputs.files_written }} SAVED_TO: ${{ steps.guard.outputs.analysis_branch || steps.guard.outputs.synced_branch }} # A failed sync has no pull request to comment on; the summary is where it says why. - FAILURE_REASON: ${{ steps.guard.outputs.failure_reason || steps.analysis_check.outputs.failure_reason || steps.quota.outputs.failure_reason || steps.state.outputs.failure_reason || steps.sync_analyze.outputs.failure_reason || steps.sync_commit.outputs.failure_reason }} + FAILURE_REASON: ${{ steps.guard.outputs.failure_reason || steps.analysis_check.outputs.failure_reason || steps.state.outputs.failure_reason || steps.sync_analyze.outputs.failure_reason || steps.sync_commit.outputs.failure_reason }} run: "$GITHUB_ACTION_PATH/scripts/action/sync-summary.sh" - name: Generate review baseline @@ -983,11 +977,10 @@ runs: if-no-files-found: error retention-days: 14 - # The analysis steps remove the credentials themselves; this covers a run that - # failed before them (they are configured ahead of the checkout), and a setup PR's - # run, which keeps them for its previews. + # The head and preview steps remove the credentials themselves; this covers a run that + # failed before them, and a setup PR's run, which keeps them for its previews. - name: Remove analysis credentials - if: always() && steps.guard.outputs.skip != 'true' + if: always() && steps.guard.outputs.skip != 'true' && steps.guard.outputs.mode == 'review' shell: bash run: '"$GITHUB_ACTION_PATH/scripts/action/clear-auth.sh"' @@ -1019,6 +1012,6 @@ runs: message: | ### CodeBoarding review · failed - ${{ steps.quota.outputs.failure_reason || steps.review_baseline.outputs.failure_reason || steps.review_analyze.outputs.failure_reason }} + ${{ steps.review_baseline.outputs.failure_reason || steps.review_analyze.outputs.failure_reason }} See the [workflow logs](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}). diff --git a/scripts/action/configure-auth.sh b/scripts/action/configure-auth.sh index 93136ff7..6abcc9da 100755 --- a/scripts/action/configure-auth.sh +++ b/scripts/action/configure-auth.sh @@ -1,9 +1,9 @@ #!/usr/bin/env bash # Starts the hosted credential relay when the resolved plan calls for it. # -# The plan was decided by verify-credentials.sh. The relay is stdlib-only, so it starts -# before the checkout and the engine install, in time for the quota check. A -# direct-provider run has nothing to do here: its key never leaves the runner. +# The plan itself was decided by verify-credentials.sh before the checkout; this step only +# does the part that needs the engine's Python present. A direct-provider run has +# nothing to do here: its key never leaves the runner. set -euo pipefail AUTH_DIR="${RUNNER_TEMP}/codeboarding-auth" HOSTED_PROXY_URL="https://auduihjmm4b735zci7vyabuikq0hppqn.lambda-url.us-east-1.on.aws" diff --git a/scripts/action/quota_check.py b/scripts/action/quota_check.py deleted file mode 100755 index e8da065f..00000000 --- a/scripts/action/quota_check.py +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/env python3 -"""Stops a run whose LLM can no longer be called, before any analysis starts. - -A spent quota otherwise shows at the first model call, after the static analysis. -Only a definite "spent" stops the run; any other answer lets the analysis try. -""" - -from __future__ import annotations - -import json -import os -import sys -from pathlib import Path -from urllib.error import HTTPError -from urllib.request import Request, urlopen - -OPENROUTER_KEY_URL = "https://openrouter.ai/api/v1/key" - -HOSTED_SPENT = ( - "Your CodeBoarding quota is used up, so no analysis ran. " - "Buy a license at https://codeboarding.org/pricing, or wait for the weekly reset." -) -KEY_SPENT = ( - "The key in `openrouter_api_key` has reached its OpenRouter spending limit, so no analysis ran. " - "Raise the key's limit on openrouter.ai, or use another key." -) - - -def _get(url: str, headers: dict[str, str] | None = None) -> tuple[int, bytes]: - try: - with urlopen(Request(url, headers=headers or {}), timeout=30) as response: # nosec B310 - fixed URLs - return response.status, response.read() - except HTTPError as error: - return error.code, error.read() - - -def verdict(auth_dir: Path) -> str | None: - """The reason the run cannot call its LLM, or None when it can or that is unknown.""" - tier = (auth_dir / "tier").read_text(encoding="utf-8").strip() - env = auth_dir / "env" - if tier in ("hosted", "license"): - # Asked through the relay, which signs the request as this run. The proxy checks - # the quota before forwarding; a request without a body runs no model and costs nothing. - status, _ = _get((env / "OPENROUTER_BASE_URL").read_text(encoding="utf-8").rstrip("/") + "/models") - if status == 402: - return HOSTED_SPENT - if status != 200: - print(f"::notice::Could not check the CodeBoarding quota (HTTP {status}); analyzing anyway.") - return None - if (auth_dir / "provider-name").read_text(encoding="utf-8").strip() != "openrouter": - return None - key = (env / "OPENROUTER_API_KEY").read_text(encoding="utf-8").strip() - status, body = _get(OPENROUTER_KEY_URL, {"Authorization": f"Bearer {key}"}) - if status != 200: - print(f"::notice::Could not check the OpenRouter key's limit (HTTP {status}); analyzing anyway.") - return None - remaining = json.loads(body).get("data", {}).get("limit_remaining") - # None means the key has no limit. - if remaining is not None and remaining <= 0: - return KEY_SPENT - return None - - -def main() -> int: - try: - reason = verdict(Path(os.environ["RUNNER_TEMP"]) / "codeboarding-auth") - except Exception as error: # best effort: never the reason a run fails - print(f"::notice::Could not check the LLM quota ({type(error).__name__}); analyzing anyway.") - return 0 - if reason is None: - return 0 - print(f"::error title=CodeBoarding LLM quota::{reason}") - with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as output: - output.write(f"failure_reason={reason}\n") - return 1 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/tests/test_quota_check.py b/tests/test_quota_check.py deleted file mode 100644 index 4ec5437e..00000000 --- a/tests/test_quota_check.py +++ /dev/null @@ -1,176 +0,0 @@ -"""The quota check stops a run whose LLM cannot be called, and nothing else.""" - -from __future__ import annotations - -import importlib.util -import json -import os -import subprocess -import tempfile -import threading -import unittest -from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer -from pathlib import Path - -ROOT = Path(__file__).resolve().parent.parent -SCRIPT = ROOT / "scripts" / "action" / "quota_check.py" - - -class _Upstream: - """Answers every request with one status and body, and records what was asked.""" - - def __init__(self, status: int, body: bytes) -> None: - requests: list[dict[str, str | None]] = [] - - class Handler(BaseHTTPRequestHandler): - def do_GET(self) -> None: # noqa: N802 - requests.append( - { - "path": self.path, - "authorization": self.headers.get("Authorization"), - "content_length": self.headers.get("Content-Length"), - } - ) - self.send_response(status) - self.send_header("Content-Length", str(len(body))) - self.end_headers() - self.wfile.write(body) - - def log_message(self, *_args: object) -> None: - return - - self.requests = requests - self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) - threading.Thread(target=self.server.serve_forever, daemon=True).start() - self.url = f"http://127.0.0.1:{self.server.server_port}" - - def close(self) -> None: - self.server.shutdown() - self.server.server_close() - - -class QuotaCheckTests(unittest.TestCase): - def setUp(self) -> None: - temp_dir = tempfile.TemporaryDirectory() - self.addCleanup(temp_dir.cleanup) - self.root = Path(temp_dir.name) - self.auth = self.root / "codeboarding-auth" - (self.auth / "env").mkdir(parents=True) - - def _plan(self, tier: str, provider: str, **env: str) -> None: - (self.auth / "tier").write_text(tier) - (self.auth / "provider-name").write_text(provider) - for name, value in env.items(): - (self.auth / "env" / name).write_text(value) - - def _upstream(self, status: int, body: object = b"") -> _Upstream: - upstream = _Upstream(status, body if isinstance(body, bytes) else json.dumps(body).encode()) - self.addCleanup(upstream.close) - return upstream - - def _check(self) -> tuple[subprocess.CompletedProcess, str]: - output = self.root / "github-output" - output.write_text("") - result = subprocess.run( - ["python3", str(SCRIPT)], - env={"PATH": os.environ["PATH"], "RUNNER_TEMP": str(self.root), "GITHUB_OUTPUT": str(output)}, - capture_output=True, - text=True, - check=False, - ) - return result, output.read_text() - - def test_a_spent_hosted_quota_stops_the_run_with_the_reason(self) -> None: - proxy = self._upstream(402, {"error": {"message": "Resource exhausted: token limit reached"}}) - self._plan("hosted", "openrouter", OPENROUTER_BASE_URL=proxy.url) - - result, output = self._check() - - self.assertEqual(result.returncode, 1) - self.assertIn("failure_reason=Your CodeBoarding quota is used up", output) - self.assertIn("https://codeboarding.org/pricing", output) - self.assertIn("::error title=CodeBoarding LLM quota::", result.stdout) - # No body, so the proxy runs no model. - self.assertEqual([request["path"] for request in proxy.requests], ["/models"]) - self.assertIn(proxy.requests[0]["content_length"], (None, "0")) - - def test_a_hosted_quota_with_room_lets_the_run_go_on(self) -> None: - proxy = self._upstream(200, {"data": []}) - self._plan("license", "openrouter", OPENROUTER_BASE_URL=proxy.url) - - result, output = self._check() - - self.assertEqual(result.returncode, 0, result.stdout) - self.assertEqual(output, "") - - def test_any_other_answer_is_no_reason_to_stop(self) -> None: - for status in (401, 500, 502): - with self.subTest(status=status): - proxy = self._upstream(status, {"error": {"message": "no"}}) - self._plan("hosted", "openrouter", OPENROUTER_BASE_URL=proxy.url) - - result, output = self._check() - - self.assertEqual(result.returncode, 0, result.stdout) - self.assertEqual(output, "") - self.assertIn("::notice::", result.stdout) - - def test_an_unreachable_proxy_is_no_reason_to_stop(self) -> None: - proxy = self._upstream(200) - url = proxy.url - proxy.close() - self._plan("hosted", "openrouter", OPENROUTER_BASE_URL=url) - - result, output = self._check() - - self.assertEqual(result.returncode, 0, result.stdout) - self.assertEqual(output, "") - self.assertIn("::notice::", result.stdout) - - def test_a_direct_provider_other_than_openrouter_is_not_asked(self) -> None: - self._plan("byok", "anthropic", ANTHROPIC_API_KEY="sk-ant") - - result, output = self._check() - - self.assertEqual(result.returncode, 0, result.stdout) - self.assertEqual(output, "") - - -class OpenRouterKeyTests(unittest.TestCase): - """The key's own limit, read in-process so the URL can point at a local server.""" - - def setUp(self) -> None: - module_spec = importlib.util.spec_from_file_location("quota_check", SCRIPT) - assert module_spec and module_spec.loader - self.module = importlib.util.module_from_spec(module_spec) - module_spec.loader.exec_module(self.module) - temp_dir = tempfile.TemporaryDirectory() - self.addCleanup(temp_dir.cleanup) - self.auth = Path(temp_dir.name) - (self.auth / "env").mkdir() - (self.auth / "tier").write_text("byok") - (self.auth / "provider-name").write_text("openrouter") - (self.auth / "env" / "OPENROUTER_API_KEY").write_text("sk-or-user") - - def _verdict(self, key_data: dict) -> tuple[str | None, list[dict[str, str | None]]]: - upstream = _Upstream(200, json.dumps({"data": key_data}).encode()) - self.addCleanup(upstream.close) - self.module.OPENROUTER_KEY_URL = f"{upstream.url}/api/v1/key" - return self.module.verdict(self.auth), upstream.requests - - def test_a_key_at_its_limit_stops_the_run(self) -> None: - reason, requests = self._verdict({"limit": 5, "limit_remaining": 0}) - - self.assertEqual(reason, self.module.KEY_SPENT) - self.assertEqual(requests[0]["path"], "/api/v1/key") - self.assertEqual(requests[0]["authorization"], "Bearer sk-or-user") - - def test_a_key_with_room_or_no_limit_lets_the_run_go_on(self) -> None: - for remaining in (3.5, None): - with self.subTest(limit_remaining=remaining): - reason, _requests = self._verdict({"limit_remaining": remaining}) - self.assertIsNone(reason) - - -if __name__ == "__main__": - unittest.main()