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-10-25
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Design: Roadmap Service Job Errors and Traceback Suppression

## Context

See `proposal.md` for background. The roadmap Service executes queued jobs for repositories via `RepoWorker`. Currently, errors raised during round execution lose repository context, clone errors are swallowed without being recorded, and missing configuration files trigger tracebacks on every polling loop.

## Goals / Non-Goals

**Goals:**
- Surface git clone errors alongside job runner failures in a unified `RoadmapRunError`.
- Tag job failures onto an `ExceptionGroup` cause with PEP 678 notes naming the affected jobs.
- Eliminate tracebacks when logging `ConfigurationError` and configuration-only `RoadmapRunError` in `RepoWorker._execute_batch`.
- Convert `GitHubFileNotFoundError` for `.github/roadmap.toml` to `ConfigurationError` at the `service_job` boundary without breaking CLI triage.
- Propagate `GitHubRateLimitError` from refine visibility queries so the service pauses on budget exhaustion.
- Maintain ratchet ceilings for swallowed exceptions (`tests/fixtures/swallowed_failures_ceilings.json`).

**Non-Goals:**
- Modifying `open_roadmap` or `read_roadmap_config` (which would break CLI triage expecting `GitHubFileNotFoundError`).
- Changing CLI traceback policy for other commands (#1006).
- Adding worker state to suppress repeat logs across polling cycles (each poll logs once per misconfigured repository).

## Decisions

### Decision 1: Use PEP 654 `ExceptionGroup` and PEP 678 `BaseException.add_note`
- *Rationale*: Standard library features supported natively by Python 3.14. `traceback` and `logging` render exception groups and their notes automatically.
- *Alternatives considered*: Custom composite error class. Rejected because standard library exception groups integrate seamlessly with Python exception formatting tools and logging formatters.

### Decision 2: Consolidate clone and runner error handling in `_execute_due_rows`
- *Rationale*: Ruff checks for blind exception catches (`BLE001`). When `logger.exception` is removed from `_execute_due_rows`, catching `Exception` becomes a BLE001 site unless handled carefully. Removing the `except Exception` from `_prepare_clone` and allowing the single loop handler to catch both clone errors and runner errors maintains `run.py`'s ceiling of 5 without `# noqa`.
- *Alternatives considered*: Narrowing `_prepare_clone`'s catch to `GitOperationError`, `subprocess.TimeoutExpired`, and `OSError`. Rejected because `run_subprocess` can also raise `SecurityError`, which would terminate the round abruptly and discard previously collected job errors.

### Decision 3: Direct `exc_info` selection in `_execute_batch`
- *Rationale*: `_execute_batch` logs inside its `except Exception as exc:` handler. Keeping `logger.error` directly in the handler (with `exc_info=not is_config_only`) prevents ruff from flagging the handler as a new BLE001 site.
- *Alternatives considered*: Extracting a helper function for error logging. Rejected because moving the logging call outside the `except` block turns the handler into an unlogged exception catch under BLE001.

### Decision 4: Conversion of missing roadmap configuration in `service_job`
- *Rationale*: In `service_job`, `.github/roadmap.toml` is expected because the repository is explicitly listed in `service.repos`. Wrapping the `open_roadmap` call to catch `GitHubFileNotFoundError` and raise `ConfigurationError(key="service.repos", details={"path": ".github/roadmap.toml"})` keeps `open_roadmap` unchanged for `devops gh issues triage`.
- *Alternatives considered*: Changing `read_roadmap_config` to raise `ConfigurationError`. Rejected because `devops gh issues triage` requires `GitHubFileNotFoundError` to determine that a repository has no roadmap board.

### Decision 5: Move reset tracking onto group members and remove `RoadmapRunError.reset_at`
- *Rationale*: Storing `reset_at` both on the exception and on member exceptions duplicates state. `_refused_reset` scans member exceptions for `refusal_reset`.
- *Alternatives considered*: Keeping `reset_at` parameter on `RoadmapRunError`. Rejected per design refinement to keep rate limit reset timestamps on the underlying rate limit errors.

## Risks / Trade-offs

- **[Risk] Long error messages in summary logs** → *Mitigation*: Cap each job's quoted error line at 256 characters and truncate newlines, ensuring bounded message lengths while preserving full tracebacks on the exception members.
- **[Risk] Rich markup formatting collision in terminal output** → *Mitigation*: Use `print_error(str(exc), safe=True)` in `devops roadmap run --confirm` to treat brackets and markup characters as literal text.
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Proposal: Roadmap Service Job Errors and Traceback Suppression

## Why

When roadmap jobs fail in `devops serve --service`, the service logs configuration errors with a full 1.5 KB traceback on every poll, splits runner failures across two disconnected log records (one with the cause and one with the repository), and drops git clone failures entirely (#1365). This change provides unified failure reporting with repository context and eliminates noisy configuration tracebacks.

## What Changes

This change fits into one pull request. The changes alter observable service logging and command output, so they carry a spec delta:

- **Missing configuration handling in service**: In `service_job`, catching `GitHubFileNotFoundError` when reading `.github/roadmap.toml` and re-raising a `ConfigurationError(key="service.repos", details={"path": ".github/roadmap.toml"})` stating to commit the file or remove the repository from `service.repos`.
- **Structured RoadmapRunError with ExceptionGroup**: `RoadmapRunError` aggregates each failed job's first error line (capped at 256 characters) including clone errors, attaches a PEP 654 `ExceptionGroup` as its `__cause__` with PEP 678 job notes, and provides a property `is_configuration_only` checking if all members are `ConfigurationError` instances.
- **Traceback suppression for configuration-only errors in service**: In `RepoWorker._execute_batch`, logging configuration-only failures (`ConfigurationError` or `RoadmapRunError` with only configuration errors) without `exc_info` (no traceback), while continuing to log unexpected failures with `exc_info=True`.
- **Refine visibility rate limit propagation**: In `roadmap/refine.py`, re-raising `GitHubRateLimitError` when checking repository visibility so rate-limit budget refusals propagate to the worker pause.
- **Reset calculation cleanup**: Removing `reset_at` from `RoadmapRunError` and deriving pause resets directly from `refusal_reset` across group members.
- **CLI literal formatting**: In `devops roadmap run --confirm`, printing `str(exc)` with `print_error(..., safe=True)` and exiting 1.

## Capabilities

### New Capabilities
- `roadmap-service-logs`: Roadmap service failure logging without configuration tracebacks, unified job failure messages with clone error retention, and rate limit propagation.

### Modified Capabilities
*(None)*

## Impact

- `src/devops_cli/exceptions/roadmap.py`: `RoadmapRunError` signature, properties, and removal of `reset_at`.
- `src/devops_cli/roadmap/run.py`: `_execute_due_rows`, `_prepare_clone`, `_refused_reset`, `service_pause_until`, `service_job`.
- `src/devops_cli/roadmap/refine.py`: `run_research_step` re-raising `GitHubRateLimitError`.
- `src/devops_cli/server/service.py`: `_execute_batch` error logging and span message.
- `src/devops_cli/commands/roadmap.py`: CLI error printing with `safe=True`.
- Tests in `tests/test_roadmap_run.py`, `tests/test_server_service.py`, `tests/test_roadmap_refine.py`.

## Feasibility

- **ExceptionGroup and add_note**: Tested in Python 3.14 runtime. Standard library `ExceptionGroup` and `BaseException.add_note` are available and natively formatted by `traceback` and Python `logging`.
- **Ruff and Ratchet checks**: Verified with `ruff check --select=BLE001,S110,S112` and `pytest tests/test_swallowed_failures_ratchet.py`. Unifying clone and job runner error handling in `run.py` maintains the ratchet ceiling at 5 without adding any `# noqa`.
- **No-network offline testing**: Verified that tests can use local temporary directories, mock stores, and `RepoWorker` public methods without network egress.

## Existing Tool Considered

Standard library `ExceptionGroup` (PEP 654) and `BaseException.add_note` (PEP 678) provide built-in exception aggregation and annotation. No third-party error-chaining library or ad-hoc custom group container is introduced.
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Spec Delta

## Purpose

Provides unified failure logging and error reporting for roadmap service jobs, retains git clone failures, and suppresses noisy tracebacks for configuration errors.

## ADDED Requirements

### Requirement: Configuration error handling in roadmap service
When a managed repository listed in `service.repos` lacks `.github/roadmap.toml`, `service_job` SHALL raise a `ConfigurationError` specifying the missing path and advising to commit the configuration or remove the repository.

#### Scenario: Missing roadmap configuration in service
- **WHEN** `service_job` executes for a repository lacking `.github/roadmap.toml`
- **THEN** it raises a `ConfigurationError` with `key="service.repos"` and `details={"path": ".github/roadmap.toml"}`

### Requirement: Unified job failure reporting with clone error retention
When roadmap jobs fail during execution, `run_due_jobs` SHALL raise a `RoadmapRunError` naming each failed job alongside the first line of its error, preserving clone errors and attaching an `ExceptionGroup` containing all member failures annotated with their job names.

#### Scenario: Multiple jobs fail including clone failure
- **WHEN** jobs fail due to a clone error and a job runner error
- **THEN** `RoadmapRunError` message names each job and error line capped at 256 characters, and `__cause__` is an `ExceptionGroup` containing each exception

### Requirement: Configuration-only failure traceback suppression in service logging
When a service job execution fails exclusively due to configuration errors, the service worker SHALL log a single ERROR record without `exc_info` containing the repository and error message. For any unexpected error, the worker SHALL log an ERROR record with full `exc_info`.

#### Scenario: Service logs configuration-only failure
- **WHEN** a service job execution raises a `ConfigurationError` or a `RoadmapRunError` containing only `ConfigurationError`s
- **THEN** the service logs one ERROR record without a traceback, recording `repo` and `result="error"`

#### Scenario: Service logs unexpected failure
- **WHEN** a service job execution raises an unexpected error or a mixed error group
- **THEN** the service logs an ERROR record with `exc_info=True` showing the exception traceback

### Requirement: CLI literal error printing on failed roadmap run
When `devops roadmap run --confirm` encounters a `RoadmapRunError`, it SHALL print the exception message literally using safe markup printing without tracebacks and exit with code 1.

#### Scenario: CLI run failure output
- **WHEN** `devops roadmap run --confirm` fails with a `RoadmapRunError`
- **THEN** the command prints the error message safely without evaluating Rich markup and exits with code 1
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Tasks

## 1. Exception Group and Rate Limit Re-raise

- [x] 1.1 Write failing tests for `RoadmapRunError` (exception group cause, job notes, `is_configuration_only`, removal of `reset_at`) and refine visibility `GitHubRateLimitError` re-raise. Verify with `uv run devops ci test tests/test_roadmap_run.py tests/test_roadmap_refine.py`.
- [x] 1.2 Implement `RoadmapRunError` updates in `src/devops_cli/exceptions/roadmap.py` and rate limit re-raise in `src/devops_cli/roadmap/refine.py`. Verify with `uv run devops ci test tests/test_roadmap_run.py tests/test_roadmap_refine.py`.

## 2. Roadmap Execution Error Handling and Clone Retention

- [x] 2.1 Write failing tests in `tests/test_roadmap_run.py` for clone failure retention, unified message formatting with 256-character truncation, `service_pause_until` member scanning, and `service_job` missing `.github/roadmap.toml` conversion to `ConfigurationError`. Verify with `uv run devops ci test tests/test_roadmap_run.py`.
- [x] 2.2 Implement `_prepare_clone`, `_execute_due_rows`, `_refused_reset`, `service_pause_until`, and `service_job` in `src/devops_cli/roadmap/run.py`. Verify with `uv run devops ci test tests/test_roadmap_run.py`.

## 3. Service Worker Traceback Suppression and CLI Literal Output

- [x] 3.1 Write failing tests in `tests/test_server_service.py` for `RepoWorker._execute_batch` configuration-only traceback suppression vs unexpected error `exc_info=True`, and in `tests/test_roadmap_run.py` for `devops roadmap run --confirm` safe output. Verify with `uv run devops ci test tests/test_server_service.py tests/test_roadmap_run.py`.
- [x] 3.2 Implement traceback suppression in `src/devops_cli/server/service.py` and literal safe error printing in `src/devops_cli/commands/roadmap.py`. Verify with `uv run devops ci test tests/test_server_service.py tests/test_roadmap_run.py`.
- [x] 3.3 Regenerate documentation with `uv run devops docs generate --sync-readme` and verify with `uv run pytest tests/test_swallowed_failures_ratchet.py`.

## Workflow follow-up

- Pending a person: once the Service runs again (as D2's App or a reinstated account): verify Loki queries (a), (b), and (c).
- Pending a person: review the diff in tuicr (tuicr -r origin/main..HEAD).
38 changes: 38 additions & 0 deletions openspec/specs/roadmap-service-logs/spec.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# roadmap-service-logs Specification

## Purpose
Provides unified failure logging and error reporting for roadmap service jobs, retains git clone failures, and suppresses noisy tracebacks for configuration errors.

## Requirements

### Requirement: Configuration error handling in roadmap service
When a managed repository listed in `service.repos` lacks `.github/roadmap.toml`, `service_job` SHALL raise a `ConfigurationError` specifying the missing path and advising to commit the configuration or remove the repository.

#### Scenario: Missing roadmap configuration in service
- **WHEN** `service_job` executes for a repository lacking `.github/roadmap.toml`
- **THEN** it raises a `ConfigurationError` with `key="service.repos"` and `details={"path": ".github/roadmap.toml"}`

### Requirement: Unified job failure reporting with clone error retention
When roadmap jobs fail during execution, `run_due_jobs` SHALL raise a `RoadmapRunError` naming each failed job alongside the first line of its error, preserving clone errors and attaching an `ExceptionGroup` containing all member failures annotated with their job names.

#### Scenario: Multiple jobs fail including clone failure
- **WHEN** jobs fail due to a clone error and a job runner error
- **THEN** `RoadmapRunError` message names each job and error line capped at 256 characters, and `__cause__` is an `ExceptionGroup` containing each exception

### Requirement: Configuration-only failure traceback suppression in service logging
When a service job execution fails exclusively due to configuration errors, the service worker SHALL log a single ERROR record without `exc_info` containing the repository and error message. For any unexpected error, the worker SHALL log an ERROR record with full `exc_info`.

#### Scenario: Service logs configuration-only failure
- **WHEN** a service job execution raises a `ConfigurationError` or a `RoadmapRunError` containing only `ConfigurationError`s
- **THEN** the service logs one ERROR record without a traceback, recording `repo` and `result="error"`

#### Scenario: Service logs unexpected failure
- **WHEN** a service job execution raises an unexpected error or a mixed error group
- **THEN** the service logs an ERROR record with `exc_info=True` showing the exception traceback

### Requirement: CLI literal error printing on failed roadmap run
When `devops roadmap run --confirm` encounters a `RoadmapRunError`, it SHALL print the exception message literally using safe markup printing without tracebacks and exit with code 1.

#### Scenario: CLI run failure output
- **WHEN** `devops roadmap run --confirm` fails with a `RoadmapRunError`
- **THEN** the command prints the error message safely without evaluating Rich markup and exits with code 1
3 changes: 1 addition & 2 deletions src/devops_cli/commands/roadmap.py
Original file line number Diff line number Diff line change
Expand Up @@ -316,8 +316,7 @@ def run_cmd(
if ran:
print_success(f"Roadmap jobs completed: {', '.join(ran)}")
except RoadmapRunError as exc:
msg = f"Roadmap jobs failed: {', '.join(exc.failed_jobs)}" if exc.failed_jobs else str(exc)
print_error(msg)
print_error(str(exc), safe=True)
raise typer.Exit(1) from exc


Expand Down
22 changes: 11 additions & 11 deletions src/devops_cli/exceptions/roadmap.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,44 +3,44 @@
from __future__ import annotations

from collections.abc import Sequence
from datetime import datetime
from typing import Any

from devops_cli.config.constants import (
CONST_ERROR_CODE_ROADMAP_CARD_CHANGED,
CONST_ERROR_CODE_ROADMAP_INTAKE_FAILED,
CONST_ERROR_CODE_ROADMAP_REFINE_FAILED,
CONST_GRAPHQL_REFUSAL_RESET_KEY,
)
from devops_cli.exceptions.base import DevOpsCLIError
from devops_cli.exceptions.config import ConfigurationError
from devops_cli.exceptions.git import GitHubOperationError


class RoadmapRunError(DevOpsCLIError):
"""Raised when one or more roadmap jobs fail during execution.

`reset_at` is the earliest reset a failed job's GraphQL budget refusal named, None when no
job was refused; the Service starts no round before it (#1400).
"""
"""Raised when one or more roadmap jobs fail during execution."""

def __init__(
self,
message: str,
*,
failed_jobs: Sequence[str] = (),
reset_at: datetime | None = None,
details: dict[str, Any] | None = None,
**kwargs: Any,
) -> None:
self.failed_jobs = tuple(failed_jobs)
self.reset_at = reset_at
extra = dict(details) if details is not None else {}
if failed_jobs and "failed_jobs" not in extra:
extra["failed_jobs"] = list(failed_jobs)
if reset_at is not None:
extra[CONST_GRAPHQL_REFUSAL_RESET_KEY] = reset_at.isoformat()
super().__init__(message, details=extra, **kwargs)

@property
def is_configuration_only(self) -> bool:
"""Whether every job failure in the round's cause group was a ConfigurationError."""
cause = self.__cause__
if isinstance(cause, BaseExceptionGroup):
match, rest = cause.split(ConfigurationError)
return match is not None and rest is None
return isinstance(cause, ConfigurationError)


class RoadmapCardChangedError(GitHubOperationError):
"""Raised before a job's board write that would revert a change made since it read the card.
Expand Down
4 changes: 3 additions & 1 deletion src/devops_cli/roadmap/refine.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@
from devops_cli.core.process import run_subprocess
from devops_cli.core.repo import get_repo_origin_name
from devops_cli.dry_run.requests import PlannedRequest
from devops_cli.exceptions.git import GitHubOperationError
from devops_cli.exceptions.git import GitHubOperationError, GitHubRateLimitError
from devops_cli.exceptions.roadmap import RoadmapRefineError
from devops_cli.lang import MESSAGES
from devops_cli.roadmap.store import (
Expand Down Expand Up @@ -464,6 +464,8 @@ def run_research_step(
"""
try:
is_private = store.repository_is_private()
except GitHubRateLimitError:
raise
except Exception as exc:
logger.warning("Could not read repository visibility: %s", exc)
return [], set()
Expand Down
Loading
Loading