Repository navigation
Record and price the requests a client walks away from - #24
Merged
Merged
Conversation
A client that disconnects mid-stream (Esc in Claude Code) produced no terminal event. hyper drops the response body, the stream is dropped at whatever await it was suspended on, and the code at its end that emits RequestFinished or RequestFailed never runs. The recorder held the request in memory until it was evicted and never wrote it, so the tokens the upstream had already billed - the full input, and the output up to the disconnect - never reached history, and the live row in the desktop app stayed in progress. The ending now travels with the stream, the same way the in-flight pass does. `tw_gateway::ending::Ending` owns what is known about the response so far: bytes received, the usage sniffer and the response body tap. The two normal ends report explicitly and consume it. If it is dropped without having reported, Drop reports a new `Event::RequestCancelled` with the status, the bytes and duration so far, and the usage seen so far, so a request has exactly one ending. A drop during unwinding from a panic in the stream reports `RequestFailed` with source `internal` instead, rather than blaming the client. A new event rather than `RequestFailed` with another source, for two reasons: a cancellation carries usage so it can be priced, and it must not count as a failure. The failure count, the failure rate and the upstream baseline's error rate all read `error IS NOT NULL`, and pressing Esc should not make an upstream look unreliable. The recorder writes the row through the same path as a finished request, with a new `cancelled` column (schema 10) and no `error`. The cost of a cancellation is always marked estimated: Anthropic reports cumulative output only at the end of the stream, so the output count at the disconnect is a placeholder and the amount can only be low. `HistoryRow` and `TurnView` carry `cancelled`, and the partial response body is archived like any other. Each new test was run against the broken version it guards: with Drop reporting nothing, the mid-stream disconnect test sees no ending; with the normal end not marked as reported, a completed stream reports Finished and then Cancelled; without the panicking check, a panic is blamed on the client; pricing a cancellation as exact, or ignoring it in the recorder, fails the recorder tests. The smoke script now abandons a slow stream against the real binary and finds the row in /history, marked cancelled, with its input usage and an estimated cost. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
|
Thanks for the PR. One thing before review: this targets
No need to close and reopen: click Edit next to the PR title and change the base branch to See CONTRIBUTING.md and CONTRIBUTING.md for the branch contract. |
This was referenced Sep 16, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What this changes
A streaming request the client abandons mid-stream (Esc in Claude Code) now
produces exactly one terminal event, and the recorder writes it as a row with
the usage seen so far and a price.
tw_api::Event::RequestCancelled { id, status, bytes, duration_ms, usage }.tw_gateway::ending::Endingcarries a response's ending with the stream: itowns the byte count, the usage sniffer and the response body tap. The normal
end calls
finished(), a broken or cut stream callsfailed(), and if it isdropped without either,
DropreportsRequestCancelled. A drop whileunwinding from a panic in the stream reports
RequestFailedwith sourceinternalinstead.new
cancelledcolumn (schema 10),errorleft empty, cost always markedestimated,
RequestPricedreported as usual. The partial response body isarchived.
HistoryRowandTurnViewgaincancelled(#[serde(default)]).Why
When the client disconnects, hyper drops the response body and the stream is
dropped at whatever
awaitit was suspended on. The code at the end of thestream block that emitted
RequestFinished/RequestFailednever ran, so therecorder kept the request in its in-flight map until eviction and never wrote
it. The upstream had already billed the full input and the output up to the
disconnect; none of it reached history, and the live row in the desktop app
stayed in progress. PR #23 found this while adding the in-flight counter.
Why a new event and not
RequestFailedwith aclientsource. Acancellation has to carry usage to be priced, and it must not count as a
failure: the failure count, the failure rate, session error counts and the
upstream baseline's error rate all read
error IS NOT NULL. Someone whopresses Esc often should not see an upstream that looks unreliable.
Why the cost is always estimated. Anthropic reports input (and cache)
usage in
message_start, at the top of the stream, but cumulative output onlyin the final
message_delta. At a mid-stream disconnect the output count inhand is the placeholder from
message_start, so the amount is a lower bound.Recording it as measured would quietly understate the day's spend.
Why the guard owns the sniffer instead of reading it from outside. The
stream's locals are all dropped together; putting what an ending needs in the
one object that reports it means there is no state to share and no second
place to forget. It also removed the
Arc<AtomicU64>byte counter, which wasonly there so the tail of the stream could read a count kept outside it.
The only other thing that drops the body early is a panic inside the stream,
which is why
Dropchecksstd::thread::panicking(): a unit test drives a realstream!generator into a panic and confirms the drop sees it.How it was checked
crates/tw-gateway/tests/live.rs, against a real gateway and upstream:message_startand drops the body gets exactly oneending,
RequestCancelled, with 5,000 input and 4,000 cache-read tokens andthe bytes of that frame;
RequestFinished;RequestFailed.crates/tw-gateway/src/ending.rsunit tests cover each ending, a drop beforethe first chunk (usage
None, not zeros), the archived partial body, and thepanic path.
crates/tw-store/src/recorder.rstests: a cancellation becomes arow with tokens and an estimated cost, is not counted as failed, reports its
price on the bus as an estimate, is written without a price when no usage was
seen, shows as cancelled in its session, and a later ending for the same id
does not overwrite it. The migration test now also drops
cancelled.Each test was run against the broken version it guards:
Dropreportingnothing ("该恰好有一个结局:[]"); the normal end not marked as reported (a
completed stream reports
RequestFinishedand thenRequestCancelled); nopanicking check; a cancellation priced as exact; the recorder ignoring the
event.
scripts/smoke.shgains a step: against the real binary,curl -m 2abandonsa stream that sends
message_startand then stalls, and/historyshows therow marked cancelled, with its input tokens and an estimated cost.
Gates:
cargo fmt --check,cargo clippy --workspace --all-targets -D warnings,cargo test --workspace(1,143 passed),./scripts/smoke.sh(47 passed; theexisting 35 MB memory warning is unchanged).
The workspace version is not bumped. The desktop app pins
tw-apito a tag,so it can render the new state once a release carries this.
Found along the way, not fixed here
ending. The handler future is dropped inside
pipeline, while it waits onthe upstream (a non-streaming request, or a slow relay). A guard there would
have to tell "dropped" from "returned
Err", and the handler returns earlywith
?andreturn Errin several places, soDropmeaning "cancelled" isnot safe there without restructuring.
denyreturns afterRequestStartedwithout emittingRequestFailed(server.rs, theOutcome2::DenyandErrarms insidethe attempt loop). Those requests are never written either, and their live
rows stay in progress.
RequestStartedand never an ending;ws.rshasno terminal event.
RequestFailedwithout usage, so the input it was billed for is notrecorded.
Ending::failednow has the usage at hand, but carrying it changeswhat a failed row means for cost totals, which deserves its own decision.
TurnViewhas nocost_estimated, so the session waterfall showsestimated amounts (cross-platform prices, and now cancellations) as exact.
Summary::unpriced_requestscountscost_micros IS NULL AND billing = 'per-token', which includes every failedrow, so a failure reads as "a model with no price".
🤖 Generated with Claude Code