diff --git a/CHANGELOG.md b/CHANGELOG.md index cc470b6..3881109 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 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. 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/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..b174a3b 100644 --- a/tests/test_http_retry.py +++ b/tests/test_http_retry.py @@ -111,6 +111,157 @@ 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("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() + 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()