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
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-11-17
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Design

## Decisions

### One retry, same limit

The reported failure passed some seconds later, so a second attempt recovers it. Each attempt gets
the same 5 second limit, and the worst case stays at 10 seconds. A larger second limit doubles the
worst case and makes the test depend on it.

### Retry inside `_lookup_github_token`

That function sets the limit and turns the timeout into the message. A retry in
`_session_github_token` would not run for `devops gh api`, because `github_token()` passes
`retry_now=True` and skips the failure record. A retry in the process runner would retry every
subprocess.

### Only a timeout retries

An `OSError`, such as a missing gh, and a nonzero exit return at once. A repeated missing gh would
only double the fast error path.

### The attempt count is a constant

`DEFAULT_GH_AUTH_TOKEN_ATTEMPTS` in `src/devops_cli/config/defaults.py` sits beside the timeout. A
test can set it to 1, and no operational setting is added.

## Rejected alternatives

- **Raise the timeout to 30 seconds:** a broken gh blocks every GitHub call for 30 seconds.
- **A larger second limit:** it doubles the worst case.
- **Retry in `_session_github_token`:** it never runs for `devops gh api`.
- **Retry every subprocess:** it retries calls that are no token lookup.
- **Retry an `OSError`:** the issue shows a timeout, and a missing gh should fail fast.
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# Proposal: #4940

## Why

`devops gh api` can fail once with "GitHub is not authenticated" on a loaded host. The lookup gives
`gh auth token` 5 seconds, and the start of gh alone can take longer, so a valid login reads as not
authenticated. The command stops with no retry. Closes #4940.

## What Changes

- `_lookup_github_token` tries `gh auth token` again after a timeout, up to
`DEFAULT_GH_AUTH_TOKEN_ATTEMPTS` attempts, with the same 5 second limit for each attempt.
- An `OSError`, a nonzero exit or a missing gh still fails at once.
- The process keeps a token that a retry finds.

## Capabilities

### Modified

- `github-app-identity`: the gh login fallback retries a timed-out token lookup.

## Impact

A slow host no longer turns a valid gh login into an authentication error. The worst case is one
more 5 second attempt. A repeated success keeps the token for the process.

## Feasibility

Confirmed against the issue and the code: `_lookup_github_token` in
`src/devops_cli/core/process.py` sets the 5 second limit and turns the timeout into the error.
`_session_github_token` keeps the token that the lookup returns, and `reset_github_token` clears it.

## Existing Tool Considered

No open tool covers this need. The alternatives check of 2026-11-15 returned `none`; no external
tool changes the limit that this function gives `gh auth token` or retries the lookup inside the
process. The retry costs about 3,000 tokens to build and 1,000 to keep.
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
## ADDED Requirements

### Requirement: A timed-out gh auth token lookup is tried again

The process SHALL run `gh auth token` up to `DEFAULT_GH_AUTH_TOKEN_ATTEMPTS` times when an attempt
times out, with the same `DEFAULT_GH_AUTH_TOKEN_TIMEOUT_SECONDS` limit for each attempt. It SHALL
NOT retry an `OSError` or an exit status other than zero. It SHALL keep a token that a retry finds
for the session.

#### Scenario: The first attempt times out and the second answers

- **WHEN** the first `gh auth token` call raises `subprocess.TimeoutExpired` and the second returns
a token
- **THEN** the lookup returns that token and `run_subprocess` is called exactly twice

#### Scenario: Every attempt times out

- **WHEN** each attempt of `gh auth token` raises `subprocess.TimeoutExpired`
- **THEN** the lookup returns the unauthenticated message, `run_subprocess` is called
`DEFAULT_GH_AUTH_TOKEN_ATTEMPTS` times, and the message names the time limit

#### Scenario: gh is not on PATH

- **WHEN** the first `gh auth token` call raises `OSError`
- **THEN** the lookup returns the not-found message and `run_subprocess` is called exactly once

#### Scenario: A later GitHub call after a retried lookup

- **WHEN** the lookup finds a token on its second attempt and `github_token()` is called again
- **THEN** `github_token()` returns the same token and runs no subprocess
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Tasks

## 1. Behavior

- [x] 1.1 Write the failing tests for a timeout that the second attempt answers, every attempt
timing out, an `OSError`, a nonzero exit, and the kept token.
- Verification: `$ uv run devops ci test tests/core/test_github_auth_token.py`
- [x] 1.2 Retry the timed-out lookup up to `DEFAULT_GH_AUTH_TOKEN_ATTEMPTS` attempts.
- Verification: `$ uv run devops ci test tests/core/test_github_auth_token.py`

## 2. Documents

- [x] 2.1 Update the `github-app-identity` specification.
- Verification: `$ uv run devops openspec check`
- [x] 2.2 Archive the change into the main specification.
- Verification: `$ uv run devops openspec archive 4940-slow-gh-auth-token-on-a-loaded-host`
29 changes: 29 additions & 0 deletions openspec/specs/github-app-identity/spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,3 +143,32 @@ When the setting `service.github_app.token_repository` holds `owner/name`, the i
#### Scenario: A bad value
- **WHEN** the setting holds `project`
- **THEN** the settings refuse it

### Requirement: A timed-out gh auth token lookup is tried again

The process SHALL run `gh auth token` up to `DEFAULT_GH_AUTH_TOKEN_ATTEMPTS` times when an attempt
times out, with the same `DEFAULT_GH_AUTH_TOKEN_TIMEOUT_SECONDS` limit for each attempt. It SHALL
NOT retry an `OSError` or an exit status other than zero. It SHALL keep a token that a retry finds
for the session.

#### Scenario: The first attempt times out and the second answers

- **WHEN** the first `gh auth token` call raises `subprocess.TimeoutExpired` and the second returns
a token
- **THEN** the lookup returns that token and `run_subprocess` is called exactly twice

#### Scenario: Every attempt times out

- **WHEN** each attempt of `gh auth token` raises `subprocess.TimeoutExpired`
- **THEN** the lookup returns the unauthenticated message, `run_subprocess` is called
`DEFAULT_GH_AUTH_TOKEN_ATTEMPTS` times, and the message names the time limit

#### Scenario: gh is not on PATH

- **WHEN** the first `gh auth token` call raises `OSError`
- **THEN** the lookup returns the not-found message and `run_subprocess` is called exactly once

#### Scenario: A later GitHub call after a retried lookup

- **WHEN** the lookup finds a token on its second attempt and `github_token()` is called again
- **THEN** `github_token()` returns the same token and runs no subprocess
3 changes: 3 additions & 0 deletions src/devops_cli/config/defaults.py
Original file line number Diff line number Diff line change
Expand Up @@ -816,6 +816,9 @@
DEFAULT_GH_RESOURCE: str = "core"
# `gh auth token` answers locally; a hung keyring must not stall the first gh or git call (#767).
DEFAULT_GH_AUTH_TOKEN_TIMEOUT_SECONDS: float = 5.0
# A loaded host can start gh slower than the timeout above. One more attempt keeps a valid login
# from reading as an authentication error (#4940).
DEFAULT_GH_AUTH_TOKEN_ATTEMPTS: int = 2
# After `gh auth token` printed no token, git runs without one and looks again only this much later;
# gh calls look again every time, since they cannot run without one.
DEFAULT_GH_AUTH_TOKEN_RETRY_SECONDS: float = 60.0
Expand Down
52 changes: 30 additions & 22 deletions src/devops_cli/core/process.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
CONST_GITHUB_HOST,
)
from devops_cli.config.defaults import (
DEFAULT_GH_AUTH_TOKEN_ATTEMPTS,
DEFAULT_GH_AUTH_TOKEN_RETRY_SECONDS,
DEFAULT_GH_AUTH_TOKEN_TIMEOUT_SECONDS,
DEFAULT_GITHUB_APP_TOKEN_RENEW_SECONDS,
Expand Down Expand Up @@ -330,32 +331,39 @@ def github_identity() -> GitHubIdentity:
def _lookup_github_token() -> tuple[str, str]:
"""Run `gh auth token`; it applies GH_TOKEN, then GITHUB_TOKEN, then gh's stored login.

The child is a `gh auth` call, so it gets the ambient tokens and never a pinned one. Returns
the token, or "" and the unauthenticated error's message when there is none.
The child is a `gh auth` call, so it gets the ambient tokens and never a pinned one. A timeout
tries again, because a loaded host can start gh slower than the limit (#4940). Returns the
token, or "" and the unauthenticated error's message when there is none.
"""
from devops_cli.lang import ERRORS

timeout = DEFAULT_GH_AUTH_TOKEN_TIMEOUT_SECONDS
try:
proc = run_subprocess(
[CONST_GH_CLI, CONST_GH_AUTH_SUBCOMMAND, "token"],
check=False,
quiet=True,
timeout=timeout,
extra_allowed_env=CONST_GH_LOGIN_ENV_VARS,
)
except subprocess.TimeoutExpired:
reason = ERRORS.git.github_token_lookup_timed_out.format(seconds=timeout)
return "", ERRORS.git.github_token_lookup_failed.format(reason=reason)
except OSError as err:
return "", ERRORS.git.github_token_lookup_failed.format(reason=type(err).__name__)
token = proc.stdout.strip() if proc.returncode == 0 else ""
if token:
return token, ""
if proc.returncode == CONST_EXIT_COMMAND_NOT_FOUND:
reason = ERRORS.git.github_token_lookup_not_found
return "", ERRORS.git.github_token_lookup_failed.format(reason=reason)
return "", ERRORS.git.github_unauthenticated.format(status=proc.returncode)
attempts = max(1, DEFAULT_GH_AUTH_TOKEN_ATTEMPTS)
for attempt in range(attempts):
try:
proc = run_subprocess(
[CONST_GH_CLI, CONST_GH_AUTH_SUBCOMMAND, "token"],
check=False,
quiet=True,
timeout=timeout,
extra_allowed_env=CONST_GH_LOGIN_ENV_VARS,
)
except subprocess.TimeoutExpired:
if attempt + 1 < attempts:
continue
reason = ERRORS.git.github_token_lookup_timed_out.format(seconds=timeout)
return "", ERRORS.git.github_token_lookup_failed.format(reason=reason)
except OSError as err:
return "", ERRORS.git.github_token_lookup_failed.format(reason=type(err).__name__)
token = proc.stdout.strip() if proc.returncode == 0 else ""
if token:
return token, ""
if proc.returncode == CONST_EXIT_COMMAND_NOT_FOUND:
reason = ERRORS.git.github_token_lookup_not_found
return "", ERRORS.git.github_token_lookup_failed.format(reason=reason)
return "", ERRORS.git.github_unauthenticated.format(status=proc.returncode)
reason = ERRORS.git.github_token_lookup_timed_out.format(seconds=timeout)
return "", ERRORS.git.github_token_lookup_failed.format(reason=reason)


def _lookup_session_token() -> tuple[str, str, datetime | None]:
Expand Down
81 changes: 81 additions & 0 deletions tests/core/test_github_auth_token.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
"""The `gh auth token` lookup retries a timeout on a loaded host (#4940)."""

from __future__ import annotations

import subprocess
from collections.abc import Iterator

import pytest

from devops_cli.core import process
from tests.support.fakes.process import ProcessAnswer, ProcessCall, ProcessFake

TOKEN_COMMAND = ["gh", "auth", "token"]


@pytest.fixture(autouse=True)
def _clean_token() -> Iterator[None]:
process.reset_github_token()
yield
process.reset_github_token()


def test_a_lookup_returns_the_token_of_its_second_attempt(process_fake: ProcessFake) -> None:
calls: list[ProcessCall] = []

def answer(call: ProcessCall) -> subprocess.CompletedProcess[str]:
calls.append(call)
if len(calls) == 1:
raise subprocess.TimeoutExpired(call.argv, 5.0)
return subprocess.CompletedProcess(call.argv, 0, "gh-token\n", "")

process_fake.answer(TOKEN_COMMAND, ProcessAnswer(side_effect=answer))

assert (process._lookup_github_token(), len(process_fake.calls)) == (
("gh-token", ""),
2,
)


def test_every_attempt_that_times_out_reports_the_limit(process_fake: ProcessFake) -> None:
process_fake.answer(
TOKEN_COMMAND, ProcessAnswer(side_effect=subprocess.TimeoutExpired(TOKEN_COMMAND, 5.0))
)

token, why = process._lookup_github_token()

assert (token, "no answer within 5 s" in why, len(process_fake.calls)) == ("", True, 2)


def test_a_missing_gh_is_not_retried(process_fake: ProcessFake) -> None:
process_fake.answer(TOKEN_COMMAND, ProcessAnswer(side_effect=FileNotFoundError()))

token, why = process._lookup_github_token()

assert (token, "FileNotFoundError" in why, len(process_fake.calls)) == ("", True, 1)


def test_a_failed_gh_call_is_not_retried(process_fake: ProcessFake) -> None:
process_fake.answer(TOKEN_COMMAND, ProcessAnswer(returncode=1))

token, why = process._lookup_github_token()

assert (token, bool(why), len(process_fake.calls)) == ("", True, 1)


def test_the_process_keeps_the_token_that_a_retry_found(process_fake: ProcessFake) -> None:
calls: list[ProcessCall] = []

def answer(call: ProcessCall) -> subprocess.CompletedProcess[str]:
calls.append(call)
if len(calls) == 1:
raise subprocess.TimeoutExpired(call.argv, 5.0)
return subprocess.CompletedProcess(call.argv, 0, "gh-token\n", "")

process_fake.answer(TOKEN_COMMAND, ProcessAnswer(side_effect=answer))

assert (process.github_token(), process.github_token(), len(calls)) == (
"gh-token",
"gh-token",
2,
)
6 changes: 4 additions & 2 deletions tests/core/test_subprocess_env_boundary.py
Original file line number Diff line number Diff line change
Expand Up @@ -852,16 +852,18 @@ def test_a_lookup_that_cannot_run_leaves_git_working_and_says_why(
failure: Exception, reason: str, unresolved_identity: None
) -> None:
"""A hung or unrunnable gh means no token: git still runs, and gh's error names the cause."""
lookup = (failure, failure) if isinstance(failure, subprocess.TimeoutExpired) else (failure,)
with faked_children(
side_effect=(children := _Children(failure, _gh_answers(), failure))
side_effect=(children := _Children(*lookup, _gh_answers(), failure))
) as run:
proc = run_subprocess(["git", "fetch"])
with pytest.raises(GitHubUnauthenticatedError) as raised:
run_subprocess([CONST_GH_CLI, "issue", "list"])
git_child = next(env for env in _child_envs(children) if env[0] == ["git", "fetch"])
assert (
run.call_args_list[0].kwargs["timeout"],
proc.returncode,
_child_envs(children)[1],
git_child,
reason in raised.value.message,
) == (DEFAULT_GH_AUTH_TOKEN_TIMEOUT_SECONDS, 0, (["git", "fetch"], None, None), True)

Expand Down