Call the cancel endpoint eagerly when the editor abandons a stream
Release blocker — the client half of an InferenceInfra fix. Depends on the sidecar exposing POST /v1/requests/{id}/cancel and the gateway forwarding x-request-id (RunanywhereAI/InferenceInfra#440).
Problem
When the editor abandons a stream (Esc in Claude Code, app quit), the shim today drops the upstream request only implicitly: the upstream content receiver in src/anthropic/messages.cpp returns false when sink.write to the editor fails (~L238), which makes cpp-httplib close the socket. Two gaps:
- It fires only when the next upstream chunk arrives. During a long prefill (a 100k-token coding prompt is exactly when a user gives up) nothing arrives, so nothing fires.
- It is only a TCP close, and that is the signal the managed edge loses: measured through the public hostname, the engine keeps decoding 22–41 s after the client is gone, and the customer is billed for it.
Fix
- Capture the
x-request-idfrom the upstream response headers as soon as they arrive (before the first body chunk). - Detect the editor's close eagerly — a failed write, the connection's close callback, or the process exiting — rather than waiting for the next chunk.
- On close,
POST {base_url}/requests/{id}/cancelwith the session's bearer, fire-and-forget with a short timeout, in addition to dropping the upstream socket. Log it toshim.log, never to the editor's terminal. - On normal completion, do nothing.
Done when
Abandoning a stream from Claude Code through wally stops the engine within 2 s (the InferenceInfra issue's acceptance), including when abandoned during prefill.
Related: the keep-alive issue (same file — coordinate so the pooled client owns the header capture).
Implementation handoff — 2026-09-13
Status: active teammate work; no dedicated #81 PR published at this check. Aman owns the reviewed cancellation implementation; Siddhesh coordinates Wally merging. Sanchit revalidated the issue and avoided a competing fix. This issue remains open, and cancellation is not claimed implemented or live-validated by this handoff.
Current merge sequence for the overlapping translator code: #82 → #103 → #104, then rebase Aman's #81 branch onto the resulting main (or the agreed stack head before those merges). #103 currently targets issue-80-shim-keepalive; #104 targets codex/issue83-stream-overload. Retarget dependent PRs to main after their prerequisites land. Re-run abandonment tests with the overload and incomplete-stream changes present.
Server prerequisite: InferenceInfra #475, targeting development, must be deployed to the relevant control plane and nodes before end-to-end cancellation acceptance.
Acceptance clarification: the reviewed pinned LiteLLM path delays the request ID until the first token. Consequently, the client change alone cannot meet the original two-second cancellation target during a longer prefill; the gateway early-ID requirement remains tracked with InferenceInfra #440. Validate cancellation after ID arrival, no replay after abandonment, bounded shutdown, both translators, and final engine-stop/billing behavior. Preserve the original prefill requirement as outstanding.
Detailed final handoff: https://github.com/RunanywhereAI/wally/issues/81#issuecomment-5651887056
@AmanSwar - solved!
Plan (initial) — posted before implementation, per the review loop; a fresh-context review follows as the next comment
Worktree: dev/wallyWorktrees/issue-81-shim-cancel, branch issue-81-shim-cancel,
based on issue-80-shim-keepalive (PR #82) — #81 builds on the pool and the
RetryOnFreshConnection rule, and the issue itself says "coordinate so the
pooled client owns the header capture". If #82 merges first the branch is
rebased onto main; otherwise the PR is opened against issue-80-shim-keepalive
and retargeted. Server half: InferenceInfra PR #475 (#440).
What the code does today, and the two gaps (verified in the tree)
src/anthropic/messages.cpp HandleStreaming: the provider thread blocks in
PostUpstream → lease.client().Post(...); the editor's close is noticed only
inside the upstream content receiver, when sink.write fails (L272) — i.e. on
the next upstream chunk. Two consequences:
- Prefill window is blind. No chunk arrives during prefill, so nothing notices the editor left; the engine prefills and decodes for a client that is gone. A 100k coding prompt is exactly where a person gives up.
- The only signal sent is a TCP close, and that is the signal the managed
edge loses (InferenceInfra
disconnect-propagation.md§6: 22–41 s of paid decode after the client is gone).
src/ide/openai_proxy.cpp (JetBrains) has the same shape (L346, forward()).
Three facts from cpp-httplib 0.46.1 (the fetched header) that the design rests on:
DataSink::is_writable()→strm.is_peer_alive()→select_read(0)thenrecv(MSG_PEEK): an eager, zero-cost check for the editor's FIN/RST that the provider can poll while the upstream call is in flight (L7461, L5568).Client::stop()is designed to be called from another thread while a request is in flight: it shuts the socket down so the blockedPostreturns (L14808–14826).Client::send(const Request&)honoursRequest::response_handler, called with the headers before any body byte —x-request-idcapture without waiting for a chunk (L984, L1291, L2209).Post(...)has no such overload.
One fact from the server side that decides how good the prefill case can be:
the customer receives x-request-id on the response start (credit_gate
_with_contract_headers stamps http.response.start; the sidecar forwards the
engine's headers as soon as Client.Do returns; SGLang's StreamingResponse
sends headers before the generator's first yield). Whether the ALB/Cloud Run
front end releases those headers before the first body byte is unmeasured.
If it does, a prefill-time cancel fires within one poll interval. If it does
not, the id is unknown until the first token and the design below degrades to
"cancel as soon as the id is known" — still strictly better than today's
swallowed TCP close, but bounded by prefill time. Measurement is step 7.
Design
A. One shared "watched upstream call" in src/net/ (both translators use it)
src/net/upstream_call.{h,cpp}:
struct WatchedCall {
std::string path, body; // content type application/json
httplib::ContentReceiver receiver; // as today
std::function<bool()> reader_alive; // the sink's is_writable
// Fires at most once, from the watch thread, the moment the reader is
// found gone: request_id is the captured x-request-id, or "" if the
// headers have not arrived yet.
std::function<void(const std::string& request_id)> on_abandoned;
std::chrono::milliseconds poll{100};
std::chrono::seconds header_wait{30}; // see (b) below
};
struct WatchedResult {
httplib::Result reply;
bool received_any = false;
bool abandoned = false;
std::string request_id; // "" if never seen
};
WatchedResult PostWatched(UpstreamLease& lease, const WatchedCall& call);
Behaviour:
- Builds an
httplib::Request(POST, bearer already on the lease's client),response_handlercapturesx-request-id(case-insensitive; alsoX-Request-Id),content_receiverwrapscall.receiverand setsreceived_any. - Starts a watch thread for the duration of
client.send(). Everypollit callsreader_alive(). When false: (a)abandoned = true; if the id is known →on_abandoned(id), thenclient.stop()so the blockedsendreturns; (b) if the id is not known (prefill, headers not yet through) → keep the upstream open and keep polling until the headers arrive (the response handler then fireson_abandoned(id)itself and returnsfalse, which makes cpp-httplib abort the request withError::Canceled) orheader_waitexpires →on_abandoned("")+stop(). Rationale: a TCP close alone is what the edge swallows; keeping the socket a little longer to learn the id costs nothing the engine is not already spending. - Once abandoned, the wrapped receiver discards body bytes (never writes
to the dead sink) and returns
trueuntil the stop lands. - Joins the watch thread before returning. The watch thread never runs the
cancel HTTP call itself (that would hold the provider thread for the cancel's
timeout) —
on_abandonedis expected to hand the call off (B). - Thread-safety argument, stated in the header comment: the watch thread only
ever calls
reader_alive()(a peek on the server socket — syscalls only, no cpp-httplib state) andclient.stop()(documented thread-safe for this).
RetryOnFreshConnection gains nothing; instead both callers pass
abandoned as a veto: an abandoned call is never retried on a fresh
connection (today the stale-retry rule would happily re-send a 100k prompt
after the editor left, because "nothing received + connection error + reused"
is exactly what an abandon-during-prefill looks like). Table test row added.
B. The cancel call, contract-first (src/account/)
Per AGENTS.md "P0 contract-first network rule": a RunAnywhere-owned HTTP call goes through the pinned artifact and the generated binding, never hand-built.
contracts/extract-cli-contract.py: add"cancelRequest"toCLI_OPERATION_IDS; re-run against PR #475'scontracts/control-plane-v1.openapi.json→contracts/wally-cli-v1.openapi.jsongainsPOST /v1/requests/{request_id}/cancel(202CancelRequestResponse, 422, defaultApiError) and theRequestIdscalar.contracts/generate_console_binding.py→src/account/console_contract.hgainsstruct CancelRequestResponse { RequestId request_id; Status status; }(generated, DO NOT EDIT). Pin hash bumped besideSCHEMA_LOCK;test_wally_contractand the CI--checkkeep the three in step.ConsoleClient::CancelRequest(console_url, token, request_id, &error) -> CancelOutcome(Cancelled/NotFound/Failed) inconsole.cpp, through the existingTransport— sameSend/ParseContractpath asFetchUsage.request_idis percent-encoded into the path (QueryEscapeexists).HttpRequestgainsint timeout_ms = 0(0 = today's 10 s connect / 30 s total), honoured by both transports (curlCURLOPT_TIMEOUT_MS/CURLOPT_CONNECTTIMEOUT_MS, WinHTTPWinHttpSetTimeouts). The cancel uses 3 s total, 2 s connect: it is fire-and-forget, and it bounds how long an exiting wrapper waits (D).
C. The translators
harness::Endpoint gains std::string console_url (empty for a local server;
Resolve already has credentials.console_url in hand at harness.cpp:447).
The shim Runtime keeps it.
messages.cpp: PostUpstream takes the WatchedCall pieces instead of a raw
receiver; HandleStreaming passes reader_alive = [&sink]{ return sink.is_writable(); }
and on_abandoned = [owner, id]{ owner->Cancel(id); }. Non-streaming requests
are unchanged (no sink to watch; a non-streaming abandon is rare and the
response is short).
openai_proxy.cpp: the same two hooks in the for(;;) loop; the abandon veto
on the stale retry; the auth-renew retry is also vetoed when abandoned.
Runtime::Cancel(id): if console_url or api_key is empty (local server) →
no-op. Otherwise pushes a std::thread onto Runtime::background that calls
ConsoleClient::CancelRequest(console_url, api_key, id) with the 3 s timeout
and appends one line to shim.log (cancel <id> -> 202|404|error, never the
token, never the editor's terminal). Stop() joins background — bounded by
the 3 s timeout, typically ~200 ms — so app-quit still sends the cancel
before the wrapper exits, which is half of the issue's "Esc or app quit".
Normal completion: the watch thread exits with the call; nothing is sent.
D. Logging
shim.log (existing helper, generalised from LogUpstreamError to
ShimLog(line)): abandoned during=prefill|stream id=<id|unknown> cancel=202|404|timeout|skipped(local).
Steps (each: implement → test → green before the next)
- Contract re-vendor — extractor op added, artifact + binding + pin
regenerated together;
test_wally_contractgreen;--checkgreen. HttpRequest.timeout_ms+ConsoleClient::CancelRequest— unit tests with a mock transport: URL is{console_url}/v1/requests/{id}/cancel, POST, bearer set, id percent-encoded; 202 → Cancelled, 404 → NotFound, transport error → Failed; timeout field reaches both transports (curl side asserted via a transport test that setstimeout_ms=1against a socket that never answers → returns within ~1 s).net::PostWatched— hermetic tests againstFakeUpstreamextended with: anx-request-idper streaming response,POST /v1/requests/{id}/cancelrecording(id, bearer),hold_headers_until(n)(handler blocks before returning, so headers are withheld — "edge still buffering") alongside the existinghold_streams_until(headers out, body withheld — "prefill"):- reader gone during body hold →
on_abandoned(id)within 300 ms, the upstream socket dropped,abandoned=true, no bytes to the sink after; - reader gone during header hold → nothing yet; headers released →
on_abandoned(id)fires from the handler, request abortedCanceled; - reader gone during header hold and headers never come →
on_abandoned("")afterheader_wait(set to 500 ms in the test), socket dropped; - reader stays → completes normally,
on_abandonednever called,request_idcaptured.
- reader gone during body hold →
- messages.cpp wiring —
test_wally_anthropic.cpp: an "editor" client opens a streaming request to the shim, the fake holds the body, the editorstop()s → the fake's cancel handler sees the same id withBearer <session key>within 1 s,arrivals == 1(no stale retry re-sent the prompt), and the upstream connection is gone; mid-stream variant (two frames then hold); normal completion sends no cancel; local endpoint (empty console_url) sends no cancel. Break test: veto removed → the "no re-send" assertion goes RED (arrivals == 2). - openai_proxy.cpp wiring — the same abandon test in
test_wally_ide_proxy.cpp. - Stop() joins the cancel — test: abandon then
Stop()immediately; the fake still records the cancel;Stop()returns within the timeout. - Live measurement (needs a dev key — still blocked, see #82 step 6):
(i) does
x-request-idreach the client before the first body byte through the edge? (curl -N -D -with a ~20k-token prompt, header time vs firstdata:); (ii) the issue's acceptance — abandon from Claude Code through wally, engine stops within 2 s — needs a node running a sidecar built from #475, which ships dark until a contract pins that image. Until then the live check can only prove the cancel reaches the control plane (expect 404 today). Both recorded on the PR, neither claimed as done. - Docs:
docs/EDITORS.md(what happens on Esc/quit), AGENTS.md's console call list (seven calls now), PR body with break tests and the two live unknowns stated plainly.
Decisions I am making unless told otherwise
- Poll interval 100 ms, header wait 30 s, cancel timeout 3 s/2 s connect.
- Both translators in this PR (as with #80: "no separate PR" for JetBrains).
- Non-streaming requests are not watched.
Stop()waits for in-flight cancels (bounded 3 s) rather than exiting past them.
Out of scope
- Cancelling on the client's own id during prefill when the edge buffers headers: needs a client-chosen id the server accepts, which #440 deliberately removed. If step 7(i) shows the edge buffers, that is a follow-up on #440.
- The Codex/OpenCode harnesses: they point the tool at the console directly
(
credentials.console_url + "/v1", no shim), so there is no wally process in the path to cancel from.
Plan (revised) after the fresh-context review — final; implementation starts from here
Reviewer's verdict (Fable 5.1 subagent, fresh context), verbatim
Verdict: solves it with the revisions below. The mechanism (watch thread → peek the editor's socket →
Client::stop()/response_handlerabort → contract-first cancel throughConsoleClient) is sound and every cpp-httplib claim checks out in substance. Three things the plan asserts are wrong or untestable as written, and one server-side fact the plan calls "unmeasured" is already answerable from the pinned source — and the answer changes the parameters and the claims the PR may make.Blocking: (1)
x-request-idcannot arrive before the first token on either path wally uses — the pinned LiteLLM (39e4f1ae) buffers the first chunk (common_request_processing.pyL867_buffer_first_chunk_honoring_disconnect) before constructing theStreamingResponse(L958), andcredit_gatestampsx-request-idonhttp.response.start; the keepalive early-open path needssse_keepalive_ping_interval_seconds, unset here, and would carry nox-litellm-call-idanyway. Both edge routes go straight to LiteLLM, so the ALB question is moot. So state (b) is the NORMAL prefill path; the cancel fires at TTFT and kills the decode (most of the value); "within 2 s including during prefill" is not achievable client-side for TTFT > 2 s and the PR must say so;header_waitis "how long after abandon we still wait for TTFT" and must be generous; file the #440 follow-up with a specific ask. (2)Stop()is not bounded by 3 s —Server::stop()only closes the listener;listen_internaljoins the thread pool, soanthropic::Stopblocks until the streaming provider returns (TTFT orheader_wait): design it (astoppingflag the watch thread polls, an explicit exit bound, a stderr line) and test it. (3) The veto break test cannot go red —RetryOnFreshConnectionis false unlessreused; warm the pool with one completed request first.Corrections: "today the stale-retry rule would re-send the prompt" is false today (today's only abandon path yields
Error::Canceled, excluded by the table) and true only for the newstop()path (Error::Read) — the veto is load-bearing for the new design, not a latent-bug fix; the chunked-provideris_writableis L7570;Request::content_receiverisContentReceiverWithProgress(four args);is_socket_alivereturns alive when readable with unread inbound bytes even after FIN; userequest.is_connection_closed(captures the fd by value) rather thansink.is_writable()— safe cross-thread while the socket lives, and available in the non-streaming handler too, which removes that exclusion for free; re-issuestop()on every poll after abandonment untilsendreturns (a one-shotstop()landing with no request in flight just disconnects, andsend_reconnects); reapRuntime::background(one cancel worker with a queue); skip the cancel for status ≥ 400; "app quit still sends the cancel" holds forRun()only —--servenever callsStop(); contract tooling:statusis{"const":"cancelling"}→std::string,cancelRequest's path param lives undercomponents/parameters, which the extractor never traverses (dangling refs on top of the 13 already carried — fix or acknowledge); step 6's fake cancel handler must DELAY its answer or an un-joinedStop()still sees the cancel by luck; carryingcredentials.console_urlis right (dev →…/api-dev/v1/requests/{id}/cancel→ra-api-dev-bes, prod → priority-3/v1/requests/→ra-api-prod-bes; ledger matches by construction).Risks: the server half on the retired
/api/v1relay shape — the relay forwards its minted id asx-litellm-call-id, which #475's strip drops, so every cancel would 404 there (raise on #475);CPPHTTPLIB_EXPECT_100_THRESHOLD= 1024 bytes, so every pooled chat POST sendsExpect: 100-continueand waits up to 1 s (a #80 latency finding); tests that pass neutered: the two negatives, step 6 as written, the veto without warm-up; missing:header_waitexpiry (cancel count 0,id=unknownlogged), thestoppingflag, a TSAN run, Windowsshutdown()semantics; JetBrains' abort-closes-the-connection behaviour is assumed.What is right:
Client::stop()is designed for cross-thread use (L14808-14826);response_handlerruns after headers and before any body byte,false→Error::Canceled;Server::Server()ignores SIGPIPE; the veto placement; the contract-first shape andtimeout_mssafety on both transports;FakeUpstreamcan withhold headers (block in the handler) vs body (block in the provider); the editor'sClient::stop()is a FIN, which is what undici'ssocket.destroy()produces;Stop()ordering; Codex/OpenCode exclusion.
The revised plan
Worktree: dev/wallyWorktrees/issue-81-shim-cancel, branch issue-81-shim-cancel,
based on issue-80-shim-keepalive (PR #82) — #81 builds on the pool and the
RetryOnFreshConnection rule, and the issue itself says "coordinate so the
pooled client owns the header capture". If #82 merges first the branch is
rebased onto main; otherwise the PR is opened against issue-80-shim-keepalive
and retargeted. Server half: InferenceInfra PR #475 (#440).
What the code does today, and the two gaps (verified in the tree)
src/anthropic/messages.cpp HandleStreaming: the provider thread blocks in
PostUpstream → lease.client().Post(...); the editor's close is noticed only
inside the upstream content receiver, when sink.write fails (L272) — i.e. on
the next upstream chunk. Two consequences:
- Prefill window is blind. No chunk arrives during prefill, so nothing notices the editor left; the engine prefills and decodes for a client that is gone. A 100k coding prompt is exactly where a person gives up.
- The only signal sent is a TCP close, and that is the signal the managed
edge loses (InferenceInfra
disconnect-propagation.md§6: 22–41 s of paid decode after the client is gone).
src/ide/openai_proxy.cpp (JetBrains) has the same shape (L346, forward()).
Three facts from cpp-httplib 0.46.1 (the fetched header) that the design rests on:
DataSink::is_writable()→strm.is_peer_alive()→select_read(0)thenrecv(MSG_PEEK): an eager, zero-cost check for the editor's FIN/RST that the provider can poll while the upstream call is in flight (L7461, L5568).Client::stop()is designed to be called from another thread while a request is in flight: it shuts the socket down so the blockedPostreturns (L14808–14826).Client::send(const Request&)honoursRequest::response_handler, called with the headers before any body byte —x-request-idcapture without waiting for a chunk (L984, L1291, L2209).Post(...)has no such overload.
One fact from the server side that decides how good the prefill case can be:
the customer receives x-request-id on the response start (credit_gate
_with_contract_headers stamps http.response.start; the sidecar forwards the
engine's headers as soon as Client.Do returns; SGLang's StreamingResponse
sends headers before the generator's first yield). Whether the ALB/Cloud Run
front end releases those headers before the first body byte is unmeasured.
If it does, a prefill-time cancel fires within one poll interval. If it does
not, the id is unknown until the first token and the design below degrades to
"cancel as soon as the id is known" — still strictly better than today's
swallowed TCP close, but bounded by prefill time. Measurement is step 7.
Design (revision 2, after the fresh-context review — verdict in plan-wally-81-review.md)
The fact that reshapes everything: the pinned LiteLLM buffers the first
chunk before it opens the response (_buffer_first_chunk_honoring_disconnect,
then the StreamingResponse), and credit_gate stamps x-request-id on that
response start. So on both paths wally uses, the id is not knowable before the
first token. The cancel therefore fires at TTFT and kills the decode — the
22–41 s the issue measures, which is most of the value — and a client cannot
cancel during prefill until the gateway changes (a #440 follow-up, filed with a
specific ask: an early response start that carries the call id; LiteLLM's
keepalive ping alone would not, its early headers carry no x-litellm-call-id).
The PR says so; "within 2 s including during prefill" is not claimable
client-side for TTFT > 2 s.
A. src/net/upstream_call.{h,cpp} — one watched upstream POST, shared by both translators
struct WatchedCall {
std::string path, body; // application/json
httplib::ContentReceiver receiver; // as today
std::function<bool()> reader_gone; // the server request's is_connection_closed
std::function<bool()> stopping; // Runtime::stopping — the wrapper is exiting
// At most once, from the watch thread or the response handler, the moment
// both are true: the reader is gone AND the id is known (or the wait for
// it ended). request_id is "" when the headers never came.
std::function<void(const std::string& request_id, int status)> on_abandoned;
std::chrono::milliseconds poll{100};
std::chrono::seconds id_wait{120}; // how long after abandon we still wait for TTFT
};
struct WatchedResult { httplib::Result reply; bool received_any = false; bool abandoned = false; std::string request_id; };
WatchedResult PostWatched(UpstreamLease& lease, const WatchedCall& call);
- Builds an
httplib::Requestforclient.send():response_handlercapturesx-request-id(case-insensitive) and, if the reader is already gone, callson_abandoned(id, status)only for status < 400 (a 4xx/5xx ran nothing to cancel) and returnsfalse(Error::Canceled).content_receiver(the four-argumentContentReceiverWithProgress) wrapsreceiver, setsreceived_any, and once abandoned discards bytes without touching the sink. - Watch thread, every
poll:reader_gone()→abandoned = true. Then: id known →on_abandoned(id, status)once,client.stop(); id unknown → keep waiting until the handler learns it,id_waitexpires, orstopping()— the last two end withon_abandoned("", 0)andstop().stop()is re-issued on every poll after abandonment untilsendreturns (a one-shot landing with no request in flight only disconnects, andsend_reconnects). reader_goneisrequest.is_connection_closed—detail::is_socket_aliveon an fd captured by value: pure syscalls, no cpp-httplib state, and it works for the non-streaming handler too, so non-streaming requests are watched as well. Cross-thread safety rests on the join:PostWatchedjoins the watch thread before returning, and the request object outlives the call.- Retry veto: an abandoned call is never retried on a fresh connection. This is
load-bearing for the new design (a
stop()while blocked yieldsError::Read, which the stale-retry rule would otherwise re-send on a reused lease), not a latent bug today (today's only abandon path yieldsError::Canceled, already excluded).
B. The cancel call, contract-first (src/account/)
contracts/extract-cli-contract.py: addcancelRequest; also carry thecomponents/parametersandcomponents/responsesa kept operation references (the extractor never traversed those, which is why the artifact already holds thirteen dangling refs — fixed while here, guarded by the extractor's own check). Regeneratecontracts/wally-cli-v1.openapi.jsonandsrc/account/console_contract.h(CancelRequestResponse{request_id, status}, bothstd::string— theconstis not an enum to the generator); pin hash bumped;test_wally_contractkeeps them in step.HttpRequestgainsint timeout_ms = 0(0 = today's 10 s/30 s); honoured by the curl and WinHTTP transports. The cancel uses 3000 ms.ConsoleClient::CancelRequest(console_url, token, request_id, timeout_ms)→Cancelled/NotFound/Failed, throughTransport+ParseContract; the id percent-encoded into the path.
C. The translators and the runtime
harness::Endpointgainsconsole_url(empty for a local server), filled fromcredentials.console_urlwherebase_urlis built — dev keeps its/api-devbase path, so the cancel lands on the dev control plane, whose ledger admitted the request.Runtimegainsstd::atomic<bool> stoppingand one cancel worker: a queue of ids drained sequentially by a single thread (3 s per call; nothing grows per abandon).Runtime::Cancel(id)enqueues unlessconsole_url/api_keyis empty (local server) — logged toshim.logasskipped(local).Stop()order:stopping = true(watch threads bail out on their next poll) →server.stop()and join (bounded now by one poll + the cancel enqueue, not by TTFT) → drain the cancel queue and join the worker (bounded by 3 s per queued id, typically one) →g_runtime.reset(). If it had to wait, one status line to stderr (the terminal is free once the editor exited). Holds forRun()only:--servenever callsStop()(Ctrl-C kills the process) — stated.messages.cppandopenai_proxy.cppcallPostWatchedin place oflease.client().Post, passreader_gone/stopping/on_abandoned, and veto their stale (and, for JetBrains, auth-renew) retries when abandoned.shim.log:abandoned during=prefill|stream id=<id|unknown> cancel=202|404|timeout|skipped(local).
D. Decisions
poll100 ms;id_wait120 s (a prefill longer than that loses the cancel — TCP close only — which is today's behaviour; the bound exists so an abandoned request cannot hold a server thread and a pooled connection forever); cancel timeout 3 s.- Both translators; non-streaming watched too.
Tests
Unit/hermetic, extending tests/fake_upstream.h with: an x-request-id per
streaming response, hold_headers_until(n) (block in the handler → headers
withheld) beside hold_streams_until (block in the provider → body withheld), a
POST /v1/requests/:id/cancel route recording (id, bearer) with an optional
answer delay, and a release for both holds.
PostWatched: reader gone during body hold →on_abandoned(id)within ~300 ms, socket dropped,abandoned=true, no bytes to the sink after; reader gone during header hold → nothing yet; headers released →on_abandoned(id)from the handler,Canceled; header hold never released →on_abandoned("")afterid_wait(500 ms in the test), fake's cancel count stays 0; reader gone- a 429 reply → no cancel; reader stays → completes,
on_abandonednever called, id captured;stopping()flips during the header hold → returns within one poll.
- a 429 reply → no cancel; reader stays → completes,
ConsoleClient::CancelRequestwith a mock transport: URL{console_url}/v1/requests/{id}/cancel, POST, bearer, percent-encoding, 202 → Cancelled, 404 → NotFound, transport error → Failed;timeout_ms=1against a never-answering socket returns within ~1 s (bites: 30 s red without it).messages.cpp: the pool is warmed with one completed request first (so the lease isreusedand the veto is the thing under test); editor stops during the body hold → fake's cancel sees the same id withBearer <session key>within 1 s;arrivals == 2, not 3 (no re-send); mid-stream variant; normal completion → no cancel; local endpoint → no cancel andskipped(local)logged;Stop()right after an abandon with the fake's cancel handler delayed 500 ms → the cancel is still recorded andStop()returns within the bound.openai_proxy.cpp: the warmed-pool abandon test.- A TSAN build of the anthropic + ide-proxy suites (
-fsanitize=thread) once, quoted in the PR — the thread-safety argument is the join ordering. - Break tests (WIP safety commit first): veto removed →
arrivals == 3; thestoppingcheck removed → theStop()test exceeds its bound; status ≥ 400 skip removed → the 429 test records a cancel;is_connection_closedpolling removed → the body-hold test times out.
Live (not this PR; needs a dev key and #475 on a node): the cancel reaching the control plane (expect 404 while no node has the route); TTFT-time cancel stopping the engine.
Out of scope
-
Cancelling during prefill: impossible client-side while the gateway opens the response only at the first token — a #440 follow-up with a specific ask (an early response start carrying the call id), filed.
-
The
Expect: 100-continuefinding (every pooled chat POST over 1 KiB waits up to 1 s for a100): #80's, raised on #82. -
The retired
/api/v1relay shape, where #475's strip drops the relay's own forwarded id and every cancel would 404: raised on #475. -
Signal handling for
--serve(Ctrl-C kills the process withoutStop()). -
Cancelling on the client's own id during prefill when the edge buffers headers: needs a client-chosen id the server accepts, which #440 deliberately removed. If step 7(i) shows the edge buffers, that is a follow-up on #440.
-
The Codex/OpenCode harnesses: they point the tool at the console directly (
credentials.console_url + "/v1", no shim), so there is no wally process in the path to cancel from.
@Siddhesh2377 @AmanSwar — Sanchit here. I revalidated #81 for the release handoff and found Aman's recent revised implementation plan and existing #82 dependency. Aman is already working on the client change, so I am preserving that ownership and will not open a competing implementation PR.
The issue is still legitimate on current main (9a262ea): the Anthropic shim notices abandonment at sink.write in src/anthropic/messages.cpp:238, and the JetBrains proxy does the same in src/ide/openai_proxy.cpp:325; neither path currently calls an explicit cancel operation. Shubham's server-side progress does not by itself implement this client half.
Merge/deployment sequence:
- Wally #82 (
issue-80-shim-keepalive→main) provides the shared upstream pool. It remains draft with its stated live acceptance outstanding. - Aman's #81 implementation builds on
issue-80-shim-keepalive; if opened before #82 merges, use that branch as its base, then rebase/retarget tomainafter #82. No dedicated #81 PR or published remote branch was present at this check. - InferenceInfra #475 (
issue-440-cancel-endpoint→development) is the server prerequisite. Its cancellation contract and node implementation must be deployed before claiming end-to-end client cancellation works; merging the client alone is not sufficient.
Acceptance must retain the limitation identified in Aman's revised review: the current LiteLLM path withholds the request ID until the first token, so a client-only fix cannot establish cancellation within two seconds during a longer prefill. Keep the gateway early-ID work tracked with #440 and explicitly validate cancellation after ID arrival, no request replay after abandonment, bounded shutdown, both translators, and the eventual live engine-stop/billing behavior. The original prefill acceptance remains outstanding until that server behavior is addressed.
Status: active teammate implementation, not independently implemented or runtime-validated by this handoff. Leaving this issue open for review and final end-to-end acceptance.
@Siddhesh2377, please take over/coordinate this issue for the release: Aman is actively implementing the reviewed cancellation plan on top of PR #82; the server dependency is InferenceInfra PR #475. Sanchit (@sanchitmonga22) checked the current ownership and is avoiding a competing implementation so we do not conflict. Existing assignees are preserved. Please merge the relevant work in dependency order and retain this issue open for the final end-to-end acceptance round. The final standup handoff will include this issue and its merge sequence.
@Siddhesh2377 @AmanSwar — final handoff for Sanchit's issue pass: #81 remains with Aman; there is no dedicated cancellation PR published at this check, so this is not reported as implemented.
Please coordinate the shared translator changes in this order: #82 → #103 → #104, then rebase Aman's #81 branch onto the resulting main (or the agreed stack head while those PRs remain open) and retest cancellation against the overload and incomplete-stream changes. #103 currently targets issue-80-shim-keepalive; #104 targets codex/issue83-stream-overload; retarget each dependent PR to main after its prerequisite lands. This updates the earlier two-item sequence to include the newly opened streaming PRs.
InferenceInfra #475 must also be deployed to the relevant control plane and nodes before live cancellation acceptance. The gateway's delayed request ID still prevents claiming cancellation within two seconds during a long prefill; retain that acceptance explicitly. Keep #81 open through implementation review and the final end-to-end engine-stop/billing test.
Implementation — draft PR #106 (not end-to-end tested)
Built from the revised plan above, on issue-81-shim-cancel stacked on #82. Draft only; nothing is claimed live-validated. What is in it, in one paragraph: one upstream POST that watches the reader (PostWatched) — the server request's is_connection_closed polled every 100 ms, and a failed write to the editor treated as the same abandon (the path most real abandons take; it was missing in the first cut and the fresh-context code review caught it) — captures x-request-id at the headers, names the cancel once, stops the upstream socket and vetoes both retries; one worker thread per wrapper sends the cancels off the request path with a 3 s bound and drains on Stop(); contract-first cancelRequest vendored from #475's control-plane-v1.openapi.json; both translators wired; docs.
Limit, as the plan review established: the pinned gateway names the request only at the first token, so an abandon during prefill cancels at the first token (ends the decode) and cannot end the prefill itself. The ask for an earlier id is on InferenceInfra #440.
Proof: 20 new tests across four suites, each guard neutered and watched go red (record in the PR and in the commit message), TSAN clean on the final tree, ctest 13/13.
Needs @AmanSwar:
- Base. Sanchit's handoff asks for #82 → #103 → #104, then #81 rebased onto that head.
git merge-treeagainstcodex/issue84-stream-terminaltoday: 9 conflict hunks / 275 lines insrc/anthropic/messages.cpp, 2 / 61 intests/test_wally_anthropic.cpp. The PR is againstissue-80-shim-keepaliveas this plan said; I will rebase onto whichever base you name and re-run the abandonment suites there. - The live round (a dev session + a node running #475): Esc in Claude Code → engine stops within 2 s, and the same during prefill, measured and quoted on the PR before it leaves draft.
Client half verified against the Rust port (merge-tmp-port, wally 0.7.0 / commons 0.20.38). The CancelWorker path (src/account/cancel_worker.rs + src/anthropic/messages.rs post_upstream/abandon handling) does what the issue asks:
- Editor leaves mid-stream (or during prefill) → shim captures the
x-request-idand callsPOST {console}/v1/requests/{id}/cancelwith the session bearer, fire-and-forget off the request path (3s-per-cancel bound) - 7 integration tests green over real sockets, including: cancel names the abandoned request within 1s, mid-token Esc, prefill abandon cancels at first token, completed streams and local endpoints never cancel, and the pool never re-sends the prompt (arrivals stay at 2)
- Live shim.log confirms the flow:
abandoned during=stream id=req-1 … cancel=queued→cancel id=req-1 result=202
Demo:

Recording committed at docs/demo-recordings/issue81.gif on merge-tmp-port.
Full end-to-end (abandon-through-public-hostname stopping the engine within 2s) still needs the InferenceInfra side per #440 — that's out of this repo's scope. Leaving open — nothing closed here.
Client half fixed on main (Rust port). When the editor leaves, the shim takes the x-request-id and calls POST /v1/requests/{id}/cancel off the request path (src/account/cancel_worker.rs). Checked today: the cancel tests in test_wally_anthropic and test_wally_net_call pass on main, including mid-stream, during prefill (cancels at the first token), and never for a completed stream or a local endpoint. Stopping the engine during a long prefill still depends on the gateway sending the request id earlier (InferenceInfra #440).