Skip to content

Record and price the requests a client walks away from - #24

Merged
fylorn merged 1 commit into
mainfrom
fix/record-abandoned-streams
Sep 16, 2026
Merged

fylorn merged 1 commit into
mainfrom
fix/record-abandoned-streams

Conversation

@fylorn

@fylorn fylorn commented Sep 16, 2026

Copy link
Copy Markdown
Contributor

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.

  • New tw_api::Event::RequestCancelled { id, status, bytes, duration_ms, usage }.
  • tw_gateway::ending::Ending carries a response's ending with the stream: it
    owns the byte count, the usage sniffer and the response body tap. The normal
    end calls finished(), a broken or cut stream calls failed(), and if it is
    dropped without either, Drop reports RequestCancelled. A drop while
    unwinding from a panic in the stream reports RequestFailed with source
    internal instead.
  • The recorder writes cancellations through the same path as finished requests:
    new cancelled column (schema 10), error left empty, cost always marked
    estimated, RequestPriced reported as usual. The partial response body is
    archived.
  • HistoryRow and TurnView gain cancelled (#[serde(default)]).

Why

When the client disconnects, hyper drops the response body and the stream is
dropped at whatever await it was suspended on. The code at the end of the
stream block that emitted RequestFinished / RequestFailed never ran, so the
recorder 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 RequestFailed with a client source. A
cancellation 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 who
presses 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 only
in the final message_delta. At a mid-stream disconnect the output count in
hand 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 was
only 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 Drop checks std::thread::panicking(): a unit test drives a real
stream! 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:

  • a client that reads message_start and drops the body gets exactly one
    ending, RequestCancelled, with 5,000 input and 4,000 cache-read tokens and
    the bytes of that frame;
  • a stream that runs to its end reports only RequestFinished;
  • a stream the upstream breaks reports only RequestFailed.

crates/tw-gateway/src/ending.rs unit tests cover each ending, a drop before
the first chunk (usage None, not zeros), the archived partial body, and the
panic path. crates/tw-store/src/recorder.rs tests: a cancellation becomes a
row 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: Drop reporting
nothing ("该恰好有一个结局:[]"); the normal end not marked as reported (a
completed stream reports RequestFinished and then RequestCancelled); no
panicking check; a cancellation priced as exact; the recorder ignoring the
event.

scripts/smoke.sh gains a step: against the real binary, curl -m 2 abandons
a stream that sends message_start and then stalls, and /history shows the
row 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; the
existing 35 MB memory warning is unchanged).

The workspace version is not bumped. The desktop app pins tw-api to a tag,
so it can render the new state once a release carries this.

Found along the way, not fixed here

  • A client that leaves before the response headers arrive still leaves no
    ending.
    The handler future is dropped inside pipeline, while it waits on
    the upstream (a non-streaming request, or a slow relay). A guard there would
    have to tell "dropped" from "returned Err", and the handler returns early
    with ? and return Err in several places, so Drop meaning "cancelled" is
    not safe there without restructuring.
  • A phase-two deny returns after RequestStarted without emitting
    RequestFailed
    (server.rs, the Outcome2::Deny and Err arms inside
    the attempt loop). Those requests are never written either, and their live
    rows stay in progress.
  • WebSocket sessions emit RequestStarted and never an ending; ws.rs has
    no terminal event.
  • A stream the upstream breaks, or the tool firewall cuts, still reports
    RequestFailed without usage
    , so the input it was billed for is not
    recorded. Ending::failed now has the usage at hand, but carrying it changes
    what a failed row means for cost totals, which deserves its own decision.
  • TurnView has no cost_estimated, so the session waterfall shows
    estimated amounts (cross-platform prices, and now cancellations) as exact.
  • Failed requests count as unpriced. Summary::unpriced_requests counts
    cost_micros IS NULL AND billing = 'per-token', which includes every failed
    row, so a failure reads as "a model with no price".

🤖 Generated with Claude Code

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>
@github-actions

Copy link
Copy Markdown

Thanks for the PR. One thing before review: this targets main, and it should target dev.

main is a release-only line — branch-protected, linear history, and every commit on it is a tagged release snapshot. Routine work lands on dev and reaches main with the next release. GitHub pre-filled main here because it is the default branch, so this is our defaults being unhelpful rather than anything you did wrong.

No need to close and reopen: click Edit next to the PR title and change the base branch to dev. The commits and the discussion carry over.

See CONTRIBUTING.md and CONTRIBUTING.md for the branch contract.

@fylorn
fylorn merged commit 2fed2c8 into main Sep 16, 2026
2 checks passed
@fylorn
fylorn deleted the fix/record-abandoned-streams branch September 16, 2026 15:24
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.

1 participant