Collecting from the GitHub API without starving your other automation
If a report job and your other automation read GitHub with the same token, the report can use up the quota and stop the automation. Give the report a budget it must leave untouched, make it stop with a visible gap instead of a quiet partial result, cache only the data that has stopped changing, and refuse any list that came back cut short. This guide is written from one incident in our own development setup and the change that fixed it the same day. The code below is a short sketch of each idea in a general form, not the code we run. We ran each sketch on November 21, 2026, with read-only GitHub calls and with a stubbed quota for the boundary of the floor.
What happened
Our development setup has two programs that read GitHub. One is a supervise loop that watches Issues and pull requests and moves each one a step forward. The other builds Engineering Intelligence reports: counts of pull requests, CI runs, reviews and their costs, rebuilt from GitHub records. Both use the same REST quota of 5,000 calls per hour.
On November 14, 2026, a report for one full month over every repository took 25 minutes and used up the REST quota. The supervise loop could no longer read GitHub either. The Issue that recorded it (ziv-labs/agentic-factory-vnext#333) named the risk plainly: the loop and the reports share one quota, so measuring could stop development, and the rule for the measurements was that a failing measurement must not stop the flow. The Issue was opened at 07:47 UTC and closed about 28 minutes later; the fix went in as pull request #334.
The decision was not to make fewer calls on the API side but to keep the assembled result locally and to stop before the quota runs low. The rest of this guide is what that change does. We searched our Issues for other times the limit was hit and found none; two other Issues (#234, #235) are measurements and forecasts, not incidents. We did not search pull request comments or logs.
1. Keep a budget for the others, and stop before it
Before collecting, read how many REST calls are left. gh api rate_limit returns it under resources.core.remaining; that is the REST quota, not the GraphQL one, and reading it does not count against the quota.
# What is left of the REST quota this hour (reading it does not use the quota)
gh api rate_limit --jq '.resources.core.remaining'Four choices make the check useful:
- A floor, not zero. Collection stops when 1,500 calls or fewer are left (
MIN_BUDGET = 1500), so the loop keeps its share. The comparison is "at or below": a test checks that the guard stops when the remaining count equals the floor. - Unknown means stop. If the remaining count cannot be read, the check returns 0, which means "do not collect". A check that fails open would let the job run blind exactly when GitHub is having trouble.
- Not on every call. The quota is read on the first call and then on every tenth (
CHECK_EVERY = 10). - Count the calls until the next check. One check lets ten calls through, so a check that compares only the remaining count with the floor can let the job go below it: at 1,501 left it passes, and the ten calls that follow end at 1,491. The sketch adds the ten calls before comparing, so it stops at 1,510 left or fewer and goes on at 1,511, which ends at 1,501. Our collector compares the remaining count alone, as described above; the sketch is stricter on purpose. The guard limits only the collector's own batch, based on the last balance it observed, so other jobs that use the same quota at the same time can still take it below the floor.
import json, subprocess
MIN_BUDGET = 1500 # calls left for everything else that shares the token
CHECK_EVERY = 10 # read the quota on the 1st call and every 10th after it
class BudgetLow(RuntimeError):
pass
def remaining() -> int:
try:
out = subprocess.run(["gh", "api", "rate_limit"], capture_output=True,
text=True, check=True, timeout=30).stdout
return int(json.loads(out)["resources"]["core"]["remaining"])
except Exception:
return 0 # cannot tell: treat the budget as spent and do not collect
calls = 0
def guard() -> None:
global calls
calls += 1
# this check covers this call and the next CHECK_EVERY - 1: count them all
if calls % CHECK_EVERY == 1 and remaining() - CHECK_EVERY <= MIN_BUDGET:
raise BudgetLow("GitHub API budget kept for the loop")When the guard trips, it raises its own error type with a fixed reason, "GitHub API budget kept for the loop". The reason is what later shows up in the report.
2. Show a stop as a gap, not as a result
A report that stopped halfway is not a smaller report. If the missing part is silently left out, a week with no data looks like a quiet week, and a count of zero looks like nothing happened.
- Record what was not collected. The collector works in windows (one repository, one week). Once one window trips the budget, every later window is skipped without fetching and recorded as a gap with its repository, its start and end, and the reason. A stop in the middle of one window is caught per part (Issues, commits, agent runs) and recorded as a gap too.
- Say it at the top of the report. The report prints "Collected? No" and lists the ranges that could not be collected, with the repository and the reason for each, so a reader knows the numbers for them are missing.
- Unknown is not 0. A value that could not be measured is written "Unknown", never 0, and a total that has unknown parts says so ("and N more Unknown").
- The same for any API error. There is no retry or backoff in the report collector. A rate-limit error from GitHub becomes the reason "GitHub API rate limit exceeded" and the window becomes a gap. Error text is scrubbed of IDs and account names before it is written down.
results, gaps = [], []
stopped = None
for window in windows: # e.g. one repository x one week
if stopped:
gaps.append({**window, "reason": stopped}) # no more fetching once one window trips
continue
try:
results.append(fetch(window)) # calls guard() before every request
except BudgetLow as e:
stopped = str(e)
gaps.append({**window, "reason": stopped})3. Keep only the weeks that have settled
Most of a month-long report is about weeks that will not change again. The fix keeps them on disk:
- One file per repository and week. Weeks start on Monday 00:00 UTC and are clipped at the ends of the period. Each repository-week is one JSON file, keyed by the repository and the window's start and end, inside the git directory and never committed:
<git common dir>/engineering-events/<owner>__<repo>/<since>_<until>.json- Only settled weeks are kept. A week is stored only if it ended at least 14 days ago (
SETTLE = 14), has no gaps and has no invalid records. Newer weeks still change, because findings are fixed or skipped later and CI runs are rerun, so they are rebuilt every time. - A version number rebuilds everything. The files carry a cache version (4 today), raised whenever the way events are assembled changes. A file of another version is ignored and rebuilt.
- A broken file is rebuilt, not trusted. Files that cannot be read, have the wrong shape or contain events that fail the schema are ignored and rebuilt. Tests cover each case.
- Deleting the cache is always safe. It only means the next run reads GitHub again. Writes go to a temporary file named after the process and then replace the real one, so two runs at once do not overwrite each other's half-written file; a failed write is ignored.
All three report scripts pass the same cache and the same budget check into the collector. A test checks the point of the change: a second run over the same period makes no API calls for the settled weeks.
4. Read one page at a time, and refuse a cut list
Fetching every page of a list in one command hides the calls from the budget check and can return a list that stopped early. The collector reads REST lists one page at a time, 100 items per page, so the guard runs between pages:
MAX_PAGES = 50
def list_all(path: str) -> list:
items = []
for page in range(1, MAX_PAGES + 1):
guard() # the budget is checked between pages
batch = gh_json(f"{path}?per_page=100&page={page}")
items += batch
if len(batch) < 100:
return items
raise RuntimeError(f"{path}: more than {MAX_PAGES} pages, refusing a partial list")- A ceiling on pages. At most 50 pages per list. Beyond that the collector raises an error instead of returning what it has.
- Count what arrived. For responses that report a total (Actions runs and check runs), it raises if fewer items arrived than the total says.
- Search results have their own ceiling. Pull request and Issue lists from search are read with a limit of 1,000. If a result reaches 1,000, the pull request list is an error and the Issue list becomes a gap; a truncated list is never used.
- Ask only for what can matter. Only pull requests updated in the window and created before its end are fetched, so later pull requests and Issues cost nothing.
- Every kind of call goes through the guard. Collecting review costs means listing up to 200 workflow runs and reading one log per completed run. The same guard runs before each of those calls; when it trips, the report shows a gap for "Claude review costs" instead of a smaller cost.
5. Know what the other consumers spend
A floor of 1,500 is only a guess unless you know what the others need. We had measured the supervise loop earlier (Issue #234, November 2, 2026) by reading rate_limit before and after a pass:
- An idle pass costs about 10 GraphQL points (out of 5,000 per hour) and no REST core calls.
- The loop runs a pass every 60 seconds, every 300 seconds while it only waits for a person, and stops after at most 180 passes.
- At 300 seconds that is about 120 points an hour per repository; for 7 repositories about 840 an hour, about 17% of the GraphQL limit (forecast in #235).
So the loop and the reports mostly draw on different quotas while idle: the loop on GraphQL, the report collector on REST. The loop is not GraphQL only, though. It reads an Issue's body and labels with GraphQL, and comments with REST, 100 per page. Our reading is that this is a reason to keep a REST floor for the loop rather than assume it never touches REST.
The loop also survives a bad moment on its own: a pass that fails because GitHub or git failed is skipped, not fatal, and only 10 failed passes in a row end the loop with a "stalled" exit code (Issue #267, pull request #274). Its waits are fixed intervals, not exponential backoff.
Parallel work adds up on the same token too. Up to 3 Codex reviews run side by side, and the status command reads every repository in its own thread with no cap. When you size a floor, count these as well.
What this does not cover
- The sketches are not our code. They show the shape of each idea, and we ran them (read-only GitHub calls, the quota stubbed for the floor's boundary; the cache path is a layout, not code). The behavior of our own collector described here comes from reading its code and tests, not from running it again.
- One incident. We found one time the limit was hit, in Issues only. The floor of 1,500 was chosen for our loop; yours depends on what else uses the token.
- No retry. The collector does not wait for the quota to reset and try again. A stopped run has to be started again; the settled weeks it already stored cost no API calls the second time.
Sources
All in the private repository ziv-labs/agentic-factory-vnext, read on November 21, 2026: Issue #333 and pull request #334 (the incident and the fix), the decision record ADR-0015 (section "A local copy"), Issues #234 and #235 (the loop's measured cost), and Issue #267 with pull request #274 (how the loop handles failed passes).
Related notes
- A month of AI-agent development in numbers: October 2026 — Counted from GitHub records by a script, not from memory: 203 merged pull requests, 70 agent runs, 693 CI runs, what Codex and Claude reviews found and how much of it was fixed, where the time went, and what we could not measure.
- Where we stop reviewing an AI agent's pull request, and three times our auto-revert was wrong — Review rounds stopped by the weight of a finding, three pull requests that still hit the limit, a final review that found what two approvals missed, and three automatic reverts that were wrong.