Skip to content

fix(roadmap): the stage window estimate drops tools too early #4221

Closed

Description

@dan-petty

Problem

The stage run takes the function tools from the model too early. The run counts the input with tokens_of (src/devops_cli/roadmap/refine/refine_investigation.py). tokens_of counts the tokens of the JSON dump of the messages (ModelMessagesTypeAdapter.dump_json), and the dump is longer than the text that the model reads. _limit_reached compares this count with tool_stop(window). tool_stop(200000) is 150,000 (CONST_ROADMAP_INVESTIGATION_REPLY_WINDOW_SHARE is 4).

Live run of 2026-11-09 (devops roadmap stage --plan --item 3599, model claude-sonnet-5-5, window 200000, 15 requests):

  • The real input of request 13 was about 105,000 tokens (usage of the reply). The estimate was about 1.4 times higher, so it passed 150,000.
  • Request 14 offered only final_result. The model still asked for read_file and search_code.
  • pydantic-ai answered with the retry prompt "Unknown tool name: 'read_file'. Available tools: 'final_result'". This used the one output retry (_REPLY_RETURNS is 1, in chat_structured).
  • The next fault (the 4096 output limit, fix(roadmap): a Claude stage reply stops at 4096 tokens #4220) then ended the run with no second retry.

At the real input, the run had about 95,000 tokens of room before the limit. It gave up that room, and the model had no chance to finish its reading. Not verified: how often other runs (#3592, #3576, #4004, #3612, #4028, #4043) stop for this cause.

Expected

  • The count tracks the real input within 10 percent. The source is the usage of the last reply (input_tokens) plus the tokens that were added after it. For the first request, which has no reply yet, the source is a token count of the text parts of the messages, not of their JSON dump. No fixed factor such as 1.4 is used.
  • The function tools stay offered until the real input passes the window minus the room for the reply.

Acceptance criteria

  1. A test builds the messages of a run: a first request, then replies with tool calls and tool returns of file text, where the last reply has usage.input_tokens of 105,412. It asserts that tokens_of(messages) is within 10 percent of 105,412. It fails today, because tokens_of ignores the usage and the estimate is about 1.4 times higher.
  2. A test runs _limit_reached with the same messages and a window of 200000, and asserts that it returns None (the tools stay offered). It fails today: it returns RunLimit.WINDOW.
  3. A test for the same run asserts that the retry prompt names the offered tools. It passes today (pydantic-ai names them), so it guards the text of the return.
  4. uv run devops roadmap stage --plan --item 3599 with the Service config offers the function tools in every request whose real input is under 150,000 tokens. Today request 14 offers none at about 105,000.

Existing tool considered

  • The usage of the last reply is in the pydantic-ai messages already (ModelResponse.usage). It is the count of the provider and needs no new tool.
  • tiktoken through count_tokens (src/devops_cli/ai/context_budget.py, model gpt-4o) is the project counter, and the stage uses it for its plan checks. It is not the tokenizer of Claude, so it serves only for the first request and for the tokens added since the last reply. tokens_of uses it today, but on the JSON dump.
  • No new tool is built.

Cost

Tokens to build: about 60,000 (one function, three tests). Tokens to keep: none. Tokens to fix a second fault, if the live run shows one: unknown. Elapsed time: about 1.5 hours, plus one live stage run on Sonnet (about 1 to 3 USD).

Related

#4220 (the output limit of 4096 tokens, found in the same run), #3529 (a return request leaves room for the planner tools), #3880 (closed: the stage job fails when the window starves the planner).

Scope note (2026-11-09)

The third bullet of Expected and criterion 3 were removed. Their premise was false: pydantic-ai handles an unknown tool name as a per-tool retry (budget retries['tools'], 2 here), not as an output retry. A run that asks for a tool that is not offered, then answers, ends with the answer. The loss at request 15 of the live run came from the 4096 output cut (#4220). Pull request #4238 delivers the other criteria.

Proposed design

Problem statement

The stage run takes the function tools from the model too early. tokens_of counts the tokens of the JSON dump of the messages. The dump is about 1.4 times longer than the text that the model reads. _limit_reached therefore passes tool_stop(window) at about 105,000 real tokens, and request 14 offers only final_result. The model still asks for read_file. pydantic-ai answers with an unknown-tool retry that spends the single output retry. The next fault then ends the run.

Acceptance criteria

Requirement: Count follows the usage of the last reply

The function tokens_of SHALL return a count within 10 percent of usage.input_tokens of the last reply, plus the tokens added after that reply.

Scenario: Last reply reports 105,412 input tokens

  • WHEN The messages hold a first request, replies with tool calls, tool returns of file text, and a last reply with usage.input_tokens of 105,412
  • THEN tokens_of(messages) is within 10 percent of 105,412

Requirement: Count of the first request uses text parts

The function tokens_of SHALL count the text parts of the messages, and not their JSON dump, when no reply exists yet.

Scenario: First request with no reply

  • WHEN The messages hold only the instructions and the first request
  • THEN tokens_of(messages) equals the token count of the text parts and is below the count of the JSON dump

Requirement: Tools stay offered below the stop

The function _limit_reached SHALL return None while the real input is below the window minus the room for the reply.

Scenario: Real input of 105,412 with a window of 200000

  • WHEN _limit_reached runs with the messages of the first criterion and a window of 200000
  • THEN It returns None and does not return RunLimit.WINDOW

Requirement: Unknown tool request does not spend the output retry

The function investigate MUST NOT spend the single output retry when the model asks for a tool that the request does not offer.

Scenario: Model asks for read_file while only final_result is offered

  • WHEN A test model asks for read_file in a request that offers only final_result, and then answers with a valid final_result
  • THEN The run ends with that valid answer

Requirement: Return names the offered tools

The return for a request of a tool that is not offered SHALL name the tools that are offered and SHALL tell the model to call final_result.

Scenario: Retry prompt of the unknown tool

  • WHEN The test model asks for read_file while only final_result is offered
  • THEN The retry prompt names final_result as the offered tool and tells the model to call it

Existing Tool Considered

pydantic-ai already holds the provider count: ModelResponse.usage.input_tokens of the last reply needs no new tool. tiktoken through count_tokens (src/devops_cli/ai/context_budget.py) is the project counter. It is not the Claude tokenizer, so it serves only for the first request and for the tokens added after the last reply. For the unknown-tool return, pydantic-ai's own hooks (the PrepareTools capability that investigate already uses, and its retry settings) are the tool, and no new library is built. Cost to build: about 60,000 tokens (one function and four tests) and about 1.5 hours, plus one live stage run on Sonnet (about 1 to 3 USD). Cost to keep: none.

Key questions

  • Why does the count pass the limit at about 105,000 real tokens?: tokens_of counts the JSON dump of the messages (ModelMessagesTypeAdapter.dump_json). The dump is longer than the text the model reads, so the count is about 1.4 times the real input. _limit_reached compares this count with tool_stop(window). [sources: src/devops_cli/roadmap/refine/refine_investigation.py:355, src/devops_cli/roadmap/refine/refine_investigation.py:392]
  • What source gives the count of the input tokens?: Use usage.input_tokens of the last ModelResponse, plus the token count of the text parts of every message after it. The text parts are the instructions, the user prompts, the tool returns and the text and tool-call arguments of replies. For a run with no reply, count the text parts of the messages. Use no fixed factor. (best practice) [sources: src/devops_cli/roadmap/refine/refine_investigation.py:392, src/devops_cli/ai/context_budget.py]
    • Chosen: Provider usage plus the text added after it. The provider count is exact for the model, and tiktoken only measures the small added part.
    • Rejected: A fixed factor on the JSON dump count. The factor changes with the content, and the body forbids it.
    • Rejected: tiktoken on the text parts only. It is not the Claude tokenizer, so the error grows with each request. It serves only for the first request.
  • How does a request for an unoffered tool avoid the spend of the output retry?: The unknown-tool retry is raised by pydantic-ai and counts against the output retries that investigate sets (retries={'tools': ..., 'output': ...}). investigate already owns the hook _offering, so the smallest change is in investigate. Keep pydantic-ai's return text, which already names the offered tools. Give the run one more output retry only when a request offered no function tool, by adding it to the output value of retries. That is not a custom retry loop. If the installed pydantic-ai gives a capability hook that turns an unknown tool call into a retry outside the output budget, use that hook instead. The build checks the installed pydantic_ai source for it, and the criterion 4 test shows which of the two works. The search of the web gave no page on this hook, so the source is the code of investigate. (best practice) [sources: src/devops_cli/roadmap/refine/refine_investigation.py:373, src/devops_cli/roadmap/refine/refine_investigation.py:497, src/devops_cli/roadmap/refine/refine_investigation.py:503]
    • Chosen: One more output retry when the run offers no function tool. It uses the retry setting of pydantic-ai, needs a few lines in investigate, and keeps its return text that names the offered tools.
    • Rejected: A pydantic-ai capability hook that handles the unknown tool call. The hook is not verified in the installed version, so it is the fallback if the test shows it is simple.
    • Rejected: Offer the function tools as a stub that returns a call-final_result message. It defeats the purpose of taking the tools away and costs tokens for the tool definitions.

Fit

Fits in one pull request.

Suspected block

None.

Dependencies

None.

Activity

  1. added
    source/agent
    type/bug
    scope/roadmap
    status/new
    value/high
    effort/medium
    on Nov 9, 2026
  2. dan-petty commented on Nov 9, 2026

    @dan-petty
    OwnerAuthor

    Intake placed this item to the backlog: intake puts every new item in the backlog. A person plans the milestones.

    • Type: type/bug. The fix prefix of the title gives the type.
    • Scope: scope/roadmap. The (roadmap) scope of the title gives the scope.
    • Priority: P1-High. Production stage runs lose all function tools mid-run and cannot finish, which blocks the roadmap pipeline.
    • Value: High. Every affected stage run produces an incomplete or failed result, so the fix restores correct behaviour for all users of the stage command.
    • Effort: Medium. One function rewrite plus three tests, estimated at about 1.5 hours in the body.
    • Related: fix(roadmap): a plan request leaves room for the planner tools #3477, which asks for a different change. Both deal with the window limit dropping tools too early in the same file, but #3477 fixes the first-request size while this candidate fixes the inflated estimate for all requests.
  3. added
    priority/p1-high
    owner/agent
    on Nov 9, 2026
  4. added
    status/ready
    and removed
    status/new
    on Nov 9, 2026
  5. devops-cli-service commented on Nov 9, 2026

    @devops-cli-service
    Contributor

    Status set to Ready at 7411967 (see proposed design in issue body).

  6. added
    status/in-progress
    and removed
    status/ready
    on Nov 9, 2026
  7. dan-petty commented on Nov 9, 2026

    @dan-petty
    OwnerAuthor

    Scope note for pull request #4238.

    Criterion 3 and the third bullet of Expected (an unknown-tool request must not spend the output retry) have a false premise. pydantic-ai handles an unknown tool name as a per-tool retry (budget retries['tools'], 2 here), not as an output retry. A run of investigate() with a model that asks for read_file while no tool is offered, then answers, ends with the answer, also after two rounds. A third round stops with "exceeded max retries count of 2", which existing tests cover. The loss at request 15 of the live run came from the 4096 output cut (#4220).

    Pull request #4238 delivers criteria 1, 2 and 5. Criteria 3 and 4 are dropped, not moved: nothing is left to build. A guard test of the retry text is in the pull request and passes today.

  8. added
    status/in-review
    and removed
    status/in-progress
    on Nov 9, 2026
  9. added a commit that references this issue on Nov 9, 2026
    af9c27a
  10. removed
    status/in-review
    owner/agent
    on Nov 9, 2026
  11. devops-cli-service commented on Nov 9, 2026

    @devops-cli-service
    Contributor

    Live since 2026-11-09 17:44 UTC

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    effort/mediumpriority/p1-highscope/roadmapsource/agenttype/bugvalue/high

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions