From 283a9ea10a667c12b7b25a33bc9b219598c8493d Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Sun, 25 Oct 2026 20:39:14 +0000 Subject: [PATCH] fix(roadmap): the roadmap service logs each failed job's own error with its repository, and a configuration error without a traceback Aggregate job failures into RoadmapRunError with ExceptionGroup cause. Format the error line for each failed job and mask secrets. Log configuration errors in RepoWorker without a traceback. Log unexpected errors with exc_info and job notes. Raise ConfigurationError when .github/roadmap.toml is missing. Closes #1365 Change: openspec/changes/archive/2026-10-25-1365-roadmap-service-job-errors/ Fail-to-pass: 11 failed on base (11 failed and 170 passed in tests/test_roadmap_refine.py, tests/test_roadmap_run.py, tests/test_server_service.py; 0 errored). --- .../.openspec.yaml | 2 + .../design.md | 47 ++++ .../proposal.md | 43 ++++ .../specs/roadmap-service-logs/spec.md | 39 ++++ .../tasks.md | 22 ++ openspec/specs/roadmap-service-logs/spec.md | 38 +++ src/devops_cli/commands/roadmap.py | 3 +- src/devops_cli/exceptions/roadmap.py | 22 +- src/devops_cli/roadmap/refine.py | 4 +- src/devops_cli/roadmap/run.py | 89 +++---- src/devops_cli/server/service.py | 6 +- tests/test_roadmap_refine.py | 50 +++- tests/test_roadmap_run.py | 220 +++++++++++++++++- tests/test_server_service.py | 113 ++++++++- 14 files changed, 622 insertions(+), 76 deletions(-) create mode 100644 openspec/changes/archive/2026-10-25-1365-roadmap-service-job-errors/.openspec.yaml create mode 100644 openspec/changes/archive/2026-10-25-1365-roadmap-service-job-errors/design.md create mode 100644 openspec/changes/archive/2026-10-25-1365-roadmap-service-job-errors/proposal.md create mode 100644 openspec/changes/archive/2026-10-25-1365-roadmap-service-job-errors/specs/roadmap-service-logs/spec.md create mode 100644 openspec/changes/archive/2026-10-25-1365-roadmap-service-job-errors/tasks.md create mode 100644 openspec/specs/roadmap-service-logs/spec.md diff --git a/openspec/changes/archive/2026-10-25-1365-roadmap-service-job-errors/.openspec.yaml b/openspec/changes/archive/2026-10-25-1365-roadmap-service-job-errors/.openspec.yaml new file mode 100644 index 0000000000..7ccf7c3695 --- /dev/null +++ b/openspec/changes/archive/2026-10-25-1365-roadmap-service-job-errors/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-10-25 diff --git a/openspec/changes/archive/2026-10-25-1365-roadmap-service-job-errors/design.md b/openspec/changes/archive/2026-10-25-1365-roadmap-service-job-errors/design.md new file mode 100644 index 0000000000..a87e174d87 --- /dev/null +++ b/openspec/changes/archive/2026-10-25-1365-roadmap-service-job-errors/design.md @@ -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. diff --git a/openspec/changes/archive/2026-10-25-1365-roadmap-service-job-errors/proposal.md b/openspec/changes/archive/2026-10-25-1365-roadmap-service-job-errors/proposal.md new file mode 100644 index 0000000000..44bebe5580 --- /dev/null +++ b/openspec/changes/archive/2026-10-25-1365-roadmap-service-job-errors/proposal.md @@ -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. diff --git a/openspec/changes/archive/2026-10-25-1365-roadmap-service-job-errors/specs/roadmap-service-logs/spec.md b/openspec/changes/archive/2026-10-25-1365-roadmap-service-job-errors/specs/roadmap-service-logs/spec.md new file mode 100644 index 0000000000..b90e502015 --- /dev/null +++ b/openspec/changes/archive/2026-10-25-1365-roadmap-service-job-errors/specs/roadmap-service-logs/spec.md @@ -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 diff --git a/openspec/changes/archive/2026-10-25-1365-roadmap-service-job-errors/tasks.md b/openspec/changes/archive/2026-10-25-1365-roadmap-service-job-errors/tasks.md new file mode 100644 index 0000000000..77d157d9c1 --- /dev/null +++ b/openspec/changes/archive/2026-10-25-1365-roadmap-service-job-errors/tasks.md @@ -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). diff --git a/openspec/specs/roadmap-service-logs/spec.md b/openspec/specs/roadmap-service-logs/spec.md new file mode 100644 index 0000000000..b605a17215 --- /dev/null +++ b/openspec/specs/roadmap-service-logs/spec.md @@ -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 diff --git a/src/devops_cli/commands/roadmap.py b/src/devops_cli/commands/roadmap.py index 5664545a55..75d9c73ec4 100644 --- a/src/devops_cli/commands/roadmap.py +++ b/src/devops_cli/commands/roadmap.py @@ -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 diff --git a/src/devops_cli/exceptions/roadmap.py b/src/devops_cli/exceptions/roadmap.py index 255f5ba25f..44d65c75e1 100644 --- a/src/devops_cli/exceptions/roadmap.py +++ b/src/devops_cli/exceptions/roadmap.py @@ -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. diff --git a/src/devops_cli/roadmap/refine.py b/src/devops_cli/roadmap/refine.py index 19d1ddead4..562d17cac8 100644 --- a/src/devops_cli/roadmap/refine.py +++ b/src/devops_cli/roadmap/refine.py @@ -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 ( @@ -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() diff --git a/src/devops_cli/roadmap/run.py b/src/devops_cli/roadmap/run.py index ed67a77271..6d931c3e5b 100644 --- a/src/devops_cli/roadmap/run.py +++ b/src/devops_cli/roadmap/run.py @@ -583,27 +583,11 @@ def _simulate_dry_run(rows: Sequence[JobRow], initially_due: Mapping[str, bool]) return tuple(due_list) -def _prepare_clone( - row: JobRow, - repo: str, - base_data: Path, - remote_url: str | None, - clone_path: Path | None, - clone_error: Exception | None, - clone_dirname: str, -) -> tuple[Path | None, Exception | None]: - """Ensure git clone `clone_dirname` is ready for a job requiring checkout.""" - if not row.needs_clone: - return clone_path, clone_error - if clone_error is not None: - return None, clone_error - if clone_path is not None: - return clone_path, None - try: - path = ensure_checkout(repo, base_data, remote_url, clone_dirname) - return path, None - except Exception as exc: - return None, exc +def _format_error_line(exc: BaseException) -> str: + """The first line of an exception's message, masked and capped at 256 chars.""" + lines = str(exc).strip().splitlines() + first = lines[0] if lines else type(exc).__name__ + return mask_secrets(first)[:256] def _execute_due_rows( @@ -623,10 +607,11 @@ def _execute_due_rows( Each runner also gets the repository's data directory and the round's time.""" succeeded_jobs: list[str] = [] failed_jobs: list[str] = [] - resets: list[datetime] = [] outcomes: dict[str, JobOutcome] = {} clone_path: Path | None = None clone_error: Exception | None = None + clone_jobs: list[str] = [] + error_entries: list[tuple[list[str], Exception]] = [] for row in rows: is_due = initially_due[row.name] @@ -635,15 +620,15 @@ def _execute_due_rows( if not is_due: continue - if row.needs_clone: - clone_path, clone_error = _prepare_clone( - row, repo, base_data, remote_url, clone_path, clone_error, clone_dirname - ) - if clone_error is not None: - failed_jobs.append(row.name) - continue + if row.needs_clone and clone_error is not None: + failed_jobs.append(row.name) + clone_jobs.append(row.name) + continue try: + if row.needs_clone and clone_path is None: + clone_path = ensure_checkout(repo, base_data, remote_url, clone_dirname) + outcome = row.runner( store=store, clone_path=clone_path, @@ -657,17 +642,25 @@ def _execute_due_rows( succeeded_jobs.append(row.name) _record_success(schedule_path, row.name, current_time) except Exception as exc: - logger.exception("Roadmap job %s failed", row.name) failed_jobs.append(row.name) - if (reset := refusal_reset(exc)) is not None: - resets.append(reset) + if row.needs_clone and clone_path is None: + clone_error = exc + clone_jobs.append(row.name) + error_entries.append((clone_jobs, exc)) + else: + error_entries.append(([row.name], exc)) if failed_jobs: - raise RoadmapRunError( - f"Roadmap jobs failed: {', '.join(failed_jobs)}", - failed_jobs=failed_jobs, - reset_at=min(resets, default=None), - ) + error_parts: list[str] = [] + exceptions: list[Exception] = [] + for job_names, entry_exc in error_entries: + entry_exc.add_note(", ".join(job_names)) + error_parts.append(f"{', '.join(job_names)}: {_format_error_line(entry_exc)}") + exceptions.append(entry_exc) + + msg = f"Roadmap jobs failed: {'; '.join(error_parts)}" + cause = ExceptionGroup("Roadmap jobs failed", exceptions) + raise RoadmapRunError(msg, failed_jobs=failed_jobs) from cause return tuple(succeeded_jobs) @@ -749,8 +742,14 @@ def log_round_spend(repo: str, store: RoadmapStore, *, read: bool = True) -> Non def _refused_reset(exc: BaseException) -> datetime | None: """The reset a round's GraphQL budget refusal names: from the refusal itself, or the - earliest of the failed jobs' in `RoadmapRunError`; None for any other error.""" - return exc.reset_at if isinstance(exc, RoadmapRunError) else refusal_reset(exc) + earliest among the member exceptions of a RoadmapRunError; None for any other error.""" + if isinstance(exc, RoadmapRunError): + cause = exc.__cause__ + if isinstance(cause, BaseExceptionGroup): + resets = [r for sub in cause.exceptions if (r := _refused_reset(sub)) is not None] + return min(resets) if resets else None + return refusal_reset(cause) if cause is not None else None + return refusal_reset(exc) def service_pause_until(exc: Exception) -> datetime | None: @@ -768,10 +767,20 @@ def service_job(batch: TriggerBatch, *, table: Sequence[JobRow], clone_dirname: """Service mode adapter that runs one lane's due roadmap jobs, `table`, in its clone `clone_dirname` for a coalesced trigger batch, ending, however the round ends, with its GraphQL spend line; a round a budget refusal ended reads no budget for it.""" + from devops_cli.exceptions.config import ConfigurationError + from devops_cli.exceptions.git import GitHubFileNotFoundError from devops_cli.roadmap.config import open_roadmap repo = batch.repo - _config, store = open_roadmap(repo, ref=None, board_filter=CONST_ROADMAP_RUN_BOARD_FILTER) + try: + _config, store = open_roadmap(repo, ref=None, board_filter=CONST_ROADMAP_RUN_BOARD_FILTER) + except GitHubFileNotFoundError as exc: + raise ConfigurationError( + f"Repository {repo} is missing .github/roadmap.toml; commit the file or remove {repo} from service.repos", + key="service.repos", + details={"path": ".github/roadmap.toml"}, + ) from exc + refused = False try: run_due_jobs(repo, store, batch=batch, table=table, clone_dirname=clone_dirname) diff --git a/src/devops_cli/server/service.py b/src/devops_cli/server/service.py index 6221223788..5ec030854f 100644 --- a/src/devops_cli/server/service.py +++ b/src/devops_cli/server/service.py @@ -34,6 +34,7 @@ get_service_webhook_secrets, load_settings, ) +from devops_cli.exceptions import ConfigurationError, RoadmapRunError from devops_cli.lang import MESSAGES from devops_cli.server.routes.webhooks import ( DeliveryLRUCache, @@ -262,12 +263,15 @@ def _execute_batch(self, batch: TriggerBatch) -> None: span.set_status("ERROR", str(exc)[:256]) span.set_attribute("error", True) span.set_attribute("error.message", str(exc)[:256]) + is_config_only = isinstance(exc, ConfigurationError) or ( + isinstance(exc, RoadmapRunError) and exc.is_configuration_only + ) logger.error( "Service job execution failed for %s: %s", self.repo, exc, extra={**self._labels, "result": "error"}, - exc_info=True, + exc_info=True if not is_config_only else None, ) self.pause.after(exc, self.repo) finally: diff --git a/tests/test_roadmap_refine.py b/tests/test_roadmap_refine.py index 7644ec10cf..502f7e3e78 100644 --- a/tests/test_roadmap_refine.py +++ b/tests/test_roadmap_refine.py @@ -12,6 +12,7 @@ import logging import subprocess import time +import traceback from collections import Counter from collections.abc import Callable, Mapping from datetime import date, datetime, timedelta @@ -47,7 +48,7 @@ ) from devops_cli.config.settings import reset_settings_cache from devops_cli.exceptions import RoadmapRefineError, RoadmapRunError -from devops_cli.exceptions.git import GitHubOperationError +from devops_cli.exceptions.git import GitHubOperationError, GitHubRateLimitError from devops_cli.roadmap import store as roadmap_store_module from devops_cli.roadmap.intake import ( IntakeDecision, @@ -278,6 +279,35 @@ def _fail_search(query: str, **_: Any) -> Any: ) +def test_run_research_step_visibility_errors( + store: InMemoryRoadmapStore, caplog: pytest.LogCaptureFixture +) -> None: + """Checking repository visibility re-raises GitHubRateLimitError, and logs a warning and + returns ([], set()) for any other error (#1365).""" + llm = MockLLMClient() + + with ( + patch.object( + store, + "repository_is_private", + side_effect=GitHubRateLimitError("GraphQL budget exhausted"), + ), + pytest.raises(GitHubRateLimitError), + ): + run_research_step(store, "body", llm) + + with ( + patch.object( + store, "repository_is_private", side_effect=RuntimeError("transient read failure") + ), + caplog.at_level(logging.WARNING), + ): + res, urls = run_research_step(store, "body", llm) + + assert (res, urls) == ([], set()) + assert any("Could not read repository visibility" in rec.getMessage() for rec in caplog.records) + + def test_validate_proposal_sources_and_questions( git_repo: Path, store: InMemoryRoadmapStore ) -> None: @@ -1112,23 +1142,19 @@ def test_a_failed_item_fails_the_refine_job_of_a_run_without_its_model_text( store: InMemoryRoadmapStore, scripted_gateway: Callable[..., list[httpx2.Request]], tmp_path: Path, - caplog: pytest.LogCaptureFixture, failing_answer: Callable[[], Answer], named: str, ) -> None: """Verify run_due_jobs records `refine` as failed once the other items are written, whether - the item's reply never fit the schema or the gateway timed out, and its logged record names - the error class and holds none of the model's reply.""" + the item's reply never fit the schema or the gateway timed out, and the raised error + names the error class and holds none of the model's reply.""" first, second, third = _seed_new_items(store) scripted_gateway({first: failing_answer()}) table = build_stub_table( {"refine": lambda **kwargs: _run_refine_adapter(**(kwargs | {"clone_path": git_repo}))} ) - with ( - caplog.at_level(logging.ERROR, logger="devops_cli.roadmap.run"), - pytest.raises(RoadmapRunError) as raised, - ): + with pytest.raises(RoadmapRunError) as raised: run_due_jobs( REPO, store, @@ -1137,13 +1163,13 @@ def test_a_failed_item_fails_the_refine_job_of_a_run_without_its_model_text( data_dir=tmp_path, ) - logged = logging.Formatter().format(caplog.records[-1]) + formatted = "".join(traceback.format_exception(raised.value)) assert ( raised.value.failed_jobs, _bodies_written(store), - named in logged, - "leaked_model_key" in logged, - "During handling" in logged, + named in formatted, + "leaked_model_key" in formatted, + "During handling" in formatted, ) == (("refine",), [second, third], True, False, False) diff --git a/tests/test_roadmap_run.py b/tests/test_roadmap_run.py index d464fcbbc6..4b630617c2 100644 --- a/tests/test_roadmap_run.py +++ b/tests/test_roadmap_run.py @@ -46,8 +46,9 @@ ) from devops_cli.config.defaults import DEFAULT_ROADMAP_METRICS_INTERVAL_MINUTES from devops_cli.config.settings import ServiceConfig -from devops_cli.exceptions import GitOperationError, RoadmapRunError +from devops_cli.exceptions import ConfigurationError, GitOperationError, RoadmapRunError from devops_cli.exceptions.git import ( + GitHubFileNotFoundError, GitHubOperationError, GitHubRateLimitError, GitHubUnauthenticatedError, @@ -450,7 +451,7 @@ def ok_refine(**_: Any) -> JobOutcome: sched_data = _schedule(tmp_path) def failing_adapter(*_: Any, **__: Any) -> JobOutcome: - raise RoadmapRunError("Crash", failed_jobs=("intake",)) + raise RoadmapRunError("Crash [bold red]markup[/bold red]", failed_jobs=("intake",)) with patch("devops_cli.roadmap.run.run_due_jobs", side_effect=failing_adapter): res = runner.invoke(roadmap_app, ["run", "--confirm", "-R", REPO]) @@ -461,7 +462,7 @@ def failing_adapter(*_: Any, **__: Any) -> JobOutcome: "intake" not in sched_data, "refine" in sched_data, res.exit_code, - "intake" in res.output, + "[bold red]markup[/bold red]" in res.output, ) == (("intake",), ("intake", "refine"), True, True, 1, True) @@ -1255,22 +1256,23 @@ def crash(**_: Any) -> JobOutcome: _poll_round(store, tmp_path, table=refusing, batch={OPENED: 1}) with pytest.raises(RoadmapRunError) as crashed: _poll_round(store, tmp_path, table=build_stub_table({"intake": crash}), batch={OPENED: 1}) + assert not hasattr(refused.value, "reset_at") assert ( refused.value.failed_jobs, - refused.value.reset_at, - refused.value.details["reset_at"], + "reset_at" in refused.value.details, + refused.value.__cause__ is not None, + refusal_reset(refused.value.__cause__.exceptions[0]), ran, github.board.remaining, - crashed.value.reset_at, service_pause_until(refused.value), service_pause_until(crashed.value), ) == ( ("intake",), + False, + True, RESET, - RESET.isoformat(), ["refine"], 249, - None, RESET + timedelta(seconds=CONST_GH_RATE_LIMIT_CLOCK_SKEW_BOUND_SECONDS), None, ) @@ -1579,3 +1581,205 @@ def lane_round(table: Sequence[JobRow], clone_dirname: str) -> tuple[str, ...]: }, "work in progress\n", ) + + +def test_roadmap_run_error_is_configuration_only() -> None: + """RoadmapRunError.is_configuration_only checks if all cause group exceptions are ConfigurationError (#1365).""" + cfg1 = ConfigurationError("bad toml 1", key="service.repos") + cfg2 = ConfigurationError("bad toml 2", key="board") + unexpected = RuntimeError("unexpected crash") + + # Group of configuration errors only + group_cfg = ExceptionGroup("jobs", [cfg1, cfg2]) + err1 = RoadmapRunError("failed", failed_jobs=("intake", "metrics")) + err1.__cause__ = group_cfg + assert err1.is_configuration_only is True + + # Group of mixed errors + group_mixed = ExceptionGroup("jobs", [cfg1, unexpected]) + err2 = RoadmapRunError("failed", failed_jobs=("intake", "metrics")) + err2.__cause__ = group_mixed + assert err2.is_configuration_only is False + + # Group of unexpected errors only + group_unexpected = ExceptionGroup("jobs", [unexpected]) + err3 = RoadmapRunError("failed", failed_jobs=("metrics",)) + err3.__cause__ = group_unexpected + assert err3.is_configuration_only is False + + # Single ConfigurationError cause + err4 = RoadmapRunError("failed", failed_jobs=("intake",)) + err4.__cause__ = cfg1 + assert err4.is_configuration_only is True + + # No cause or non-config single cause + err5 = RoadmapRunError("failed", failed_jobs=("intake",)) + err5.__cause__ = unexpected + assert err5.is_configuration_only is False + + err6 = RoadmapRunError("failed", failed_jobs=()) + assert err6.is_configuration_only is False + + +def test_failed_run_keeps_every_job_error_and_clone_error( + seeded_store: InMemoryRoadmapStore, tmp_path: Path, caplog: pytest.LogCaptureFixture +) -> None: + """A failed run keeps every job's error, names intake and metrics, refine with clone failure, + carries ExceptionGroup cause with PEP 678 notes, is not config-only, and emits no ERROR log (#1365).""" + data_dir = tmp_path / "data" + missing_remote = tmp_path / "missing_remote" + ran: list[str] = [] + + def fail_intake(**_: Any) -> JobOutcome: + raise ConfigurationError("invalid roadmap.toml key", key="board") + + def stub(name: str) -> Callable[..., JobOutcome]: + return _recorded(ran, name) + + table = build_stub_table( + {"intake": fail_intake, "metrics": stub("metrics"), "refine": stub("refine")}, + needs_clone=True, + ) + + with caplog.at_level(logging.ERROR, logger="devops_cli.roadmap.run"): + with pytest.raises(RoadmapRunError) as exc_info: + run_due_jobs( + REPO, + seeded_store, + batch={OPENED: 1}, + table=table, + data_dir=data_dir, + remote_url=str(missing_remote), + now=NOW, + ) + + err = exc_info.value + assert err.failed_jobs == ("metrics", "intake", "refine") + assert "intake: invalid roadmap.toml key" in str(err) + assert "metrics, refine: git clone " in str(err) + assert err.is_configuration_only is False + + cause = err.__cause__ + assert isinstance(cause, ExceptionGroup) + assert len(cause.exceptions) == 2 + notes = {exc.__notes__[0]: exc for exc in cause.exceptions} + assert "intake" in notes + assert isinstance(notes["intake"], ConfigurationError) + assert "metrics, refine" in notes + assert isinstance(notes["metrics, refine"], GitOperationError) + + # No ERROR records emitted by devops_cli.roadmap.run + error_records = [ + r + for r in caplog.records + if r.name == "devops_cli.roadmap.run" and r.levelno >= logging.ERROR + ] + assert error_records == [] + + +def test_failed_run_configuration_only(seeded_store: InMemoryRoadmapStore, tmp_path: Path) -> None: + """A run failing only with ConfigurationError is marked is_configuration_only (#1365).""" + data_dir = tmp_path / "data" + + def fail_intake(**_: Any) -> JobOutcome: + raise ConfigurationError("missing board", key="board") + + table = build_stub_table({"intake": fail_intake}) + + with pytest.raises(RoadmapRunError) as exc_info: + run_due_jobs( + REPO, + seeded_store, + batch={OPENED: 1}, + table=table, + data_dir=data_dir, + now=NOW, + ) + + err = exc_info.value + assert err.failed_jobs == ("intake",) + assert "intake: missing board" in str(err) + assert err.is_configuration_only is True + assert isinstance(err.__cause__, ExceptionGroup) + assert len(err.__cause__.exceptions) == 1 + assert err.__cause__.exceptions[0].__notes__ == ["intake"] + + +def test_clone_fails_with_missing_git_binary( + seeded_store: InMemoryRoadmapStore, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """When git binary is missing, clone rows fail with FileNotFoundError as group member (#1365).""" + data_dir = tmp_path / "data" + empty_bin = tmp_path / "empty_bin" + empty_bin.mkdir() + monkeypatch.setenv("PATH", str(empty_bin)) + + missing_remote = tmp_path / "missing_remote" + ran: list[str] = [] + + def stub(name: str) -> Callable[..., JobOutcome]: + return _recorded(ran, name) + + table = build_stub_table( + {"metrics": stub("metrics"), "refine": stub("refine")}, + needs_clone=True, + ) + + with pytest.raises(RoadmapRunError) as exc_info: + run_due_jobs( + REPO, + seeded_store, + batch={OPENED: 1}, + table=table, + data_dir=data_dir, + remote_url=str(missing_remote), + now=NOW, + ) + + err = exc_info.value + assert err.failed_jobs == ("metrics", "refine") + cause = err.__cause__ + assert isinstance(cause, ExceptionGroup) + assert len(cause.exceptions) == 1 + assert isinstance(cause.exceptions[0], FileNotFoundError) + assert cause.exceptions[0].__notes__ == ["metrics, refine"] + assert str(cause.exceptions[0]).splitlines()[0] in str(err) + + +def test_service_job_missing_roadmap_config_raises_configuration_error( + roadmap_store: Any, +) -> None: + """service_job converts missing .github/roadmap.toml to ConfigurationError, and leaves + GitHubOperationError unchanged (#1365).""" + batch = TriggerBatch(repo="example/repo", counts={OPENED: 1}, first_at=NOW, last_at=NOW) + + with pytest.raises(ConfigurationError) as exc_info: + service_job( + batch, + table=STATUS_LANE_ROWS, + clone_dirname=CONST_ROADMAP_RUN_CLONE_DIRNAME, + ) + + err = exc_info.value + assert err.key == "service.repos" + assert err.details["path"] == ".github/roadmap.toml" + assert "example/repo" in str(err) + assert ".github/roadmap.toml" in str(err) + assert "service.repos" in str(err) + + +def test_service_job_unreadable_github_roadmap_propagates_unchanged( + unreadable_github_roadmap: Any, +) -> None: + """service_job propagates GitHubOperationError (e.g. HTTP 503) unchanged (#1365).""" + batch = TriggerBatch(repo="example/repo", counts={OPENED: 1}, first_at=NOW, last_at=NOW) + + with pytest.raises(GitHubOperationError) as exc_info: + service_job( + batch, + table=STATUS_LANE_ROWS, + clone_dirname=CONST_ROADMAP_RUN_CLONE_DIRNAME, + ) + + assert not isinstance(exc_info.value, ConfigurationError) + assert not isinstance(exc_info.value, GitHubFileNotFoundError) diff --git a/tests/test_server_service.py b/tests/test_server_service.py index c18bd9f51f..cf2ed575b5 100644 --- a/tests/test_server_service.py +++ b/tests/test_server_service.py @@ -41,7 +41,7 @@ WebhookProviderName, ) from devops_cli.config.settings import ServiceConfig, Settings -from devops_cli.exceptions import RoadmapRunError +from devops_cli.exceptions import ConfigurationError, RoadmapRunError from devops_cli.exceptions.git import GitHubRateLimitError from devops_cli.roadmap.board_read import GraphQLBudget, require_budget, require_write_floor from devops_cli.roadmap.memory_store import InMemoryRoadmapStore @@ -990,6 +990,117 @@ def job(batch: TriggerBatch) -> None: ) == (True, [0, 1], 2, [1.0, 1.0]) +def test_repo_worker_logs_configuration_errors_without_traceback( + caplog: pytest.LogCaptureFixture, +) -> None: + """The Service logs a configuration-only failure without a traceback, and every other + failure with exc_info (#1365).""" + test_repo = "example-org/traceback-suppression-test" + test_lane = "status" + counter_labels = {"repo": test_repo, "lane": test_lane} + + cfg1 = ConfigurationError("missing .github/roadmap.toml", key="service.repos") + cfg2 = ConfigurationError("invalid yaml", key="service.repos") + + g_cfg1 = ConfigurationError("toml error 1", key="board") + g_cfg1.add_note("intake") + g_cfg2 = ConfigurationError("toml error 2", key="board") + g_cfg2.add_note("metrics") + cfg_group_err = RoadmapRunError( + "Roadmap jobs failed: intake, metrics", failed_jobs=("intake", "metrics") + ) + cfg_group_err.__cause__ = ExceptionGroup("jobs", [g_cfg1, g_cfg2]) + + g_mixed1 = ConfigurationError("toml error", key="board") + g_mixed1.add_note("intake") + g_mixed2 = RuntimeError("transient db crash") + g_mixed2.add_note("metrics") + mixed_group_err = RoadmapRunError( + "Roadmap jobs failed: intake, metrics", failed_jobs=("intake", "metrics") + ) + mixed_group_err.__cause__ = ExceptionGroup("jobs", [g_mixed1, g_mixed2]) + + runtime_err = RuntimeError("runner crash") + + stages: list[Any] = [ + cfg1, + cfg2, + cfg_group_err, + mixed_group_err, + runtime_err, + "success", + ] + stage_idx = 0 + + def job(batch: TriggerBatch) -> None: + nonlocal stage_idx + item = stages[stage_idx] + stage_idx += 1 + if isinstance(item, Exception): + raise item + + err_count_before = GLOBAL_METRICS.get_counter_value( + CONST_SERVICE_METRIC_JOBS, labels={**counter_labels, "result": "error"} + ) + success_count_before = GLOBAL_METRICS.get_counter_value( + CONST_SERVICE_METRIC_JOBS, labels={**counter_labels, "result": "success"} + ) + + worker = RepoWorker( + repo=test_repo, + lane=test_lane, + job_func=job, + clock=lambda: datetime.now(UTC), + ) + worker.start() + with caplog.at_level(logging.WARNING, logger="devops_cli.server.service"): + for _ in range(6): + worker.enqueue("poll", "", "") + assert worker.wait_active(THREAD_HANDOFF_BOUND_SECONDS) + worker.stop() + assert worker.join(THREAD_HANDOFF_BOUND_SECONDS) + + records = [ + r + for r in caplog.records + if r.name == "devops_cli.server.service" and r.levelno >= logging.WARNING + ] + assert len(records) == 5 + assert all(r.levelno == logging.ERROR for r in records) + assert all(getattr(r, "repo", None) == test_repo for r in records) + assert all(getattr(r, "lane", None) == test_lane for r in records) + assert all(getattr(r, "result", None) == "error" for r in records) + + # First 3 are configuration-only: no exc_info + assert records[0].exc_info is None + assert records[1].exc_info is None + assert records[2].exc_info is None + + # Next 2 are unexpected: exc_info present + assert bool(records[3].exc_info) is True + assert bool(records[4].exc_info) is True + + # Check metrics + err_count_after = GLOBAL_METRICS.get_counter_value( + CONST_SERVICE_METRIC_JOBS, labels={**counter_labels, "result": "error"} + ) + success_count_after = GLOBAL_METRICS.get_counter_value( + CONST_SERVICE_METRIC_JOBS, labels={**counter_labels, "result": "success"} + ) + assert err_count_after - err_count_before == 5.0 + assert success_count_after - success_count_before == 1.0 + + # JsonLogFormatter formatting + formatter = JsonLogFormatter() + formatted_1 = json.loads(formatter.format(records[0])) + assert "exception" not in formatted_1 + + formatted_4 = json.loads(formatter.format(records[3])) + assert "exception" in formatted_4 + assert "intake" in formatted_4["exception"] + assert "metrics" in formatted_4["exception"] + + # ── A GraphQL budget refusal holds every repository's rounds (#1400) ────────── REPO_A, REPO_B = "example-org/repo1", "example-org/repo2"