Skip to content

fix(gh_client): fail fast on 401/403 auth errors instead of retrying forever (#5325) - #5329

Merged
rolandtannous merged 6 commits into
unslothai:mainfrom
Anai-Guo:fix/gh-client-fail-fast-on-auth-errors
May 8, 2026
Merged

rolandtannous merged 6 commits into
unslothai:mainfrom
Anai-Guo:fix/gh-client-fail-fast-on-auth-errors

Conversation

@Anai-Guo

@Anai-Guo Anai-Guo commented May 7, 2026

Copy link
Copy Markdown
Contributor

What this PR does

Fixes #5325.

The Studio data-recipe GitHub Crawler treats 401 Unauthorized from the
GitHub GraphQL API as a transient network error and keeps retrying. Because
the token is invalid (rotated, expired, or wrong scope), every retry returns
401, the job stays alive emitting [WARNING] GraphQL network error: 401 ... Retry. lines, and the user has to notice and cancel it manually.

The same problem applies to 403 Forbidden responses that aren't actually
rate-limited (the existing 403 branch already handles Retry-After and
X-RateLimit-Remaining: 0, but otherwise falls back to a permanent
time.sleep(60); continue).

Root cause

gh_client.py only special-cases 502/503/504 and 403/429. Any other
non-2xx — including 401 — falls through to r.raise_for_status(), which
raises requests.HTTPError. That gets caught by the outer
except requests.RequestException and logged as a "network error" — same
path as a real connection failure.

Fix

  1. New GitHubAuthError(RuntimeError) exception.

  2. New _is_auth_failure(response) helper:

    • 401 → always auth failure.
    • 403 → auth failure unless the response carries Retry-After
      (secondary rate limit) or X-RateLimit-Remaining: 0 (primary rate
      limit).
  3. Auth-failure check inserted in both .graphql() and .rest() before the
    existing 403/429 rate-limit branch, so auth errors bypass the
    sleep-and-retry loop.

  4. The token source resolved at construction time (recipe-level argument,
    GH_TOKEN, or GITHUB_TOKEN) is captured on self._token_source and
    embedded in the raised error message — so the user knows exactly which
    credential to rotate:

    GitHub GraphQL returned 401 Unauthorized. Token source: GH_TOKEN environment
    variable. The token is invalid, expired, or missing required scopes —
    retrying will not recover. Response: ...
    

What does NOT change

  • Genuine rate limiting (Retry-After or X-RateLimit-Remaining: 0) still
    takes the existing retry path.
  • Transient network errors (requests.ConnectionError etc.) still retry
    through the existing except requests.RequestException branch.
    GitHubAuthError is a RuntimeError, not a RequestException, so it
    propagates up and aborts the job as intended.
  • 5xx upstream errors (502/503/504) still retry.

Files

  • studio/backend/plugins/data-designer-github-repo-seed/src/data_designer_github_repo_seed/scraper_impl/gh_client.py

🤖 Generated with Claude Code

…forever (unslothai#5325)

Fixes unslothai#5325. The Studio data-recipe GitHub Crawler swallows 401 Unauthorized
(and 403 Forbidden without rate-limit headers) into the generic
"network error" retry path, so a job with a stale or wrong-scoped GitHub
token spins indefinitely emitting "Retry." lines until the user cancels.

Changes:

- Add GitHubAuthError. Raised on 401, and on 403 unless the response carries
  a clear rate-limit signal (Retry-After header for secondary limits, or
  X-RateLimit-Remaining: 0 for primary limits).
- Track which token source resolved at construction time: explicit argument
  (recipe-level field), GH_TOKEN, or GITHUB_TOKEN. Surfaced in the error
  message so the user knows which credential to rotate.
- Insert the auth-failure check before the existing 403/429 rate-limit branch
  in both .graphql() and .rest() so auth failures bypass the sleep-and-retry
  loop and abort the recipe immediately.

Genuine rate limiting still retries via the existing path. requests.RequestException
handling is unchanged because GitHubAuthError does not inherit from it.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
@Anai-Guo
Anai-Guo requested a review from rolandtannous as a code owner May 7, 2026 16:22

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 731a0b37e4

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +85 to +89
if r.headers.get("Retry-After"):
return False
if r.headers.get("X-RateLimit-Remaining") == "0":
return False
return True

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Treat headerless secondary 403s as retryable

_is_auth_failure classifies every 403 as credential failure unless Retry-After or X-RateLimit-Remaining: 0 is present, but GitHub secondary rate limiting can return 403 without those headers (the signal is often only in the response body/message). In that case both graphql() and rest() now raise GitHubAuthError immediately (because they call this helper before the 403/429 retry branch), so valid tokens can cause jobs to fail instead of backing off and recovering.

Useful? React with 👍 / 👎.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a new GitHubAuthError exception and logic to distinguish between authentication failures and rate limiting in the GitHubClient. It also tracks the source of the GitHub token for more informative error messages. The review feedback suggests optimizing the token resolution logic in the init method by using the walrus operator to eliminate redundant environment variable lookups.

Comment on lines 44 to 53
if token:
self._token_source = "explicit token argument (recipe-level field)"
elif os.environ.get("GH_TOKEN"):
self._token_source = "GH_TOKEN environment variable"
token = os.environ["GH_TOKEN"]
elif os.environ.get("GITHUB_TOKEN"):
self._token_source = "GITHUB_TOKEN environment variable"
token = os.environ["GITHUB_TOKEN"]
else:
raise RuntimeError("GH_TOKEN not set in environment")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

This block for resolving the GitHub token can be simplified to avoid redundant lookups in os.environ. Currently, you call os.environ.get(...) to check for existence and then os.environ[...] to retrieve the value. Using the walrus operator (:=) allows you to assign the value and check for truthiness in one step, avoiding the second lookup and improving efficiency.

        if token:
            self._token_source = "explicit token argument (recipe-level field)"
        elif (token := os.environ.get("GH_TOKEN")):
            self._token_source = "GH_TOKEN environment variable"
        elif (token := os.environ.get("GITHUB_TOKEN")):
            self._token_source = "GITHUB_TOKEN environment variable"
        else:
            raise RuntimeError("GH_TOKEN not set in environment")
References
  1. To improve efficiency, avoid redundant data iterations. Combine checks and transformations into a single loop and return computed values for callers to reuse.

wasimysaid added 2 commits May 8, 2026 14:27
Preserve GitHub token source through the repo seed scraper and fail fast on non-rate-limit auth errors while keeping genuine rate-limit retries.
@wasimysaid

Copy link
Copy Markdown
Collaborator

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request enhances GitHub token resolution and error handling by introducing a ResolvedToken structure and a new GitHubAuthError exception. It adds logic to distinguish between authentication failures and rate limiting, and improves Retry-After header parsing to support both durations and timestamps. Feedback focuses on centralizing the token resolution logic, which is currently duplicated between scraper.py and gh_client.py, to improve maintainability.

@rolandtannous

Copy link
Copy Markdown
Contributor

tested and validated by @wasimysaid . delivered ok to merge . merging

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.

[Bug] [Studio] GitHub Crawler retries indefinitely on 401 Unauthorized

3 participants