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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -371,7 +371,7 @@ and excessive permissions fail it, and every other finding is shown. |
| | `devops pr update [OPTIONS] <number>` | Update pull request branch with latest commits from its base branch. |
| | `devops pr hardening-report [OPTIONS]` | Audit merged defect pull requests for guardrail additions to declared hardening surfaces. |
| | `devops pr threads COMMAND [ARGS]...` | GitHub Pull Request workflows and reviews. |
| **gh** | `devops gh api [OPTIONS] <endpoint>` | Execute a GitHub API request with token-bucket pacing, rate-limit backoff, and optional caching. |
| **gh** | `devops gh api [OPTIONS] <endpoint>` | Execute a GitHub API request with quota-derived spacing, rate-limit backoff, and optional caching. |
| | `devops gh rate-limit [OPTIONS]` | Display GitHub REST and GraphQL API rate limits, quotas, and reset countdowns. |
| | `devops gh status [OPTIONS]` | Display GitHub published operational status, key components, and active incidents. |
| | `devops gh metrics [OPTIONS]` | Display comprehensive project metrics including release frequency, PRs, commits, CI pass rates, and milestones. |
Expand Down
2 changes: 1 addition & 1 deletion docs/CLI_REFERENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -6611,7 +6611,7 @@ GitHub Views, Projects, Issues, Pages, Milestones, and Labels automation.

### `devops gh api`

**Execute a GitHub API request with token-bucket pacing, rate-limit backoff, and optional caching.**
**Execute a GitHub API request with quota-derived spacing, rate-limit backoff, and optional caching.**

```bash
devops gh api [OPTIONS] <endpoint>
Expand Down
2 changes: 1 addition & 1 deletion docs/SELF_IMPROVEMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -1196,7 +1196,7 @@ The DevSecOps and robustness review session `20260913-231617` produced 13 findin
- Disarmed `HALLUCINATION-NONEXISTENT-FIXER-PAYLOAD` (non-existent `src/devops_cli/ai/fixer.py` and claims of unbounded payload in `repair_json_string`).
- Disarmed `HALLUCINATION-CI-ALLOW-BLOCKED-STATE` (false claims of insecure bypass for transient in-flight CI mergeable states).
6. **Native DevOps CLI GitHub Rate Management**:
- Replaced bare `gh` invocations with native `devops gh` and centralized `run_gh()` runner featuring token-bucket pacing, quota safety thresholds, exponential backoff with jitter on secondary rate limits, and TTL read caching.
- Replaced bare `gh` invocations with native `devops gh` and centralized `run_gh()` runner featuring quota-derived spacing, quota safety thresholds, exponential backoff with jitter on secondary rate limits, and TTL read caching.

### Session `20260915-124521` (GitHub Rate Limiting, Container Sandbox Isolation & Path Traversal Remediation)

Expand Down
2 changes: 1 addition & 1 deletion docs/commands/gh.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ GitHub Views, Projects, Issues, Pages, Milestones, and Labels automation.

## `devops gh api`

**Execute a GitHub API request with token-bucket pacing, rate-limit backoff, and optional caching.**
**Execute a GitHub API request with quota-derived spacing, rate-limit backoff, and optional caching.**

```bash
devops gh api [OPTIONS] <endpoint>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
schema: spec-driven
created: 2026-10-24
skip_specs: true
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# Design

## Context

See `proposal.md` - Why.
`run_gh` passes gh commands through an in-memory burst ceiling using `ratelimit`.
The `ratelimit` package is abandoned and introduces unbounded blocking up to 60 seconds on the 61st call.
GitHub API pacing is already handled by `GitHubRateLimiter.acquire`, which enforces quota calculations and mutation intervals.

## Goals / Non-Goals

**Goals:**
- Eliminate the abandoned `ratelimit` dependency from the project.
- Execute gh commands directly with `run_subprocess`.
- Ensure gh calls do not stall for up to a minute when exceeding 60 requests.
- Preserve inter-thread spacing across parallel callers.
- Ensure all tests pass with zero imports of `ratelimit`.

**Non-Goals:**
- Implement a new cross-process burst ceiling library.
- Change the calculation formula for `GitHubRateLimiter.acquire`.
- Modify GraphQL mutation classification beyond existing implementations.

## Decisions

### Decision 1: Remove ratelimit and Execute via run_subprocess

`_execute_gh_single_attempt` will call `run_subprocess` directly instead of `limiter._run_burst_protected`.
The helper function `_burst_protected_subprocess` and the attribute `_run_burst_protected` will be removed.
`run_subprocess` returns `subprocess.CompletedProcess[str]`, removing the need for `typing.cast`.

*Alternatives considered:*
- Replacing `ratelimit` with another third-party library: rejected because GitHub API limits are already managed by `GitHubRateLimiter`.

### Decision 2: Remove Clock Contract Tests for ratelimit

`tests/core/test_clock_contract.py` tested the monotonic clock seam using `ratelimit.limits`.
These tests and the `ratelimit` imports will be removed.
The clock seam contract will test monotonic time advancement directly.

*Alternatives considered:*
- Keeping `ratelimit` in the dev dependencies solely for tests: rejected because `ratelimit` is unmaintained and should be completely removed.

### Decision 3: Update Test doubles to Patch run_subprocess

Existing tests that mocked `_burst_protected_subprocess` will mock `devops_cli.github.rate_limiter.run_subprocess` instead.
This aligns test seams with standard process execution.

*Alternatives considered:*
- Keeping an internal alias `_burst_protected_subprocess`: rejected because no shims or backward-compatibility wrappers are kept in alpha versions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# Proposal

## Why

The `ratelimit` library is abandoned upstream (#1118).
Its fixed window of 60 calls per 60 seconds causes silent stalls for up to one minute.
The library does not provide type information and ships only as a source distribution.
Existing rate limiter logic in `GitHubRateLimiter` already paces requests using quota reset timing and backoff.

## What Changes

- Remove the `ratelimit` dependency from `pyproject.toml` and lockfile manifests.
- Remove `_burst_protected_subprocess` and the 60-call fixed ceiling from `src/devops_cli/github/rate_limiter.py`.
- Call `run_subprocess` directly for gh command execution without `cast`.
- Remove `type: ignore` comments related to `ratelimit`.
- Update test cases that patched `_burst_protected_subprocess` to patch `run_subprocess`.
- Remove clock contract tests for the `ratelimit` window and update clock seam documentation.
- Add tests to verify no minute-long stall occurs on 61 calls and that parallel calls stay spaced.
- Update documentation and help text to replace token-bucket phrasing with quota-derived spacing.
- This change alters no behavior that an external consumer observes. The change sets `skip_specs: true` in `.openspec.yaml`.
- This change fits in one pull request.

## Capabilities

### New Capabilities

None.

### Modified Capabilities

None.

## Impact

- Code: `src/devops_cli/github/rate_limiter.py`, `src/devops_cli/core/clock.py`, `src/devops_cli/commands/gh.py`, `src/devops_cli/lang/en/help.py`, `pyproject.toml`, `uv.lock`.
- Tests: `tests/test_github_rate_limiter.py`, `tests/core/test_clock_contract.py`, `tests/support/fakes/clock.py`, `tests/support/fakes/github.py`, and test suites patching `_burst_protected_subprocess`.
- Documents: `README.md`, `docs/commands/gh.md`, `docs/CLI_REFERENCE.md`, `docs/SELF_IMPROVEMENT.md`.

## Feasibility

- Verified that `ratelimit==2.2.1` has had no release since 2018-12-17.
- Verified that `_execute_gh_single_attempt` delegates to `limiter._run_burst_protected`, which wraps `_burst_protected_subprocess`.
- Verified that `run_subprocess` returns `CompletedProcess[str]` directly and requires no `cast`.
- Verified that `GitHubRateLimiter.acquire` spaces requests across threads using quota state and minimum mutation intervals.
- Verified that `devops docs generate --sync-readme` updates documentation after modifying help text.

## Existing Tool Considered

Standard library `subprocess` and DevOps CLI `run_subprocess` provide subprocess execution without third-party wrapper overhead.
`GitHubRateLimiter` provides native quota pacing and backoff following GitHub API guidelines.
No additional third-party rate limiting library is required.
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Tasks

## 1. Specification and Behavioral Tests

- [x] 1.1 Add a unit test in `tests/test_github_rate_limiter.py` asserting that 61 calls do not stall for up to a minute, and verify initial failure before removing `ratelimit`.
- [x] 1.2 Add a unit test in `tests/test_github_rate_limiter.py` asserting that parallel callers stay spaced across threads using `threading.Barrier`.
- [x] 1.3 Add a unit test in `tests/test_github_rate_limiter.py` asserting that a non-exempt call without an endpoint still calls `acquire`.

## 2. Remove ratelimit and Internal Ceiling Wrapper

- [x] 2.1 Remove `ratelimit==2.2.1` from `pyproject.toml` and update `uv.lock`.
- [x] 2.2 Remove `_burst_protected_subprocess`, `_run_burst_protected`, and `ratelimit` imports from `src/devops_cli/github/rate_limiter.py`.
- [x] 2.3 Call `run_subprocess` directly in `_execute_gh_single_attempt` and remove unused `cast` import.

## 3. Update Test doubles and Test Suites

- [x] 3.1 Update all tests patching `_burst_protected_subprocess` to patch `run_subprocess`.
- [x] 3.2 Update `tests/core/test_clock_contract.py`, `tests/support/fakes/clock.py`, and `src/devops_cli/core/clock.py` to remove `ratelimit` references.
- [x] 3.3 Verify all tests in `tests/test_github_rate_limiter.py` and `tests/core/test_clock_contract.py` pass.

## 4. Documentation and Help String Updates

- [x] 4.1 Update help strings in `src/devops_cli/lang/en/help.py` and `src/devops_cli/commands/gh.py` to replace token-bucket phrasing with quota-derived spacing.
- [x] 4.2 Run `uv run devops docs generate --sync-readme` and verify `uv run devops docs check` passes.

## 5. Verification and Quality Gate

- [x] 5.1 Run `uv run devops ci fail-to-pass --base origin/main` to verify the failing test evidence.
- [x] 5.2 Run `uv run devops ci` to ensure all static checks and test suites pass.
- [x] 5.3 Archive OpenSpec change with `uv run devops openspec archive 1118-remove-ratelimit-ceiling`.
1 change: 0 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ dependencies = [
"opentelemetry-exporter-otlp-proto-grpc==1.45.1",
"textual==8.2.8",
"tenacity==9.1.4",
"ratelimit==2.2.1",
"tree-sitter==0.26.0",
"tree-sitter-python==0.25.0",
"tree-sitter-typescript==0.23.2",
Expand Down
2 changes: 1 addition & 1 deletion src/devops_cli/commands/gh.py
Original file line number Diff line number Diff line change
Expand Up @@ -1201,7 +1201,7 @@ def api_cmd(
typer.Option("--cache-ttl", help="Cache TTL in seconds (default 15.0)"),
] = 15.0,
) -> None:
"""Execute a GitHub API request with token-bucket pacing, rate-limit backoff, and optional caching."""
"""Execute a GitHub API request with quota-derived spacing, rate-limit backoff, and optional caching."""
args = ["api", endpoint]
if method:
args.extend(["-X", method.upper()])
Expand Down
2 changes: 1 addition & 1 deletion src/devops_cli/core/clock.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""The waiting functions the libraries take, and the monotonic reading `ratelimit` takes (#1320)."""
"""The waiting functions and the monotonic clock reading the libraries take (#1320)."""

from __future__ import annotations

Expand Down
51 changes: 10 additions & 41 deletions src/devops_cli/github/rate_limiter.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,13 @@
import subprocess
import threading
import time
from collections.abc import Callable, Generator
from collections.abc import Generator
from contextlib import contextmanager
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import Any, cast
from typing import Any

from ratelimit import limits, sleep_and_retry # type: ignore[import-untyped]
from tenacity import RetryCallState, Retrying, wait_random_exponential

from devops_cli.config.constants import (
Expand All @@ -54,7 +53,6 @@
DEFAULT_GH_SECONDARY_MAX_CAP,
DEFAULT_GH_SECONDARY_RATE_WAIT,
)
from devops_cli.core import clock
from devops_cli.core.process import github_token, is_local_gh_command, run_subprocess
from devops_cli.exceptions.git import (
GitHubOperationError,
Expand All @@ -81,28 +79,6 @@
)


def _burst_protected_subprocess(
cmd: list[str],
*,
input: str | None = None,
cwd: Path | None = None,
check: bool = False,
quiet: bool = False,
timeout: float = 30.0,
capture_output: bool = True,
) -> subprocess.CompletedProcess[str]:
"""Execute raw gh command through ratelimit burst-ceiling protector."""
return run_subprocess(
cmd,
input=input,
cwd=cwd,
check=check,
quiet=quiet,
timeout=timeout,
capture_output=capture_output,
)


@dataclass
class _CacheEntry:
data: str
Expand Down Expand Up @@ -831,10 +807,6 @@ def __init__(
self._total_throttles: int = 0
self._total_wait_seconds: float = 0.0
self._quotas: dict[str, QuotaState] = {}
burst_limit: Any = limits(calls=60, period=60, clock=clock.monotonic)
self._run_burst_protected: Callable[..., Any] = sleep_and_retry(
burst_limit(lambda *args, **kwargs: _burst_protected_subprocess(*args, **kwargs))
)
if persist_path:
self._sync_from_disk_locked()
self.prune_expired_cache()
Expand Down Expand Up @@ -1648,17 +1620,14 @@ def _execute_gh_single_attempt(
if not is_exempt:
limiter.acquire(subcommand=target_resource, is_mutation=is_mutation, cost=cost)
try:
proc = cast(
subprocess.CompletedProcess[str],
limiter._run_burst_protected(
full_cmd,
input=input,
cwd=cwd,
check=False,
quiet=quiet,
timeout=timeout,
capture_output=capture_output,
),
proc = run_subprocess(
full_cmd,
input=input,
cwd=cwd,
check=False,
quiet=quiet,
timeout=timeout,
capture_output=capture_output,
)
except subprocess.TimeoutExpired:
proc = subprocess.CompletedProcess(
Expand Down
5 changes: 4 additions & 1 deletion src/devops_cli/lang/en/help.py
Original file line number Diff line number Diff line change
Expand Up @@ -902,7 +902,10 @@ class PRCommandHelp:
@dataclass(frozen=True)
class GHCommandHelp:
app: str = "GitHub Views, Projects, Issues, Pages, Milestones, and Labels automation."
api: str = "Execute a GitHub API request with token-bucket pacing, rate-limit backoff, and optional caching."
api: str = (
"Execute a GitHub API request with quota-derived spacing, rate-limit backoff, and"
" optional caching."
)
rate_limit: str = (
"Display GitHub REST and GraphQL API rate limits, quotas, and reset countdowns."
)
Expand Down
71 changes: 11 additions & 60 deletions tests/core/test_clock_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,15 @@

from __future__ import annotations

import subprocess
import time
from datetime import UTC, datetime
from unittest.mock import patch

import httpx2
import pytest
from ratelimit import limits, sleep_and_retry
from tenacity import wait_chain, wait_fixed

from devops_cli.ai.retries import create_retry_config, create_retry_transport
from devops_cli.core import clock as clock_seam
from devops_cli.github.rate_limiter import reset_github_rate_limiter, run_gh
from tests.support.fakes.clock import ClockFake

_TOLERANCE = 1e-3
Expand Down Expand Up @@ -85,64 +81,19 @@ def handle_request(self, req: httpx2.Request) -> httpx2.Response:
) == (200, 3, True, True, [d1, d2])


@pytest.mark.parametrize(("mode", "period"), [("fake", 60.0), ("real", 0.03)])
def test_a_ratelimit_window_built_with_the_seam_makes_the_third_call_wait_out_the_period(
request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch, mode: str, period: float
@pytest.mark.parametrize(("mode", "duration"), [("fake", 1.5), ("real", 0.02)])
def test_a_sync_wait_advances_the_monotonic_clock_by_at_least_its_duration(
request: pytest.FixtureRequest, mode: str, duration: float
) -> None:
"""`ratelimit.limits(calls=2, period=period, clock=clock_seam.monotonic)` lets the first two
calls through and holds the third until `period` has passed since the window opened.

`sleep_and_retry` waits through `time.sleep`, which the test records in order with the calls.
The window opens when it is built, so the test measures from a seam reading taken just before
that, not from the first call: a stall between the two shortened the measured time (#2092).
The fake clock moves only when the seam waits, so the fake case holds the third call with one
wait of the whole period. The real clock moves on its own: a stall longer than the period
before the third call ends the window, and that call then goes through with no wait. So the
real case asserts the lower bound the contract needs, and no case bounds a real time from
above (#1902).
"""
"""After a sync wait of `duration`, `clock_seam.monotonic()` has advanced by at least
`duration`, and the fake records the wait."""
fake = _install_mode(request, mode)
stamps: list[float] = []
events: list[str] = []
sleep = time.sleep

def recorded_sleep(seconds: float) -> None:
events.append("wait")
sleep(seconds)

def stamp() -> None:
events.append("call")
stamps.append(clock_seam.monotonic())

monkeypatch.setattr(time, "sleep", recorded_sleep)
opened = clock_seam.monotonic()
window = limits(calls=2, period=period, clock=clock_seam.monotonic)
call = sleep_and_retry(window(stamp))
before_mono = clock_seam.monotonic()

for _ in range(3):
call()
clock_seam.sleep(duration)

after_mono = clock_seam.monotonic()
assert (
events[:2],
events.count("call"),
stamps[2] - opened >= period - _TOLERANCE,
fake.waits if fake is not None else None,
) == (["call", "call"], 3, True, [period] if fake is not None else None)


def test_the_github_rate_limiter_builds_its_burst_limit_with_the_seam_when_constructed(
clock: ClockFake,
) -> None:
"""Each `GitHubRateLimiter` builds its 60-calls-per-60s burst limit with `clock_seam.monotonic`
when constructed, so the 61st exempt call in one window waits 60 s and a fresh limiter starts
its own window."""
reset_github_rate_limiter()
payload = '{"resources": {"core": {"limit": 5000, "remaining": 5000, "reset": 1999999999}}}'
answer = subprocess.CompletedProcess(["gh", "api", "rate_limit"], 0, payload, "")
with patch("devops_cli.github.rate_limiter.run_subprocess", return_value=answer):
for _ in range(61):
run_gh(["api", "rate_limit"])
reset_github_rate_limiter()
run_gh(["api", "rate_limit"])

assert clock.waits == [60.0]
after_mono - before_mono >= duration - _TOLERANCE,
fake.waits if fake is not None else [duration],
) == (True, [duration])
Loading
Loading