Cancelling the completable future of an OpenAI call doesn't cancel the underlying OkHttp request
Nobody has claimed this yet.
- Dominant language
- Kotlin
- Stars
- 1.5k
- Forks
- 264
- Avg merge
- 9h 46m
- Merged PRs (30d)
- 96
Description
I have a few scenarios where we may opportunistically issue a request to an LLM but then cancel it, sometimes quickly so potentially before it's even been processed by the backend and charged for. It would seem natural that using the cancel method of an async call would do that, but it doesn't appear that this propagates to the underlying OkHttp layer.
This method appears to be the bridge between the SDK interfaces and the underlying HTTP engine:
override fun executeAsync(
request: HttpRequest,
requestOptions: RequestOptions,
): CompletableFuture<HttpResponse> {
val future = CompletableFuture<HttpResponse>()
request.body?.run { future.whenComplete { _, _ -> close() } }
newCall(request, requestOptions)
.enqueue(
object : Callback {
override fun onResponse(call: Call, response: Response) {
future.complete(response.toResponse())
}
override fun onFailure(call: Call, e: IOException) {
future.completeExceptionally(OpenAIIoException("Request failed", e))
}
}
)
return future
}
The problem appears to be that the completable future here doesn't link to the HttpRequest. The Call interface from OkHttp has a cancel method, but this is not called as a result of the future being cancelled.
Instead what appears to happen is that the request is orphaned if the outer future is cancelled, leading to a resource leak.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start at the shown executeAsync bridge and trace how newCall(...).enqueue connects the CompletableFuture to the underlying Call. Check how cancellation is currently handled and identify the relevant async HTTP tests; done means cancelling the returned future also cancels the request without breaking normal response or failure completion.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- kotlin
- Domain
- api, backend
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Quiet
- Clarity
- Mostly clear
- Newbie friendliness
- 55/100