From cb6832f8a0c80a3981cc0bcb7eeed9047f9b44c6 Mon Sep 17 00:00:00 2001 From: Leo Li Date: Tue, 3 Nov 2026 23:36:35 -0800 Subject: [PATCH 1/5] ci(nightly-next): read branch refs with git ls-remote so an exhausted API budget never stalls the tick Ticks 41791114042 and 41791169626 promoted nothing because the rolling rule's refs API read of nightly-next was refused (installation rate limit), and the notarization preflight 41790985234 failed on its first read. nightly-next's head now comes from git ls-remote of the public repo (no token, no REST budget) in the rolling rule, the stuck-run rescue and the feed watch, with the refs API as fallback. The preflight turns nightly-next sources away before any read and waits through rate limits with gh_budget_wait.sh, bounded at 75 min. Co-Authored-By: Claude Opus 5.5 Agent-Session: https://cmux.com/deeplink/agent?id=aid-3bab30503f0b9a7059e5 --- .../auto-resume-nightly-notarization.yml | 25 +++++++++++++ .github/workflows/nightly-next-tick.yml | 6 ++-- scripts/ci/nightly_next_feed_watch.py | 25 +++++++++++++ scripts/ci/nightly_next_rolling.py | 28 ++++++++++----- scripts/ci/nightly_next_stuck_run.py | 26 ++++++++++++-- tests/test_nightly_next_rolling.py | 35 +++++++++++++++++-- tests/test_nightly_next_stuck_run.py | 30 ++++++++++++++++ 7 files changed, 159 insertions(+), 16 deletions(-) diff --git a/.github/workflows/auto-resume-nightly-notarization.yml b/.github/workflows/auto-resume-nightly-notarization.yml index 53762fbd7af6..72f3ef3d7c54 100644 --- a/.github/workflows/auto-resume-nightly-notarization.yml +++ b/.github/workflows/auto-resume-nightly-notarization.yml @@ -37,6 +37,8 @@ jobs: ((github.event.workflow_run.conclusion == 'failure' || github.event.workflow_run.conclusion == 'success') && github.event.workflow_run.head_repository.full_name == github.repository) runs-on: ${{ github.repository_owner != 'manaflow-ai' && 'ubuntu-24.04' || vars.CI_CLOUD_OVERFLOW_SAVED && 'blacksmith-16vcpu-ubuntu-2404' || 'blacksmith-4vcpu-ubuntu-2404' }} + # Room for gh_budget_wait.sh to wait out an exhausted API budget (at most an hour). + timeout-minutes: 75 permissions: actions: read contents: read @@ -59,6 +61,22 @@ jobs: SOURCE_BRANCH: ${{ github.event_name == 'workflow_dispatch' && inputs.source_branch || github.event.workflow_run.head_branch }} SOURCE_REPOSITORY: ${{ github.event_name == 'workflow_dispatch' && github.repository || github.event.workflow_run.head_repository.full_name }} steps: + # Run 41790985234 (2026-11-04) failed here on its first read with "HTTP 403 API rate + # limit exceeded for installation". The wrapper waits for the budget's reset and tries + # again (scripts/ci/gh_budget_wait.sh), bounded by this job's timeout. + - name: Checkout the rate-limit wrapper + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + ref: refs/heads/main + path: .preflight-tooling + sparse-checkout: | + scripts/ci/gh_budget_wait.sh + sparse-checkout-cone-mode: false + + - name: Wait through GitHub API rate limits in this job's gh calls + run: bash .preflight-tooling/scripts/ci/gh_budget_wait.sh --install + - name: Verify source run and recovery artifacts id: check run: | @@ -66,6 +84,13 @@ jobs: [[ "$SOURCE_RUN_ID" =~ ^[0-9]+$ ]] || { echo "invalid source run id" >&2; exit 1; } [[ "$SOURCE_RUN_ATTEMPT" =~ ^[0-9]+$ ]] || { echo "invalid source run attempt" >&2; exit 1; } [[ "$SOURCE_HEAD_SHA" =~ ^[0-9a-fA-F]{40}$ ]] || { echo "invalid source head SHA" >&2; exit 1; } + # nightly-next continues on its own track (below), so its runs, most of this + # workflow's triggers, need no API read to be turned away. + if [ "$SOURCE_BRANCH" = nightly-next ]; then + echo "ready=false" >> "$GITHUB_OUTPUT" + echo "reason=nightly-next-continues-on-its-own-track" >> "$GITHUB_OUTPUT" + exit 0 + fi gh api "repos/$GITHUB_REPOSITORY/actions/runs/$SOURCE_RUN_ID" > "$RUNNER_TEMP/source-run.json" python3 - "$RUNNER_TEMP/source-run.json" "$SOURCE_REPOSITORY" "$SOURCE_HEAD_SHA" "$SOURCE_BRANCH" "$SOURCE_RUN_ATTEMPT" <<'PY' > "$RUNNER_TEMP/source-check" import json diff --git a/.github/workflows/nightly-next-tick.yml b/.github/workflows/nightly-next-tick.yml index 3f5f287a3100..c7461494f64e 100644 --- a/.github/workflows/nightly-next-tick.yml +++ b/.github/workflows/nightly-next-tick.yml @@ -150,8 +150,10 @@ jobs: # The rolling rule (scripts/ci/nightly_next_rolling.py): promote at once when nothing is # 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 through the API only; - # its failure modes are in the script's docstring. + # 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. - name: Apply the rolling rule id: rolling if: vars.NIGHTLY_NEXT_TRAIN != 'on' && inputs.sha == '' diff --git a/scripts/ci/nightly_next_feed_watch.py b/scripts/ci/nightly_next_feed_watch.py index 2aa52a418067..602017ff952d 100755 --- a/scripts/ci/nightly_next_feed_watch.py +++ b/scripts/ci/nightly_next_feed_watch.py @@ -41,6 +41,7 @@ import json import os import re +import subprocess import sys import urllib.parse import urllib.request @@ -229,9 +230,28 @@ def stamp(when: dt.datetime) -> str: return when.astimezone(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") +def ls_remote_sha(repo: str, branch: str, timeout: float = 60) -> str: + """A branch's tip from git's smart-HTTP ref advertisement, not the REST API. + + The repository is public, so this needs no token and spends none of the installation's + API budget. On 2026-11-04 that budget ran out and the tick's `git/ref/heads/nightly-next` + read failed, so ticks 41791114042 and 41791169626 promoted nothing. Raises OSError, + subprocess.SubprocessError or ValueError; callers fall back to the API.""" + server = os.environ.get("GITHUB_SERVER_URL", "https://github.com").rstrip("/") + out = subprocess.run( + ["git", "ls-remote", "--exit-code", f"{server}/{repo}", f"refs/heads/{branch}"], + capture_output=True, text=True, timeout=timeout, check=True, stdin=subprocess.DEVNULL, + env={**os.environ, "GIT_TERMINAL_PROMPT": "0"}).stdout + sha = out.split()[0].lower() if out.split() else "" + if not re.fullmatch(r"[0-9a-f]{40}", sha): + raise ValueError(f"git ls-remote {branch}: no sha in {out[:80]!r}") + return sha + + class GitHub: def __init__(self, repo: str, token: str, dry_run: bool): self.base = f"https://api.github.com/repos/{repo}" + self.repo = repo self.token = token self.dry_run = dry_run @@ -298,6 +318,11 @@ def recent_runs(self, workflow: str, branch: str | None = None, return runs def ref_sha(self, branch: str) -> str: + """git ls-remote first (no API budget), the refs API only when that fails.""" + try: + return ls_remote_sha(self.repo, branch) + except (OSError, subprocess.SubprocessError, ValueError) as error: + print(f"git ls-remote {branch} failed ({error!r}); reading it through the API") return self.call("GET", f"/git/ref/heads/{branch}")["object"]["sha"] def ref_commit(self, branch: str) -> tuple[str, dt.datetime | None]: diff --git a/scripts/ci/nightly_next_rolling.py b/scripts/ci/nightly_next_rolling.py index 3e6a5dae4038..086a3e6195cd 100755 --- a/scripts/ci/nightly_next_rolling.py +++ b/scripts/ci/nightly_next_rolling.py @@ -28,10 +28,13 @@ A dispatch for one commit (a person, or the feed watch's starvation guard) never reaches this rule: the tick runs it only when its `sha` input is empty. -Every read goes through the API with the job's token (no git remote, no -shallow history). A failed read of nightly-next 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 +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 +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 move nightly-next forward. @@ -191,15 +194,23 @@ def gh_api(path: str): def evaluate(now: dt.datetime, repo: str, tip: str, api=gh_api, - window_minutes: float = WINDOW_MINUTES) -> tuple[bool, str]: - """Read everything through the API (the job's token) and decide. + window_minutes: float = WINDOW_MINUTES, ls_remote=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. 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 a failed read here costs at most that backstop's delay and never a burst of builds. Any other failed read promotes, with a warning: the promotion ignores a request that moves nothing.""" + head = None + if ls_remote is not None: + try: + head = ls_remote(repo, "nightly-next") + except Exception as error: # noqa: BLE001 - the refs API below is the fallback + print(f"git ls-remote nightly-next failed ({error!r}); reading it through the API") try: - head = api(f"repos/{repo}/git/ref/heads/nightly-next")["object"]["sha"] + if head is None: + head = api(f"repos/{repo}/git/ref/heads/nightly-next")["object"]["sha"] except Exception as error: # noqa: BLE001 print(f"::warning title=nightly-next rolling rule::could not read nightly-next ({error!r}); " "waiting for the feed watch's backstop dispatch") @@ -242,7 +253,8 @@ def main(argv: list[str]) -> int: parser.add_argument("--tip", required=True, help="the feat-cmux-next commit the tick checked out") 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) + go, reason = evaluate(dt.datetime.now(dt.timezone.utc), args.repo, args.tip, window_minutes=args.window_minutes, + ls_remote=watch.ls_remote_sha) print(f"rolling rule: {'promote' if go else 'wait'}: {reason}") output = os.environ.get("GITHUB_OUTPUT") if output: diff --git a/scripts/ci/nightly_next_stuck_run.py b/scripts/ci/nightly_next_stuck_run.py index e14347efd6af..35b74877365b 100644 --- a/scripts/ci/nightly_next_stuck_run.py +++ b/scripts/ci/nightly_next_stuck_run.py @@ -183,9 +183,20 @@ def gh_cli(args: Sequence[str], write: bool) -> str: return result.stdout +def ls_remote_sha(repo: str, branch: str) -> str: + """A branch's tip from git's ref advertisement of the public repository: no token and none of + the installation's API budget, which ran out on 2026-11-04 and failed the refs API read.""" + server = os.environ.get("GITHUB_SERVER_URL", "https://github.com").rstrip("/") + out = subprocess.run( + ["git", "ls-remote", "--exit-code", f"{server}/{repo}", f"refs/heads/{branch}"], + capture_output=True, text=True, timeout=60, check=True, stdin=subprocess.DEVNULL, + env={**os.environ, "GIT_TERMINAL_PROMPT": "0"}).stdout + return out.split()[0].lower() if out.split() else "" + + class Api: - def __init__(self, repo: str, gh: Gh = gh_cli): - self.repo, self.gh = repo, gh + def __init__(self, repo: str, gh: Gh = gh_cli, ls_remote: Callable[[str, str], str] | None = None): + self.repo, self.gh, self.ls_remote = repo, gh, ls_remote def get(self, path: str) -> Any: text = self.gh(["api", f"repos/{self.repo}/{path}"], False) @@ -221,6 +232,15 @@ def listing(self, path: str, key: str) -> list[Any]: return items def tip(self) -> str: + """nightly-next's head: git ls-remote when given one (main does), else or on its failure the refs API.""" + if self.ls_remote is not None: + try: + sha = self.ls_remote(self.repo, "nightly-next") + if SHA.fullmatch(sha): + return sha + print(f"git ls-remote nightly-next answered {sha!r}; reading it through the API") + except (OSError, subprocess.SubprocessError) as error: + print(f"git ls-remote nightly-next failed ({error!r}); reading it through the API") sha = field(field(self.get("git/ref/heads/nightly-next"), "object", (dict,)), "sha", (str,)) if not SHA.fullmatch(sha): raise Unreadable(f"nightly-next is {sha!r}") @@ -442,7 +462,7 @@ def main(argv: list[str]) -> int: if len(argv) != 2: print("usage: nightly_next_stuck_run.py OWNER/REPO", file=sys.stderr) return 2 - tick(Api(argv[1])) + tick(Api(argv[1], ls_remote=ls_remote_sha)) return 0 diff --git a/tests/test_nightly_next_rolling.py b/tests/test_nightly_next_rolling.py index fa2f5f8a5c90..2d28492bf8ff 100755 --- a/tests/test_nightly_next_rolling.py +++ b/tests/test_nightly_next_rolling.py @@ -298,8 +298,9 @@ def api_for(compare_answer, ref=None, runs=None, jobs=None) -> Api: class ApiReadTests(unittest.TestCase): - """Every read is an API read with the job's token: no git remote (the tick checks out with - persist-credentials: false) and no shallow history (it fetches 150 commits).""" + """nightly-next's head comes from git ls-remote of the public repository (no token, no API + budget), the refs API as its fallback; every other read is an API read with the job's token + and no shallow history (it fetches 150 commits).""" def test_the_head_comes_from_the_refs_api_and_the_gap_from_compare(self): api = api_for(compare("ahead", [(WAITING, 4), ("d" * 40, 2)])) @@ -307,7 +308,35 @@ def test_the_head_comes_from_the_refs_api_and_the_gap_from_compare(self): self.assertFalse(go, reason) self.assertIn("repos/o/r/git/ref/heads/nightly-next", api.paths) self.assertIn(f"repos/o/r/compare/{HEAD}...{TIP}?per_page=1&page=1", api.paths) - self.assertNotIn("ls-remote", SCRIPT.read_text(encoding="utf-8")) + + def test_the_head_comes_from_ls_remote_first_and_spends_no_api_read(self): + """2026-11-04: an exhausted installation budget failed the refs API read, and ticks + 41791114042 and 41791169626 promoted nothing. git ls-remote costs no API budget.""" + api = api_for(compare("ahead", [(WAITING, 4), ("d" * 40, 2)])) + asked = [] + go, reason = rolling.evaluate(NOW, "o/r", TIP, api=api, + ls_remote=lambda repo, branch: asked.append((repo, branch)) or HEAD) + self.assertFalse(go, reason) + self.assertEqual(asked, [("o/r", "nightly-next")]) + self.assertNotIn("repos/o/r/git/ref/heads/nightly-next", api.paths) + self.assertIn(f"repos/o/r/compare/{HEAD}...{TIP}?per_page=1&page=1", api.paths) + + def test_a_rate_limited_refs_api_still_decides_when_ls_remote_answers(self): + api = api_for(compare("ahead", [(WAITING, 30)]), ref=OSError("HTTP 403: API rate limit exceeded for installation")) + go, reason = rolling.evaluate(NOW, "o/r", TIP, api=api, ls_remote=lambda repo, branch: HEAD) + self.assertNotIn("could not read nightly-next", reason) + self.assertTrue(go, reason) + + def test_a_failed_ls_remote_falls_back_to_the_refs_api(self): + def broken(repo, branch): + raise OSError("git: not found") + api = api_for(compare("ahead", [(WAITING, 4), ("d" * 40, 2)])) + go, reason = rolling.evaluate(NOW, "o/r", TIP, api=api, ls_remote=broken) + self.assertFalse(go, reason) + self.assertIn("repos/o/r/git/ref/heads/nightly-next", api.paths) + + def test_main_reads_the_head_with_ls_remote(self): + self.assertIn("ls_remote=watch.ls_remote_sha", SCRIPT.read_text(encoding="utf-8")) def test_the_oldest_waiting_commit_is_page_one_of_a_one_per_page_compare(self): """Page 1 at per_page=1 is the oldest commit after nightly-next (the API's documented order).""" diff --git a/tests/test_nightly_next_stuck_run.py b/tests/test_nightly_next_stuck_run.py index b4eff7b06965..9b9e62574733 100644 --- a/tests/test_nightly_next_stuck_run.py +++ b/tests/test_nightly_next_stuck_run.py @@ -455,5 +455,35 @@ def test_the_tick_cancels_before_it_re_runs_a_cancelled_tip_in_its_serialized_gr names.index("Re-run a cancelled nightly-next tip")) self.assertIn("python3 tests/test_nightly_next_stuck_run.py", CI_GUARDS.read_text()) + +class TipRead(unittest.TestCase): + """2026-11-04: the installation's API budget ran out and the refs API read of nightly-next + failed. git ls-remote reads the head with no API budget; the refs API is the fallback.""" + + def refs_api(self, calls): + def gh(args, write): + calls.append(args[-1]) + return json.dumps({"object": {"sha": "c" * 40}}) + return gh + + def test_ls_remote_answers_without_an_api_read(self): + calls = [] + api = stuck.Api("o/r", self.refs_api(calls), ls_remote=lambda repo, branch: "a" * 40) + self.assertEqual(api.tip(), "a" * 40) + self.assertEqual(calls, []) + + def test_a_failed_or_odd_ls_remote_falls_back_to_the_refs_api(self): + def broken(repo, branch): + raise OSError("no git") + for reader in (broken, lambda repo, branch: ""): + calls = [] + api = stuck.Api("o/r", self.refs_api(calls), ls_remote=reader) + self.assertEqual(api.tip(), "c" * 40) + self.assertEqual(calls, ["repos/o/r/git/ref/heads/nightly-next"]) + + def test_main_reads_with_ls_remote(self): + self.assertIn("Api(argv[1], ls_remote=ls_remote_sha)", Path(stuck.__file__).read_text()) + + if __name__ == "__main__": unittest.main() From a6f116f71f408bbe6d85918d8302634c6cce8e23 Mon Sep 17 00:00:00 2001 From: Leo Li Date: Tue, 3 Nov 2026 23:48:06 -0800 Subject: [PATCH 2/5] tests: select the notarization preflight's check step by id, not position Co-Authored-By: Claude Opus 5.5 Agent-Session: https://cmux.com/deeplink/agent?id=aid-3bab30503f0b9a7059e5 --- tests/test_nightly_notarization_poll_loop.py | 2 +- tests/test_nightly_resume_tracks.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/test_nightly_notarization_poll_loop.py b/tests/test_nightly_notarization_poll_loop.py index b1995c84593f..d2109e9664d9 100644 --- a/tests/test_nightly_notarization_poll_loop.py +++ b/tests/test_nightly_notarization_poll_loop.py @@ -48,7 +48,7 @@ def test_recovery_is_resolved_once_before_status_polling(self) -> None: def test_preflight_uses_metadata_only_when_all_variants_exist(self) -> None: workflow = yaml.safe_load(WORKFLOW.read_text(encoding="utf-8")) - check = workflow["jobs"]["preflight"]["steps"][0]["run"] + check = next(s for s in workflow["jobs"]["preflight"]["steps"] if s.get("id") == "check")["run"] program = re.search(r'<<\'PY\' > "\$RUNNER_TEMP/artifact-check"\n(.*?)\nPY', check, re.S).group(1) variants = ("arm64", "x86_64", "universal") recovery = [f"cmux-nightly-notarization-recovery-{v}-aaaaaaa" for v in variants] diff --git a/tests/test_nightly_resume_tracks.py b/tests/test_nightly_resume_tracks.py index 9b68194c2f53..a0528e452cd5 100644 --- a/tests/test_nightly_resume_tracks.py +++ b/tests/test_nightly_resume_tracks.py @@ -24,7 +24,7 @@ def preflight_check(branch: str) -> tuple[str, str]: """Runs the preflight step up to the artifact lookup; returns (exit code, GITHUB_OUTPUT).""" - step = yaml.safe_load(WORKFLOW.read_text())["jobs"]["preflight"]["steps"][0] + step = next(s for s in yaml.safe_load(WORKFLOW.read_text())["jobs"]["preflight"]["steps"] if s.get("id") == "check") script = step["run"].split('gh api "repos/$GITHUB_REPOSITORY/actions/runs/$SOURCE_RUN_ID/artifacts', 1)[0] with tempfile.TemporaryDirectory() as temp: temp_path = Path(temp) From 7934d2e3e948da116698515c89eb1dee6ce6fde2 Mon Sep 17 00:00:00 2001 From: Leo Li Date: Wed, 4 Nov 2026 09:01:07 -0800 Subject: [PATCH 3/5] ci(nightly-next-tick): move the unstick job's reads to the cmux-bot App and cut the request job's reads The tick was the biggest spender of the repository's GITHUB_TOKEN pool (about 1,100 calls an hour of 5,000, which ran dry every hour on 2026-11-04). - unstick: mints a cmux-bot installation token (actions: read, contents: read; the existing CMUX_BOT_APP_ID / CMUX_BOT_APP_KEY) and installs gh_app_token.sh in a new --reads-only mode: gh reads go out as the App, github.token again when the App is refused; cancels and re-runs stay github.token's, sent once. Its runs-on now names the linux_2 pool's members, since a job holding an App key may not run where a variable can move it. - request: keeps only its GITHUB_TOKEN (CI_CONTROL_RUNNER may move it to a reused machine). The rolling rule reads the gap to the tip from the tick's own checkout instead of the compare API, and a tip already on nightly-next reads nothing more and requests nothing. - Neither job starts for a cmux-next or cmux-tui artifacts run on nightly-next (a promotion's push), which makes nothing buildable and is not a finished build. Co-Authored-By: Claude Opus 5.5 Agent-Session: https://cmux.com/deeplink/agent?id=aid-fb75b7af9902231028aa --- .github/workflows/nightly-next-tick.yml | 54 +++++++++-- scripts/ci/gh_app_token.sh | 55 ++++++++++- scripts/ci/nightly_next_rolling.py | 72 +++++++++++++-- tests/test_gh_app_token.py | 118 +++++++++++++++++++++++- tests/test_nightly_next_rolling.py | 90 ++++++++++++++++++ 5 files changed, 373 insertions(+), 16 deletions(-) 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..4cc329552df6 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,57 @@ 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: + first = run("rev-list", "--reverse", "--topo-order", f"{head}..{tip}").split()[0] + landed = run("show", "-s", "--format=%cI", first).strip() + return first, dt.datetime.fromisoformat(landed.replace("Z", "+00:00")) + except (OSError, subprocess.SubprocessError, IndexError, 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 +260,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 +288,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 +314,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..38d38a793822 100755 --- a/tests/test_nightly_next_rolling.py +++ b/tests/test_nightly_next_rolling.py @@ -394,5 +394,95 @@ 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_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) From a0884c679b97d97a8eee47c80974035b97e33312 Mon Sep 17 00:00:00 2001 From: Leo Li Date: Wed, 4 Nov 2026 09:14:03 -0800 Subject: [PATCH 4/5] ci(nightly-next): the local gap picks the oldest landing by committer date, as the compare API does Co-Authored-By: Claude Opus 5.5 Agent-Session: https://cmux.com/deeplink/agent?id=aid-fb75b7af9902231028aa --- scripts/ci/nightly_next_rolling.py | 14 ++++++++++---- tests/test_nightly_next_rolling.py | 13 +++++++++++++ 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/scripts/ci/nightly_next_rolling.py b/scripts/ci/nightly_next_rolling.py index 4cc329552df6..54813e4897cc 100755 --- a/scripts/ci/nightly_next_rolling.py +++ b/scripts/ci/nightly_next_rolling.py @@ -225,10 +225,16 @@ def ancestor(a: str, b: str) -> bool: if not ancestor(head, tip): return UNKNOWN try: - first = run("rev-list", "--reverse", "--topo-order", f"{head}..{tip}").split()[0] - landed = run("show", "-s", "--format=%cI", first).strip() - return first, dt.datetime.fromisoformat(landed.replace("Z", "+00:00")) - except (OSError, subprocess.SubprocessError, IndexError, ValueError) as error: + # 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 diff --git a/tests/test_nightly_next_rolling.py b/tests/test_nightly_next_rolling.py index 38d38a793822..3a9f16eade5c 100755 --- a/tests/test_nightly_next_rolling.py +++ b/tests/test_nightly_next_rolling.py @@ -436,6 +436,19 @@ def test_the_oldest_commit_after_head_and_when_it_landed(self): 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_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])) From d5f6ec7d65f614180e0ac3821f48b981cbadf3cc Mon Sep 17 00:00:00 2001 From: Leo Li Date: Wed, 4 Nov 2026 10:44:22 -0800 Subject: [PATCH 5/5] ci(nightly-next): the local gap falls back to the compare API when the shallow checkout cuts it Co-Authored-By: Claude Opus 5.5 Agent-Session: https://cmux.com/deeplink/agent?id=aid-fb75b7af9902231028aa --- scripts/ci/nightly_next_rolling.py | 11 +++++++++++ tests/test_nightly_next_rolling.py | 22 ++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/scripts/ci/nightly_next_rolling.py b/scripts/ci/nightly_next_rolling.py index 54813e4897cc..c2c90a885d43 100755 --- a/scripts/ci/nightly_next_rolling.py +++ b/scripts/ci/nightly_next_rolling.py @@ -224,6 +224,17 @@ def ancestor(a: str, b: str) -> bool: 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 diff --git a/tests/test_nightly_next_rolling.py b/tests/test_nightly_next_rolling.py index 3a9f16eade5c..6e9e34ea29e5 100755 --- a/tests/test_nightly_next_rolling.py +++ b/tests/test_nightly_next_rolling.py @@ -449,6 +449,28 @@ def test_the_oldest_landing_is_by_date_not_topological_order(self): 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]))