diff --git a/openspec/changes/archive/2026-11-11-4513-decide-all-can-hang-a-test/.openspec.yaml b/openspec/changes/archive/2026-11-11-4513-decide-all-can-hang-a-test/.openspec.yaml new file mode 100644 index 0000000000..9d55295e5d --- /dev/null +++ b/openspec/changes/archive/2026-11-11-4513-decide-all-can-hang-a-test/.openspec.yaml @@ -0,0 +1,3 @@ +schema: spec-driven +created: 2026-11-11 +skip_specs: false diff --git a/openspec/changes/archive/2026-11-11-4513-decide-all-can-hang-a-test/design.md b/openspec/changes/archive/2026-11-11-4513-decide-all-can-hang-a-test/design.md new file mode 100644 index 0000000000..557a96fcc4 --- /dev/null +++ b/openspec/changes/archive/2026-11-11-4513-decide-all-can-hang-a-test/design.md @@ -0,0 +1,16 @@ +# Design + +## Decisions + +- One event loop for all requests of one `decide_all` call, in the calling thread. A model that the requests share then uses its lock and its client on the loop that bound them. A model that `decide_all` builds for a request still closes its client on that loop (#4319). +- `asyncio.timeout(timeout)` wraps each request inside its semaphore slot. The wait for a free slot does not use the time of the request, and the limit also covers the enter and exit of the model, where the lock wait was. +- `asyncio.gather` with no `return_exceptions` raises the first error, as before. `asyncio.run` then cancels the other requests and lets each close its own client. +- The default `timeout` is `CONST_ROADMAP_JEV_TIMEOUT_SECONDS`, the constant of the project for one Jev request. +- The timeout test calls `decide_all` in a thread of the test and waits for its outcome with `THREAD_HANDOFF_BOUND_SECONDS` (docs/TESTING.md). The test releases the held request in `finally`, so on the base the test fails at the bound and the worker does not stay stuck. + +## Rejected alternatives + +- Keep the threads and add `future.result(timeout=...)`. The exit of the `with ThreadPoolExecutor` block joins the stuck thread (the traceback of #4513), and the exit of the interpreter joins pool threads too. A shared model also still crosses loops. +- Build a model for each thread. A caller can give its own model (the decision point and the tests do), and `decide_all` cannot copy it. +- `asyncio.TaskGroup` or an AnyIO task group. Both wrap the first error in an `ExceptionGroup`, which `FAILED` does not catch, so the step would not fail open. AnyIO would also add nothing that the standard library does not give. +- Rely on the `timeout` setting of the model. That is the HTTP timeout of the client, and it does not cover the lock wait or a transport that does not answer. diff --git a/openspec/changes/archive/2026-11-11-4513-decide-all-can-hang-a-test/proposal.md b/openspec/changes/archive/2026-11-11-4513-decide-all-can-hang-a-test/proposal.md new file mode 100644 index 0000000000..9bdd084711 --- /dev/null +++ b/openspec/changes/archive/2026-11-11-4513-decide-all-can-hang-a-test/proposal.md @@ -0,0 +1,36 @@ +# Proposal: #4513 + +## Why + +`decide_all` can stop a test worker for good (#4513). It sent each request in its own pool thread, each with its own event loop from `asyncio.run`, and the callers give one model to all of the requests. The provider of that model holds one `anyio.Lock` and one HTTP client, and both bind to the loop that first uses them. A request that waits for the lock on a second loop does not wake up when the first loop releases it. The calling thread then waits on the pool with no time limit, and the pool exit joins the stuck thread again, so pytest-timeout cannot stop the test. Two CI shards stopped at their 30-minute job limit on 2026-11-11. Closes #4513. + +## What Changes + +- `decide_all` sends all requests of one call on one event loop in the calling thread, with `asyncio.gather`. An `asyncio.Semaphore` keeps the limit of `CONST_ROADMAP_DECISION_STEP_CONCURRENCY` requests at the same time. +- `asyncio.timeout` bounds each request, the wait for the lock of the model included. A request that does not end raises `TimeoutError`, which is in `FAILED`, so the step fails open. +- The default `timeout` of `decide_all` is `CONST_ROADMAP_JEV_TIMEOUT_SECONDS`, the limit of one Jev request, in place of the literal `30.0`. +- The fake of the Jev endpoint records the event loop of each request and can hold a request open until the test releases it. + +The change alters behavior that a caller sees (a stuck request now ends in `TimeoutError`), so it carries a delta of the `decision-steps` capability. + +## Capabilities + +- `decision-steps`: ADDED requirement for one event loop and a time limit for each request. + +## Impact + +- `src/devops_cli/roadmap/decision_step.py`: `decide_all` and `_decide_one`; the `ThreadPoolExecutor` fan-out is removed. +- `tests/support/fakes/jev.py` and `tests/roadmap/test_roadmap_decision_step.py`. +- `src/devops_cli/config/constants.py`: the comment of `CONST_ROADMAP_JEV_TIMEOUT_SECONDS` names the decision step as a second user. +- A caller must not call `decide_all` from a thread that runs an event loop, because `asyncio.run` refuses that. The callers (the stage review screen, the screen evaluation and the decision-point resolver) are synchronous code, as are the other Jev calls of `devops_cli.ai.jev`, which also use `asyncio.run`. +- The change fits one pull request. + +## Feasibility + +- Library source, pydantic-ai-slim 2.59.0: `Provider._enter_lock` in `pydantic_ai/providers/__init__.py` is a cached `anyio.Lock`, and its comment says that the lock binds to the event loop on which it is first used. `Provider.__aenter__` and `__aexit__` take that lock for each request. anyio is 4.15.1. +- The traceback of #4513 shows the main thread in `ThreadPoolExecutor.__exit__` → `shutdown` → `Thread.join`, and the pool thread in `asyncio.run` → `selectors.select`, so the wait has no limit at two levels. +- Command output on base 5f75d256 with the new tests: `uv run pytest tests/roadmap/test_roadmap_decision_step.py` gave `test_a_shared_model_serves_every_request_on_one_event_loop - assert 3 == 1` (three loops for one model) and `test_a_request_that_is_never_answered_ends_in_timeout_error - _queue.Empty` after the 30 s bound of the test. + +## Existing Tool Considered + +The standard library `asyncio` covers the need: `asyncio.run`, `asyncio.gather`, `asyncio.Semaphore` and `asyncio.timeout`. No new dependency. The change deletes the `ThreadPoolExecutor` fan-out of `decide_all` and the `asyncio.run` for each request in `_decide_one`. diff --git a/openspec/changes/archive/2026-11-11-4513-decide-all-can-hang-a-test/specs/decision-steps/spec.md b/openspec/changes/archive/2026-11-11-4513-decide-all-can-hang-a-test/specs/decision-steps/spec.md new file mode 100644 index 0000000000..065a95eba3 --- /dev/null +++ b/openspec/changes/archive/2026-11-11-4513-decide-all-can-hang-a-test/specs/decision-steps/spec.md @@ -0,0 +1,12 @@ +## ADDED Requirements + +### Requirement: Decision requests use one event loop and a time limit +`decide_all` SHALL send all requests of one call on one event loop in the calling thread, so that a model that the requests share stays on the loop of its lock and client. It SHALL raise `TimeoutError` when a request does not end within `timeout` seconds, so that the step fails open and no caller waits for good. + +#### Scenario: A shared model serves every request on one loop +- **WHEN** `decide_all` sends three requests with one model over a fake Jev endpoint +- **THEN** the endpoint records the same event loop for the three requests + +#### Scenario: A request that is never answered +- **WHEN** the fake Jev endpoint holds a request open and `decide_all` runs with a timeout of 0.01 seconds +- **THEN** `decide_all` raises `TimeoutError` diff --git a/openspec/changes/archive/2026-11-11-4513-decide-all-can-hang-a-test/tasks.md b/openspec/changes/archive/2026-11-11-4513-decide-all-can-hang-a-test/tasks.md new file mode 100644 index 0000000000..f5f019bd00 --- /dev/null +++ b/openspec/changes/archive/2026-11-11-4513-decide-all-can-hang-a-test/tasks.md @@ -0,0 +1,12 @@ +# Tasks + +## 1. One event loop and a time limit for each request + +Kind: behavior. Reads: `src/devops_cli/roadmap/decision_point.py`, `src/devops_cli/roadmap/stage/stage_screen_eval.py`. Changes: `src/devops_cli/roadmap/decision_step.py`, `src/devops_cli/config/constants.py`, `tests/support/fakes/jev.py`, `tests/roadmap/test_roadmap_decision_step.py`. + +- [x] 1.1 Write `test_a_shared_model_serves_every_request_on_one_event_loop` and `test_a_request_that_is_never_answered_ends_in_timeout_error`, and watch them fail on the base (three loops, and the 30 s bound of the test) + - Verification: `$ uv run devops ci fail-to-pass --base origin/main` +- [x] 1.2 Send all requests of `decide_all` on one event loop with `asyncio.gather`, bound each request with `asyncio.timeout`, and default `timeout` to `CONST_ROADMAP_JEV_TIMEOUT_SECONDS` + - Verification: `$ uv run pytest -q tests/roadmap/test_roadmap_decision_step.py` + +- Pending a person: review the diff in tuicr (tuicr -r origin/main..HEAD). diff --git a/openspec/specs/decision-steps/spec.md b/openspec/specs/decision-steps/spec.md index 2cb85a4d37..b87b5f1ee6 100644 --- a/openspec/specs/decision-steps/spec.md +++ b/openspec/specs/decision-steps/spec.md @@ -68,3 +68,14 @@ A decision step SHALL send the case to the existing path when Jev raises an erro #### Scenario: No decision model is configured - **WHEN** a decision step runs with `ai.decision_model` empty - **THEN** the existing path runs and no request goes to Jev + +### Requirement: Decision requests use one event loop and a time limit +`decide_all` SHALL send all requests of one call on one event loop in the calling thread, so that a model that the requests share stays on the loop of its lock and client. It SHALL raise `TimeoutError` when a request does not end within `timeout` seconds, so that the step fails open and no caller waits for good. + +#### Scenario: A shared model serves every request on one loop +- **WHEN** `decide_all` sends three requests with one model over a fake Jev endpoint +- **THEN** the endpoint records the same event loop for the three requests + +#### Scenario: A request that is never answered +- **WHEN** the fake Jev endpoint holds a request open and `decide_all` runs with a timeout of 0.01 seconds +- **THEN** `decide_all` raises `TimeoutError` diff --git a/src/devops_cli/config/constants.py b/src/devops_cli/config/constants.py index 1b8d3fd01b..a576632389 100644 --- a/src/devops_cli/config/constants.py +++ b/src/devops_cli/config/constants.py @@ -3721,7 +3721,8 @@ class WebhookExposure(StrEnum): # The least probability of a noul answer that flags a nearest item as the possible original of a # candidate. A false duplicate is worse than a missed one, so the bar is high. CONST_ROADMAP_JEV_DUPLICATE_THRESHOLD: Final[float] = 0.90 -# The seconds that one request to Jev may take before intake uses the triage model. +# The seconds that one request to Jev may take. Then intake uses the triage model, and a decision +# step fails open (#4513). CONST_ROADMAP_JEV_TIMEOUT_SECONDS: Final[float] = 30.0 # The most model calls that `devops roadmap eval jev` makes. At about 0.042 USD for 1M input # tokens of Jev and a few cents for the triage model, this keeps a run under 1 USD. diff --git a/src/devops_cli/roadmap/decision_step.py b/src/devops_cli/roadmap/decision_step.py index a3c6f212df..73af4c1ec9 100644 --- a/src/devops_cli/roadmap/decision_step.py +++ b/src/devops_cli/roadmap/decision_step.py @@ -7,9 +7,11 @@ in the repository with the model, the date and the numbers that gave them. - `band_of`: the band for the probabilities of a case. A probability under `continue_below` for every question is *continue*. One at or above `flag_at` is *flag*. Any other case is *review*. -- `decide_all`: one request for each piece of evidence, sent at the same time. Each request uses - its own model and closes it on the loop that used it, so a second request does not meet a - closed loop (#4319). Any error raises, and the step then fails open to the existing path. +- `decide_all`: one request for each piece of evidence, sent at the same time on one event loop in + the calling thread. A model that the requests share binds its lock and its client to the loop + that first uses them, so all of its requests stay on that loop (#4513). With no model given, + each request builds its own model and closes it on that loop (#4319). `timeout` bounds each + request. Any error raises, and the step then fails open to the existing path. The module sends no text of an answer anywhere. A Jev answer is evidence and never the only control of a path. @@ -20,7 +22,6 @@ import asyncio import json from collections.abc import Mapping, Sequence -from concurrent.futures import ThreadPoolExecutor from enum import StrEnum from pathlib import Path from typing import TYPE_CHECKING, Any, Final, Self, cast @@ -35,7 +36,11 @@ NoulAnswer, ) -from devops_cli.config.constants import CONST_AI_JEV_MODEL, CONST_ROADMAP_DECISION_STEP_CONCURRENCY +from devops_cli.config.constants import ( + CONST_AI_JEV_MODEL, + CONST_ROADMAP_DECISION_STEP_CONCURRENCY, + CONST_ROADMAP_JEV_TIMEOUT_SECONDS, +) from devops_cli.exceptions.base import DevOpsCLIError from devops_cli.lang import MESSAGES @@ -143,23 +148,46 @@ async def _decide_closing( await client.aclose() -def _decide_one( +async def _decide_one( request: DecisionRequest, model: DecisionModel[Any] | None, model_name: str, settings: Settings | None, timeout: float, + slots: asyncio.Semaphore, ) -> DecisionResponse: """The one place that sends a request of a decision step. A model that this call builds from `model_name` serves this request only, and the call closes its client on the loop of the - request (#4319).""" + request (#4319). `timeout` bounds the whole request, so a request that does not end raises + `TimeoutError` (#4513).""" from devops_cli.ai.jev import create_jev_model - decider = model or create_jev_model(model_name, settings=settings) - options = cast( - DecisionModelSettings, {**(getattr(decider, "settings", None) or {}), "timeout": timeout} + async with slots: + decider = model or create_jev_model(model_name, settings=settings) + options = cast( + DecisionModelSettings, + {**(getattr(decider, "settings", None) or {}), "timeout": timeout}, + ) + async with asyncio.timeout(timeout): + return await _decide_closing(request, decider, options, own=model is None) + + +async def _decide_gathered( + requests: Sequence[DecisionRequest], + model: DecisionModel[Any] | None, + model_name: str, + settings: Settings | None, + timeout: float, +) -> list[DecisionResponse]: + slots = asyncio.Semaphore(CONST_ROADMAP_DECISION_STEP_CONCURRENCY) + return list( + await asyncio.gather( + *( + _decide_one(request, model, model_name, settings, timeout, slots) + for request in requests + ) + ) ) - return asyncio.run(_decide_closing(request, decider, options, own=model is None)) def decide_all( @@ -168,19 +196,15 @@ def decide_all( model: DecisionModel[Any] | None = None, model_name: str = CONST_AI_JEV_MODEL, settings: Settings | None = None, - timeout: float = 30.0, + timeout: float = CONST_ROADMAP_JEV_TIMEOUT_SECONDS, ) -> list[DecisionResponse]: - """The responses of the decision model to `requests`, in order, sent at the same time. With no - `model`, each request builds its own model, the one that `model_name` names, from `settings`. - The first error raises.""" + """The responses of the decision model to `requests`, in order, sent at the same time on one + event loop in the calling thread. With no `model`, each request builds its own model, the one + that `model_name` names, from `settings`. A request that takes longer than `timeout` seconds + raises `TimeoutError`. The first error raises.""" if not requests: return [] - with ThreadPoolExecutor(max_workers=CONST_ROADMAP_DECISION_STEP_CONCURRENCY) as pool: - futures = [ - pool.submit(_decide_one, request, model, model_name, settings, timeout) - for request in requests - ] - return [future.result() for future in futures] + return asyncio.run(_decide_gathered(requests, model, model_name, settings, timeout)) __all__ = [ diff --git a/tests/roadmap/test_roadmap_decision_step.py b/tests/roadmap/test_roadmap_decision_step.py index 282043ba8d..530a193cd9 100644 --- a/tests/roadmap/test_roadmap_decision_step.py +++ b/tests/roadmap/test_roadmap_decision_step.py @@ -4,6 +4,8 @@ from __future__ import annotations import json +import queue +import threading from typing import TYPE_CHECKING import pytest @@ -19,6 +21,7 @@ decide_all, probabilities_of, ) +from tests.support.waits import THREAD_HANDOFF_BOUND_SECONDS if TYPE_CHECKING: from pathlib import Path @@ -68,6 +71,40 @@ def test_the_requests_are_answered_in_order_and_each_is_one_request(jev: JevFake assert sorted(jev.asked) == [["a"], ["a", "b"], ["b"]] +def test_a_shared_model_serves_every_request_on_one_event_loop(jev: JevFake) -> None: + """The provider of a model binds its lock and its client to the loop that first uses them, and + a wait on that lock from another loop does not wake (#4513).""" + decide_all([_request("a"), _request("b"), _request("a", "b")], model=jev.model) + + assert len(jev.loops) == 3 + assert len(set(jev.loops)) == 1 + + +def test_a_request_that_is_never_answered_ends_in_timeout_error(jev: JevFake) -> None: + """The timeout of `decide_all` ends a request that the endpoint never answers, so the step + fails open and the caller does not wait for good (#4513). The call runs in a thread of the + test: with no limit, the test fails at the bound and then releases the held request.""" + jev.hold() + outcome: queue.Queue[object] = queue.Queue() + + def call() -> None: + try: + outcome.put(decide_all([_request("a")], model=jev.model, timeout=0.01)) + except Exception as exc: # the test asserts on the error that the call raised + outcome.put(exc) + + caller = threading.Thread(target=call, daemon=True) + caller.start() + try: + result = outcome.get(timeout=THREAD_HANDOFF_BOUND_SECONDS) + finally: + jev.release() + caller.join(THREAD_HANDOFF_BOUND_SECONDS) + + assert type(result) is TimeoutError + assert jev.asked == [] + + def test_a_failed_request_raises_so_the_step_can_fail_open(jev: JevFake) -> None: jev.fail(503) diff --git a/tests/support/fakes/jev.py b/tests/support/fakes/jev.py index 2e502e6832..2ae12714c4 100644 --- a/tests/support/fakes/jev.py +++ b/tests/support/fakes/jev.py @@ -3,12 +3,14 @@ Doubles the `/v1/systemone` endpoint that `SystemOneModel` posts to. The fake is a transport under the real model, so the request body is built and the answers are validated by the library for real: an answer the real endpoint would not send fails the test the way it fails in production. -It answers every question of a request from the picks a test gives, records each request, and -fails a request on demand, without a socket. +It answers every question of a request from the picks a test gives, records each request and +the event loop that sent it, fails a request on demand, and holds a request open until the test +releases it, without a socket. """ from __future__ import annotations +import asyncio import json import threading from collections.abc import Iterator @@ -54,6 +56,10 @@ def __init__(self) -> None: self.requests: list[dict[str, Any]] = [] self.status: int | None = None self.error: Exception | None = None + self.loops: list[asyncio.AbstractEventLoop] = [] + self._held = False + self._waiting: list[tuple[asyncio.AbstractEventLoop, asyncio.Event]] = [] + self._lock = threading.Lock() self._server: ThreadingHTTPServer | None = None self.model: SystemOneModel = SystemOneModel( CONST_AI_JEV_MODEL, @@ -75,6 +81,30 @@ def unreachable(self, error: Exception) -> None: """Raise this transport error for every request.""" self.error = error + def hold(self) -> None: + """Keep every request open until `release`, as an endpoint that never answers does.""" + self._held = True + + def release(self) -> None: + """Answer the held requests and hold no more. A thread other than the one that sends the + requests can call it.""" + with self._lock: + self._held = False + for loop, answered in self._waiting: + loop.call_soon_threadsafe(answered.set) + + async def _wait_while_held(self) -> None: + with self._lock: + if not self._held: + return + entry = (asyncio.get_running_loop(), asyncio.Event()) + self._waiting.append(entry) + try: + await entry[1].wait() + finally: + with self._lock: + self._waiting.remove(entry) + @property def asked(self) -> list[list[str]]: """The question names of each request, in order.""" @@ -114,9 +144,11 @@ def _reply(self, body: dict[str, Any]) -> tuple[int, dict[str, Any]]: usage = {"input_tokens": 64, "output_tokens": len(answers)} return 200, {"model": CONST_AI_JEV_MODEL, "answers": answers, "usage": usage} - def _handle(self, request: httpx2.Request) -> httpx2.Response: + async def _handle(self, request: httpx2.Request) -> httpx2.Response: + self.loops.append(asyncio.get_running_loop()) if self.error is not None: raise self.error + await self._wait_while_held() status, payload = self._reply(json.loads(request.content)) return httpx2.Response(status, json=payload)