Repository navigation
feat(github): send fewer GitHub requests and read GitHub through GraphQL - #649
Conversation
An analyze of a large GitHub repository can hit the rate limit (#618). On the 11-repository corpus, REST core requests drop from 2082 to 141 and the wall time from 18:20 to 4:05, with identical JSON reports. Count every request. internal/httpcount counts requests per host and per rate-limit quota, and `analyze --debug[=file]` writes a markdown report of them, with query strings outside the GitHub API redacted. Repeated 2xx and 404 GETs to the GitHub API and raw hosts are answered from memory. A raw 404 is trusted only with a token, at a commit SHA, in a repository whose contents API accepted that token. One GraphQL query per 25 actions checks which entrypoint guesses exist, and a branch GitHub redirects to another name is dropped before its protection is read. Read action metadata through batched GraphQL. On github.com, repository info, releases, tags, branches, commits, the immutable release flag, advisories and tag listings go out as aliased queries, ten repositories per query, and fill the caches Resolve already reads. A null alias reads as a 404 did. A 5xx or a timeout splits the batch down to one repository. SHA pins are lowercased, so uppercase pins resolve as before. Read the scanned repository in one query: default branch, visibility, full name, the protected flag of the branches branchMustBeProtected names, and release authors. NOT_FOUND and FORBIDDEN map to REST's 404 and 403. The branch listing and protection details stay on REST. Read remote-mode workflows in one tree query, plus one for local composite actions. The ref is tried as refs/heads/, then refs/tags/, then as written, since the contents API prefers the branch when a branch and a tag share a name. Blob.text is checked against the blob oid, and a file that fails, or is truncated or binary, is read over the contents API. GitHub Enterprise Server keeps REST for advisories, the immutable flag and the scanned repository. GraphQL has no anonymous access, so a GitHub analyze without a token stops at startup and lists the ways to provide one. A local run can go on without the API with PLUMBER_DISABLE_GITHUB_API=1. Remote mode always needs a token. Closes #637 Refs #618 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
e56a00b to
6eeb12a
Compare
|
Squashed the 9 commits into 6eeb12a. The tree hasn't changed: |
| } | ||
| more := queryScannedRepo(gql, owner, repo, missing, false) | ||
| for _, b := range missing { | ||
| if more.err != nil { |
There was a problem hiding this comment.
🔴 Test coverage
Low: the incremental branch-load failure path in loadScannedRepo (second query fails as a whole) has no test, leaving a reachable branchMustBeProtected failure mode unguarded. (Low)
loadScannedRepo has two distinct query paths: the first-use full query (r == nil, line 123) and the incremental query for branches a later read asks about that an earlier prefetch did not (r != nil, line 127). The incremental path is reached in production: FetchGitHubBranchProtection on github.com calls loadScannedRepo(host, owner, repo, opts.ExactNames) (github_branch_protection.go:1893), and when branchMustBeProtected is configured with a wildcard pattern the listing fallthrough checks branch names that prefetchScannedRepo never asked, so those names are missing here and trigger the second queryScannedRepo(..., full=false).
The tests cover the incremental path only on success — TestScannedRepo_ReadsLoadOnFirstUse sends a second query that returns a branch — but never the case where that second query fails as a whole (more.err != nil, line 129). That branch records r.branches[b] = branchFact{err: more.err} for every missing branch, which (*scannedRepo).branch (line 149-155) then surfaces as (nil, err), propagating up to FetchGitHubBranchProtection as a verification error.
Missing edge case: a second (incremental) scanned-repo query that fails with a 5xx / timeout / rate limit while resolving wildcard-matched branches. Because this path is untested, a regression that dropped the error propagation — e.g. recording branchFact{} instead of branchFact{err: more.err} — would go unnoticed: branch() would then return (nil, nil) (read as "branch does not exist"), and branchMustBeProtected would silently skip a branch whose protection could not actually be verified, turning an unverifiable branch into a false pass on a security control.
Suggested test: extend TestScannedRepo_ReadsLoadOnFirstUse (or add a sibling) that stubs the first query to succeed (default branch + repo fields) and the second query (the one carrying b0 for a not-yet-asked branch) to fail entirely (e.g. 401 and 500). Assert that FetchGitHubBranchProtection with that branch in ExactNames returns a non-nil error for the 500 case (and, per the existing contract, a quiet degrade for 401), rather than reporting the branch as absent/unprotected.
Control: .github/claude-prompts/test-coverage.md · resolve this conversation once addressed.
The scanned repository's query answers five reads at once (default branch, visibility, full name, branch protection flags, bot releases), and the remote workflow tree is one query too. queryReposChunk splits a batch GitHub could not finish; these two have nothing to split, so one 502 or one timeout cost the run every read behind them. doRetrying sends such a query again, twice at most, a second then three apart, on the same predicate the split uses (unfinished: a 5xx or our own timeout). Any other error comes back at once. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Ft8dmcMLK7V9XZh7JX4vzs
| VulnerableRange: n.VulnerableVersionRange, | ||
| Severity: advisorySeverity(n.Advisory.Severity), | ||
| } | ||
| if n.FirstPatchedVersion != nil { |
There was a problem hiding this comment.
🔴 Test coverage
No test exercises a matched advisory with a null firstPatchedVersion (or non-MODERATE severity) in storeAdvisories, leaving a nil-deref panic path and the severity-lowercasing branch uncovered. (Medium)
storeAdvisories keeps an advisory only when strings.EqualFold(n.Package.Name, key) matches, then at line 380 does if n.FirstPatchedVersion != nil { a.PatchedVersions = n.FirstPatchedVersion.Identifier } and at line 378 calls advisorySeverity(n.Advisory.Severity).
In the only decode test (TestQueryRepos_DecodesTheAnswer, metadata_graphql_test.go:86), the single matched advisory GHSA-1 is MODERATE with a non-null firstPatchedVersion. The one node that is CRITICAL with firstPatchedVersion: null (GHSA-2) has package.name = someone/else, so it is dropped by the name filter (line 372) before reaching line 380 or advisorySeverity. As a result:
- A matched advisory whose
FirstPatchedVersionisnilis never tested. Unpatched CVEs (nullfirstPatchedVersion) are common and real; a regression dropping the nil guard would nil-deref panic mid-run on exactly those entries. advisorySeverityis only ever exercised forMODERATE→medium. The plainstrings.ToLowerbranch (e.g.CRITICAL→critical) is never reached through a matched advisory — the facts-level tests (TestResolve_ShaPinMapsToItsVersionForAdvisories,advisory_severity_test.go) setSeveritydirectly and bypassadvisorySeverity. A regression that stopped lower-casing would silently break the Rego severity match with no failing test.
Suggested test: call storeAdvisories (or decode a query answer) with a node whose package.name == owner/repo, advisory.severity: "CRITICAL", and firstPatchedVersion: null; assert the cached advisoryInfo has Severity == "critical", empty PatchedVersions, and no panic.
Control: .github/claude-prompts/test-coverage.md · resolve this conversation once addressed.
| } | ||
| l.tags[sha] = n.Name | ||
| } | ||
| if answer.Refs.PageInfo.HasNextPage && l.pages < maxTagPages { |
There was a problem hiding this comment.
🔴 Test coverage
The maxTagPages (20-page) pagination cap in queryTags is never exercised, so the bound that prevents runaway tag-listing requests could regress undetected. (Medium)
queryTags continues paging a repository's tag listing while GitHub reports hasNextPage:true, bounded by l.pages < maxTagPages (line 500). TestQueryTags_PeelsToTheCommitAndPages pages exactly twice and the second page returns hasNextPage:false, so the loop always terminates on HasNextPage, never on the l.pages < maxTagPages guard. TestQueryTags_FailureKeepsWhatWasRead ends on an error, also never hitting the cap.
A regression that dropped or inverted the l.pages < maxTagPages guard would let queryTags keep requesting pages as long as GitHub keeps returning hasNextPage:true — on a repository with tens of thousands of tags this is unbounded request volume. The REST walk this replaces capped at 2000 tags (maxTagPages * 100), and reducing request count is the stated purpose of this PR, so this is precisely the cost regression the change exists to prevent, yet no test would catch it.
Suggested test: a stub that always returns hasNextPage:true with a distinct commit/tag per page; call queryTags for one repo and assert exactly maxTagPages queries were sent and the loop terminated.
Control: .github/claude-prompts/test-coverage.md · resolve this conversation once addressed.
| body, err := fetchFileContentContext(ctx, f.rest, owner, repo, p, ref) | ||
| // With a raw token set, the API client sends that same token: both | ||
| // read PLUMBER_METADATA_TOKEN, then GH_TOKEN, then GITHUB_TOKEN. | ||
| if f.rawToken != "" && (err == nil || isNotFound(err)) { |
There was a problem hiding this comment.
🔴 Test coverage
The err == nil arm that marks a repository "proven" when the contents API serves a file (not just on a 404) is never verified to make a later commit-SHA raw-miss final. (Medium)
In readWith, a repository is added to provenRepos when the contents API either 404s or returns a file: if f.rawToken != "" && (err == nil || isNotFound(err)) { f.provenRepos.Store(...) } (lines 267-268). Being proven lets a subsequent commit-SHA raw-miss short-circuit to fetchMissing without re-hitting the contents API (lines 72-76 / the provenRepos.Load check).
Every test proves a repo only via the 404 arm: TestReadWith_AuthenticatedRawMissIsFinal and TestReadWith_TokenIsProvenPerRepository. The err == nil arm runs in TestReadWith_FallsBackToContentsAPIOnGitHubCom, but at ref "v1" (not a commit SHA), so _isCommitSha(ref) is false and the proven status is never consulted. Thus no test asserts that serving a file proves the repo.
A regression dropping err == nil || from the store condition would stop proving a repo the API only ever serves files for, so every subsequent commit-SHA raw-miss in that repo would redundantly re-hit the contents API against the token's quota — the exact per-quota cost (plumber#618) this logic eliminates — with all tests staying green.
Suggested test: at a commit SHA, have the contents API serve one entrypoint file (200, proving the repo), then read a different path the raw host 404s at the same repo+SHA and assert it returns fetchMissing with no additional API request.
Control: .github/claude-prompts/test-coverage.md · resolve this conversation once addressed.
| } | ||
| return workflowFiles(c, raw), nil | ||
| } | ||
| if ref == "" { |
There was a problem hiding this comment.
🔴 Test coverage
The empty-repository branch of loadWorkflowTree (default branch requested, HEAD resolves null → empty pipeline, not an error) has no test. (Low)
loadWorkflowTree distinguishes the ISSUE-222 cases: a missing repo (line 173) and a missing named ref (line 203) hard-error, while an existing ref whose workflows directory is null degrades to an empty pipeline. Line 199-202 handles a distinct case: ref == "" (default branch) where the single HEAD candidate itself resolves null — an empty repository with no commits — returning workflowTree{rev: "HEAD"}, nil.
No test exercises this. TestScanGitHubWorkflowsRemote_NoWorkflowsDir has a live HEAD with a non-workflows file (so the c0 commit is non-null); TestWorkflowTree_RefShapes's {"", "HEAD", 1} case also has a live HEAD; _NonexistentBranchErrors uses a named missing ref. None drive ref == "" with a null HEAD.
A regression that removed or reordered this guard would make an empty-repository remote scan hard-error (branch or ref "" not found) instead of returning an empty pipeline — or, if the guard were broadened, make a genuinely missing default branch silently return a vacuous 100%-compliant pipeline (the original ISSUE-222 bug).
Suggested test: swapGitRepo(gitRepo{refs: nil}) (repository present, no HEAD) scanned with ref == "" should return no error and zero jobs.
Control: .github/claude-prompts/test-coverage.md · resolve this conversation once addressed.
| } | ||
| for i, c := range cands { | ||
| n := strconv.Itoa(i) | ||
| if ferr := failed["c"+n]; ferr != nil { |
There was a problem hiding this comment.
🔴 Test coverage
The per-alias commit-failure branch in loadWorkflowTree (failed["c"+n] != nil) is untested; only a whole-query failure is covered. (Low)
loadWorkflowTree surfaces an error GitHub tied to a specific commit alias via if ferr := failed["c"+n]; ferr != nil { return workflowTree{}, ferr } (line 179). TestWorkflowTree_FailedQuery only covers a whole-query 401 (via scannedRepoErrors returning a top-level error); no test produces a GraphQL errors entry whose path is ["repository", "c0"], which scannedRepoErrors routes into the per-alias failed map rather than a whole-query error.
A regression that mishandled or ignored this per-alias error (e.g. fell through to the isNull(fields["c"+n]) check and treated the alias as absent) would turn a commit GitHub merely failed to resolve into a wrong "ref not found" or a silently empty listing, instead of propagating the real error.
Suggested test: have the fake endpoint return a body with the c0 alias nulled plus an errors entry {"path":["repository","c0"],"message":"timeout"}, scan at that ref, and assert the scan returns that error rather than an empty/not-found result.
Control: .github/claude-prompts/test-coverage.md · resolve this conversation once addressed.
Three cases where a GraphQL read gave a wrong answer with no error, found in the review of #649. An error GitHub ties to the scanned repository's default branch or releases was dropped, and the empty value read as the answer: no default branch turned defaultMustBeProtected into a no-op. FetchGitHubDefaultBranch now returns that error, and the default token's effect route logs unread releases and proves nothing. An error on a field can also null the repository, which read as "not found"; it is now that field's error, in the scanned repository's query and in the remote workflow tree. A Blob carries no git mode, and the blob of a symlink holds the path it points at. A local composite whose action.yml is a symlink was parsed as that path, so its steps were never resolved in remote mode. The composite query now lists each directory with its modes, and a definition that is not a regular file reads over the contents API, which follows the link. Checked on git/git on 2026-11-26: HEAD:RelNotes answers the link target as text, with mode 40960 in the root tree. unfinished also matches a timeout GitHub answers as a 200: a GraphQL error with no path, no type and GitHub's timeout message. Such a batch is split and such a single query retried, like a 502. A rate limit, which has a type, is still sent once. This shape was not reproduced: two queries too heavy for GitHub both answered a 502 with an HTML body. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
No production change. Each test fails when the line it covers is broken. - a later branch query of the scanned repository that fails as a whole: a 500 is an error, a 401 the quiet degrade, and the branch is never read as absent - an advisory with no patched version, and a severity other than MODERATE - the tag listing stops at maxTagPages - the contents API serving a file proves the repository, so a later raw 404 at a commit SHA does not ask it again - an empty repository scanned at its default branch has no workflows, while a named ref that does not exist is still an error - an error on a candidate's commit is that error, and the ref does not read as missing Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
| data, failed, err := c.graphQL(fmt.Sprintf("releases, second page: %d repositories", len(pages)), params, q.String(), vars) | ||
| for i, p := range pages { | ||
| alias := "r" + strconv.Itoa(i) | ||
| if aliasError(alias, data, failed, err) != nil { |
There was a problem hiding this comment.
🔴 Test coverage
Low: queryReleasesPage's documented failure mode — a failed second releases page keeps the already-read first page — has no test, unlike the success path. (Low)
queryReleasesPage (github/metadata_graphql.go:442-470) fetches the second page of a repository's releases and appends it to the first page already stored by storeRepo. Its doc comment promises a specific failure guarantee: "A failure keeps the first page." On a whole-query failure the guard at line 457 (if aliasError(alias, data, failed, err) != nil { continue }) skips every alias, so nothing is appended and the first 100 releases survive.
The success path is covered by TestQueryRepos_ReadsTheNewest150Releases (metadata_graphql_test.go:370), which drives page 1 (100) + page 2 (50) = 150 releases. But no test exercises the case where the second-page query itself fails (5xx, rate limit, GraphQL error, or an alias error). This is a real failure mode the new code introduces, and the only place the second page matters is populating c.releases, which drives latestSemverRelease/latestReleaseTag → LatestTag and LatestReleaseSha (ISSUE-709).
Concrete regression it would let through: on a repository with >100 releases, if the append were moved out of the continue guard or the per-key slice were reset instead of appended (e.g. c.releases[key] = more rather than append(...)), a failed second page would drop the already-read first 100 releases, leaving c.releases[key] empty and silently changing the computed LatestTag/LatestReleaseSha (or emptying them) for that repo. The current code is correct, but nothing pins the behavior.
Suggested test: in graphQLMetadataClient, return a normal 100-release first page with hasNextPage:true, then answer the second-page query (identified by the presence of variable c0) with an error (e.g. {"message":"rate limited"}, 403, or a timeoutBody). Assert that len(c.releases["o/r"]) == 100 and that c.repoCache["o/r"].err == nil — i.e. the first page is retained and the repository is not marked unreadable. This mirrors the existing TestQueryTags_FailureKeepsWhatWasRead pattern used for the tag listing's analogous guarantee.
Control: .github/claude-prompts/test-coverage.md · resolve this conversation once addressed.
A failed second releases page keeps the first page, which the review bot asked for. The rest comes from running the same test-coverage prompt over the whole branch: error and fallback paths of the GraphQL metadata loader, the remote workflow tree, the scanned repository, httpcount and the debug report. Tests only, no production change. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
## [0.7.24](v0.7.23...v0.7.24) (2026-11-30) ### ✨ Features * **control:** tag patterns must be protected (tagMustBeProtected, ISSUE-510) ([#581](#581)) ([e2b13ab](e2b13ab)), closes [#398](#398) * **github:** send fewer GitHub requests and read GitHub through GraphQL ([#649](#649)) ([53c5406](53c5406)), closes [#618](#618) [#637](#637) [#618](#618) ### 🐛 Bug Fixes * **github:** match trusted owner lists without regard to case ([#629](#629)) ([4160592](4160592)), closes [#623](#623) ### 🔧 Chores * code owners only on the action lockfile, owned by the cli team ([#656](#656)) ([80c4d31](80c4d31)) ### 📚 Documentation * explain the release process ([#601](#601)) ([67557b9](67557b9)) * **readme:** add InvokeAI and Clash Nyanpasu to the adopters row ([#613](#613)) ([798fd9f](798fd9f)), closes [invoke-ai/InvokeAI#9944](invoke-ai/InvokeAI#9944) [#10109](https://github.com/getplumber/plumber/issues/10109) [libnyanpasu/clash-nyanpasu#6286](libnyanpasu/clash-nyanpasu#6286) [#6323](https://github.com/getplumber/plumber/issues/6323) [#6324](https://github.com/getplumber/plumber/issues/6324) ### 👷 CI/CD * keep the corpus under -race, lint through golangci-lint-action, harden the scan gate ([f7960e6](f7960e6)) * run the corpus without the race detector, cache golangci-lint, scan the image only when it changed ([d69f9ac](d69f9ac)) * trust golangci-lint-action in the Plumber action allowlist ([3d71094](3d71094))
What type of PR is this?
feat, perf
What this PR does / why we need it:
An analyze of a GitHub repository sent many requests, one at a time, and large repositories hit the rate limit (#618). This PR measures what a run sends, cuts the repeated reads, then moves every read GraphQL can batch to the GraphQL API (#637). It gathers #619, #639, #646 and #648 into one branch, one commit per step:
internal/httpcountcounts each request per host and per rate-limit quota, andanalyze --debug[=file]writes a markdown report of every request and of the rate limit before and after the run.httpcount.MemoTransport): only 2xx and 404 answers are kept, keyed by the URL and every header, with identical concurrent requests sent once and bodies capped at 1 MB each and 32 MB in total. The OIDC token,--score-push, the update check, the job logs and the GraphQL client stay on the counting-only transport, so nothing one-shot is ever replayed.action.js,index.js,dist/index.js,src/index.js) are checked with one GraphQL query per 25 actions.branchMustBeProtectednames with their protected flag, and the authors of its latest releases come from one query. REST'sprotectedflag is a classic rule or a ruleset; the query readsrefUpdateRuleandrules, which together matched REST on about 620 branches of the corpus. The branch listing stays on REST: with the protected flag, a GraphQL listing was 4 to 6 times slower. Protection details stay on REST, and GHES keeps all these reads on REST. A 5xx or a timeout on this query is retried twice (a second, then three apart): it has nothing to split, and without a retry one 502 cost every read it answers.name:pathreads the tag (checked on getplumber-examples/cli-working-lab, branch and tagtest/2026-11-25-ref-precedence), so the query asksrefs/heads/<ref>first. GraphQL'sBlob.textis not byte-faithful (it turned a literal\^@in a home-assistant/core workflow into\^@), so each file is checked against its blob oid, and one that fails, or comes back truncated or binary, is read over REST.GH_TOKEN,GITHUB_TOKEN,GH_ENTERPRISE_TOKENandgh auth login.PLUMBER_DISABLE_GITHUB_API=1still analyzes a local clone without the API. Remote mode always needs a token. The GitHub Action passesGH_TOKENalready.Measured on 11 repositories (remote mode, pinned tags, default config), each build back to back with the one before it. The JSON reports, exit codes and scores match from one build to the next apart from
cliVersion, and #619's matched v0.7.23. The one exception is getplumber/plumber, scanned atmain, where a branch was deleted between two runs (branch count 46 → 45, read from the REST branch listing).All requests (REST, GraphQL, raw host):
REST core requests counted against the token:
GraphQL queries across the corpus: 86 after step 2, 97 after step 3, 112 after step 4, one point each. v0.7.23 could not count its quota use, so its column is in the first table only.
Wall time of one analysis, in minutes:seconds (the first run of each build):
Timings vary from one session to the next (the same step 2 build took 6:07 in one session and 7:00 in the next), so each step is best read against the build before it in the same session: step 2 went from 18:20 to 6:07 (−67%), step 3 from 7:00 to 5:18 (−24%), and step 4 from 6:31 to 4:05 (−37%). The last column was measured on the build just before the oid check, which adds one REST read on home-assistant/core.
What stays on REST for the scanned repository: the branch listing, the protection details of protected branches, environments, the Actions workflows and runs, and the files GraphQL does not give exactly.
Which issue(s) this PR is related to:
Closes #637
Refs #618
This PR replaces #619, which is closed; its review carries over here. #639, #646 and #648 stay open as drafts for reference.
Special notes for your reviewer:
GH_TOKENexported are the ones in the first table.internal/httpcount(step 1),github/metadata_graphql.goandgithub/metadata_facts.go(step 2),github/scanned_repo.go(step 3),github/remote_tree.go(step 4),requireGitHubTokenincmd/analyze_github.go(step 5).rateLimit { cost remaining }, shown in the--debugreport's GraphQL section.permissions: contents: read,GITHUB_TOKENonly). One branch under a classic rule, one under a ruleset, one open and one missing, with exact names and with a wildcard pattern:branchProtectionResultis byte-identical betweenmain(798fd9f, REST) and this branch (6eeb12a), both protected branches read protected with their details, the open one unprotected.Does this PR introduce a user-facing change?
How was this tested?
make build,make testandgolangci-lint. Lint reports one govet finding incontrol/catalog.gothat is already on main.metadata_graphql_test.goandmetadata_facts_test.go(query shape, variables, decoding, missing and failed aliases, chunk splitting, release paging, GHES path, tag paging, cost recording, prefetch grouping), and the REST tests ported.scanned_repo_test.go(one query for every read, variables, lazy and extra queries, not found, unauthorized, server error, failed branch alias, no token, GHES on REST) and the control prefetch test.remote_tree_test.go(one query, variables, branch before tag, ref shapes, truncated and altered files over REST, failed query, local composites, git blob id) and the remote-mode tests ported against a fake repository.analyze_github_test.go(each local/remote, token/no-token, API-disabled case, both entry points stopping before collection, the message, the Auth row, the init hint).PLUMBER_DISABLE_GITHUB_API=1it writes its report; remote mode stops even with the API disabled.AI usage disclosure:
YES. Claude Code wrote the code and tests under my direction, ran the experiments against GitHub and the corpus comparisons, and drafted this description. The author is responsible for the change and reviews it (see CONTRIBUTING.md and AI_POLICY.md).
🤖 Generated with Claude Code