Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-11-10
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Design

## Decisions

- **Print the facts on every `stage reply refused` line, not only on `degenerate`.**: A comparison of a `refused` line with a `degenerate` line shows which fact differs, and the code has one path.
- **Put the new fields before `result=`.**: A reader of the end of the line keeps working.
- **Print `none` for a fact the run does not hold.**: A kept plan or a plain client has no run, and an empty value breaks a `key=value` parser.
- **Take `finish_reason` and `answered` from the last reply of the run.**: The last reply is the one that the gates refuse.

## Rejected alternatives

- **Log the text of the reply.**: The reply may hold private data, and `<n>.refused.json` keeps it already with masking (#4204).
- **Add a metric.**: A metric does not tie the facts to one item. The line does, and a later change may count what the line shows.
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Proposal: #4313

## Why

84 of 161 failures of the stage job in 7 days that the checks caused hold a plan reply in which every text is a placeholder, and nothing records why (#4313). The log line `stage reply refused` gives the request number, the input size and whether a tool was offered. It does not give the stop reason of the reply, the number of tool calls, the limit that ended the tools, or the model that answered. Closes #4313.

## What Changes

- `RunTrace` in `src/devops_cli/roadmap/agent_run.py` keeps the stop reason (`finish_reason`) and the model name of the last reply of the run.
- `_note_refused` in `src/devops_cli/roadmap/stage/stage.py` adds `tool_calls`, `limit`, `finish_reason` and `answered` to the log line, for the results `refused` and `degenerate`. `none` stands for a fact that the run does not hold.
- The scripted model of the tests (`tests/support/scripted_model.py`) gives the model name and the finish reason of a scripted reply to its streamed reply, as a provider does.
- The change carries a spec delta because it changes the content of a logged line.

## Capabilities

### New Capabilities

None.

### Modified Capabilities

- `roadmap-stage`: A refused reply is logged

## Impact

- Code: `src/devops_cli/roadmap/agent_run.py`, `src/devops_cli/roadmap/stage/stage.py`
- Tests: `tests/roadmap/stage/test_roadmap_stage_refused_reply.py`, `tests/support/scripted_model.py`
- Log consumers: a query that reads `result=` at the end of the line keeps working, because the new fields come before it.

## Feasibility

- Premise checked in Loki (`service_name=roadmap-service`, 2026-11-04 to 2026-11-10): the placeholder failures are 86 item failures of 50 distinct items, up to 4 times for one item, in 52 failure lines. The last one is from 2026-11-09 16:24Z. Since the line `stage reply refused` exists (first line 2026-11-09 22:55Z), Loki holds 16 refused replies and no degenerate one.
- The cause is not shown by the old lines, so the log gets the facts first. The facts exist in the run: `ModelResponse.finish_reason` and `ModelResponse.model_name` of pydantic-ai 2.59.0, the tool calls and the limit of `RunTrace`.
- Findings from the metrics, to read with the new line: `devops_cli_ai_model_answers_total` shows only `asked == answered` (no gateway fallback) since it exists; the placeholders began before the Sonnet trial (2026-11-04) and none fell in the trial hours (11:00Z to 12:25Z on 2026-11-09); `devops_cli_roadmap_tool_limit_hits_total{limit="window"}` fell from 20 to 37 hits per 3 hours to 2 to 8 hits per 3 hours after #4238 (merged 2026-11-09 16:57Z), the same hours in which the placeholder replies stopped.
- Check: `uv run devops ci test tests/roadmap/stage/test_roadmap_stage_refused_reply.py`, and `uv run devops roadmap eval stage --replay` keeps its result.

## Existing Tool Considered

`RunTrace` and `ModelResponse` already hold the facts, and `logging` prints them. No library is needed. The change adds two fields and four log fields. Cost: about 25 000 tokens to build, 2 000 to keep and 1 hour.
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
## MODIFIED Requirements

### Requirement: A refused reply is logged
The stage job SHALL log one line `stage reply refused` for each reply of the model that it refuses, with the number of the item, the number of the last request of the plan run, the input of that request in tokens, whether that request offered a function tool, the number of tool calls of the run, the limit that ended its tools, the stop reason and the model name of the last reply, and the result `refused` or `degenerate`. A fact that the run does not hold SHALL be written as `none`.

#### Scenario: A reply that the gates refuse
- **WHEN** the gates refuse the reply of item 1 in the second request of a plan run, and that request offered a tool
- **THEN** the log holds one line with `item=#1`, `request=2`, the input of the request in tokens, `tools_offered=True` and `result=refused`

#### Scenario: A degenerate reply that a provider stopped at its length
- **WHEN** the reply of item 1 is a placeholder in every text, after one tool call, and its stop reason is `length` and its model name is `fallback-model`
- **THEN** the log holds one line with `tool_calls=1`, `limit=none`, `finish_reason=length`, `answered=fallback-model` and `result=degenerate`

#### Scenario: A plan with no run
- **WHEN** the gates refuse a kept plan that no toolbox run made
- **THEN** the log holds one line with `tool_calls=0`, `limit=none`, `finish_reason=none` and `answered=none`
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Tasks

## 1. Log the stop facts of a refused reply

Reads: `src/devops_cli/roadmap/agent_run.py`, `src/devops_cli/roadmap/stage/stage.py`. Changes: `src/devops_cli/roadmap/agent_run.py`, `src/devops_cli/roadmap/stage/stage.py`, `tests/roadmap/stage/test_roadmap_stage_refused_reply.py`, `tests/support/scripted_model.py`.

- [x] 1.1 In `tests/roadmap/stage/test_roadmap_stage_refused_reply.py`, assert that the line of a degenerate reply holds `tool_calls`, `limit`, `finish_reason` and `answered`
- Verification: `$ uv run devops ci test tests/roadmap/stage/test_roadmap_stage_refused_reply.py` fails on the base
- [x] 1.2 In `src/devops_cli/roadmap/agent_run.py` and `src/devops_cli/roadmap/stage/stage.py`, keep the stop reason and the model name of the last reply and print the four fields
- Verification: `$ uv run devops ci test tests/roadmap/stage/test_roadmap_stage_refused_reply.py` passes

## 2. Keep the golden replay

- [x] 2.1 Run the replay and state that every gate refuses what it must refuse and that 5 of 5 good plans pass
- Verification: `$ uv run devops roadmap eval stage --replay`

## Workflow follow-up

- Pending a person: review the diff in tuicr (tuicr -r <base>..HEAD).
- Pending a person: read the new line after the next deploy, and fix the cause at its source in a later change.
10 changes: 9 additions & 1 deletion openspec/specs/roadmap-stage/spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -3737,12 +3737,20 @@ A plan run or a review run of the stage job that ends because a tool call of its
- **THEN** the stop is not marked as a stop by invalid arguments

### Requirement: A refused reply is logged
The stage job SHALL log one line `stage reply refused` for each reply of the model that it refuses, with the number of the item, the number of the last request of the plan run, the input of that request in tokens, whether that request offered a function tool, and the result `refused` or `degenerate`.
The stage job SHALL log one line `stage reply refused` for each reply of the model that it refuses, with the number of the item, the number of the last request of the plan run, the input of that request in tokens, whether that request offered a function tool, the number of tool calls of the run, the limit that ended its tools, the stop reason and the model name of the last reply, and the result `refused` or `degenerate`. A fact that the run does not hold SHALL be written as `none`.

#### Scenario: A reply that the gates refuse
- **WHEN** the gates refuse the reply of item 1 in the second request of a plan run, and that request offered a tool
- **THEN** the log holds one line with `item=#1`, `request=2`, the input of the request in tokens, `tools_offered=True` and `result=refused`

#### Scenario: A degenerate reply that a provider stopped at its length
- **WHEN** the reply of item 1 is a placeholder in every text, after one tool call, and its stop reason is `length` and its model name is `fallback-model`
- **THEN** the log holds one line with `tool_calls=1`, `limit=none`, `finish_reason=length`, `answered=fallback-model` and `result=degenerate`

#### Scenario: A plan with no run
- **WHEN** the gates refuse a kept plan that no toolbox run made
- **THEN** the log holds one line with `tool_calls=0`, `limit=none`, `finish_reason=none` and `answered=none`

### Requirement: A failed item keeps its refused replies
When a plan fails, the stage job SHALL write the refused replies and their problems to the file `<n>.refused.json` beside the plan file of item `<n>`, under the key of the plan input. A new failed plan SHALL replace the file, and the staging of the item SHALL delete it. A reply over the byte bound SHALL be dropped with its size kept, and a problem SHALL be masked for secrets and cut to the character bound.

Expand Down
10 changes: 9 additions & 1 deletion src/devops_cli/roadmap/agent_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,9 @@ class RunTrace:
(#3039). A request that offered none holds an empty tuple. `limit` is the limit that ended the
tools of the run, or None (#3240). `last_input_tokens` is the input of the last request, the one
that the last reply answered (#4204). `row` is the job row of the run, such as the plan or the
review of the stage job, and is empty for a run that no job names (#4257)."""
review of the stage job, and is empty for a run that no job names (#4257). `finish_reason` and
`answered` are the stop reason and the model name of the last reply, and are empty when the
provider gave none (#4313)."""

tool_calls: list[ToolCallRecord] = field(default_factory=list)
requests: int = 0
Expand All @@ -216,6 +218,8 @@ class RunTrace:
limit: RunLimit | None = None
tool_answers: list[str] = field(default_factory=list)
last_input_tokens: int = 0
finish_reason: str = ""
answered: str = ""
row: str = ""

@classmethod
Expand All @@ -233,6 +237,8 @@ def combined(cls, traces: Iterable[RunTrace]) -> RunTrace:
total.violations = trace.violations or total.violations
total.violation_texts = trace.violation_texts or total.violation_texts
total.last_input_tokens = trace.last_input_tokens or total.last_input_tokens
total.finish_reason = trace.finish_reason or total.finish_reason
total.answered = trace.answered or total.answered
total.limit = trace.limit or total.limit
return total

Expand Down Expand Up @@ -279,6 +285,8 @@ def _add_reply(
) -> None:
self.requests += 1
self.last_input_tokens = reply.usage.input_tokens
self.finish_reason = reply.finish_reason or ""
self.answered = reply.model_name or ""
self.input_tokens += reply.usage.input_tokens
self.output_tokens += reply.usage.output_tokens
for part in reply.parts:
Expand Down
15 changes: 11 additions & 4 deletions src/devops_cli/roadmap/stage/stage.py
Original file line number Diff line number Diff line change
Expand Up @@ -1192,17 +1192,24 @@ def _toolbox_traces(self) -> list[RunTrace]:

def _note_refused(self, target: StageTarget, floor: int, result: str) -> None:
"""Log one line for a refused reply: the item, the number of the last request of the plan
run and its input in tokens, whether that request offered a tool, and the result. `floor`
is the number of runs before this item was asked, so a run of another item is no source. A
plan that no toolbox run made (a kept plan, a plain client) is one request with no count."""
run and its input in tokens, whether that request offered a tool, the tool calls of the
run, the limit that ended its tools, the stop reason and the model of the last reply, and
the result (#4313). `floor` is the number of runs before this item was asked, so a run of
another item is no source. A plan that no toolbox run made (a kept plan, a plain client)
is one request with no count, and `none` stands for a fact that the run does not hold."""
traces = self._toolbox_traces()
trace = traces[-1] if len(traces) > floor else None
logger.warning(
"stage reply refused: item=#%d request=%d input_tokens=%d tools_offered=%s result=%s",
"stage reply refused: item=#%d request=%d input_tokens=%d tools_offered=%s "
"tool_calls=%d limit=%s finish_reason=%s answered=%s result=%s",
target.item.number,
trace.requests if trace else 1,
trace.last_input_tokens if trace else 0,
bool(trace and trace.offered and trace.offered[-1]),
len(trace.tool_calls) if trace else 0,
(trace.limit if trace else None) or "none",
(trace.finish_reason if trace else "") or "none",
(trace.answered if trace else "") or "none",
result,
)

Expand Down
41 changes: 39 additions & 2 deletions tests/roadmap/stage/test_roadmap_stage_refused_reply.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from typing import TYPE_CHECKING, Any, cast

import pytest
from pydantic_ai.messages import ModelResponse, ToolCallPart

from devops_cli.ai.client.models import StructuredOutputValidationError
from devops_cli.config.constants import (
Expand Down Expand Up @@ -297,10 +298,42 @@ def test_a_refused_reply_of_a_plan_run_logs_the_request_size_the_request_number_

(record,) = [r for r in caplog.records if "stage reply refused" in r.getMessage()]
tokens = client.traces[-1].last_input_tokens
finish = client.traces[-1].finish_reason or "none"
answered = client.traces[-1].answered or "none"
assert tokens > 0
assert record.getMessage() == (
f"stage reply refused: item=#1 request=2 input_tokens={tokens} tools_offered=True "
"result=degenerate"
f"tool_calls=1 limit=none finish_reason={finish} answered={answered} result=degenerate"
)


def test_the_log_line_of_a_degenerate_reply_names_the_stop_reason_the_limit_and_the_model(
store: InMemoryRoadmapStore,
stage_repo: StageRepo,
caplog: pytest.LogCaptureFixture,
) -> None:
item = store.item(1)
assert item is not None
sha = stage_repo.git("rev-parse", "HEAD")
reply = ModelResponse(
parts=[
ToolCallPart(tool_name="final_result", args=_placeholders().model_dump()),
],
model_name="fallback-model",
finish_reason="length",
)
script = Script(call("list_files", directory="src"), reply, reports_input=True)
client = ToolboxClient(script.model(), cast("StageClient", object()), stage_repo.clone, sha)

with (
caplog.at_level(logging.WARNING),
pytest.raises(RoadmapStageDegenerateError, match="placeholder"),
):
plan_item(item, client=client, checkout=stage_repo.clone, sha=sha)

(record,) = [r for r in caplog.records if "stage reply refused" in r.getMessage()]
assert record.getMessage().endswith(
"tool_calls=1 limit=none finish_reason=length answered=fallback-model result=degenerate"
)


Expand All @@ -317,7 +350,11 @@ def test_a_gate_refusal_logs_one_line_for_each_refused_reply(

lines = [r.getMessage() for r in caplog.records if "stage reply refused" in r.getMessage()]
assert [line.rsplit(" ", 1)[1] for line in lines] == ["result=refused", "result=refused"]
assert all("item=#1 request=1 input_tokens=0 tools_offered=False" in line for line in lines)
assert all(
"item=#1 request=1 input_tokens=0 tools_offered=False tool_calls=0 limit=none "
"finish_reason=none answered=none result=" in line
for line in lines
)


# ── The reply that breaks the schema ──────────────────────────────────────────
Expand Down
28 changes: 24 additions & 4 deletions tests/support/scripted_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

from pydantic import BaseModel
from pydantic_ai.messages import (
FinishReason,
ModelMessage,
ModelResponse,
TextPart,
Expand All @@ -29,7 +30,12 @@
class _ReportingModel(FunctionModel):
"""A `FunctionModel` whose streamed replies report the input of the request, as a provider
does (#4221). The usage that a streamed `FunctionModel` estimates by itself is a constant that
does not follow the messages."""
does not follow the messages. A scripted `ModelResponse` also gives its model name and its
finish reason to the streamed reply, as a provider does (#4313)."""

def __init__(self, script: Script) -> None:
super().__init__(script, stream_function=script.stream)
self._script = script

@asynccontextmanager
async def request_stream(
Expand All @@ -43,6 +49,16 @@ async def request_stream(
messages, model_settings, model_request_parameters, run_context
) as response:
response._usage = RequestUsage(input_tokens=tokens_of(messages))
events = response._get_event_iterator

async def with_reply_facts() -> AsyncIterator[Any]:
async for event in events():
yield event
name, reason = self._script.reply_facts
response._model_name = name or response._model_name
response.finish_reason = reason

response._get_event_iterator = with_reply_facts
yield response


Expand All @@ -66,6 +82,7 @@ def __init__(
self.seen: list[list[ModelMessage]] = []
self.tools_offered: list[list[str]] = []
self.instructions: list[str | None] = []
self.reply_facts: tuple[str | None, FinishReason | None] = (None, None)

def __call__(self, messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
self.seen.append(list(messages))
Expand All @@ -89,7 +106,9 @@ async def stream(
self, messages: list[ModelMessage], info: AgentInfo
) -> AsyncIterator[str | DeltaToolCalls]:
"""The same answer as a stream, as the investigation asks for it."""
for index, part in enumerate(self(messages, info).parts):
answer = self(messages, info)
self.reply_facts = (answer.model_name, answer.finish_reason)
for index, part in enumerate(answer.parts):
if isinstance(part, ToolCallPart):
yield {
index: DeltaToolCall(
Expand All @@ -104,8 +123,9 @@ async def stream(
def model(self) -> FunctionModel:
"""A `FunctionModel` that answers through this script, streamed or not. With
`reports_input`, its streamed replies report the input of the request."""
cls = _ReportingModel if self.reports_input else FunctionModel
return cls(self, stream_function=self.stream)
if self.reports_input:
return _ReportingModel(self)
return FunctionModel(self, stream_function=self.stream)

def prompt(self, request: int = 0) -> str:
"""The user prompt of the request at index `request`."""
Expand Down
Loading