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-11-17
skip_specs: false
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Design

## Decisions

- **Pass one session to workflow and milestone readers.** `collect_project_metrics_report` accepts an optional `session: GitHubSession | None = None`. It passes that session to `get_ci_workflow_metrics` and `get_milestone_metrics` so both calls share the same ETag cache and quota ledger. When no session is provided, `get_github_session()` provides one.
- **Derive taxonomy from open Items in the store.** `get_label_taxonomy_metrics` takes `store: RoadmapStore`. It iterates over open Items (`item.state is GitHubState.OPEN`) in `store.items()`, extracting labels containing `/`. It makes no network call to `repos/<repo>/issues?state=open`.
- **Lower the request budget to 4.** The metrics row round previously budgeted 5 requests: every-issue listing, CI runs, milestones, open issues, and repository metadata. Removing the open-issue listing reduces the baseline budget to 4 requests.

## Rejected alternatives

- **Create a separate session in each reader.** Rejected: creating separate sessions fragments the ETag response cache and could cause duplicate fetches.
- **Keep the open-issue listing alongside store counts.** Rejected: the store already holds all open items, and duplicate listings waste GitHub API quota.
- **Add a second taxonomy cache.** Rejected: caching outside the roadmap store duplicates data and introduces a second source of truth.
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# Proposal: #3941

## Why

The row `metrics` of the roadmap Service sends too many GitHub requests. It runs `collect_project_metrics_report` with `GhCliClient.api`, which has no ETag cache and counts every call. It also sends a second paginated listing for open issues after the roadmap store has already read all issues. Closes #3941.

## What Changes

- `get_ci_workflow_metrics` and `get_milestone_metrics` take an optional `session: GitHubSession | None = None` argument and query GitHub through `session.rest` with conditional requests.
- `collect_project_metrics_report` accepts `session: GitHubSession | None = None`, sharing one session across workflow run and milestone collection.
- `get_label_taxonomy_metrics` takes `store: RoadmapStore` and derives taxonomy label counts from open Items that the store already holds, removing the redundant `repos/<repo>/issues?state=open` request.
- `METRICS_ROW_GITHUB_REQUEST_BUDGET` in `src/devops_cli/github/metrics.py` drops from 5 to 4 because the open issues listing is removed.
- Tests verify that no open issues listing request is made and that workflow runs and milestones use the session.

The change fits one pull request.

## Capabilities

### New Capabilities

None.

### Modified Capabilities

- `project-metrics-dashboard`: Derives taxonomy from store-held open Items and queries workflow runs and milestones through the GitHub session.

## Impact

- `src/devops_cli/github/metrics.py`: `get_ci_workflow_metrics`, `get_milestone_metrics`, `get_label_taxonomy_metrics`, `collect_project_metrics_report`, `METRICS_ROW_GITHUB_REQUEST_BUDGET`.
- `tests/github/test_github_metrics.py`, `tests/github/test_github_metrics_request_budget.py`.

## Feasibility

- `collect_project_metrics_report` receives `store: RoadmapStore`. The store already reads every issue via `store.items()` for `get_item_metrics`.
- `GitHubSession` is available via `get_github_session()` and supports conditional GET requests via `session.rest("GET", ...)`.
- Offline tests verify that `devops_cli_github_requests_total` under `row="metrics"` drops by 1 request per round.

## Existing Tool Considered

`GitHubSession` with ETags covers the need for conditional requests. It is existing project code and requires no external dependency.
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
## ADDED Requirements

### Requirement: Store-derived taxonomy
The metrics collector SHALL derive taxonomy counts from the open Items that the roadmap store holds.

#### Scenario: No second open issue listing
- **WHEN** One metrics round runs for a repository with a roadmap store.
- **THEN** The collector sends no request to `repos/<repo>/issues?state=open` and the taxonomy counts match the labels of the open Items in the store.

### Requirement: Session-based workflow run read
The metrics collector SHALL read workflow runs through the GitHub session that sends conditional requests.

#### Scenario: Workflow runs use the session
- **WHEN** The metrics collector reads workflow runs for a repository.
- **THEN** The read goes through the session and makes no uncached `gh api repos/<repo>/actions/runs` call.

### Requirement: Session-based milestone read
The metrics collector SHALL read milestones through the GitHub session that sends conditional requests.

#### Scenario: Milestones use the session
- **WHEN** The metrics collector reads milestones for a repository.
- **THEN** The read goes through the session and makes no uncached `gh api repos/<repo>/milestones` call.
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Tasks

## 1. Test session-based reads and store-derived taxonomy

- [x] 1.1 Add unit tests for session-based `get_ci_workflow_metrics` and `get_milestone_metrics` and store-based `get_label_taxonomy_metrics`.
Verification: `uv run pytest tests/github/test_github_metrics.py -k "test_get_ci_workflow_metrics or test_get_milestone_metrics or test_get_label_taxonomy_metrics"`
- [x] 1.2 Update `tests/github/test_github_metrics_request_budget.py` for the reduced budget of 4 requests.
Verification: `uv run pytest tests/github/test_github_metrics_request_budget.py`

## 2. Implement session reads and store-derived taxonomy

- [x] 2.1 Update `get_ci_workflow_metrics` and `get_milestone_metrics` in `src/devops_cli/github/metrics.py` to accept `session: GitHubSession | None = None` and call `session.rest`.
Verification: `uv run pytest tests/github/test_github_metrics.py -k "workflow or milestone"`
- [x] 2.2 Update `get_label_taxonomy_metrics` in `src/devops_cli/github/metrics.py` to accept `store: RoadmapStore` and count labels of open items.
Verification: `uv run pytest tests/github/test_github_metrics.py -k taxonomy`
- [x] 2.3 Update `collect_project_metrics_report` in `src/devops_cli/github/metrics.py` to pass `session` and pass `roadmap` to `get_label_taxonomy_metrics`, and update `METRICS_ROW_GITHUB_REQUEST_BUDGET` to 4.
Verification: `uv run pytest tests/github/test_github_metrics.py tests/github/test_github_metrics_request_budget.py`
- [x] 2.4 Verify all checks and tests pass with `devops ci`.
Verification: `uv run devops ci --check --only lint,format,typecheck`
21 changes: 21 additions & 0 deletions openspec/specs/project-metrics-dashboard/spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -224,3 +224,24 @@ The project dashboard SHALL hold the bar gauge panel "Inbox Items by Kind" in th
#### Scenario: The panel query
- **WHEN** A test reads the panel "Inbox Items by Kind" of `project-metrics.json`
- **THEN** Its type is bargauge, its query is the one above with legend `{{kind}}`, its unit is `short`, and no panel of the dashboard overlaps it

### Requirement: Store-derived taxonomy
The metrics collector SHALL derive taxonomy counts from the open Items that the roadmap store holds.

#### Scenario: No second open issue listing
- **WHEN** One metrics round runs for a repository with a roadmap store.
- **THEN** The collector sends no request to `repos/<repo>/issues?state=open` and the taxonomy counts match the labels of the open Items in the store.

### Requirement: Session-based workflow run read
The metrics collector SHALL read workflow runs through the GitHub session that sends conditional requests.

#### Scenario: Workflow runs use the session
- **WHEN** The metrics collector reads workflow runs for a repository.
- **THEN** The read goes through the session and makes no uncached `gh api repos/<repo>/actions/runs` call.

### Requirement: Session-based milestone read
The metrics collector SHALL read milestones through the GitHub session that sends conditional requests.

#### Scenario: Milestones use the session
- **WHEN** The metrics collector reads milestones for a repository.
- **THEN** The read goes through the session and makes no uncached `gh api repos/<repo>/milestones` call.
89 changes: 42 additions & 47 deletions src/devops_cli/github/metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
from collections.abc import Callable, Collection, Iterable, Mapping
from pathlib import Path
from typing import TYPE_CHECKING, Any, Final
from urllib.parse import quote

if TYPE_CHECKING:
from devops_cli.dry_run.requests import PlannedRequest
Expand All @@ -37,9 +38,10 @@
from devops_cli.core.process import run_subprocess
from devops_cli.core.repo import find_worktree_root, get_repo_origin_name
from devops_cli.exceptions.git import GitHubOperationError
from devops_cli.github.client import GhCliClient, PullStatus, parse_paginated_json
from devops_cli.github.client import GhCliClient, PullStatus
from devops_cli.github.error_classifier import is_gh_refused_by_token
from devops_cli.github.repo_ref import RepoRef
from devops_cli.github.session import GitHubSession, get_github_session
from devops_cli.roadmap.phase import (
ACTIVE_PHASES,
find_running_units,
Expand Down Expand Up @@ -85,9 +87,9 @@
emit,
)

METRICS_ROW_GITHUB_REQUEST_BUDGET: Final[int] = 5
METRICS_ROW_GITHUB_REQUEST_BUDGET: Final[int] = 4
"""The GitHub requests that one metrics-row round may send for one page of each listing, so a
new read or an extra page fails the offline test (#3794)."""
new read or an extra page fails the offline test (#3794, #3941)."""

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -370,18 +372,19 @@ def classify_workflow_conclusion(
return 0, 0, 1


def get_ci_workflow_metrics(repo: str, limit: int = 50) -> list[WorkflowRunMetric]:
def get_ci_workflow_metrics(
repo: str, limit: int = 50, session: GitHubSession | None = None
) -> list[WorkflowRunMetric]:
"""Collect CI workflow runs and calculate pass/fail rates per workflow."""
client = GhCliClient()
endpoint = f"repos/{repo}/actions/runs?per_page={min(limit, 100)}"
active_session = session if session is not None else get_github_session()
endpoint = f"/repos/{quote(repo, safe='/')}/actions/runs?per_page={min(limit, 100)}"
try:
raw_output = client.api(endpoint)
data = json.loads(raw_output)
data = active_session.rest("GET", endpoint)
except Exception as err:
logger.warning("Failed to query GitHub Actions runs for %s: %s", repo, err)
return []

runs = data.get("workflow_runs", [])
runs = data.get("workflow_runs", []) if isinstance(data, dict) else []
aggregates: dict[str, dict[str, int]] = {}

for run in runs:
Expand Down Expand Up @@ -439,13 +442,14 @@ def build_milestone_metric(raw: dict[str, Any]) -> MilestoneMetric:
)


def get_milestone_metrics(repo: str, milestone_filter: str | None = None) -> list[MilestoneMetric]:
def get_milestone_metrics(
repo: str, milestone_filter: str | None = None, session: GitHubSession | None = None
) -> list[MilestoneMetric]:
"""Query milestones and calculate item counts and completion percentages."""
client = GhCliClient()
endpoint = f"repos/{repo}/milestones?state=all&per_page=100"
active_session = session if session is not None else get_github_session()
endpoint = f"/repos/{quote(repo, safe='/')}/milestones?state=all&per_page=100"
try:
raw_output = client.api(endpoint)
payload = json.loads(raw_output)
payload = active_session.rest("GET", endpoint)
except Exception as err:
logger.warning("Failed to query milestones for %s: %s", repo, err)
return []
Expand Down Expand Up @@ -674,27 +678,16 @@ def _read_item_ages(
return [], None, []


def get_label_taxonomy_metrics(repo: str) -> list[LabelTaxonomyMetric]:
"""Count open issues categorized by taxonomy label prefixes."""
client = GhCliClient()
endpoint = f"repos/{repo}/issues?state=open&per_page=100"
try:
raw_output = client.api(endpoint, paginate=True)
issues = parse_paginated_json(raw_output)
except Exception as err:
logger.warning("Failed to query open issues for %s: %s", repo, err)
return []

def get_label_taxonomy_metrics(store: RoadmapStore) -> list[LabelTaxonomyMetric]:
"""Count open Items categorized by taxonomy label prefixes (#3941)."""
counts: Counter[tuple[str, str]] = Counter()
for issue in issues:
if not isinstance(issue, dict) or "pull_request" in issue:
for item in store.items():
if item.state is not GitHubState.OPEN:
continue
labels = issue.get("labels", [])
for lbl in labels:
name = lbl.get("name", "") if isinstance(lbl, dict) else str(lbl)
if "/" in name:
cat, _val = name.split("/", 1)
counts[(cat, name)] += 1
for label in item.labels:
if "/" in label:
cat, _val = label.split("/", 1)
counts[(cat, label)] += 1

metrics = [
LabelTaxonomyMetric(category=cat, label=label, count=cnt)
Expand Down Expand Up @@ -869,6 +862,7 @@ def collect_project_metrics_report(
store: RoadmapStore | None = None,
item_ages: bool = False,
clock: Callable[[], datetime.datetime] = _utc_now,
session: GitHubSession | None = None,
) -> ProjectMetricsReport:
"""Aggregate complete project metrics across releases, CI checks, milestones, and the
roadmap's Items.
Expand All @@ -890,13 +884,20 @@ def collect_project_metrics_report(
now_str = datetime.datetime.now(datetime.UTC).strftime("%Y-%m-%d %H:%M:%S UTC")

roadmap = store if store is not None else roadmap_store.get_roadmap_store(target_repo)
active_session = (
session
if session is not None
else (getattr(roadmap, "_session", None) or get_github_session())
)
items = get_item_metrics(
roadmap, get_item_releases(project_root), milestone_filter=milestone_filter
)
releases = get_release_cadence_metrics(project_root, limit=release_limit)
workflow_runs = get_ci_workflow_metrics(target_repo, limit=ci_limit)
milestones = get_milestone_metrics(target_repo, milestone_filter=milestone_filter)
taxonomy_labels = get_label_taxonomy_metrics(target_repo)
workflow_runs = get_ci_workflow_metrics(target_repo, limit=ci_limit, session=active_session)
milestones = get_milestone_metrics(
target_repo, milestone_filter=milestone_filter, session=active_session
)
taxonomy_labels = get_label_taxonomy_metrics(roadmap)
traffic = get_repository_traffic_metrics(target_repo)
ages, claim_age, phases = (
_read_item_ages(roadmap, target_repo, clock) if item_ages else ([], None, [])
Expand Down Expand Up @@ -928,28 +929,22 @@ def project_metrics_requests(
ci_limit: int = 50,
) -> list[PlannedRequest]:
"""Planned requests for collecting project velocity metrics."""
from devops_cli.roadmap.request_plan import StoreRequests, planned_gh
from devops_cli.roadmap.request_plan import StoreRequests, planned_gh, planned_session_read

requests: list[PlannedRequest] = []
requests.extend(StoreRequests(repo).every_issue())
requests.append(
planned_gh(
["api", f"repos/{repo}/actions/runs?per_page={min(ci_limit, 100)}"],
planned_session_read(
f"/repos/{repo}/actions/runs?per_page={min(ci_limit, 100)}",
f"repos/{repo}/actions/runs",
)
)
requests.append(
planned_gh(
["api", f"repos/{repo}/milestones?state=all&per_page=100"],
planned_session_read(
f"/repos/{repo}/milestones?state=all&per_page=100",
f"repos/{repo}/milestones",
)
)
requests.append(
planned_gh(
["api", f"repos/{repo}/issues?state=open&per_page=100", "--paginate"],
f"repos/{repo}/issues",
)
)
requests.append(planned_gh(["api", f"repos/{repo}"], f"repos/{repo}"))
for endpoint in ("views", "clones", "popular/referrers", "popular/paths"):
requests.append(
Expand Down
2 changes: 1 addition & 1 deletion tests/fixtures/swallowed_failures_ceilings.json
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@
"src/devops_cli/git/operations.py": 8,
"src/devops_cli/git/worktree.py": 4,
"src/devops_cli/github/issues.py": 1,
"src/devops_cli/github/metrics.py": 4,
"src/devops_cli/github/metrics.py": 3,
"src/devops_cli/github/pages.py": 1,
"src/devops_cli/github/secrets.py": 1,
"src/devops_cli/http/pool.py": 5,
Expand Down
Loading