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,3 @@
schema: spec-driven
created: 2026-10-31
skip_specs: true
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Design: Handle Traffic API 403 for Integration Tokens

## Context
When collecting repository metrics (`get_repository_traffic_metrics`), four traffic endpoints are queried:
- views (`repos/{repo}/traffic/views`)
- clones (`repos/{repo}/traffic/clones`)
- referrers (`repos/{repo}/traffic/popular/referrers`)
- popular paths (`repos/{repo}/traffic/popular/paths`)

When running under an integration token (GitHub App installation token), each call fails with `Resource not accessible by integration (HTTP 403)`.

## Design Decisions
1. **Error detection**:
- In `_read_json`, inspect errors raised during `client.api(path)`.
- Identify whether an error is a refusal by token using `is_gh_refused_by_token(str(err.details.get("stderr", "")))` or matching `"Resource not accessible by integration"` in the error message.
2. **Logging**:
- For errors matching the integration restriction, do NOT log at WARNING level.
- In `get_repository_traffic_metrics`, if any/all traffic calls were refused by integration token:
Log exactly one DEBUG line per repository:
`logger.debug("Traffic API not accessible by integration for %s: skipping traffic metrics", repo)`
- For all other errors, preserve `logger.warning("Failed to query %s: %s", what, err)`.
3. **Telemetry emission**:
- When traffic endpoints are refused by the integration token, return `TrafficSummaryMetric` with `traffic_collected=False`.
- `emit_project_metrics_telemetry` checks `report.traffic.traffic_collected` before calling `_emit_traffic`. When `traffic_collected` is False, no `PROJECT_TRAFFIC_*` gauges are emitted.
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Proposal

## Why
Issue #2626: The roadmap Service logs four WARNING lines per repository per metrics cycle when running with a GitHub App integration token:
`Failed to query traffic <endpoint> for <repo>: gh api call failed with exit code 1: gh: Resource not accessible by integration (HTTP 403)`
GitHub returns `Resource not accessible by integration (HTTP 403)` on each traffic endpoint for an integration token because integration tokens lack the repository Administration permission. This restriction is permanent by design.
In addition, `get_repository_traffic_metrics` returns a `TrafficSummaryMetric` with `traffic_collected=True` and zeroes for traffic counts, causing `emit_project_metrics_telemetry` to emit zero-valued `PROJECT_TRAFFIC_*` gauges that misrepresent repository activity.

## What Changes
- Detect `Resource not accessible by integration` on GitHub traffic API calls.
- When the traffic API returns the integration restriction for a repository, log exactly one DEBUG line per repository instead of four WARNING lines.
- Preserve WARNING logs for other traffic API failures (such as HTTP 502, network errors, or rate limits).
- Mark `traffic_collected=False` in `TrafficSummaryMetric` when traffic collection is refused by the integration token, preventing the emission of zero-valued `PROJECT_TRAFFIC_*` gauges.
- Add and update tests in `tests/test_github_metrics.py`.

## Capabilities

### New Capabilities
- None.

### Modified Capabilities
- None.

## Impact
- Source files: `src/devops_cli/github/metrics.py`.
- Test files: `tests/test_github_metrics.py`.

## Feasibility
Confirmed against `src/devops_cli/github/metrics.py`:
- `_read_json` catches exceptions from `client.api(path)` and currently calls `logger.warning("Failed to query %s: %s", what, err)` unconditionally before checking `is_gh_refused_by_token`.
- `get_repository_traffic_metrics` calls the four traffic fetch functions and always sets `TrafficSummaryMetric(views_count=..., ...)` with default `traffic_collected=True`.
- In `emit_project_metrics_telemetry`, traffic metrics are emitted only when `report.traffic.traffic_collected` is true. Setting `traffic_collected=False` when traffic endpoints are refused by the token avoids emitting misleading zero gauges.
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Tasks

## 1. Write Failing Tests
- [x] Add failing test cases in `tests/test_github_metrics.py` asserting one DEBUG line, zero WARNING lines, and `traffic_collected=False` when traffic calls return integration 403 <!-- id: 1-failing-tests -->
- [x] Verify test fails against current `origin/main` <!-- id: 1-verify-fail -->

## 2. Implement Integration 403 Handling
- [x] Update `_read_json` and `get_repository_traffic_metrics` in `src/devops_cli/github/metrics.py` to suppress WARNING and emit one DEBUG line on integration 403 <!-- id: 2-update-metrics -->
- [x] Set `traffic_collected=False` when traffic endpoints are refused by the token <!-- id: 2-skip-gauges -->
- [x] Verify tests pass <!-- id: 2-verify-pass -->

## 3. Verification & PR
- [x] Run `devops ci fail-to-pass --base origin/main` <!-- id: 3-fail-to-pass -->
- [x] Run fast checks, archive change, and open draft PR <!-- id: 3-pr -->
- [x] Monitor checks and mark PR ready <!-- id: 3-ready -->
44 changes: 36 additions & 8 deletions src/devops_cli/github/metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -472,15 +472,26 @@ def get_label_taxonomy_metrics(repo: str) -> list[LabelTaxonomyMetric]:


_refused_paths: set[str] = set()
_refused_integration_repos: set[str] = set()
"""The GitHub paths that answered this process with HTTP 403 "Resource not accessible by
integration": the token lacks the permission of the path and keeps lacking it until the process
restarts, so the collector does not ask again (#2752). A path holds the repository and the
restarts, so the collector does not ask again (#2752, #2626). A path holds the repository and the
endpoint."""


def reset_refused_paths() -> None:
"""Forget the refused paths, as a new process knows none."""
_refused_paths.clear()
_refused_integration_repos.clear()


def _is_integration_refusal(err: Exception) -> bool:
"""Whether `err` indicates an HTTP 403 "Resource not accessible by integration"."""
if isinstance(err, GitHubOperationError):
stderr = str(err.details.get("stderr", ""))
if is_gh_refused_by_token(stderr):
return True
return "Resource not accessible by integration" in str(err)


def _read_json(client: GhCliClient, path: str, what: str) -> Any | None:
Expand All @@ -492,11 +503,10 @@ def _read_json(client: GhCliClient, path: str, what: str) -> Any | None:
try:
return json.loads(client.api(path))
except Exception as err:
logger.warning("Failed to query %s: %s", what, err)
if isinstance(err, GitHubOperationError) and is_gh_refused_by_token(
str(err.details.get("stderr", ""))
):
if _is_integration_refusal(err):
_refused_paths.add(path)
else:
logger.warning("Failed to query %s: %s", what, err)
return None


Expand Down Expand Up @@ -573,12 +583,30 @@ def get_repository_traffic_metrics(repo: str) -> TrafficSummaryMetric:
"""
client = GhCliClient()
stars, forks, open_issues = _fetch_repo_metadata(client, repo)
if acts_as_github_app():
if acts_as_github_app() or repo in _refused_integration_repos:
return TrafficSummaryMetric(
traffic_collected=False, stars=stars, forks=forks, open_issues=open_issues
)
views_count, views_uniques = _fetch_traffic_views(client, repo)
clones_count, clones_uniques = _fetch_traffic_clones(client, repo)
referrers = _fetch_traffic_referrers(client, repo)
paths = _fetch_traffic_paths(client, repo)

traffic_paths = {
f"repos/{repo}/traffic/views",
f"repos/{repo}/traffic/clones",
f"repos/{repo}/traffic/popular/referrers",
f"repos/{repo}/traffic/popular/paths",
}
if traffic_paths & _refused_paths:
if repo not in _refused_integration_repos:
_refused_integration_repos.add(repo)
logger.debug(
"Traffic API not accessible by integration for %s: skipping traffic metrics", repo
)
return TrafficSummaryMetric(
traffic_collected=False, stars=stars, forks=forks, open_issues=open_issues
)

return TrafficSummaryMetric(
views_count=views_count,
Expand All @@ -588,8 +616,8 @@ def get_repository_traffic_metrics(repo: str) -> TrafficSummaryMetric:
stars=stars,
forks=forks,
open_issues=open_issues,
referrers=_fetch_traffic_referrers(client, repo),
paths=_fetch_traffic_paths(client, repo),
referrers=referrers,
paths=paths,
)


Expand Down
38 changes: 34 additions & 4 deletions tests/test_github_metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -894,17 +894,47 @@ def test_a_path_that_the_token_cannot_read_is_asked_once(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
"""After one 403 "Resource not accessible by integration" for a repository and an endpoint,
the process does not ask that path again. The first refusal logs one warning."""
the process does not ask that path again. The refusal logs zero warnings and one debug line (#2626)."""
github = _github(monkeypatch, app=False, traffic_answer=REFUSED_BY_TOKEN)

with caplog.at_level(logging.WARNING, logger="devops_cli.github.metrics"):
with caplog.at_level(logging.DEBUG, logger="devops_cli.github.metrics"):
get_repository_traffic_metrics("example/repo")
get_repository_traffic_metrics("example/repo")

warnings = [
r
for r in caplog.records
if r.levelno >= logging.WARNING and "traffic" in r.getMessage().lower()
]
debugs = [
r
for r in caplog.records
if r.levelno == logging.DEBUG and "integration" in r.getMessage().lower()
]

assert (
github.traffic_calls(),
sum("Failed to query" in r.getMessage() for r in caplog.records),
) == (_traffic_paths("example/repo"), 4)
warnings,
len(debugs),
) == (_traffic_paths("example/repo"), [], 1)


def test_traffic_api_integration_403_skips_gauges(
monkeypatch: pytest.MonkeyPatch, otlp: FakeCollector
) -> None:
"""When the traffic API returns 403 integration refusal, no traffic gauges are emitted (#2626)."""
_github(monkeypatch, app=False, traffic_answer=REFUSED_BY_TOKEN)

traffic = get_repository_traffic_metrics("example/repo")
assert traffic.traffic_collected is False

report = ProjectMetricsReport(
repo="example/repo",
generated_at="2026-10-30 00:00:00 UTC",
traffic=traffic,
)
emit_project_metrics_telemetry(report)
assert [otlp.points(s.name) for s in TRAFFIC_SERIES] == [[] for _ in TRAFFIC_SERIES]


def test_a_refusal_for_one_repository_does_not_stop_the_others(
Expand Down
Loading