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-26
skip_specs: true
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# Design

## Context

See `proposal.md` - Why.
`run_gh` paces commands against rate limits by detecting their target resource with `_detect_resource`.
Before this change, `_detect_resource` only mapped `project` or arguments containing `graphql` to `graphql`.
It mapped commands with `search/` anywhere in arguments to `search`.
This caused false negatives for GraphQL porcelain commands and false positives for REST paths containing substrings.

## Goals / Non-Goals

**Goals:**
- Classify `gh` porcelain commands backed by GraphQL as `graphql` using parsed command words.
- Classify `gh api` requests using parsed endpoint path segments.
- Eliminate all `in arg` substring checks in resource detection.
- Maintain existing classification for `api graphql`, `api search/*`, `api code-scanning/*`, and `dependency-graph/sbom`.
- Ensure offline unit tests verify both positive and negative cases.

**Non-Goals:**
- Change the pacing formula or backoff strategy of `GitHubRateLimiter`.
- Replace `gh` porcelain commands with REST equivalents in callers.
- Add network calls during rate-limit resource detection.

## Decisions

### Decision 1: Structured Classification Table in constants.py

Define `CONST_GH_GRAPHQL_PORCELAIN_COMMANDS` and `CONST_GH_GRAPHQL_GROUPS` in `src/devops_cli/config/constants.py`.
Classify porcelain commands using `gh_command_words` parsed group and verb against this table.
This eliminates substring matching on arbitrary arguments such as commit titles or bodies.

*Alternatives considered:*
- Matching arguments by regex: rejected because regex on full arguments still inspects option values and flags.
- Converting all callers to use `gh api` REST endpoints: rejected because porcelain commands provide required higher-level features and formatting.

### Decision 2: Endpoint Parsing for gh api Commands

Use `parse_gh_api_args` to extract the target endpoint for `gh api` commands.
Inspect path segments rather than performing substring checks across all arguments.
Return `core` for repository names or paths containing `graphql` or `search` outside defined API prefixes.

*Alternatives considered:*
- Inspecting `clean_args[1]` directly: rejected because `gh api` accepts flags such as `-X POST` before the endpoint.

### Decision 3: Remove Substring Predicates

Remove `_is_graphql_command`, `_is_code_search_command`, `_is_code_scanning_autofix_command`, and `_is_general_search_command`.
Replace them with pure segment-matching functions `_detect_api_resource` and `_detect_porcelain_resource`.
This complies with the zero-zombie-code invariant and AGENTS.md rules.

*Alternatives considered:*
- Keeping the predicates as wrappers: rejected because pre-1.0 code maintains no backward compatibility shims.
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# Proposal

## Why

In #1415, `_detect_resource` in `src/devops_cli/github/rate_limiter.py` misclassifies GitHub CLI commands.
It classifies porcelain commands such as `pr checks`, `pr list`, and `issue list` as `core` REST requests.
GitHub runs these porcelain commands through GraphQL queries and mutations.
`run_gh` paces and plans them against the core REST rate-limit quota instead of the GraphQL quota.
Also, `_detect_resource` uses substring checks on arguments.
Arguments that contain substrings like `graphql` or `search/` cause false classifications.

This change fits one pull request.

## What Changes

- Classify GraphQL-backed GitHub CLI porcelain commands with a table of command words in `src/devops_cli/config/constants.py`.
- Classify `gh api` requests using the parsed endpoint path rather than argument substrings.
- Return `core` for REST endpoints whose path segments contain substrings like `graphql` or `search`.
- Update `_detect_resource` and `gh_request_resource` to use these structured classifiers.
- Update tests to assert that `pr checks`, `pr list`, `issue list`, and related porcelain commands map to `graphql`.
- Add test coverage for false-positive substring paths.

This change alters internal request pacing and dry-run display labels.
It does not change command lines, options, or external configurations.
The change sets `skip_specs: true` in `.openspec.yaml`.

## Capabilities

### New Capabilities

None.

### Modified Capabilities

None.

## Impact

- `src/devops_cli/config/constants.py`: defines `CONST_GH_GRAPHQL_PORCELAIN_COMMANDS`, `CONST_GH_GRAPHQL_GROUPS`, and REST endpoint prefix constants.
- `src/devops_cli/github/rate_limiter.py`: refactors `_detect_resource` to use structured endpoint and porcelain command classification.
- `tests/test_github_rate_limiter.py`: tests porcelain and REST endpoint rate-limit resource classification.
- `src/devops_cli/roadmap/request_plan.py`: reads `gh_request_resource` for accurate dry-run labels.

## Feasibility

- Confirmed with GitHub CLI version 2.103.2 that `pr checks`, `pr list`, `pr view`, `pr edit`, `pr ready`, `pr close`, `issue list`, `issue create`, and `release list` send GraphQL operations.
- Confirmed that `label list` sends a REST `GET /repos/{owner}/{repo}/labels` request.
- Confirmed that `_detect_resource` previously returned `core` for `["pr", "checks", "1"]` and `["pr", "list"]`.
- Confirmed that `_detect_resource` previously returned `graphql` for `["api", "repos/graphql/graphql-js/issues"]` due to substring matching.
- Confirmed that `_detect_resource` previously returned `search` for `["api", "repos/octo/research/issues"]`.

## Existing Tool Considered

GitHub CLI (`gh`) and GitHub's REST and GraphQL APIs execute repository requests.
The rate limiter in DevOps CLI paces requests to prevent API rate-limit exhaustion.
No open Python library maps GitHub CLI porcelain subcommands to GitHub API quota resources.
This change replaces internal substring checks in `src/devops_cli/github/rate_limiter.py` with structured table lookups.
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Tasks

## 1. Specification Tests

- [x] 1.1 Add failing unit tests in `tests/test_github_rate_limiter.py` asserting `gh_request_resource` returns `graphql` for porcelain commands (`pr checks`, `pr list`, `issue list`, `release list`, `issue create`, `pr view`, `pr edit`, `pr ready`, `pr close`). Verify failure with `uv run devops ci test tests/test_github_rate_limiter.py`.
- [x] 1.2 Add failing unit tests in `tests/test_github_rate_limiter.py` asserting `gh_request_resource` returns `core` for REST endpoints with substring matches (`repos/graphql/graphql-js/issues`, `repos/octo/research/issues`, `repos/octo/app/contents/docs/search/index.md`, and issue comments mentioning search). Verify failure with `uv run devops ci test tests/test_github_rate_limiter.py`.

## 2. Constants and Implementation

- [x] 2.1 Add `CONST_GH_GRAPHQL_GROUPS`, `CONST_GH_GRAPHQL_PORCELAIN_COMMANDS`, and REST endpoint prefix constants to `src/devops_cli/config/constants.py`.
- [x] 2.2 Refactor `_detect_resource` in `src/devops_cli/github/rate_limiter.py` to use `parse_gh_api_args` and `gh_command_words`. Remove substring predicate helpers.
- [x] 2.3 Verify `tests/test_github_rate_limiter.py` and `tests/test_roadmap_dry_runs.py` pass with `uv run devops ci test tests/test_github_rate_limiter.py`.

## 3. Documentation and Verification Gate

- [x] 3.1 Run `uv run devops docs generate --sync-readme` and verify `uv run devops docs check` passes.
- [x] 3.2 Run `uv run devops ci fail-to-pass --base origin/main` to verify the failing test evidence.
- [x] 3.3 Run `uv run devops ci` to ensure all quality gates pass.
- [x] 3.4 Archive OpenSpec change with `uv run devops openspec archive 1415-graphql-porcelain-pacing`.

## Workflow follow-up

- Pending a person: review the diff in tuicr (`tuicr -r origin/main..HEAD`).
28 changes: 28 additions & 0 deletions src/devops_cli/config/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -2446,6 +2446,34 @@ class WebhookExposure(StrEnum):
}
)

# gh porcelain command groups that use the GraphQL API (#1415).
CONST_GH_GRAPHQL_GROUPS: Final[frozenset[str]] = frozenset({"project"})

# gh porcelain commands that use the GraphQL API (#1415).
CONST_GH_GRAPHQL_PORCELAIN_COMMANDS: Final[frozenset[tuple[str, str]]] = frozenset(
{
("issue", "create"),
("issue", "list"),
("issue", "view"),
("pr", "checks"),
("pr", "close"),
("pr", "create"),
("pr", "edit"),
("pr", "list"),
("pr", "ready"),
("pr", "view"),
("release", "list"),
}
)

# REST endpoint segments for GitHub rate-limit resource detection (#1415).
CONST_GH_REST_SEARCH_CODE_PREFIX: Final[str] = "search/code"
CONST_GH_REST_SEARCH_PREFIX: Final[str] = "search"
CONST_GH_REST_REPOS_PREFIX: Final[str] = "repos"
CONST_GH_REST_CODE_SCANNING_SEGMENT: Final[str] = "code-scanning"
CONST_GH_REST_AUTOFIX_SEGMENT: Final[str] = "autofix"
CONST_GH_REST_SBOM_SEGMENTS: Final[tuple[str, str]] = ("dependency-graph", "sbom")

# ── AI Gateway & Distributed Router Constants ─────────────────────────────────
CONST_AI_GATEWAY_VIRTUAL_MODELS: Final[tuple[str, ...]] = (
"devops-chat",
Expand Down
104 changes: 65 additions & 39 deletions src/devops_cli/github/rate_limiter.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
import subprocess
import threading
import time
from collections.abc import Generator
from collections.abc import Generator, Sequence
from contextlib import contextmanager
from dataclasses import dataclass
from datetime import datetime
Expand All @@ -35,11 +35,21 @@
from devops_cli.config.constants import (
CONST_CACHE_DIR_NAME,
CONST_GH_API_DEFAULT_METHOD,
CONST_GH_API_GRAPHQL_ENDPOINT,
CONST_GH_API_SUBCOMMAND,
CONST_GH_CLI,
CONST_GH_GRAPHQL_GROUPS,
CONST_GH_GRAPHQL_PORCELAIN_COMMANDS,
CONST_GH_QUOTA_CACHE_FILENAME,
CONST_GH_RATE_LIMIT_CLOCK_SKEW_BOUND_SECONDS,
CONST_GH_RATE_LIMIT_RESET_MARGIN_SECONDS,
CONST_GH_READ_VERBS,
CONST_GH_REST_AUTOFIX_SEGMENT,
CONST_GH_REST_CODE_SCANNING_SEGMENT,
CONST_GH_REST_REPOS_PREFIX,
CONST_GH_REST_SBOM_SEGMENTS,
CONST_GH_REST_SEARCH_CODE_PREFIX,
CONST_GH_REST_SEARCH_PREFIX,
CONST_GITHUB_IDENTITY_DIGEST_CHARS,
CONST_GITHUB_IDENTITY_LIMITERS_KEPT,
)
Expand Down Expand Up @@ -432,57 +442,73 @@ def calculate_request_delay(
return time_until_reset / remaining


def _is_graphql_command(clean_args: list[str]) -> bool:
"""Predicate checking if command targets GraphQL."""
return clean_args[0] == "project" or any("graphql" in arg for arg in clean_args)


def _is_code_search_command(clean_args: list[str]) -> bool:
"""Predicate checking if command targets code search."""
if len(clean_args) >= 2 and clean_args[0] == "search" and clean_args[1] == "code":
return True
return any("search/code" in arg for arg in clean_args)


def _is_code_scanning_autofix_command(clean_args: list[str]) -> bool:
"""Predicate checking if command targets code scanning autofix."""
return any(
("code-scanning" in arg or "code_scanning" in arg) and "autofix" in arg
for arg in clean_args
)
def _detect_porcelain_resource(clean_args: Sequence[str]) -> str:
"""The rate-limit resource a gh porcelain command spends."""
words = gh_command_words(clean_args)
if words is None:
return "core"
group, verb = words
if group is None:
return "core"
group_lower = group.lower()
if group_lower in CONST_GH_GRAPHQL_GROUPS:
return "graphql"
if verb is not None:
verb_lower = verb.lower()
if (group_lower, verb_lower) in CONST_GH_GRAPHQL_PORCELAIN_COMMANDS:
return "graphql"
if group_lower == "search":
if verb is not None and verb.lower() == "code":
return "code_search"
return "search"
return "core"


def _is_general_search_command(clean_args: list[str]) -> bool:
"""Predicate checking if command targets general search."""
return clean_args[0] == "search" or any("search/" in arg for arg in clean_args)
def _detect_api_resource(api_args: Sequence[str]) -> str:
"""The rate-limit resource a `gh api` command spends, decided from its endpoint."""
args = parse_gh_api_args(api_args)
if args is None or args.endpoint is None:
return "core"
clean_endpoint = args.endpoint.strip().lstrip("/").split("?", 1)[0].lower()
if clean_endpoint == CONST_GH_API_GRAPHQL_ENDPOINT:
return "graphql"
if clean_endpoint == CONST_GH_REST_SEARCH_CODE_PREFIX or clean_endpoint.startswith(
f"{CONST_GH_REST_SEARCH_CODE_PREFIX}/"
):
return "code_search"
if clean_endpoint == CONST_GH_REST_SEARCH_PREFIX or clean_endpoint.startswith(
f"{CONST_GH_REST_SEARCH_PREFIX}/"
):
return "search"
parts = clean_endpoint.split("/")
if len(parts) >= 5 and parts[0] == CONST_GH_REST_REPOS_PREFIX:
if (parts[3], parts[4]) == CONST_GH_REST_SBOM_SEGMENTS:
return "dependency_sbom"
if (
len(parts) >= 6
and parts[3] in (CONST_GH_REST_CODE_SCANNING_SEGMENT, "code_scanning")
and CONST_GH_REST_AUTOFIX_SEGMENT in parts[4:]
):
return "code_scanning_autofix"
return "core"


def _detect_resource(args: list[str]) -> str:
def _detect_resource(args: Sequence[str]) -> str:
"""Determine the GitHub API rate limit resource / subcommand category."""
if not args:
return "core"
clean_args = [a.lower() for a in args if a not in (CONST_GH_CLI, "gh")]
clean_args = _normalize_gh_args(list(args))
if not clean_args:
return "core"

if _is_graphql_command(clean_args):
return "graphql"
if _is_code_search_command(clean_args):
return "code_search"
if _is_code_scanning_autofix_command(clean_args):
return "code_scanning_autofix"
if _is_general_search_command(clean_args):
return "search"
if any("dependency-graph/sbom" in arg for arg in clean_args):
return "dependency_sbom"

return "core"
if clean_args[0].lower() == CONST_GH_API_SUBCOMMAND:
return _detect_api_resource(clean_args[1:])
return _detect_porcelain_resource(clean_args)


def gh_request_resource(args: list[str]) -> str:
def gh_request_resource(args: Sequence[str]) -> str:
"""The rate-limit resource a `gh` command spends (`core`, `graphql`, `search`, ...), as
`run_gh` paces it."""
return _detect_resource(_normalize_gh_args(args))
return _detect_resource(_normalize_gh_args(list(args)))


def gh_request_is_paced(args: list[str]) -> bool:
Expand Down
3 changes: 2 additions & 1 deletion tests/test_github_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -474,10 +474,11 @@ def test_an_answer_that_is_no_diff_raises_the_unread_error(

def _scripted_gh(argv: list[str], **_: Any) -> subprocess.CompletedProcess[str]:
"""Answer `gh auth token` with token A, `gh api rate_limit` with a fresh quota, the rest empty."""
fresh_quota = {"limit": 5000, "remaining": 5000, "reset": time.time() + 60}
answers = {
("auth", "token"): "A\n",
("api", "rate_limit"): json.dumps(
{"resources": {"core": {"limit": 5000, "remaining": 5000, "reset": time.time() + 60}}}
{"resources": {"core": fresh_quota, "graphql": fresh_quota}}
),
}
return subprocess.CompletedProcess(
Expand Down
Loading
Loading