From 36c52bfec5d5c8d0edd17d2341d403e3e2dba493 Mon Sep 17 00:00:00 2001 From: kgrizz-git <216068303+kgrizz-git@users.noreply.github.com> Date: Mon, 16 Nov 2026 18:06:55 -0500 Subject: [PATCH 1/3] Do not retry permission 403s as rate limits GitHub attaches x-ratelimit-reset to ordinary 403 responses, so the retry helper treated permission denials as throttling: it slept up to 30s per attempt and retried three times per repository. A token without Actions read access on 25 private repos turned a ~4 minute email report into a ~40 minute one, and each affected repo was only reported as skipped after exhausting its retries. A 403 now retries only when the response signals throttling: Retry-After present, x-ratelimit-remaining == 0, or a rate-limit marker in the body. SAML/SSO enforcement 403s, which also carry rate-limit headers, now fail fast too. --- CHANGELOG.md | 1 + src/github_usage/http_retry.py | 36 ++++++++-- tests/test_http_retry.py | 128 +++++++++++++++++++++++++++++++++ 3 files changed, 158 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cc470b6..34b2d98 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ This project follows the structure from Keep a Changelog and intends to use Sema ### Fixed +- **Permission 403s no longer back off like rate limits:** `http_retry` treated any 403 carrying `x-ratelimit-reset` as throttling, but GitHub sends that header on ordinary permission denials too. A token missing `Actions: Read-only` on private repos therefore slept up to 30s per attempt (three retries per repo — about 40 minutes for a 100-repo report whose 25 private repos were inaccessible) before giving up on each repo. A 403 now retries only when it carries `Retry-After`, reports `x-ratelimit-remaining: 0`, or names a rate limit in the body; inaccessible repos fail fast and still appear as skipped in artifact storage output. - **CLI flags no longer open the TUI:** `github-usage --export` / `--no-interactive` (and any other dashed argv, including `github-usage -v`) stay on the CLI when stdin and stdout are TTYs. Only a bare `github-usage` in a terminal launches the Textual app. `./start.sh -v` is unchanged because `start.sh` already maps `-v` to `--version` before Python routing. - **Artifact storage partial failures:** a per-repo artifact API error no longer blanks the whole Actions Artifact Storage section — successfully scanned repos still render, and failed repos are listed as skipped in the text/HTML email and PDF exports. - **Email Actions section:** plain-text and HTML emails show **private-repo quota** against the 2,000 min / 500 MB free tier (with public usage labeled free) instead of comparing combined account totals to the private quota. When no visibility split is available, the report says so explicitly rather than implying the total is all quota-counted. diff --git a/src/github_usage/http_retry.py b/src/github_usage/http_retry.py index 34b0c7c..205ae3b 100644 --- a/src/github_usage/http_retry.py +++ b/src/github_usage/http_retry.py @@ -11,8 +11,11 @@ # Rate Limit and 403 Policy: # - The helper retries any status in RETRYABLE_STATUSES (408, 429, 500, 502, 503, 504) unconditionally. -# - It also retries 403 IF AND ONLY IF `Retry-After` or `x-ratelimit-reset` -# is present in the response headers. It does not retry 401, 404, or other 4xx. +# - It retries a 403 only when the response itself signals throttling: `Retry-After` +# is present, `x-ratelimit-remaining` is `0`, or the body mentions a rate limit. +# Every GitHub response carries `x-ratelimit-reset`, including plain permission +# failures, so header presence alone must not select the retry path. +# It does not retry 401, 404, or other 4xx. # - The legacy 403+Retry-After branch in api.py is deleted since this helper # natively handles 403 rate limits. @@ -60,6 +63,27 @@ def parse_rate_limit_headers(headers: http.client.HTTPMessage) -> float | None: return None +# Bodies GitHub uses for primary/secondary throttling; permission 403s say +# "Resource not accessible by ..." instead. +_RATE_LIMIT_MARKERS = ("rate limit", "abuse detection", "secondary rate") + + +def is_rate_limit_403(headers: http.client.HTTPMessage, body: bytes) -> bool: + """Return True when a 403 response represents throttling, not a permission denial. + + GitHub attaches ``x-ratelimit-reset`` to ordinary 403s too, so the header's + presence alone is not a rate-limit signal. A 403 counts as throttling when it + carries ``Retry-After``, reports ``x-ratelimit-remaining: 0``, or names a rate + limit in its body. + """ + if headers.get("Retry-After") is not None: + return True + if (headers.get("x-ratelimit-remaining") or "").strip() == "0": + return True + text = body.decode("utf-8", errors="replace").lower() + return any(marker in text for marker in _RATE_LIMIT_MARKERS) + + def backoff_seconds(attempt: int, retry_after: float | None = None) -> float: """Calculate the number of seconds to sleep before the next retry.""" if retry_after is not None: @@ -99,13 +123,11 @@ def request_with_retries( retry_after_val = None needs_retry = False - if response.status in RETRYABLE_STATUSES: + if response.status in RETRYABLE_STATUSES or ( + response.status == 403 and is_rate_limit_403(response.headers, response.body) + ): needs_retry = True retry_after_val = parse_rate_limit_headers(response.headers) - elif response.status == 403: - retry_after_val = parse_rate_limit_headers(response.headers) - if retry_after_val is not None: - needs_retry = True if not needs_retry: return response diff --git a/tests/test_http_retry.py b/tests/test_http_retry.py index a4d7378..5828ce6 100644 --- a/tests/test_http_retry.py +++ b/tests/test_http_retry.py @@ -111,6 +111,134 @@ def test_does_not_retry_on_401_and_headerless_403(self, mock_conn_class): self.assertEqual(conn.request.call_count, 2) self.assertEqual(self.sleeper.calls, []) + @mock.patch("time.time", return_value=1000000.0) + @mock.patch("http.client.HTTPSConnection") + def test_does_not_retry_permission_403_that_carries_ratelimit_reset( + self, mock_conn_class, mock_time + ): + """A permission 403 must not be retried just because GitHub sent rate-limit headers. + + Regression: every GitHub response carries ``x-ratelimit-reset``, so the retry + helper slept ~30s per attempt on inaccessible private repos and turned a + ~4 minute email report into a ~40 minute one. + """ + conn = mock.Mock() + mock_conn_class.return_value = conn + + headers = http.client.HTTPMessage() + headers["x-ratelimit-reset"] = "1000010" + headers["x-ratelimit-remaining"] = "4823" + err_resp = mock.Mock(status=403, headers=headers) + err_resp.read.return_value = ( + b'{"message":"Resource not accessible by personal access token"}' + ) + conn.getresponse.return_value = err_resp + + response = http_retry.request_with_retries( + "GET", "/foo", host="api.github.com", headers={}, sleep=self.sleeper + ) + self.assertEqual(response.status, 403) + self.assertEqual(self.sleeper.calls, []) + self.assertEqual(conn.request.call_count, 1) + + @mock.patch("time.time", return_value=1000000.0) + @mock.patch("http.client.HTTPSConnection") + def test_does_not_retry_saml_sso_403(self, mock_conn_class, mock_time): + """SAML/SSO enforcement 403s carry rate-limit headers but are not throttling.""" + conn = mock.Mock() + mock_conn_class.return_value = conn + + headers = http.client.HTTPMessage() + headers["x-ratelimit-reset"] = "1000010" + headers["x-ratelimit-remaining"] = "4823" + err_resp = mock.Mock(status=403, headers=headers) + err_resp.read.return_value = ( + b'{"message":"Resource protected by organization SAML enforcement. ' + b'You must grant your personal access token access to this organization."}' + ) + conn.getresponse.return_value = err_resp + + response = http_retry.request_with_retries( + "GET", "/foo", host="api.github.com", headers={}, sleep=self.sleeper + ) + self.assertEqual(response.status, 403) + self.assertEqual(self.sleeper.calls, []) + self.assertEqual(conn.request.call_count, 1) + + def test_is_rate_limit_403_classification(self): + """Pin the classification rules, including markers far into the body.""" + + def headers(**values): + message = http.client.HTTPMessage() + for key, value in values.items(): + message[key.replace("_", "-")] = value + return message + + cases = [ + (headers(Retry_After="5"), b"", True), + (headers(**{"x_ratelimit_remaining": "0"}), b"", True), + (headers(), b'{"message":"API rate limit exceeded"}', True), + (headers(), b"You have exceeded a secondary rate limit.", True), + (headers(), b"abuse detection mechanism", True), + (headers(), b"x" * 600 + b" API rate limit exceeded", True), + (headers(), b'{"message":"Resource not accessible by personal access token"}', False), + (headers(**{"x_ratelimit_remaining": "4823"}), b'{"message":"Forbidden"}', False), + (headers(), b"", False), + (headers(), b"\xff\xfe not utf-8", False), + ] + for case_headers, body, expected in cases: + with self.subTest(body=body[:40], expected=expected): + self.assertIs( + http_retry.is_rate_limit_403(case_headers, body), + expected, + ) + + @mock.patch("time.time", return_value=1000000.0) + @mock.patch("http.client.HTTPSConnection") + def test_retries_primary_rate_limit_403_when_remaining_is_zero( + self, mock_conn_class, mock_time + ): + conn = mock.Mock() + mock_conn_class.return_value = conn + + headers = http.client.HTTPMessage() + headers["x-ratelimit-reset"] = "1000010" + headers["x-ratelimit-remaining"] = "0" + err_resp = mock.Mock(status=403, headers=headers) + err_resp.read.return_value = b'{"message":"API rate limit exceeded"}' + succ_resp = mock.Mock(status=200, headers=http.client.HTTPMessage()) + succ_resp.read.return_value = b"Success" + + conn.getresponse.side_effect = [err_resp, succ_resp] + + response = http_retry.request_with_retries( + "GET", "/foo", host="api.github.com", headers={}, sleep=self.sleeper + ) + self.assertEqual(response.status, 200) + self.assertEqual(self.sleeper.calls, [10.0]) + + @mock.patch("http.client.HTTPSConnection") + def test_retries_secondary_rate_limit_403_by_body_marker(self, mock_conn_class): + conn = mock.Mock() + mock_conn_class.return_value = conn + + headers = http.client.HTTPMessage() + headers["Retry-After"] = "3" + err_resp = mock.Mock(status=403, headers=headers) + err_resp.read.return_value = ( + b"You have exceeded a secondary rate limit. Please wait a few minutes." + ) + succ_resp = mock.Mock(status=200, headers=http.client.HTTPMessage()) + succ_resp.read.return_value = b"Success" + + conn.getresponse.side_effect = [err_resp, succ_resp] + + response = http_retry.request_with_retries( + "GET", "/foo", host="api.github.com", headers={}, sleep=self.sleeper + ) + self.assertEqual(response.status, 200) + self.assertEqual(self.sleeper.calls, [3.0]) + @mock.patch("http.client.HTTPSConnection") def test_retries_on_remote_disconnected(self, mock_conn_class): conn = mock.Mock() From 295c57ed32168cb68b65ff7bd6a24ed8e40190b3 Mon Sep 17 00:00:00 2001 From: kgrizz-git <216068303+kgrizz-git@users.noreply.github.com> Date: Mon, 16 Nov 2026 22:36:16 -0500 Subject: [PATCH 2/3] Cover body-only 403 retries and record the legacy skipped-repo gap MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Sourcery review on PR #41: no test retried on a body-only rate-limit 403 (the existing retry tests signalled via remaining: 0 or Retry-After), so request_with_retries could stop honoring the body marker unnoticed. Add that case. The legacy artifact scan drops repos whose fetch fails, with no skipped entry. That predates this branch — the old code raised the same RuntimeError after retrying — so record it in TO_DO.md instead of widening this fix. --- TO_DO.md | 1 + tests/test_http_retry.py | 23 +++++++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/TO_DO.md b/TO_DO.md index 551fa4a..f8ede70 100644 --- a/TO_DO.md +++ b/TO_DO.md @@ -20,6 +20,7 @@ - [ ] CSV/XLSX/PDF columns/sheets for private rankings and workflow breakdown — add `TODO` comments at `repo_consumers` readers in `export_csv.py`, `export_xlsx.py`, and `export_pdf.py`. - [ ] Private-only **artifact-scan** ranking (artifact section already groups by visibility; billed storage ranking shipped in [archived plan](docs/superpowers/plans/archived/2026-07-31-private-top-consumers.md)). +- [ ] Legacy/full-report artifact scan hides repos whose artifact fetch fails (e.g. a 403 when the token lacks `Actions: Read-only`), in three ways: `storage._collect_repo_artifacts` swallows the `RuntimeError`, so (a) a repo with no release assets is dropped entirely by the `total_storage <= 0 and not items` check in `_analyze_one_repo`, (b) a repo that also has release assets is kept with `artifact_storage_gb: 0`, silently understating quota-carrying storage, and (c) `get_storage_analysis` drops any repo whose analysis raises `KeyError`/`RuntimeError`. Thread the per-repo error through `get_storage_analysis` and render skipped entries, matching the email path (`report_optional.get_artifact_storage_details`). Pre-existing gap noted in PR #41 review; the retry fix only changed how fast the 403 surfaces. - [ ] Workflow breakdown for more than the single top private repo (extend beyond the one-repo wall-clock section). - [ ] Opt-in monthly deep run analysis (top private repo by gross cost; job-level approx + calendar-month cache) — see [plan](docs/superpowers/plans/2026-07-31-opt-in-deep-run-analysis.md). - [ ] Retire dead Actions OS-from-runs path (honesty) — see [plan](docs/superpowers/plans/2026-07-31-actions-os-from-runs-honesty.md). diff --git a/tests/test_http_retry.py b/tests/test_http_retry.py index 5828ce6..b174a3b 100644 --- a/tests/test_http_retry.py +++ b/tests/test_http_retry.py @@ -217,6 +217,29 @@ def test_retries_primary_rate_limit_403_when_remaining_is_zero( self.assertEqual(response.status, 200) self.assertEqual(self.sleeper.calls, [10.0]) + @mock.patch("time.time", return_value=1000000.0) + @mock.patch("http.client.HTTPSConnection") + def test_retries_body_only_rate_limit_403(self, mock_conn_class, mock_time): + """The body marker alone selects the retry path, with no Retry-After and quota left.""" + conn = mock.Mock() + mock_conn_class.return_value = conn + + headers = http.client.HTTPMessage() + headers["x-ratelimit-reset"] = "1000010" + headers["x-ratelimit-remaining"] = "4823" + err_resp = mock.Mock(status=403, headers=headers) + err_resp.read.return_value = b"You have exceeded a secondary rate limit." + succ_resp = mock.Mock(status=200, headers=http.client.HTTPMessage()) + succ_resp.read.return_value = b"Success" + + conn.getresponse.side_effect = [err_resp, succ_resp] + + response = http_retry.request_with_retries( + "GET", "/foo", host="api.github.com", headers={}, sleep=self.sleeper + ) + self.assertEqual(response.status, 200) + self.assertEqual(self.sleeper.calls, [10.0]) + @mock.patch("http.client.HTTPSConnection") def test_retries_secondary_rate_limit_403_by_body_marker(self, mock_conn_class): conn = mock.Mock() From 803b6b28dc6a910be832b80d27047478606e9533 Mon Sep 17 00:00:00 2001 From: kgrizz-git <216068303+kgrizz-git@users.noreply.github.com> Date: Tue, 17 Nov 2026 22:18:32 -0500 Subject: [PATCH 3/3] Qualify the skipped-repo claim in the changelog The local terminal report still drops repositories whose artifact fetch fails; only the email and PDF outputs render them as skipped. --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 34b2d98..3881109 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,7 @@ This project follows the structure from Keep a Changelog and intends to use Sema ### Fixed -- **Permission 403s no longer back off like rate limits:** `http_retry` treated any 403 carrying `x-ratelimit-reset` as throttling, but GitHub sends that header on ordinary permission denials too. A token missing `Actions: Read-only` on private repos therefore slept up to 30s per attempt (three retries per repo — about 40 minutes for a 100-repo report whose 25 private repos were inaccessible) before giving up on each repo. A 403 now retries only when it carries `Retry-After`, reports `x-ratelimit-remaining: 0`, or names a rate limit in the body; inaccessible repos fail fast and still appear as skipped in artifact storage output. +- **Permission 403s no longer back off like rate limits:** `http_retry` treated any 403 carrying `x-ratelimit-reset` as throttling, but GitHub sends that header on ordinary permission denials too. A token missing `Actions: Read-only` on private repos therefore slept up to 30s per attempt (three retries per repo — about 40 minutes for a 100-repo report whose 25 private repos were inaccessible) before giving up on each repo. A 403 now retries only when it carries `Retry-After`, reports `x-ratelimit-remaining: 0`, or names a rate limit in the body. Inaccessible repos now fail fast: the email and PDF outputs list them as skipped in artifact storage, while the local terminal report omits them. - **CLI flags no longer open the TUI:** `github-usage --export` / `--no-interactive` (and any other dashed argv, including `github-usage -v`) stay on the CLI when stdin and stdout are TTYs. Only a bare `github-usage` in a terminal launches the Textual app. `./start.sh -v` is unchanged because `start.sh` already maps `-v` to `--version` before Python routing. - **Artifact storage partial failures:** a per-repo artifact API error no longer blanks the whole Actions Artifact Storage section — successfully scanned repos still render, and failed repos are listed as skipped in the text/HTML email and PDF exports. - **Email Actions section:** plain-text and HTML emails show **private-repo quota** against the 2,000 min / 500 MB free tier (with public usage labeled free) instead of comparing combined account totals to the private quota. When no visibility split is available, the report says so explicitly rather than implying the total is all quota-counted.