Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
1 change: 1 addition & 0 deletions TO_DO.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
36 changes: 29 additions & 7 deletions src/github_usage/http_retry.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Legacy reports omit inaccessible repos

When a permission 403 occurs during a legacy report’s artifact scan and the repo has no other storage entry to keep it in the results, get_all_pages raises for the fast-failing 403, but the legacy path’s _collect_repo_artifacts catches that error and returns an empty list; _analyze_one_repo can then omit the repo, and the legacy artifact-storage output has no skipped entry for it.

Record artifact-fetch failures in the legacy storage result and render them as skipped entries instead of silently dropping them.

Prompt for AI agents
In `src/github_usage/http_retry.py` at line 127:

**Legacy reports omit inaccessible repos**

When a permission 403 occurs during a legacy report’s artifact scan and the repo has no other storage entry to keep it in the results, `get_all_pages` raises for the fast-failing 403, but the legacy path’s `_collect_repo_artifacts` catches that error and returns an empty list; `_analyze_one_repo` can then omit the repo, and the legacy artifact-storage output has no skipped entry for it.

Record artifact-fetch failures in the legacy storage result and render them as skipped entries instead of silently dropping them.

):
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
Expand Down
151 changes: 151 additions & 0 deletions tests/test_http_retry.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
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()
Expand Down
Loading