Skip to content

fix(platform): book usage when a refusal cuts a streamed tool call - #5079

Closed
tale-code-bot wants to merge 1 commit into
mainfrom
fix/tool-only-stream-failure-usage
Closed

tale-code-bot wants to merge 1 commit into
mainfrom
fix/tool-only-stream-failure-usage

Conversation

@tale-code-bot

Copy link
Copy Markdown
Collaborator

Task: TALE-55 (Development board), from #4050.

What was wrong

A direct chat stream hands its tool calls to the turn only when it settles, whole (streamSse in backend/core/chat/turn_action.ts keeps the fragments in the decoder's drafts). When the provider reported a refusal on the stream (an in-stream 429, Anthropic rate_limit_error, Responses rate_limit_exceeded) after the model had begun a tool call, the stream threw before that settle. streamWithOutputGuardrails (lib/chat/turn.ts) had seen no answer, so runTurn's failure accounting classified the round as refused before any answer and booked nothing: no ledger row and no usage on the failed reply. The provider had read the prompt and the model had written.

I re-confirmed the defect on main at 9be5cadacb5f59cd6b2cc67c7840e3c0101bdde2 with a local, synthetic probe through streamProviderAnswer → streamSse → runTurn. It used in-memory SSE and an inert store, ledger and executor. fetch was stubbed to throw and was never called. The probe showed the defect for OpenAI-compatible, Anthropic (with message_start reporting no input) and Responses streams. A completed 80/20 round followed by a fragment-then-429 round booked only 80/20.

The fix

  • ModelStreamChunk gets toolCallStarted?: true. It is a monotonic evidence signal and is never a call to run; executable calls stay on toolCalls alone.
  • streamSse yields the signal once per stream, on the first event after which a draft carries a tool name or argument bytes.
  • The following are not evidence: an id-only, index-only or empty fragment, an empty role, a bare finish reason, a keep-alive, empty metadata, a zero-count usage frame, and the fragments of the failure event itself (that event is read for its usage alone, as before).
  • The turn counts the signal as answer evidence. The failure path (roundUsage and the usageBooked guard) is reused unchanged, so the round is booked once. Reported counts are kept, estimated sides are marked estimated: true, and zero-count metadata stays non-billable.
  • Execution is unchanged. Only toolCalls from a normal settle run, never after a failure or a stop.
  • The counting boundary is now stated in roundUsage's comment. The output estimate is the streamed text and reasoning and never a tool call's name or arguments, on every round, finished or cut. A failed tool-only round is therefore estimated at its prompt and zero output. Estimating tool-call output on every path would be a separate change.
  • stream_decode.ts and the model endpoints for API keys (domains/model_api) are untouched.
  • tests/manual/reference/automation.md: the CHAT-F57/F58 row now names the new boundary.

Tests

The tests run synthetic SSE through the real streamProviderAnswer → streamSse → runTurn, with no network:

  • backend/core/chat/turn_action.test.ts, new streamSse — a tool call the model began:
    • exactly one signal chunk, and toolCalls only on the settle chunk, for OpenAI-compatible and Anthropic streams;
    • no call is handed on when the stream fails;
    • the failure event's own fragments do not count;
    • nine no-answer frames across the three dialects give no signal.
  • backend/core/chat/turn_action.test.ts, new after the model began a tool call (under a failed reply books what it consumed — the wire under the turn):
    • Fragment then in-stream 429 books one estimated row, identical to a provider fault (502) at the same point. The executor is never called.
    • The same holds for an OpenAI-compatible call whose arguments follow its name, an Anthropic tool_use after a message_start of nothing, and a Responses function_call.
    • A zero-count frame, then the call, then a 429 books exactly what the call alone books.
    • Each no-answer frame (with a keep-alive comment and a frame cut mid-JSON) before a refusal books nothing.
    • A failure event's own positive usage books once, as reported. An Anthropic message_start input is kept, with only the output estimated.
    • Text before the call is the output estimate, and the call adds nothing to it.
    • A Stop while the call's arguments are still streaming books once and runs nothing.
    • A finished 80/20 tool round followed by a pre-answer 429 books exactly 80/20.
    • A finished 80/20 round followed by a fragment-then-429 round books both rounds in one row, identical to a 502 there. Only the first round's call runs.
  • lib/chat/turn.test.ts:
    • the turn books a refusal after toolCallStarted once and runs no call;
    • a stream that settles with the signal but no complete call runs nothing.

Commands, run in services/platform with the credential removed:

  • bunx vitest --run --project server backend/core/chat/turn_action.test.ts lib/chat/turn.test.ts: 203 passed.
  • The same two files with only the production files reverted to main (the tests kept): 10 failed and 193 passed. The 10 failures are exactly the signal and booking regressions; every control passes on both.
  • bunx vitest --run --project server backend/core/chat/ lib/chat/ backend/domains/chat/ backend/domains/model_api/ lib/mocks/contract/ at 95821d3a: 71 files, 1391 tests passed.
  • bunx oxlint --type-aware (the platform's lint): exit 0.
  • bunx tsc --noEmit (the platform's typecheck, with the 6 GiB heap CI gives it): exit 0.
  • bun run lint:manual: ok. oxfmt --check on the changed files: ok.

Not run: the full platform unit suite, E2E, UI, Browser and backend:integration. This PR's CI and the merge queue run them. Nothing here was checked against a live provider, an invoice or a real charge.

Closes #4050

A direct chat stream hands its tool calls to the turn only at its
settle, whole. A provider that reported a refusal (an in-stream 429,
rate_limit_error, rate_limit_exceeded) after the model had begun a tool
call threw before that settle, so the turn saw no answer and read the
round as refused before it began: the prompt the provider had read and
the call the model had written were booked nowhere.

streamSse now says once, on the event that first gives a draft a name
or argument bytes, that the model began a tool call
(ModelStreamChunk.toolCallStarted). The turn counts it as answer
evidence, so the failed round is booked by the failed-round accounting
every round shares: reported counts kept, the rest estimated and marked
so. An id-only or empty fragment, an empty role, a keep-alive, empty
metadata and zero-count usage stay no evidence; the failure event's own
fragments do not count. The call itself still runs only from a normal
settle, never after a failure or a stop. The output estimate keeps its
one boundary, the streamed text and reasoning, never a tool call's name
or arguments.

@tale-review-bot tale-review-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved at head 95821d3a0f71b1ff3f61cc0b74a8aebfd7b1f910 (base main 9be5cadacb5f59cd6b2cc67c7840e3c0101bdde2).

Scope. The PR does what TALE-55's triage and plan asked, and nothing else:

  • streamSse yields toolCallStarted once per stream, on the first normal event after which a draft carries a tool name or argument bytes.
  • The turn counts that as answered, so a refusal that cuts a begun tool call books the round through the unchanged failure path (roundUsage, usageBooked): once, with reported counts kept and estimates marked estimated.
  • stream_decode.ts and domains/model_api are untouched.

Correctness.

  • Failure frames: a failure frame goes through readStreamFailure, yields only its positive usage, and throws before the new check, so its own fragments never signal a started call.
  • What counts as answer evidence: id-only and empty fragments, empty roles, keep-alives and zero-count usage are not evidence, and zero-token metadata stays unbillable.
  • Execution: executable toolCalls still come only from the settle chunk, so a cut call never runs.
  • No double booking: a successful round was already answered on its settle chunk, so the flag only sets answered earlier, and usageBooked books once.
  • Estimate boundary: the roundUsage comment states it plainly. The estimated output is text and reasoning, never a call's name or arguments, so a failed tool-only round books its prompt and output 0.

What I ran at this head (credentials removed):

  • bunx vitest --run --project server backend/core/chat/turn_action.test.ts lib/chat/turn.test.ts: 203/203.
  • With main's turn_action.ts and lib/chat/turn.ts put back: 10 fail and 193 pass. The 10 are exactly the new started-call cases (OpenAI-compatible, Anthropic, Responses, zero-count-then-call, a finished round then a cut one, and the direct streamSse signal checks). Every control passes on both. The tree was restored afterwards.
  • lint:manual ok, lint:conflicts exit 0. The CHAT-F57/F58 register row names the new boundary.

Checks. All seven CI ready checks passed on this head: Checks 40917078861, SAST 40917078969, Commitlint 40917079293, CLI 40917078804, Security 40917078939, E2E 40917079394 and Build 40917079415. There are no review threads.

Not run: a live provider, and the queue-only tier (backend integration and the rest), which the merge queue runs. The chat spec keeps "what a failed reply books" under Not yet, so no rule card moves.

@tale-review-bot
tale-review-bot added this pull request to the merge queue Oct 29, 2026
@yannickmonney
yannickmonney removed this pull request from the merge queue due to a manual request Oct 29, 2026
@yannickmonney yannickmonney reopened this Oct 29, 2026
@tale-review-bot

Copy link
Copy Markdown
Collaborator

Not landed yet: its CI must re-run under the new landing rule. (Reviewer tale-review-bot, run 1f1d8573, 20:27 UTC.)

  • What changed. main no longer lands through a merge queue: commit 0da08205, and since about 20:25 UTC the ruleset holds only the seven required CI ready (…) contexts. This PR left the queue without merging. It is not merged, and auto-merge is off.
  • The new rule. .agents/repo.md ("Each PR lands on its own") and .github/CI.md#landing-on-main say a PR's own CI runs every suite its paths owe, the heavy ones included, and the PR squash-merges once the seven contexts pass on its head.
  • Why I'm not landing it now. The seven green contexts on the approved head 95821d3a0f71b1ff3f61cc0b74a8aebfd7b1f910 ran under the pre-0da08205 workflows. Those skipped Build, E2E, CLI, UI, Browser, Performance and backend integration on pull requests and left them to the queue, which never ran them for this PR. Enabling auto-merge now would merge it at once without those suites. A skipped check is not a pass, so I am not landing it on that evidence.
  • Next. Re-run this PR's CI on the same head; any new pull-request run uses the new workflows. Once all seven CI ready contexts pass on that run, the Reviewer lands it with gh pr merge 5079 --repo tale-project/tale --squash --auto --match-head-commit 95821d3a0f71b1ff3f61cc0b74a8aebfd7b1f910. The approval stands while the head is unchanged.

@tale-review-bot

Copy link
Copy Markdown
Collaborator

Reviewer: the CI on this head since the 20:13 UTC reopen can't be used to land it (head 95821d3a0f71b1ff3f61cc0b74a8aebfd7b1f910, still the approved head).

It ran the workflows from before 0da08205. Its checkout merged this head into the old base 9be5cadacb5f59cd6b2cc67c7840e3c0101bdde2 (job 123705469295: HEAD is now at 6f4df1a Merge 95821d3a0f71b1ff3f61cc0b74a8aebfd7b1f910 into 9be5cadac…). As a result:

  • E2E's PR scope logged e2e runs only in the merge queue; this pull request skips it (job 123705469247).
  • These runs skipped every heavy job:
    • Checks 40947168754: UI shards, UI, Browser, Build, Performance and Backend integration;
    • Build 40947168989: all 13 jobs;
    • CLI 40947169169: all 5 jobs;
    • E2E 40947169115: all of its Playwright and bundle jobs.

Without a merge queue, those suites never run before landing. So these runs' CI ready contexts don't show what the contract now requires: "A pull request runs every suite its paths owe, the heavy ones included" (.github/CI.md, Landing on main). I won't enable auto-merge on them, even once they are green. The SAST, Commitlint and Security workflows didn't change in 0da08205.

Next. This PR's merge ref is now based on 0da08205 (merge commit 3619a4b0f173). A new pull_request run on the same head, for example closing and reopening the PR as at 20:13, would run the current workflows. Once that run's seven CI ready contexts pass on 95821d3a0f71b1ff3f61cc0b74a8aebfd7b1f910, the Reviewer lands it with gh pr merge 5079 --repo tale-project/tale --squash --auto --match-head-commit 95821d3a0f71b1ff3f61cc0b74a8aebfd7b1f910.

@yannickmonney

yannickmonney commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Reopened so the checks run again. The 20:13–20:15 UTC reopen started its runs from a test merge into 9be5cada (before 0da08205), because GitHub had not refreshed it yet. This reopen's runs start from the test merge 20db4c89e1, into 0da08205. The head is unchanged (no new commit).

@yannickmonney

Copy link
Copy Markdown
Contributor

Landed on train as 219a07a: squashed at the approved head after the fast gate (formatting, typecheck, build). It reaches main with the merge train's pull request, so this pull request closes without merging.

yannickmonney pushed a commit that referenced this pull request Oct 30, 2026
Reviewed and approved in pull request #5079 at 95821d3.

Closes #4050
Task: TALE-55
@yannickmonney
yannickmonney deleted the fix/tool-only-stream-failure-usage branch October 30, 2026 10:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bug(platform): failed tool-only streams lose usage evidence

3 participants