diff --git a/.github/workflows/nightly-next-tick.yml b/.github/workflows/nightly-next-tick.yml index c7461494f64e..1749952994c8 100644 --- a/.github/workflows/nightly-next-tick.yml +++ b/.github/workflows/nightly-next-tick.yml @@ -57,8 +57,11 @@ env: jobs: request: # A workflow_run counts only for this repository's own push runs: feat-cmux-next - # landings and nightly-next builds. - if: github.repository == 'manaflow-ai/cmux' && (github.event_name != 'workflow_run' || github.event.workflow_run.event == 'push' && github.event.workflow_run.head_repository.full_name == github.repository) + # landings and nightly-next builds. cmux-next and cmux-tui artifacts runs on nightly-next + # (a promotion's push, about 7 an hour on 2026-11-04) make no feat-cmux-next commit + # buildable and are not a finished build, so they start no tick; the cron backstop and + # the landings still do. + if: github.repository == 'manaflow-ai/cmux' && (github.event_name != 'workflow_run' || github.event.workflow_run.event == 'push' && github.event.workflow_run.head_repository.full_name == github.repository && (github.event.workflow_run.head_branch != 'nightly-next' || github.event.workflow_run.name == 'Nightly macOS build')) # CI_CONTROL_RUNNER, when set, takes this control job off Blacksmith Linux # (2026-10-28: every Blacksmith Linux size stopped starting jobs from ~20:00Z). runs-on: ${{ github.repository_owner != 'manaflow-ai' && 'ubuntu-24.04' || vars.CI_CONTROL_RUNNER || 'blacksmith-2vcpu-ubuntu-2404' }} @@ -152,8 +155,10 @@ jobs: # building nightly-next, else once the oldest landing the running build does not carry # has waited 10 minutes. A dispatch for one commit skips it. It reads nightly-next with # git ls-remote (no API budget; ticks 41791114042 and 41791169626 lost their promotion to - # an exhausted budget on the refs API), the rest through the API; its failure modes are in - # the script's docstring. + # an exhausted budget on the refs API) and the gap to the tip from this checkout (the compare + # API only when nightly-next's head is not in it); a tip already on nightly-next reads nothing + # more and requests nothing. The running builds come through the API. Its failure modes are + # in the script's docstring. - name: Apply the rolling rule id: rolling if: vars.NIGHTLY_NEXT_TRAIN != 'on' && inputs.sha == '' @@ -266,10 +271,13 @@ jobs: # This job reads the reconciled 2 vCPU Linux pool (RUNNER_POOLS.linux_2, Blacksmith 2 vCPU when # the variable is unset), not the hosted pool its targets wait on, checks out only its scripts, and has its own fixed group: one runs, # the newest waits, and a dispatch for one commit (a sha input) skips it as before. It holds - # only the job's GITHUB_TOKEN; it never cancels a started job (nightly_next_stuck_run.py). + # the job's GITHUB_TOKEN for its writes and the cmux-bot App token for its reads; it never cancels a + # started job (nightly_next_stuck_run.py). unstick: - if: github.repository == 'manaflow-ai/cmux' && inputs.sha == '' && (github.event_name != 'workflow_run' || github.event.workflow_run.event == 'push' && github.event.workflow_run.head_repository.full_name == github.repository) - runs-on: ${{ github.repository_owner != 'manaflow-ai' && 'ubuntu-24.04' || fromJSON(vars.RUNNER_POOLS || '{}').linux_2 || 'blacksmith-2vcpu-ubuntu-2404' }} + if: github.repository == 'manaflow-ai/cmux' && inputs.sha == '' && (github.event_name != 'workflow_run' || github.event.workflow_run.event == 'push' && github.event.workflow_run.head_repository.full_name == github.repository && (github.event.workflow_run.head_branch != 'nightly-next' || github.event.workflow_run.name == 'Nightly macOS build')) + # The linux_2 pool's members (.github/runners.json), named here, because this job holds an App key: + # no variable may put it on a machine this line does not name (tests/test_ci_fork_runner_routing.py). + runs-on: ${{ github.repository_owner != 'manaflow-ai' && 'ubuntu-24.04' || contains(fromJSON('["blacksmith-2vcpu-ubuntu-2404","blacksmith-4vcpu-ubuntu-2404"]'), fromJSON(vars.RUNNER_POOLS || '{}').linux_2) && fromJSON(vars.RUNNER_POOLS || '{}').linux_2 || 'blacksmith-2vcpu-ubuntu-2404' }} # Two bounded steps of reads and at most one cancel and one re-run. timeout-minutes: 25 concurrency: @@ -288,6 +296,7 @@ jobs: ref: ${{ github.sha }} path: .tick-tooling sparse-checkout: | + scripts/ci/gh_app_token.sh scripts/ci/gh_budget_wait.sh scripts/ci/nightly_next_cancelled_tip.sh scripts/ci/delivery_workflows.py @@ -301,6 +310,35 @@ jobs: scripts/ci/ui_tests_dispatch.py sparse-checkout-cone-mode: false + # This job's reads spend the cmux-bot App's budget, not the repository's GITHUB_TOKEN pool + # (5,000 an hour for every workflow, which ran dry hourly on 2026-11-04 with this tick its + # biggest spender: about 1,100 calls an hour, about 575 of them this job's). + # scripts/ci/gh_app_token.sh --reads-only sends a gh call made with github.token that only + # reads (a GET, a GraphQL query, a list or view) as the App, and github.token again when the + # App is refused; the cancels and re-runs go out once as github.token, unchanged. With no App + # token (a failed mint, or no CMUX_BOT_APP_ID) nothing is installed and every call is + # github.token's. Only this job holds the App key: the request job runs where + # CI_CONTROL_RUNNER puts it, which may be a reused machine, so it keeps only its job-scoped + # GITHUB_TOKEN (tests/test_ci_cloud_overflow_switch.py) and spends fewer reads instead. + - name: Mint the cmux-bot token for this job's reads + id: read-token + if: vars.CMUX_BOT_APP_ID != '' + continue-on-error: true + timeout-minutes: 1 + uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0 + with: + app-id: ${{ vars.CMUX_BOT_APP_ID }} + private-key: ${{ secrets.CMUX_BOT_APP_KEY }} + permission-actions: read + permission-contents: read + + # Before the rate-limit wait below, which then wraps it (its waits count once per job). + - name: Send this job's gh reads as the cmux-bot App, github.token as the fallback + env: + GH_APP_TOKEN: ${{ steps.read-token.outputs.token }} + GH_FALLBACK_TOKEN: ${{ github.token }} + run: bash .tick-tooling/scripts/ci/gh_app_token.sh --install --reads-only + - name: Wait through GitHub API rate limits in this job's gh calls run: bash .tick-tooling/scripts/ci/gh_budget_wait.sh --install @@ -330,6 +368,7 @@ jobs: GH_TOKEN: ${{ github.token }} NIGHTLY_NEXT_TRAIN: ${{ vars.NIGHTLY_NEXT_TRAIN }} GH_BUDGET_WAIT_ATTEMPTS: "1" + GH_APP_TOKEN_ATTEMPTS: "1" run: python3 -u .tick-tooling/scripts/ci/nightly_next_stuck_run.py "$GITHUB_REPOSITORY" # A tip on nightly-next whose newest run ended cancelled (a rescue that lost its @@ -340,5 +379,6 @@ jobs: env: GH_TOKEN: ${{ github.token }} GH_BUDGET_WAIT_ATTEMPTS: "1" + GH_APP_TOKEN_ATTEMPTS: "1" working-directory: .tick-tooling run: bash scripts/ci/nightly_next_cancelled_tip.sh "$GITHUB_REPOSITORY" diff --git a/scripts/ci/gh_app_token.sh b/scripts/ci/gh_app_token.sh index dd780a88c30f..db91e5dc05f5 100644 --- a/scripts/ci/gh_app_token.sh +++ b/scripts/ci/gh_app_token.sh @@ -25,6 +25,15 @@ # gh_budget_wait.sh's per-job ledger and total (GH_BUDGET_WAIT_MAX_SECONDS, default 3600), so # the two wrappers together wait at most that long; gh_budget_wait.sh, installed after this, # wraps this one and still waits for a core reset. Runs on macOS's bash 3.2. +# +# gh_app_token.sh --install --reads-only +# The same, except that only a call that reads goes out as the App +# (a `gh api` GET, a GraphQL query, or `gh run|workflow|pr|issue|release +# list|view`); every other call, writes and anything this cannot tell, +# runs once with github.token as before, untouched by this wrapper. For a +# job whose writes must stay github.token's (nightly-next-tick.yml: main's +# promote job admits the tick's dispatch by its actor) and whose reads +# should spend another actor's budget. REAL_GH=gh # --install writes the real gh's path here @@ -52,6 +61,8 @@ note() { } if [ "${1:-}" = "--install" ]; then + reads_only="" + [ "${2:-}" != "--reads-only" ] || reads_only=1 real="$(command -v gh 2>/dev/null || true)" if [ -z "${GH_APP_TOKEN:-}" ] || [ -z "${GH_FALLBACK_TOKEN:-}" ]; then echo "::warning title=GitHub API token::no release App token (the mint failed or the job has no App credentials); gh calls in this job use github.token" @@ -64,10 +75,15 @@ if [ "${1:-}" = "--install" ]; then mkdir -p "$dir/bin" (umask 077 && printf '%s' "$GH_APP_TOKEN" >"$dir/token") printf '%s' "$GH_FALLBACK_TOKEN" | digest >"$dir/fallback.sha256" + if [ -n "$reads_only" ]; then : >"$dir/reads-only"; else rm -f "$dir/reads-only"; fi sed "s|^REAL_GH=gh |REAL_GH='$real' |" "$0" >"$dir/bin/gh" chmod +x "$dir/bin/gh" echo "$dir/bin" >>"$GITHUB_PATH" - echo "gh calls made with github.token in this job go out as the release App first (real gh: $real)" + if [ -n "$reads_only" ]; then + echo "gh reads made with github.token in this job go out as the App first; writes stay github.token's (real gh: $real)" + else + echo "gh calls made with github.token in this job go out as the release App first (real gh: $real)" + fi exit 0 fi @@ -77,6 +93,43 @@ if [ ! -s "$dir/token" ] || [ -z "$caller" ] || exec "$REAL_GH" "$@" fi +# Whether a call only reads (--reads-only): `gh api` with no method but GET and no request +# fields (gh sends a call with fields as POST), a GraphQL request with no mutation, or a list or +# view subcommand. Anything else counts as a write. +reads_only_call() { + local method="" fields="" graphql="" mutation="" next="" + case "${1:-}" in + api) ;; + run | workflow) case "${2:-}" in list | view) return 0 ;; esac; return 1 ;; + pr | issue | release) case "${2:-}" in list | view) return 0 ;; esac; return 1 ;; + *) return 1 ;; + esac + shift + for arg in "$@"; do + case "$arg" in *mutation*) mutation=1 ;; esac + if [ "$next" = method ]; then method="$arg"; next=""; continue; fi + if [ "$next" = value ]; then next=""; continue; fi + case "$arg" in + -X | --method) next=method ;; + --method=*) method="${arg#--method=}" ;; + -X*) method="${arg#-X}" ;; + -f | -F | --field | --raw-field | --input) fields=1; next=value ;; + --field=* | --raw-field=* | --input=* | -f?* | -F?*) fields=1 ;; + -H | --header | -q | --jq | -t | --template | --hostname | --cache | -p | --preview) next=value ;; + graphql | /graphql) graphql=1 ;; + esac + done + if [ -n "$graphql" ]; then [ -z "$mutation" ]; return; fi + case "$method" in + "") [ -z "$fields" ] ;; + GET | get) return 0 ;; + *) return 1 ;; + esac +} +if [ -e "$dir/reads-only" ] && ! reads_only_call "$@"; then + exec "$REAL_GH" "$@" +fi + # The call's API area: `gh api repos/O/R//...` gives , another subcommand its name # (`gh release ...` gives release). The release App holds Contents and Workflows write and # Variables read only, so an area it is refused ("Resource not accessible by integration", e.g. diff --git a/scripts/ci/nightly_next_rolling.py b/scripts/ci/nightly_next_rolling.py index 086a3e6195cd..c2c90a885d43 100755 --- a/scripts/ci/nightly_next_rolling.py +++ b/scripts/ci/nightly_next_rolling.py @@ -31,8 +31,11 @@ nightly-next's head comes from `git ls-remote` against the public repository (no token, no API budget: on 2026-11-04 an exhausted installation budget failed the refs API read and ticks 41791114042 and 41791169626 promoted nothing), and -from the refs API only when that fails. Every other read goes through the API -with the job's token (no shallow history). A head neither can read waits, with a +from the refs API only when that fails. The gap from that head to the tip comes +from the tick's own checkout of feat-cmux-next (git_oldest_after), and from the +compare API only when the head is not in it; a tip already on nightly-next +reads nothing more and waits (there is nothing to promote). Every other read goes through the +API with the job's token. A head neither can read waits, with a warning: the feed watch's dispatch for one commit skips this rule, so that costs at most the backstop's delay. Any other failed read, and a gap to the tip that cannot be read, promotes, with a warning: the promotion ignores a request that does not @@ -188,15 +191,74 @@ def oldest_after(api, repo: str, head: str, tip: str): return UNKNOWN +def git_oldest_after(head: str, tip: str, git=None): + """oldest_after from the tick's own checkout of feat-cmux-next (150 commits deep), no API read: + None when nothing waits, (sha, committer date) of the oldest commit after head, or UNKNOWN when + head is not an ancestor of tip and tip not one of head (a train commit), as the compare API + reports those. Raises LookupError when head is not in this checkout (an older or a train head + past the shallow history, or no checkout): the caller reads the compare API instead.""" + def run(*args: str) -> str: + if git is not None: + return git(*args) + return subprocess.run(["git", *args], check=True, capture_output=True, text=True, + stdin=subprocess.DEVNULL, timeout=60).stdout + + try: + run("cat-file", "-e", f"{head}^{{commit}}") + run("cat-file", "-e", f"{tip}^{{commit}}") + except (OSError, subprocess.SubprocessError) as error: + raise LookupError(f"{head[:12]} or {tip[:12]} is not in this checkout") from error + + def ancestor(a: str, b: str) -> bool: + try: + run("merge-base", "--is-ancestor", a, b) + return True + except subprocess.CalledProcessError as error: + if error.returncode == 1: + return False + raise LookupError(f"merge-base {a[:12]} {b[:12]} failed") from error + except (OSError, subprocess.SubprocessError) as error: + raise LookupError(f"merge-base {a[:12]} {b[:12]} failed") from error + + if head == tip or ancestor(tip, head): + return None + if not ancestor(head, tip): + return UNKNOWN + try: + # A shallow checkout's boundary commits (their parents were not fetched) inside head..tip mean + # the range may be missing older commits of a merged side history: the compare API answers. + boundary = set() + if run("rev-parse", "--is-shallow-repository").strip() == "true": + path = Path(run("rev-parse", "--path-format=absolute", "--git-path", "shallow").strip()) + boundary = set(path.read_text(encoding="utf-8").split()) if path.is_file() else set() + if boundary and boundary & set(run("rev-list", f"{head}..{tip}").split()): + raise LookupError(f"the shallow checkout cuts history between {head[:12]} and {tip[:12]}") + except (OSError, subprocess.SubprocessError) as error: + raise LookupError(f"could not check the checkout's depth after {head[:12]}") from error + try: + # The oldest landing by committer date (squash merges set it at landing), not the first in + # topological order: in a merge history a newer mainline commit can sort before an older + # side-branch one. + commits = [] + for line in run("log", "--format=%H %cI", f"{head}..{tip}").splitlines(): + sha, landed = line.split() + commits.append((dt.datetime.fromisoformat(landed.replace("Z", "+00:00")), sha)) + landed, first = min(commits) + return first, landed + except (OSError, subprocess.SubprocessError, ValueError) as error: + raise LookupError(f"could not read the commits after {head[:12]}") from error + + def gh_api(path: str): out = subprocess.run(["gh", "api", path], check=True, capture_output=True, text=True).stdout return json.loads(out) def evaluate(now: dt.datetime, repo: str, tip: str, api=gh_api, - window_minutes: float = WINDOW_MINUTES, ls_remote=None) -> tuple[bool, str]: + window_minutes: float = WINDOW_MINUTES, ls_remote=None, local_gap=None) -> tuple[bool, str]: """Read the head with `ls_remote` (main passes git ls-remote) and then the API, the rest - through the API (the job's token), and decide. + through the API (the job's token), and decide. The gap to the tip comes from `local_gap` + (main passes git_oldest_after, the tick's checkout) when it can answer, else the compare API. nightly-next's head unreadable: wait, with a warning. The rule's purpose is to coalesce, and the feed watch (every 10 minutes) dispatches a build for one commit, which skips this rule, so @@ -215,6 +277,18 @@ def evaluate(now: dt.datetime, repo: str, tip: str, api=gh_api, print(f"::warning title=nightly-next rolling rule::could not read nightly-next ({error!r}); " "waiting for the feed watch's backstop dispatch") return False, f"could not read nightly-next ({error!r}); the feed watch's backstop covers this" + # The gap to the tip, from the tick's checkout when it can answer (no API read). Nothing after + # nightly-next's head (the tip is on it already, which a finished build or the cron backstop + # often finds) needs no promotion and none of the reads below: the request would stop at the + # tip with "already on nightly-next". + local = None + if local_gap is not None: + try: + local = (local_gap(head, tip),) + except LookupError as error: + print(f"{error}; reading the gap to the tip through the compare API") + if local == (None,): + return False, f"nightly-next ({head[:12]}) already has the tip {tip[:12]}; nothing waits to be promoted" try: base = f"repos/{repo}/actions/workflows/nightly.yml/runs?" # One listing of nightly-next's recent push runs: its head's runs, and the newest start. @@ -231,11 +305,14 @@ def evaluate(now: dt.datetime, repo: str, tip: str, api=gh_api, promotions = api(base + urllib.parse.urlencode( {"branch": "main", "event": "workflow_dispatch", "per_page": 10}))["workflow_runs"] + def gap(): + return local[0] if local is not None else oldest_after(api, repo, head, tip) + def jobs_of(run: dict) -> list[dict]: return api(f"repos/{repo}/actions/runs/{run['id']}/jobs?filter=latest&per_page=100")["jobs"] return decide(now, head=head, head_runs=head_runs, jobs_of=jobs_of, promotions=promotions, - oldest_waiting=oldest_after(api, repo, head, tip), window_minutes=window_minutes, + oldest_waiting=gap(), window_minutes=window_minutes, starts=recent) except Exception as error: # noqa: BLE001 if since_start is not None and since_start < window_minutes: @@ -254,7 +331,7 @@ def main(argv: list[str]) -> int: parser.add_argument("--window-minutes", type=float, default=WINDOW_MINUTES) args = parser.parse_args(argv) go, reason = evaluate(dt.datetime.now(dt.timezone.utc), args.repo, args.tip, window_minutes=args.window_minutes, - ls_remote=watch.ls_remote_sha) + ls_remote=watch.ls_remote_sha, local_gap=git_oldest_after) print(f"rolling rule: {'promote' if go else 'wait'}: {reason}") output = os.environ.get("GITHUB_OUTPUT") if output: diff --git a/tests/test_gh_app_token.py b/tests/test_gh_app_token.py index 767e836dcb15..4b3df6e73d7a 100644 --- a/tests/test_gh_app_token.py +++ b/tests/test_gh_app_token.py @@ -26,6 +26,7 @@ SCRIPT = ROOT / "scripts" / "ci" / "gh_app_token.sh" BUDGET = ROOT / "scripts" / "ci" / "gh_budget_wait.sh" NIGHTLY = ROOT / ".github" / "workflows" / "nightly.yml" +TICK = ROOT / ".github" / "workflows" / "nightly-next-tick.yml" APP, FALLBACK = "ghs_app", "ghs_actions" # The fake gh logs the token of each call. A token with refusals left in $FAKE_STATE/ fails @@ -46,7 +47,7 @@ class Harness: - def __init__(self, app_token: str = APP, budget: bool = False, **env: str) -> None: + def __init__(self, app_token: str = APP, budget: bool = False, reads_only: bool = False, **env: str) -> None: self.tmp = tempfile.TemporaryDirectory() base = Path(self.tmp.name) self.state = base / "state" @@ -69,7 +70,7 @@ def __init__(self, app_token: str = APP, budget: bool = False, **env: str) -> No **env, } install_env = {**self.env, "GH_APP_TOKEN": app_token, "GH_FALLBACK_TOKEN": FALLBACK} - self.installed = subprocess.run(["bash", str(SCRIPT), "--install"], env=install_env, + self.installed = subprocess.run(["bash", str(SCRIPT), "--install", *(["--reads-only"] if reads_only else [])], env=install_env, capture_output=True, text=True, check=True) self.shim = real / "gh" if self.github_path.exists(): @@ -247,6 +248,119 @@ def test_no_app_token_installs_nothing(self) -> None: self.assertFalse(h.github_path.exists()) +class ReadsOnlyTests(unittest.TestCase): + """--reads-only (nightly-next-tick.yml): a read goes out as the App, every write once as + github.token. The tick's reads were about 1,100 GITHUB_TOKEN calls an hour on 2026-11-04, + when that pool ran dry every hour; its writes stay github.token's, whose actor main's promote + job admits.""" + + def harness(self, **kwargs) -> Harness: + h = Harness(reads_only=True, **kwargs) + self.addCleanup(h.tmp.cleanup) + return h + + READS = ( + ("api", "repos/o/r/actions/workflows/nightly.yml/runs?branch=nightly-next&per_page=20"), + ("api", "--paginate", "repos/o/r/actions/runs/1/attempts/1/jobs?per_page=100", "--jq", ".jobs[]"), + ("api", "-X", "GET", "repos/o/r/actions/runs", "-f", "status=queued"), + ("api", "--method=GET", "repos/o/r/actions/runs", "-F", "per_page=1"), + ("api", "graphql", "-f", "query={ repository(owner:\"o\", name:\"r\") { id } }"), + ("run", "list", "--repo", "o/r", "--workflow", "cmux-tui-artifacts.yml", "--json", "status"), + ("run", "view", "1", "--json", "jobs"), + ("workflow", "view", "nightly.yml"), + ) + WRITES = ( + ("workflow", "run", "nightly.yml", "--repo", "o/r", "--ref", "main", "-f", "promote_nightly_next_sha=tick:x"), + ("api", "-X", "POST", "repos/o/r/actions/runs/1/cancel"), + ("api", "-XPOST", "repos/o/r/actions/jobs/2/rerun"), + ("api", "--method", "post", "repos/o/r/actions/runs/1/force-cancel"), + ("api", "repos/o/r/dispatches", "-f", "event_type=x"), + ("api", "repos/o/r/dispatches", "--raw-field=event_type=x"), + ("api", "repos/o/r/git/refs", "--input", "body.json"), + ("api", "graphql", "-f", "query=mutation { addComment(input: {}) { clientMutationId } }"), + ("run", "rerun", "1", "--failed", "-R", "o/r"), + ("run", "cancel", "1"), + ("auth", "token"), + ) + + def test_a_read_goes_out_as_the_app(self) -> None: + for args in self.READS: + with self.subTest(args=args): + h = self.harness() + result = h.gh(*args) + self.assertEqual(result.returncode, 0, result) + self.assertEqual(h.calls(), [f"{APP} {' '.join(args)}"]) + + def test_a_write_goes_out_once_as_github_token(self) -> None: + for args in self.WRITES: + with self.subTest(args=args): + h = self.harness() + h.refuse(FALLBACK, 1, SECONDARY) + result = h.gh(*args) + self.assertNotEqual(result.returncode, 0, result) # refused once, returned as is + self.assertEqual(h.calls(), [f"{FALLBACK} {' '.join(args)}"]) + self.assertEqual(h.waited(), 0) + + def test_a_refused_read_falls_back_to_github_token_without_waiting(self) -> None: + h = self.harness(GH_APP_TOKEN_ATTEMPTS="1") + h.refuse(APP, 1, SECONDARY) + result = h.gh("api", "repos/o/r/actions/runs/1") + self.assertEqual(result.returncode, 0, result) + self.assertEqual(h.calls(), [f"{APP} api repos/o/r/actions/runs/1", f"{FALLBACK} api repos/o/r/actions/runs/1"]) + self.assertEqual(h.waited(), 0) + + def test_without_the_flag_a_write_still_goes_out_as_the_app(self) -> None: + h = Harness() + self.addCleanup(h.tmp.cleanup) + h.gh("workflow", "run", "x.yml") + self.assertEqual(h.calls(), [f"{APP} workflow run x.yml"]) + self.assertFalse((h.runner_temp / "gh-app-token" / "reads-only").exists()) + + +class TickWiringTests(unittest.TestCase): + """nightly-next-tick.yml's unstick job sends its gh reads as the cmux-bot App, with the + repository's existing credentials, before any gh call, and keeps its single-shot steps + single-shot. The request job holds no App key: CI_CONTROL_RUNNER may move it to a reused + machine (tests/test_ci_cloud_overflow_switch.py).""" + + def test_unstick_mints_and_installs_before_the_rate_limit_wait(self) -> None: + import yaml + steps = yaml.safe_load(TICK.read_text(encoding="utf-8"))["jobs"]["unstick"]["steps"] + names = [step.get("name") for step in steps] + tooling = next(step for step in steps if step.get("with", {}).get("path") == ".tick-tooling") + self.assertIn("scripts/ci/gh_app_token.sh", tooling["with"]["sparse-checkout"].split()) + mint = steps[names.index("Mint the cmux-bot token for this job's reads")] + self.assertTrue(mint["uses"].startswith("actions/create-github-app-token@")) + self.assertEqual(mint["with"]["app-id"], "${{ vars.CMUX_BOT_APP_ID }}") + self.assertEqual(mint["with"]["private-key"], "${{ secrets.CMUX_BOT_APP_KEY }}") + self.assertEqual({k: v for k, v in mint["with"].items() if k.startswith("permission-")}, + {"permission-actions": "read", "permission-contents": "read"}) + self.assertTrue(mint["continue-on-error"]) + install = names.index("Send this job's gh reads as the cmux-bot App, github.token as the fallback") + self.assertEqual(steps[install]["run"].strip(), "bash .tick-tooling/scripts/ci/gh_app_token.sh --install --reads-only") + self.assertEqual(steps[install]["env"], {"GH_APP_TOKEN": "${{ steps.read-token.outputs.token }}", + "GH_FALLBACK_TOKEN": "${{ github.token }}"}) + budget = names.index("Wait through GitHub API rate limits in this job's gh calls") + self.assertLess(names.index(mint["name"]), install) + self.assertLess(install, budget) # the budget wrapper wraps this one + for i, step in enumerate(steps): + env = step.get("env", {}) + if "GH_TOKEN" in env: + self.assertGreater(i, budget, step.get("name")) + # The wrapper routes only github.token's calls, and the writes need it. + self.assertEqual(env["GH_TOKEN"], "${{ github.token }}", step.get("name")) + self.assertEqual(env.get("GH_BUDGET_WAIT_ATTEMPTS"), "1", step.get("name")) + self.assertEqual(env.get("GH_APP_TOKEN_ATTEMPTS"), "1", step.get("name")) + + def test_the_request_job_holds_no_app_key(self) -> None: + import json + import yaml + job = yaml.safe_load(TICK.read_text(encoding="utf-8"))["jobs"]["request"] + self.assertIn("CI_CONTROL_RUNNER", job["runs-on"]) + self.assertNotIn("secrets.", json.dumps(job)) + self.assertNotIn("create-github-app-token", json.dumps(job)) + + spec = importlib.util.spec_from_file_location("publisher_app_token", ROOT / "scripts/ci/publish-release-assets.py") publisher = importlib.util.module_from_spec(spec) sys.modules[spec.name] = publisher diff --git a/tests/test_nightly_next_rolling.py b/tests/test_nightly_next_rolling.py index 2d28492bf8ff..6e9e34ea29e5 100755 --- a/tests/test_nightly_next_rolling.py +++ b/tests/test_nightly_next_rolling.py @@ -394,5 +394,130 @@ def test_main_writes_its_answer_without_any_git_remote(self): self.assertIn("::warning title=nightly-next rolling rule::", result.stdout) + +def git_repo(scratch: str): + """A linear history of four commits a minute apart (committer dates set), and a side commit off + the second: git(*args) runs in it.""" + env = {"GIT_AUTHOR_NAME": "t", "GIT_AUTHOR_EMAIL": "t@t", "GIT_COMMITTER_NAME": "t", + "GIT_COMMITTER_EMAIL": "t@t", "HOME": scratch, "PATH": "/usr/bin:/bin:/usr/local/bin:/opt/homebrew/bin"} + + def git(*args: str, when: str | None = None) -> str: + extra = {"GIT_COMMITTER_DATE": when, "GIT_AUTHOR_DATE": when} if when else {} + return subprocess.run(["git", "-C", scratch, *args], check=True, capture_output=True, text=True, + env={**env, **extra}).stdout + + git("init", "-q", "-b", "main") + shas = [] + for minutes in (40, 30, 20, 10): + git("commit", "-q", "--allow-empty", "-m", f"c{minutes}", when=at(minutes)) + shas.append(git("rev-parse", "HEAD").strip()) + git("checkout", "-q", "-b", "side", shas[1]) + git("commit", "-q", "--allow-empty", "-m", "side", when=at(5)) + shas.append(git("rev-parse", "HEAD").strip()) + return git, shas + + +class LocalGapTests(unittest.TestCase): + """The gap from nightly-next's head to the tip comes from the tick's checkout of feat-cmux-next + (150 commits deep), not the compare API: one REST read less per request job, on a budget that + ran dry every hour on 2026-11-04. The compare API stays the fallback when the head is not in + the checkout.""" + + def setUp(self): + self.scratch = tempfile.TemporaryDirectory() + self.addCleanup(self.scratch.cleanup) + self.git, self.shas = git_repo(self.scratch.name) + + def gap(self, head: str, tip: str): + return rolling.git_oldest_after(head, tip, git=lambda *args: self.git(*args)) + + def test_the_oldest_commit_after_head_and_when_it_landed(self): + sha, landed = self.gap(self.shas[0], self.shas[3]) + self.assertEqual(sha, self.shas[1]) + self.assertEqual(landed, NOW - dt.timedelta(minutes=30)) + + def test_the_oldest_landing_is_by_date_not_topological_order(self): + """A merge of an older side commit: the side commit landed first, whatever rev-list's order.""" + self.git("checkout", "-q", "-b", "merged", self.shas[3]) + self.git("merge", "-q", "--no-ff", "-m", "merge side", self.shas[4], when=at(1)) + # A side commit older than every mainline commit after shas[2]. + self.git("checkout", "-q", "-b", "older", self.shas[2]) + self.git("commit", "-q", "--allow-empty", "-m", "older side", when=at(15)) + self.git("checkout", "-q", "merged") + self.git("merge", "-q", "--no-ff", "-m", "merge older", "older", when=at(0.5)) + sha, landed = self.gap(self.shas[2], self.git("rev-parse", "HEAD").strip()) + self.assertEqual(sha, self.git("rev-parse", "older").strip()) + self.assertEqual(landed, NOW - dt.timedelta(minutes=15)) + + def test_a_shallow_cut_inside_the_gap_falls_back(self): + """A merged side history cut by the 150-commit fetch: the range may miss older commits, so the + compare API answers instead.""" + clone = Path(self.scratch.name) / "shallow" + self.git("checkout", "-q", "-b", "merged", self.shas[3]) + self.git("merge", "-q", "--no-ff", "-m", "merge side", self.shas[4], when=at(1)) + tip = self.git("rev-parse", "HEAD").strip() + subprocess.run(["git", "clone", "-q", "--depth", "2", "--no-local", "-b", "merged", + f"file://{self.scratch.name}", str(clone)], check=True, capture_output=True) + run = lambda *args: subprocess.run(["git", "-C", str(clone), *args], check=True, capture_output=True, + text=True).stdout + self.assertEqual(run("rev-parse", "--is-shallow-repository").strip(), "true") + with self.assertRaises(LookupError): + rolling.git_oldest_after(self.shas[3], tip, git=run) + # Deep enough, the same shallow kind of checkout answers on its own. + deep = Path(self.scratch.name) / "deep" + subprocess.run(["git", "clone", "-q", "--depth", "10", "--no-local", "-b", "merged", + f"file://{self.scratch.name}", str(deep)], check=True, capture_output=True) + run = lambda *args: subprocess.run(["git", "-C", str(deep), *args], check=True, capture_output=True, + text=True).stdout + self.assertEqual(rolling.git_oldest_after(self.shas[3], tip, git=run)[0], self.shas[4]) + + def test_nothing_waits_at_or_behind_head(self): + self.assertIsNone(self.gap(self.shas[3], self.shas[3])) + self.assertIsNone(self.gap(self.shas[3], self.shas[1])) + + def test_a_diverged_head_is_unknown(self): + self.assertEqual(self.gap(self.shas[4], self.shas[3]), rolling.UNKNOWN) + + def test_a_head_outside_the_checkout_falls_back(self): + with self.assertRaises(LookupError): + self.gap("e" * 40, self.shas[3]) + + def test_evaluate_reads_no_compare_when_the_checkout_answers(self): + api = api_for(compare("ahead", [(WAITING, 30)])) + go, reason = rolling.evaluate(NOW, "o/r", TIP, api=api, ls_remote=lambda repo, branch: HEAD, + local_gap=lambda head, tip: (WAITING, NOW - dt.timedelta(minutes=4))) + self.assertFalse(go, reason) + self.assertFalse([p for p in api.paths if "/compare/" in p], api.paths) + self.assertFalse([p for p in api.paths if "/git/ref/" in p], api.paths) + + def test_evaluate_reads_compare_when_the_head_is_not_in_the_checkout(self): + def missing(head, tip): + raise LookupError("not here") + api = api_for(compare("ahead", [(WAITING, 30)])) + go, reason = rolling.evaluate(NOW, "o/r", TIP, api=api, ls_remote=lambda repo, branch: HEAD, local_gap=missing) + self.assertTrue(go, reason) + self.assertIn(f"repos/o/r/compare/{HEAD}...{TIP}?per_page=1&page=1", api.paths) + + def test_a_tip_already_on_nightly_next_reads_nothing_and_waits(self): + """A finished build or the cron backstop often finds the tip promoted: no listing, no jobs + read, no request (it would stop at the tip with "already on nightly-next").""" + api = api_for(compare("ahead", [(WAITING, 30)])) + go, reason = rolling.evaluate(NOW, "o/r", TIP, api=api, ls_remote=lambda repo, branch: HEAD, + local_gap=lambda head, tip: None) + self.assertFalse(go, reason) + self.assertIn("nothing waits", reason) + self.assertEqual(api.paths, []) + + def test_a_real_checkout_at_the_head_reads_nothing(self): + api = api_for(compare("ahead", [(WAITING, 30)])) + go, reason = rolling.evaluate(NOW, "o/r", self.shas[3], api=api, ls_remote=lambda repo, branch: self.shas[3], + local_gap=lambda head, tip: self.gap(head, tip)) + self.assertFalse(go, reason) + self.assertEqual(api.paths, []) + + def test_main_reads_the_gap_from_the_checkout(self): + self.assertIn("local_gap=git_oldest_after", SCRIPT.read_text(encoding="utf-8")) + + if __name__ == "__main__": unittest.main(verbosity=2)