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
3 changes: 2 additions & 1 deletion docs/TESTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ Every new test follows these rules. Some of them name a path, fixture or check t
- The floor fails a test that reaches a faked edge without its fake, with an error naming the edge.
- A test that checks a service that is down refuses it through `refusing_port`, a loopback port the test binds and never listens on, so the kernel refuses each connect as a stopped service would, and the service's retry waits return at once, as [Clock](#clock) says. A test that needs a service's answers fakes it at its edge, such as the model through `model_fake`.
- After every test, the floor calls the public reset of every process-wide cache and singleton, and an invariant test fails a module-level cache or `global` in `src/devops_cli` that has no reset there.
- A command that passes its dispatch timeout leaves its worker thread running, and a worker that ends after the floor resets the tracer builds a tracer from the real settings, which exports to port 4318 during another test. At the end of each test, while the test's isolation holds, the floor waits for the dispatch workers (`finish_abandoned_dispatch_workers`). A test that does not release its hung command fails in its own teardown, not in a later test.
- Telemetry export and the Valkey cache, best-effort side channels that nearly every test reaches, go to a loopback port the floor binds for the run, `unserved_side_channel_port`, which refuses them as a workstation that serves neither does.
- Telemetry export is off unless a test opts in with the OTLP fake *(target)*.
- Ratchets hold each thing being retired to a ceiling that may only go down: `test_suppressions_stay_under_their_ceilings` in `tests/test_architectural_invariants.py` holds the suppression comments, the `# noqa: C901` markers among them, and `tests/test_swallowed_failures_ratchet.py` the swallowed failures. Patches aimed at devops-cli, imports of its private names, test accommodations in product code (`unittest.mock`, `PYTEST_CURRENT_TEST` and mock-attribute checks) and test files outside the layout get ratchets of their own *(target)*. A change that passes a ceiling is fixed, and the ceiling is never raised; a ratchet at zero becomes a ban.
Expand All @@ -171,7 +172,7 @@ Every new test follows these rules. Some of them name a path, fixture or check t

The suite moves to these conventions package by package ([ADR 0007](adr/0007-tests-double-only-process-edges.md)). Until the move is done:

- **Exists today**: the network block, with its failure of a test that connects to a loopback port or `AF_UNIX` socket the test process does not bind or looks up an external DNS name, the `refusing_port` double and the side-channel port; the floor's default deny of processes (every program except git, bwrap and kubectl's offline renderers, with `@pytest.mark.live` for live local tools) and of the keyring (`_DenyKeyring` installed before the first test); the reset of every piece of process-wide state in `src/devops_cli` after each test, guarded by an invariant test; telemetry export off by default unless a test opts in through `config`; the `cli` and `config` fixtures; the refusal to start a real gh or security scanner, by the names `tests/support/refused_programs.py` reads from the scanner registry; each test's own data directory, config and gh config, with no way onto the session bus; the pinned GitHub identity; one throwaway kubeconfig for the whole run; the config write guard, a PEP 578 audit hook in the test process in `tests/support/config_write_guard.py`, which refuses a write of a file named like a devops-cli config file, such as `config.yaml` or its copy `config.yaml.bak-<stamp>`, outside the run's temporary directory, also when the code under test catches the refusal; the workspace tripwire, in `tests/support/workspace_tripwire.py`; `tests/support/` with `paths.py`, `waits.py`, the builders in `builders.py`, the `fakes/` package, the pinned identity's `github_identity.py`, and the registration of its modules through `bootstrap.py`, the root conftest's one `pytest_plugins` entry, with the checks that hold a helper's top level and class bodies to statements that bind names, that keep a module from holding `tests.support` or a package under it, and that fail a run on a support fixture or hook its source does not show or on a test module or conftest under `tests/support/`; the check, in the full gate, against reading `__file__` outside `tests/support/` and importing a test module or a conftest; the GitHub session's fake, `GitHubApiFake` in `tests/support/fakes/github.py` behind its `github_api` fixture, which refuses any gh command the rate limiter would run (`run_gh` and the quota refresh), with its contract suite, `tests/test_github_contract.py`, which runs each case through the session over the fake and over GitHub's recorded answers; the security scanners' fake, `ScannerFake` in `tests/support/fakes/scanners.py` behind its `scanner_fake` fixture, a `ToolExecutorFake` that answers Semgrep, Gitleaks, Bandit and osv-scanner with their recorded runs, with its contract suite, `tests/test_scanner_contract.py`, which holds each recording to its adapter's command and the tools lock's version; the OpenSpec fake, `OpenSpecFake` in `tests/support/fakes/openspec.py` behind its `openspec_fake` fixture, which answers `openspec` with the pinned tool's recorded runs over the scenarios of `tests/support/openspec_scenarios.py` (`tests/support/openspec_recording.py` records them again) and fails a command the record lacks, with its contract suite, `tests/test_openspec_contract.py`, which holds the record to the tools lock's version and to the commands the gate starts; the in-memory roadmap store behind the `roadmap_store` fixture, which every test that drives a roadmap command uses, since the roadmap store factory is refused; the in-memory Valkey server behind the `valkey_server` and `valkey_client` fixtures in `tests/support/fakes/valkey.py`, which a `ValkeyClient` reaches through its `connection_pool` parameter, so a test of what the client's own `password`, `db` and decoding arguments send and read binds a loopback listener that records the commands instead, and which has no contract suite yet, since no recorded exchange or local tool stands in for a Valkey server; Hypothesis; syrupy, whose first snapshots are the fail-to-pass replay's could-not-run reports in `tests/__snapshots__/test_fail_to_pass.ambr`; the 90% coverage gate; the structural startup budget; the ast-grep rule against an upper bound on elapsed wall-clock time in `tests/`; and the suppression-ceiling and swallowed-failures ratchets.
- **Exists today**: the network block, with its failure of a test that connects to a loopback port or `AF_UNIX` socket the test process does not bind or looks up an external DNS name, the `refusing_port` double and the side-channel port; the floor's default deny of processes (every program except git, bwrap and kubectl's offline renderers, with `@pytest.mark.live` for live local tools) and of the keyring (`_DenyKeyring` installed before the first test); the reset of every piece of process-wide state in `src/devops_cli` after each test, guarded by an invariant test; the wait for the dispatch workers that a timeout abandoned, in `finish_abandoned_dispatch_workers`; telemetry export off by default unless a test opts in through `config`; the `cli` and `config` fixtures; the refusal to start a real gh or security scanner, by the names `tests/support/refused_programs.py` reads from the scanner registry; each test's own data directory, config and gh config, with no way onto the session bus; the pinned GitHub identity; one throwaway kubeconfig for the whole run; the config write guard, a PEP 578 audit hook in the test process in `tests/support/config_write_guard.py`, which refuses a write of a file named like a devops-cli config file, such as `config.yaml` or its copy `config.yaml.bak-<stamp>`, outside the run's temporary directory, also when the code under test catches the refusal; the workspace tripwire, in `tests/support/workspace_tripwire.py`; `tests/support/` with `paths.py`, `waits.py`, the builders in `builders.py`, the `fakes/` package, the pinned identity's `github_identity.py`, and the registration of its modules through `bootstrap.py`, the root conftest's one `pytest_plugins` entry, with the checks that hold a helper's top level and class bodies to statements that bind names, that keep a module from holding `tests.support` or a package under it, and that fail a run on a support fixture or hook its source does not show or on a test module or conftest under `tests/support/`; the check, in the full gate, against reading `__file__` outside `tests/support/` and importing a test module or a conftest; the GitHub session's fake, `GitHubApiFake` in `tests/support/fakes/github.py` behind its `github_api` fixture, which refuses any gh command the rate limiter would run (`run_gh` and the quota refresh), with its contract suite, `tests/test_github_contract.py`, which runs each case through the session over the fake and over GitHub's recorded answers; the security scanners' fake, `ScannerFake` in `tests/support/fakes/scanners.py` behind its `scanner_fake` fixture, a `ToolExecutorFake` that answers Semgrep, Gitleaks, Bandit and osv-scanner with their recorded runs, with its contract suite, `tests/test_scanner_contract.py`, which holds each recording to its adapter's command and the tools lock's version; the OpenSpec fake, `OpenSpecFake` in `tests/support/fakes/openspec.py` behind its `openspec_fake` fixture, which answers `openspec` with the pinned tool's recorded runs over the scenarios of `tests/support/openspec_scenarios.py` (`tests/support/openspec_recording.py` records them again) and fails a command the record lacks, with its contract suite, `tests/test_openspec_contract.py`, which holds the record to the tools lock's version and to the commands the gate starts; the in-memory roadmap store behind the `roadmap_store` fixture, which every test that drives a roadmap command uses, since the roadmap store factory is refused; the in-memory Valkey server behind the `valkey_server` and `valkey_client` fixtures in `tests/support/fakes/valkey.py`, which a `ValkeyClient` reaches through its `connection_pool` parameter, so a test of what the client's own `password`, `db` and decoding arguments send and read binds a loopback listener that records the commands instead, and which has no contract suite yet, since no recorded exchange or local tool stands in for a Valkey server; Hypothesis; syrupy, whose first snapshots are the fail-to-pass replay's could-not-run reports in `tests/__snapshots__/test_fail_to_pass.ambr`; the 90% coverage gate; the structural startup budget; the ast-grep rule against an upper bound on elapsed wall-clock time in `tests/`; and the suppression-ceiling and swallowed-failures ratchets.
- **Review tools**: `ToolExecutor` in `src/devops_cli/security/tool_executor.py` is the seam of the review-tool edge, and `ToolExecutorFake` in `tests/support/fakes/tool_executor.py` is its fake, behind the `tool_executor_fake` fixture. A test scripts a tool with `ToolAnswer` (version, binary digest, exit code, output, `timed_out`) and reads the requests back from `requests`. The fake builds the rest of each `ToolRun` with the `record_tool_run` that the real executor calls.
- **Review tools, programs and canaries**: a request for a tool that the PATH does not name, such as mypy from the interpreter of a `.venv`, names that interpreter as its `program`, and the fake answers it as it answers the tool. Mypy and the canary of each tool take a `tool_executor`, and a review gives them its own. `ScannerFake` answers each canary run, in a working directory named with `CONST_CANARY_WORKDIR_PREFIX`, with the output in `tests/fixtures/review_canary/recorded_outputs.json`, and keeps it in `canaries.requests`, apart from the runs of the scans. A test that builds an orchestrator gives it `scanner_fake` through the constructor (`tool_executor=scanner_fake`), and a test that starts a review through a command asks for `scanner_fake`, so no review starts a real tool for its canaries. A test whose scans reach a patched `run_subprocess` gives the orchestrator `recorded_canary_answers()`, a `ToolExecutorFake` that answers the canaries alone. The root conftest does not wrap `DirectToolExecutor.run` or `SandboxToolExecutor.run`.
- **Review tools, records**: the fake names itself `fake` in the record (`FAKE_EXECUTOR`). A review wraps its executor in a `RecordingToolExecutor`. A test that gives the orchestrator the fake reads the records from `orchestrator.tool_executor.runs`, from `profile.tool_runs` and from the Tool Runs table of the report.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
schema: spec-driven
created: 2026-10-26
skip_specs: true
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Design

## Cause

A dispatch that passes its timeout returns exit code 124 and leaves its worker thread running.
The worker still holds the command. When the command returns, `_execute_traced_cli_command` calls `record_metric`, and `record_metric` calls `get_tracer()`.
`get_tracer()` builds the global tracer on its first call, from the settings the process has at that moment.
After the floor tears down the test, the settings are the real ones: telemetry is on and the endpoint is port 4318.
The `devops-otel` thread of that new tracer connects to loopback port 4318, and the floor guard fails the test that is running.
`reset_tracer()` cannot help: it ran before the tracer existed.

## Fix

1. `InProcessDispatcher._dispatch_typer` starts the worker with `name=CONST_MCP_DISPATCH_THREAD_NAME`.
The name makes the worker findable by thread name, and it is clearer than `Thread-3 (_worker)` in a thread dump.
2. `tests/conftest.py` gets an autouse fixture `finish_abandoned_dispatch_workers` that depends on `isolate_devops_cli_config`.
A fixture that depends on another fixture is set up after it and torn down before it.
The wait therefore happens while the test config, the environment and the tracer reset of that fixture still hold.
The worker finishes against the isolated tracer: telemetry is off, and the refusing port is the endpoint.
3. The fixture joins every live thread with that name, with a bound of `_DISPATCH_WORKER_JOIN_SECONDS`.
A worker that is alive after the bound fails the test at its own teardown and names the thread, so a leak shows in the test that causes it.

## Test

The floor invariant test runs two inner tests under the floor with `pytester`.
The first inner test hangs a command, lets the dispatch time out, releases the command, and slows the end of the worker with a patched `_record_cli_success`.
The second inner test checks that the worker has finished.
Without the fixture the second inner test fails, because it starts while the worker sleeps.
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# Proposal

## Why

Issue #2277: a test fails at teardown with "network edge reached without a fake", because a `devops-otel` thread connects to the loopback OpenTelemetry port 4318.
The test that fails is not the test that started the thread.
Pull request #2274 made `OTelTelemetryClient.shutdown()` wait for its threads, and the failure stayed.
The cause is not a client that a reset misses. The client does not exist yet when the reset runs.

`InProcessDispatcher._dispatch_typer` runs a command in a worker thread.
When the command passes its timeout, the dispatcher returns exit code 124 and leaves the worker running: Python cannot stop a thread.
Two tests hang a command on purpose and release it in a `finally` block, so the abandoned worker finishes while the test tears down.
At its end the worker calls `record_metric`, and `record_metric` calls `get_tracer()`.
If the floor has already reset the tracer and restored the environment, `get_tracer()` builds a new tracer from the real settings.
The default `telemetry.enabled` is `true` and the default endpoint is port 4318, so the new tracer exports to loopback port 4318 from a `devops-otel` thread.
The floor guard records the connect in whichever test runs next. The race depends on the load of the host, which is why the failure is intermittent.

## What Changes

- Name the dispatcher worker thread with `CONST_MCP_DISPATCH_THREAD_NAME`.
- Add an autouse fixture to `tests/conftest.py` that waits for dispatcher workers at the end of each test, while the isolated configuration and the tracer reset still hold.
The fixture fails the test if a worker is still alive after the wait.
- Add a floor invariant test that fails when the next test starts before the abandoned worker has finished.
- The change sets `skip_specs: true` in `.openspec.yaml`.
- This change fits in one pull request.

## Capabilities

### New Capabilities

None.

### Modified Capabilities

None.

## Impact

- Code: `src/devops_cli/ai/mcp/dispatcher.py`, `src/devops_cli/config/constants.py`.
- Tests: `tests/conftest.py`, `tests/invariants/test_hermetic_floor.py`.

## Feasibility

- Premise confirmed against the code and a run of the code.
A scratch test dispatched a hung command with a 0.1 second timeout and released it after the fixtures had torn down, with no user configuration loaded.
The abandoned `Thread-1 (_worker)` created a new tracer with `enabled=True` and the default endpoint, and `devops-otel_0` exported while the next test was in setup.
The next test then failed at teardown with "network edge reached without a fake".
- In the same scratch run with the worker released inside the test, the worker used the isolated tracer and nothing was exported.
- The two tests that hang a command, `test_mcp_tool_stops_at_timeout_when_command_never_returns` and `test_in_process_dispatcher_timeout_stops_command_within_budget`, are the only places that abandon a worker.
- The port is not added to a list of allowed connections. The floor is right to refuse it.

## Existing Tool Considered

`threading.Thread.join` waits for the worker. Python has no way to stop a thread, so the product keeps the abandoned worker and the floor waits for it.
`pytest` fixture teardown order puts a fixture that depends on `isolate_devops_cli_config` before the reset of that fixture and before the restore of the environment.
No new library is necessary.
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Tasks

## 1. Failing test

- [x] Add a floor invariant test in `tests/invariants/test_hermetic_floor.py` proving that an abandoned dispatch worker is finished before the next test starts
- Verification: `uv run devops ci test tests/invariants/test_hermetic_floor.py`

## 2. Fix

- [x] Add `CONST_MCP_DISPATCH_THREAD_NAME` to `src/devops_cli/config/constants.py` and name the worker thread in `src/devops_cli/ai/mcp/dispatcher.py`
- Verification: `uv run devops ci test tests/test_fastmcp_in_process.py`
- [x] Add the `finish_abandoned_dispatch_workers` autouse fixture to `tests/conftest.py`
- Verification: `uv run devops ci test tests/invariants/test_hermetic_floor.py tests/test_fastmcp_in_process.py`

## 3. Verification and static checks

- [x] Verify fail-to-pass check run passes against base
- Verification: `uv run devops ci fail-to-pass --base origin/main`
- [x] Verify full static checks pass
- Verification: `uv run devops ci`

## Workflow follow-up

- Pending a person: review the diff in tuicr (`tuicr -r origin/main..HEAD`).
6 changes: 4 additions & 2 deletions src/devops_cli/ai/mcp/dispatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from contextlib import contextmanager
from typing import Any

from devops_cli.config.constants import CONST_MCP_DOMAINS
from devops_cli.config.constants import CONST_MCP_DISPATCH_THREAD_NAME, CONST_MCP_DOMAINS
from devops_cli.config.defaults import (
DEFAULT_MCP_SCHEMA_CACHE_MAX_ENTRIES,
DEFAULT_MCP_TOOL_SHORT_TIMEOUT_SECONDS,
Expand Down Expand Up @@ -340,7 +340,9 @@ def _worker() -> None:
) as exc:
worker_exc = exc

t = threading.Thread(target=_worker, daemon=True)
t = threading.Thread(
target=_worker, name=CONST_MCP_DISPATCH_THREAD_NAME, daemon=True
)
t.start()
t.join(timeout=timeout)

Expand Down
Loading
Loading