Skip to content

feat(github): send fewer GitHub requests per analyze - #619

Open
Exypte wants to merge 5 commits into
mainfrom
feature/618-fewer-github-api-requests
Open

Exypte wants to merge 5 commits into
mainfrom
feature/618-fewer-github-api-requests

Conversation

@Exypte

@Exypte Exypte commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

feat

What this PR does / why we need it:

An analyze of a GitHub repository sends many requests, and large repositories hit the rate limit (#618). Two commits:

1. Count every GitHub request and write a --debug report. internal/httpcount counts each request per host and per rate-limit quota. analyze --debug[=file] writes a markdown report of every request and of the rate limit before and after the run, so the cost of a run can be measured.

2. Send fewer requests.

  • Repeated GETs are answered from memory (httpcount.MemoTransport). The same request sent twice in a run reaches GitHub once.
    • Only 2xx and 404 answers are kept. A 403, a 429, a 5xx or a network error is asked again.
    • The key is the URL and every header, so a different credential, Range or API version is a separate request.
    • Identical concurrent requests are sent once. A waiting caller keeps its own deadline, and a panic in the transport cannot block later requests.
    • Kept bodies are capped at 1 MB each and 32 MB in total.
    • Only the GitHub API and raw-content clients use it. The OIDC token, --score-push, the update check and the job logs stay on the counting-only DefaultTransport, so a minted token or a signed one-shot URL is never replayed.
  • A raw-host 404 sent with a token is final, once the token is proven. The contents API is asked only until it has accepted the token once (200 or 404). An expired or revoked token gets a 404 from the raw host, but a 401 from the API, so the action still ends as could-not-verify, never as a missing file that lets the checks pass. The definition fetcher records the token its raw reads actually send instead of re-reading the environment.
  • A branch that GitHub redirects to another name (the default-branch fallback) is dropped before its protection is read, which could only 404.

The --debug report shows how many requests were answered from memory.

Which issue(s) this PR is related to:

Refs #618

Special notes for your reviewer:

A /code-review of the first version raised 10 findings, all fixed here. Two of them changed the design:

  • A first version probed a full SHA as a commit before trying it as a tag or a branch, which saved two 404s per SHA pin. It is dropped: it reported a tag or branch named like a resolving SHA as a commit, which hid the ref-confusion check (ISSUE-402).
  • A first version treated any raw 404 sent with a token as final. With an expired token, action.yml was reported missing and the mutable-exec and nested-action checks silently passed. That is why the token now has to be proven first.

The test fetchers built from a stub used to count as authenticated through PLUMBER_METADATA_TOKEN. They now say so explicitly with a tokenFetcher helper, since the fetcher no longer reads the environment.

Does this PR introduce a user-facing change?

New `analyze --debug[=file]` flag (env PLUMBER_ANALYZE_DEBUG): writes a markdown report of every GitHub request the run sent and of the rate limit before and after it.
An analyze of a GitHub repository sends fewer requests: repeated reads are answered from memory, and a file the raw host does not have is no longer asked again of the contents API once the token is proven. Findings and scores are unchanged.

How was this tested?

  • go vet ./..., go test -race ./... and golangci-lint run pass.
  • New unit tests:
    • Memo: answers kept, answers sent again, concurrent requests, a waiter's own deadline, a panic in the transport, other headers, the total budget.
    • readWith: a proven token asks the contents API once, a rejected token asks every time and returns fetchError.
    • Branch protection: a redirected branch's protection is not read.
  • Regression check against v0.7.23. Each repository was scanned by the v0.7.23 release binary (checksum verified) and by this branch, back to back, pinned to a release tag so both read the same workflows, with the built-in default config. Apart from cliVersion, the JSON reports are identical, as are the exit code and the score:
Repository Tag Score (v0.7.23 = this PR) Requests sent by this PR
facebook/react v19.3.1 D 49 242
microsoft/vscode 1.147.0 C 67 173
vercel/next.js v16.4.6 D 34 404
nodejs/node v26.13.1 C 55 332
python/cpython v3.15.2 C 67 205
rust-lang/rust 1.100.0 B 79 36
angular/angular v22.3.0 C 70 280
hashicorp/terraform v1.17.2 C 70 239
home-assistant/core 2026.11.2 D 36 493
django/django 6.1.3 B 87 155
getplumber/plumber main A 100 265

All 11 are identical. getplumber/plumber is scanned on main rather than a tag, because a tag is not a branch and would skip the branch-protection lane. Its --debug report shows the lane ran: /branches/main 200, /branches/main/protection 404 (the repo uses rulesets), /rules/branches/main 200.

Follow-up, not a regression: in that run GET /repos/getplumber/plumber/branches/main is still sent twice. v0.7.23 sends it too, but memory does not answer the second request, probably because the two calls carry different headers.

  • Not covered by these runs: a run with no token, a run with an expired token or with PLUMBER_METADATA_TOKEN, a scan inside a clone, and GitHub Enterprise Server. The unit tests cover the expired-token case.

AI usage disclosure:

YES. Claude Code wrote the code and the tests, ran the review and fixed its findings, and ran the regression check against v0.7.23. The author is responsible for the change and reviews it (see CONTRIBUTING.md and AI_POLICY.md).

🤖 Generated with Claude Code

Exypte and others added 2 commits November 18, 2026 15:53
plumber analyze --debug[=path] writes a markdown report of every GitHub
request of a run (#618): per endpoint, repeated URLs, every request in
order, the quota windows the response headers report, and GET
/rate_limit before and after. Every GitHub client sends through the
counting transport in internal/httpcount; the process-wide
http.DefaultTransport is untouched because OPA's http.send asserts its
type. --verbose is unchanged.

Refs #618

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Answer a repeated GitHub GET from memory for the rest of the run
(httpcount.MemoTransport). Only 2xx and 404 answers are kept, the key is
the URL and every header, a waiter keeps its own deadline, and the kept
bodies stay under 32 MB. Only the GitHub API and raw-content clients use
it: the OIDC token, the score push, the update check and the job logs
keep the counting-only DefaultTransport.

After a raw-host 404 sent with a token, the contents API is asked only
until it has accepted that token once. An expired or revoked token still
ends as could-not-verify, never as a missing file. The definition fetcher
now records the token its raw reads send instead of re-reading the
environment.

A branch GitHub redirects to another name is dropped before its
protection is read, which could only 404.

The --debug report counts the requests answered from memory.

Refs #618

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Comment thread github/github_token_default.go Resolved
Comment thread cmd/debug_report.go Resolved
…setup

The report kept every request's raw query, so the job-log store's signed
redirect URL landed in plumber-debug.md with its SAS signature. The log
now keeps a query only when the GitHub API answered (x-ratelimit headers)
and writes <redacted> for every other host.

Credential discovery and naming move out of startGitHubDebugReport, and
the rate-limit read becomes a seam, so tests cover the credential labels,
both auth schemes' names, and each credential's before/after row.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Totara-thib

Copy link
Copy Markdown
Contributor

Thanks, looks good overall. The memo, the request counting and the branch-redirect change don't change results. One thing to fix before merge:

A raw 404 can now hide an action the token is not allowed to read

In readWith (nested_actions.go:236), once the API has accepted the token once, every later raw 404 is taken as "file missing" and the API is never asked.

That works for expired tokens, but not when a valid token is refused for one org only:

  • SAML SSO not authorized for that org
  • org IP allow list
  • API rate limit or 5xx

In those cases the raw host answers 404, but the API would answer 403. Before this PR that gave fetchError, so the action was reported as "could not verify". Now the action counts as missing, and the nested-action and mutable-exec checks pass silently.

Suggestion: prove the token per owner/repo instead of once per run. That keeps most of the savings (the action.yml → action.yaml fallback, entrypoint lookups in the same repo).

Question: were the 11 regression runs done with GH_TOKEN / GITHUB_TOKEN exported? With only gh auth login, rawToken is empty and this new shortcut never runs, so the comparison wouldn't cover it.

Minor: a branch-pinned action that just added action.yml may 404 on the raw host for about 5 minutes because of its cache. The API fallback used to catch that.

Exypte and others added 2 commits November 20, 2026 19:01
The contents API now has to accept the token in the same repository before
a raw 404 counts as final. SAML SSO or an IP allow list can refuse a valid
token for one organization: the raw host then answers 404, the API 403, and
the read has to stay could-not-verify.

The ref also has to be a full commit SHA. The raw host's CDN keeps a 404
for about a minute (measured at 58 to 64 s, although `expires` says 5 min),
so an action.yml pushed to a branch or under a moved tag right after a miss
is still a 404 there. Reproduced on getplumber-examples/cli-working-lab,
branch 618-raw-cdn-cache: bb33a2e dropped the action's ISSUE-714 and
ISSUE-307 findings, while v0.7.23 and this commit report them.

Cost against bb33a2e, same reports: getplumber/plumber 265 -> 298 requests,
facebook/react v19.3.1 242 -> 250.

Refs #618

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The mutable-exec scan tries action.js, index.js, dist/index.js and
src/index.js for every third-party action, and most of them do not exist.
Since a raw 404 on a tag or a branch is no longer final, each miss cost a
raw request plus a contents-API request. One GraphQL query per 25 actions
now asks which of these files exist. GitHub answers null for a missing one
with no CDN cache in between, so read returns it as missing without a
request. Files that exist, and the declared main:, are read as before.

The query carries every untrusted value as a variable. A ref that is not
a plain name (rev-parse operators, `:`) or a path that climbs out of the
repository is not queried. An error GitHub ties to one repository drops
that repository's answers only; any other error drops the chunk. With no
token, or offline, no query is sent.

A name that is both a tag and a branch resolves to the tag in GraphQL,
while the raw host may serve the branch. ISSUE-402 reports that ambiguity,
so it is accepted here.

Against v0.7.23, with identical reports: getplumber/plumber main 230
requests (bb33a2e: 265), facebook/react v19.3.1 231 (bb33a2e: 242).

The test metadata client no longer keeps a live GraphQL client, and the
default --debug report is gitignored.

Refs #618

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
}
total := len(uniqueRefs)
if scanMutableExec {
defs.prefetchAbsent(candidateRefs(pipeline, defs))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Test coverage

Medium: the entrypoint prefetch is never exercised end-to-end through the mutable-exec scan, so a mismatch between the candidate paths it marks absent and the paths the scan actually reads would silently defeat the #618 request reduction with no failing test. (Medium)

The new wiring at github/github_workflows.go:329 (defs.prefetchAbsent(candidateRefs(pipeline, defs))) is the heart of the #618 optimization, but no test runs it with a working GraphQL client. Every test that reaches enrichActions/resolveMutableExec with scanMutableExec=true builds its client via stubbedMetadataClient, which now sets client.gql = nil (see github/degraded_checks_test.go:34 and the assertion in entrypoint_prefetch_test.go TestPrefetchAbsent_SendsNothing/"stubbed metadata client"). With f.gql == nil, prefetchAbsent returns immediately, so in those tests candidateRefs runs but prefetchAbsent is a no-op and no entrypoint read is ever short-circuited.

The two halves are only tested in isolation:

  • TestCandidateRefs checks the paths candidateRefs produces (path.Join(subpath, p) for each entrypointCandidates).
  • TestPrefetchAbsent_NullObjectIsAbsent checks that prefetchAbsent + defs.read with hand-written candidateRefs skips the raw host.

What no test covers is that the paths candidateRefs emits are the same keys read looks up during a real scan. read keys the absent map with containerKey(owner, repo, p, ref) (github/nested_actions.go:205) where p is the entrypoint path the scan derives independently in scanActionDefinition via key(rel) = path.Join(dir, rel) with dir = path.Dir(ymlKey) (github/action_source.go:939-945). If either side's path construction drifts (subpath joining, entrypointCandidates contents/order, or ref/case handling), prefetchAbsent would populate f.absent under keys read never queries, and every entrypoint would be re-fetched from the raw host — i.e. the optimization becomes a production no-op that re-introduces exactly the rate-limit pressure #618 set out to remove, while the entire test suite stays green.

Suggested test: in github/nested_actions_test.go (or entrypoint_prefetch_test.go), build a definitionFetcher with a stubbed GraphQL client that answers null for a nested action's entrypoint candidate, run it through enrichActions(..., scanMutableExec=true) with a real pipeline (e.g. acme/mono/tools/lint@v2, exercising a subpath), and assert the raw stub received zero reads for the prefetched-absent entrypoint while a non-null candidate is still read. This pins the candidateRefs ↔ scanActionDefinition/read key agreement that currently only holds by coincidence.

Control: .github/claude-prompts/test-coverage.md · resolve this conversation once addressed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

GitHub: cut the number of API requests per analyze (rate limit hit too often)

2 participants