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
6 changes: 6 additions & 0 deletions changelog.d/885.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
### Fixed
- **CI quality gate and subcommand execution under dry-run**:
- `devops ci` checks, runners, and subcommands start zero subprocesses and mutate no external state when `--dry-run` is active (#885).
- Return dry-run `CheckResult`s carrying `dry_run=True` and render ordered `PlannedRequest` execution plans via `render_request_plan` for single checks and aggregate runs (#885).
- Bypass coverage artifact cleanup and prevent saving or clearing gate cache under dry run (#885).
- Add planned index run preview to `devops ci coverage --build-index --dry-run` without writing cache files or hashing source trees (#885).
69 changes: 69 additions & 0 deletions docs/agent/tasks/task-885-ci-checks-run-under-dry-run.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# Task: devops ci Checks Run for Real Under the Gate (#885)

**Issue**: [#885](https://github.com/dan-petty/devops-cli/issues/885)
**Status**: Done
**Milestone**: v0.2.27
**Priority**: priority/p1-high
**Scope**: scope/ci

## Description

Under a dry run (`is_dry_run() is True`), `devops ci` checks, runners, and subcommands start zero subprocesses and mutate no external state.

- **Runner Guards** (`commands/ci.py`):
- In `_run` and `_execute_check_async`, execution branches on `is_dry_run()` before invoking any process runner. Each builds a `PlannedRequest` containing the exact argv that would execute, including the `--preview-features malware-check,check-command` flag inserted when the command begins with `uv`.
- Single check subcommands (`lint`, `format`, `test`, `coverage`, `typecheck`, etc.) call `_run`, which renders a one-request execution plan via `render_request_plan` and returns `True`.
- `devops ci --dry-run` and `devops ci run --dry-run` build ordered execution requests—the pre-fix steps when fixes are enabled (`format_fix`, `lint_fix`, `docs_fix`), followed by every row in `get_check_specs()`—and render the aggregate plan via `render_request_plan`.
- Dry-run `CheckResult` instances carry `dry_run=True` and `passed=False`. The gate prints no pass badges and no pass summary table for dry-run checks.
- `_handle_ci_results` returns early without saving or clearing gate cache when `is_dry_run()` is active.
- **Artifact Protection** (`commands/ci.py`):
- `_clean_coverage_artifacts` checks `if is_dry_run(): return`, preventing unlinking of `.coverage*` or `coverage.xml` files during dry runs.
- **Coverage Index Preview** (`commands/ci.py`):
- `devops ci coverage --build-index --dry-run` plans the test run with `--cov-context=test` and environment variable `COVERAGE_CORE=ctrace` via `_run`. It computes no hashes and writes no index file to disk.
- **Test Suite** (`tests/test_ci_dry_run.py`):
- Completely rewritten to record `subprocess.run` invocations rather than patching `_run`. Verifies zero subprocess calls across dry runs, preservation of coverage artifacts, one-request plans for subcommands, aggregate plans for full gate runs, and that live execution without `--dry-run` reaches the process runner.

## Survey of `--dry-run` Command Paths

An audit of 80 argument-free command paths declaring `--dry-run` verified that, apart from `ci`, the only subprocesses started were read-only:
- `git worktree list`
- `git rev-parse`
- `gh api rate_limit`
- `kubectl apply -k . --dry-run=client`

The 40 argument-taking `--dry-run` command paths are filed under candidate #986 for follow-up audit and preview alignment.

## Acceptance Criteria

- [x] Under a dry run, `_run` and `_execute_check_async` start no process. Each records a `PlannedRequest` holding the argv as it would run, including the `uv --preview-features` insertion.
- `devops ci lint|format|test|coverage --dry-run` each print a one-request plan.
- `devops ci --dry-run` and `devops ci run --dry-run` print, in order, the fix steps (when fixes are on) and then every row of `get_check_specs()`.
- Each exits 0 with the `subprocess.run` recorder at zero calls (`tests/test_ci_dry_run.py`).
- [x] Dry-run `CheckResult`s carry a dry-run marker (`dry_run=True`) instead of `passed=True` for checks that never ran. The gate prints no pass badges or pass summary for them. Under a dry run, `_handle_ci_results` neither saves nor clears the cache.
- [x] `devops ci coverage --build-index --dry-run` plans the index run (`--cov-context=test` with env `COVERAGE_CORE=ctrace`), hashes nothing and writes no index. Tested with index path under `tmp_path`, verifying no file is created and the recorder sees zero calls.
- [x] `devops ci --dry-run` and `devops ci run --dry-run` unlink nothing: with `PYTEST_CURRENT_TEST` removed and `_get_project_root` pointed to `tmp_path` holding `.coverage.sample` and `coverage.xml`, both files still exist afterwards.
- [x] Without the flag, `devops ci lint` calls the runner once with `uv --preview-features malware-check,check-command run ruff check --fix .`, and `devops ci --no-cache` with the recorder reaches the runner for every check row.
- [x] `tests/test_ci_dry_run.py` contains zero occurrences of patching `commands.ci._run`.
- [x] `devops ci maintain --dry-run` output is unchanged (`tests/test_ci_maintain.py::test_ci_maintain_dry_run` passes).
- [x] The new and rewritten tests take at most 1 s in total for setup, call and teardown on one worker (measured at 0.52 s call duration).
- [x] The task file records the recorder results for the 80 argument-free `--dry-run` paths (the four read-only processes) and names #986 for the 40 argument-taking paths.
- [x] `changelog.d/885.md` exists; `CHANGELOG.md` and `docs/ROADMAP.md` are untouched.
- Pending a person: `uv run devops ci` passes on this branch.

## Measurements

Measured with `uv run pytest -n 0 --durations=0 tests/test_ci_dry_run.py`:

| Test | Call Duration |
| :--- | ---: |
| `test_ci_live_control` | 0.15 s |
| `test_other_ci_subcommands_dry_run` | 0.11 s |
| `test_ci_lint_dry_run` | 0.11 s |
| `test_ci_dry_run_unlinks_nothing` | 0.04 s |
| `test_ci_test_dry_run` | 0.02 s |
| `test_ci_coverage_dry_run` | 0.02 s |
| `test_ci_coverage_build_index_dry_run` | 0.02 s |
| `test_ci_format_dry_run` | 0.02 s |
| `test_ci_run_command_dry_run` | 0.02 s |
| `test_ci_all_checks_dry_run` | 0.01 s |
| **Total Call Time** | **0.52 s** |
150 changes: 139 additions & 11 deletions src/devops_cli/commands/ci.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
)
from devops_cli.core.cli import new_typer
from devops_cli.dry_run import is_dry_run, render_dry_run_result, set_dry_run
from devops_cli.dry_run.requests import PlannedRequest, render_request_plan
from devops_cli.lang import HELP, MESSAGES
from devops_cli.output import print_error, print_info, print_success

Expand Down Expand Up @@ -150,6 +151,8 @@ class CheckResult(BaseModel):
stderr: str = ""
timed_out: bool = False
timeout_seconds: float | None = None
dry_run: bool = False
requests: tuple[PlannedRequest, ...] = ()


class CheckSpec(BaseModel):
Expand Down Expand Up @@ -186,13 +189,39 @@ def _verify_python_314_environment() -> bool:
return True


def _planned_request_for_cmd(
cmd: Sequence[str],
*,
env: dict[str, str] | None = None,
condition: str = "",
repeat: str = "",
) -> PlannedRequest:
"""Construct a PlannedRequest for a command, inserting uv preview flags when needed."""
full_cmd = list(cmd)
if full_cmd and full_cmd[0] == "uv" and "--preview-features" not in full_cmd:
full_cmd[1:1] = ["--preview-features", "malware-check,check-command"]
env_tuple = tuple((k, v) for k, v in sorted(env.items())) if env else ()
return PlannedRequest(
method="run",
target=full_cmd[0] if full_cmd else "",
argv=tuple(full_cmd),
env=env_tuple,
condition=condition,
repeat=repeat,
)


def _run(
cmd: list[str],
timeout: float = DEFAULT_SUBPROCESS_TIMEOUT_SECONDS,
capture_output: bool = False,
env: dict[str, str] | None = None,
) -> bool:
"""Run a CI check subprocess synchronously."""
if is_dry_run():
req = _planned_request_for_cmd(cmd, env=env)
render_request_plan(MESSAGES.ci.ci_dry_run_heading, [req])
return True
root = _get_project_root()
full_cmd = list(cmd)
if full_cmd and full_cmd[0] == "uv" and "--preview-features" not in full_cmd:
Expand Down Expand Up @@ -239,6 +268,8 @@ def _unlink_coverage_path(path: Path, *, force: bool) -> None:

def _clean_coverage_artifacts(*, force: bool = False) -> None:
"""Clean up residual temporary .coverage.* worker files from the checked tree and .data/."""
if is_dry_run():
return
if not force and os.getenv("PYTEST_CURRENT_TEST"):
return

Expand Down Expand Up @@ -296,6 +327,19 @@ async def _execute_check_async(
else:
check_spec = spec

if is_dry_run():
req = _planned_request_for_cmd(check_spec.cmd)
return CheckResult(
name=check_spec.name,
display_title=check_spec.display_title,
passed=False,
dry_run=True,
duration_seconds=0.0,
stdout="",
stderr="",
requests=(req,),
)

start_time = time.perf_counter()
root = _get_project_root()

Expand Down Expand Up @@ -683,6 +727,8 @@ def _assemble_ci_results(
duration_seconds=test_result.duration_seconds,
stdout=test_result.stdout,
stderr=test_result.stderr,
dry_run=test_result.dry_run,
requests=test_result.requests,
)
assembled: list[CheckResult] = [py_result]
for i, res in enumerate(raw_results):
Expand All @@ -692,6 +738,64 @@ def _assemble_ci_results(
return assembled


def _collect_fix_requests(
selected_specs: Sequence[CheckSpec],
*,
format_fix: bool,
lint_fix: bool,
docs_fix: bool,
) -> list[PlannedRequest]:
"""Collect planned requests for pre-fix steps in execution order."""
fixes = [
("format", format_fix),
("lint", lint_fix),
("docs", docs_fix),
]
spec_map = {s.name: s for s in selected_specs}
requests: list[PlannedRequest] = []
for name, enabled in fixes:
if not enabled:
continue
spec = spec_map.get(name)
if spec and spec.fix_cmd:
requests.append(_planned_request_for_cmd(spec.fix_cmd))
return requests


def _dry_run_all_checks(
selected_specs: Sequence[CheckSpec],
*,
format_fix: bool,
lint_fix: bool,
docs_fix: bool,
) -> list[CheckResult]:
"""Handle dry run for all checks: render request plan and return dry-run CheckResults."""
fix_requests = _collect_fix_requests(
selected_specs, format_fix=format_fix, lint_fix=lint_fix, docs_fix=docs_fix
)
check_requests = [_planned_request_for_cmd(s.cmd) for s in selected_specs]
render_request_plan(MESSAGES.ci.ci_dry_run_heading, [*fix_requests, *check_requests])
py_result = CheckResult(
name="python_version",
display_title=MESSAGES.ci.python_version_check,
passed=False,
dry_run=True,
duration_seconds=0.0,
)
raw_results = [
CheckResult(
name=spec.name,
display_title=spec.display_title,
passed=False,
dry_run=True,
duration_seconds=0.0,
requests=(_planned_request_for_cmd(spec.cmd),),
)
for spec in selected_specs
]
return _assemble_ci_results(py_result, selected_specs, raw_results)


async def _run_all_checks_async(
*,
lint_fix: bool = False,
Expand All @@ -700,6 +804,15 @@ async def _run_all_checks_async(
specs: Sequence[CheckSpec] | None = None,
) -> list[CheckResult]:
"""Execute CI verification gates concurrently using asyncio."""
if is_dry_run():
selected_specs = list(specs) if specs is not None else get_check_specs()
return _dry_run_all_checks(
selected_specs,
format_fix=format_fix,
lint_fix=lint_fix,
docs_fix=docs_fix,
)

_clean_coverage_artifacts()

py_ok, py_result = _run_python_version_step()
Expand Down Expand Up @@ -755,6 +868,8 @@ def _run_all_checks(

def _print_failures(results: list[CheckResult]) -> None:
"""Print diagnostic failure outputs for failed CI checks."""
if is_dry_run() or any(res.dry_run for res in results):
return
for res in results:
if not res.passed and (res.stdout or res.stderr):
_section(res.display_title)
Expand All @@ -768,6 +883,8 @@ def _print_summary(
results: list[CheckResult], total_elapsed: float, *, cached: bool = False
) -> None:
"""Render the final formatted CI Summary table."""
if is_dry_run() or any(res.dry_run for res in results):
return
from devops_cli.output import format_duration

rows: list[list[str]] = []
Expand Down Expand Up @@ -893,6 +1010,8 @@ def _try_fast_cached_ci(

def _warn_when_over_budget(results: list[CheckResult]) -> None:
"""Warn when the test step ran past its budget, naming the tests that took longest."""
if is_dry_run() or any(res.dry_run for res in results):
return
test_result = next((res for res in results if res.name == "test"), None)
if test_result is None or test_result.duration_seconds <= CONST_CI_TEST_BUDGET_SECONDS:
return
Expand Down Expand Up @@ -926,8 +1045,11 @@ def _handle_ci_results(
`--no-cache` run has done the full work and proved the tree, so discarding the proof
made the next ordinary run repeat it for no reason.
"""
if is_dry_run() or any(res.dry_run for res in results):
return

if all(res.passed for res in results):
if save_cache and not is_dry_run():
if save_cache:
_try_save_ci_cache(root, results, all_files, ci_options)
return

Expand Down Expand Up @@ -978,13 +1100,13 @@ def all_checks(
] = False,
) -> None:
"""Run all CI checks concurrently in parallel with non-blocking async execution."""
if dry_run:
set_dry_run(True)
root = _get_project_root()
if not ctx.meta.get(CONST_CI_SUBCOMMAND_SHOWS_HELP_META_KEY):
_announce_gate_root(root)
if ctx.invoked_subcommand is not None:
return
if dry_run:
set_dry_run(True)

selected_specs = resolve_selected_specs(only=only, skip=skip)
is_narrowed = bool(only or skip)
Expand All @@ -999,8 +1121,9 @@ def all_checks(
return

start_time = time.perf_counter()
_get("print_info")("Executing CI quality gates concurrently...")
sys.stdout.flush()
if not is_dry_run():
_get("print_info")("Executing CI quality gates concurrently...")
sys.stdout.flush()
results = asyncio.run(
_run_all_checks_async(
lint_fix=effective_fix,
Expand Down Expand Up @@ -1290,17 +1413,21 @@ def test(

def _handle_coverage_index_build(cmd: list[str]) -> None:
"""Execute full test suite with coverage contexts and persist coverage reverse index."""
root = _get_project_root()
index_cmd = list(cmd)
index_cmd.append("--cov-context=test")

if is_dry_run():
_run(index_cmd, env={"COVERAGE_CORE": "ctrace"})
return

from devops_cli.ci.cache import compute_worktree_blob_hashes, resolve_coverage_index_path
from devops_cli.core.coverage_index import (
build_index_from_coverage,
filter_coverage_source_hashes,
save_index,
)

root = _get_project_root()
index_cmd = list(cmd)
index_cmd.append("--cov-context=test")

hashes_before = filter_coverage_source_hashes(compute_worktree_blob_hashes(root))
env = {"COVERAGE_CORE": "ctrace"}
if not _run(index_cmd, env=env):
Expand Down Expand Up @@ -1629,5 +1756,6 @@ def run(
results = asyncio.run(_run_all_checks_async(lint_fix=fix, format_fix=fix, docs_fix=fix))
_print_failures(results)
_print_summary(results, total_elapsed=time.perf_counter() - start_time)
if not all(res.passed for res in results):
raise typer.Exit(1)
if not is_dry_run() and not any(res.dry_run for res in results):
if not all(res.passed for res in results):
raise typer.Exit(1)
3 changes: 3 additions & 0 deletions src/devops_cli/lang/en/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -815,6 +815,9 @@ class ArgoMessages:

@dataclass(frozen=True)
class CIMessages:
ci_dry_run_heading: str = (
"Dry run: no request was made. CI would make these requests, in order:"
)
python_version_check: str = "python version check (3.14+)"
no_covering_tests: str = (
"No covering tests found for: {files}. Changed code without a covering test "
Expand Down
Loading
Loading