Linux: _MultiHandle crash when cancelling chatsStream mid-flight (FoundationNetworking/libcurl)
I maintainer di solito rispondono entro 3 giorni
Nessuno ha ancora preso questa issue.
Valutazione
- Difficoltà
- 4/5
- Tempo stimato
- 3-5 giorni
- Idoneità per principianti
- 48/100
- Tipo di issue
- Bug
- Chiarezza
- Specificata chiaramente
- Stato di attività
- Tranquilla
- Stack tecnologico
- linux, swift
- Ambito
- backend, networking
Direzione di ricerca
Start by reading StreamingClient.swift and the delegate-based URLSessionDataTask path described in the report, then reproduce on Linux using the provided streaming and concurrent-request setup. Investigate how cancellation interacts with the FoundationNetworking/libcurl runloop while other requests are active. Done means mid-flight cancellation no longer crashes under concurrent URLSession activity, while streaming still completes and cancels correctly.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Descrizione
Summary
On Linux, chatsStream(query:) crashes with Signal 6 (SIGABRT) when the returned AsyncThrowingStream is cancelled mid-flight — i.e., before the SSE response has finished streaming — while concurrent URLSession requests are in flight. The crash is:
Object 0x7f33b00de390 of class _MultiHandle deallocated with non-zero retain count 2.
This object's deinit, or something called from it, may have created a strong
reference to self which outlived deinit, resulting in a dangling reference.
*** Signal 6: Program crashed: Aborted at 0x000003e80002a5f0
The crash is in libcurl's _MultiHandle deallocation, reached via CFRunLoopRunSpecific in the stack.
Environment
- MacPaw/OpenAI: 0.5.0 (latest release;
mainhas no changes toStreamingClient.swiftor the delegate path beyond 0.5.0) - Swift: 6.3.3 (swift-6.3.3-RELEASE), x86_64-unknown-linux-gnu
- OS: Amazon Linux 2023
- libcurl: 8.17.0 (OpenSSL/3.5.5)
- FoundationNetworking: swift-corelibs-foundation (libcurl-backed
URLSession)
Root cause
StreamingClient consumes the SSE response via a delegate-based URLSessionDataTask that holds libcurl's _MultiHandle across runloop iterations (CFRunLoopRunSpecific appears in the crash stack). When the AsyncThrowingStream<ChatStreamResult, Error> returned by chatsStream(query:) is cancelled mid-flight while other URLSession requests are in flight, the _MultiHandle is deallocated with a non-zero retain count, aborting the process.
The crash requires both elements:
- Concurrent
URLSessionactivity — a secondURLSession(e.g.URLSession(configuration:)) issuing requests while the SSE stream is open. Without this, the crash does not reproduce (the cancellation path completes cleanly). - Mid-flight cancellation of the
chatsStreamAsyncThrowingStream— letting the stream complete naturally does not crash, even with concurrentURLSessionactivity.
Reproduction
A minimal repro requires an OpenAI-compatible streaming endpoint, a concurrent URLSession request to a live HTTP server, and cancellation of the stream before it completes:
let openai = OpenAI(configuration: Configuration(token: "...", host: "..."))
let query = ChatQuery(
messages: [.init(role: .user, content: "List numbers 1 through 50, one per line.")],
model: "your-model",
stream: true
)
// Start the SSE stream on URLSession.shared (the default).
let task = Task {
let stream = openai.chatsStream(query: query)
for try await chunk in stream { /* drain */ }
}
// Give the stream a moment to establish its connection.
try await Task.sleep(nanoseconds: 500_000_000)
// Fire concurrent URLSession(configuration:) requests to a live HTTP
// server while the SSE stream is open. Any localhost HTTP server
// works (here we assume one is running on port 8080).
await withTaskGroup(of: Void.self) { group in
for _ in 0..<10 {
group.addTask {
let session = URLSession(configuration: URLSessionConfiguration.default)
_ = try? await session.data(from: URL(string: "http://127.0.0.1:8080/")!)
}
}
}
// Cancel the SSE stream mid-flight while the concurrent requests
// are settling. This triggers the _MultiHandle crash.
task.cancel()
await task.value // crashes with _MultiHandle deallocated, Signal 6 (~3/5 runs)
The crash reproduces ~3/5 runs on debug builds. Release builds narrow the crash window but do not eliminate it.
Note: A plain chatsStream + cancel without concurrent URLSession activity does not crash — the concurrent activity is load-bearing (it widens the timing window for the _MultiHandle deallocation race).
Stack trace (abbreviated)
Object 0x7f33b00de390 of class _MultiHandle deallocated with non-zero retain count 2.
*** Signal 6: Backtracing from 0x7f33bfa8d02c... done ***
*** Program crashed: Aborted at 0x000003e80002a5f0 ***
0 0x00007f33bfa3ff1a sigsuspend + 74 in libc.so.6
1 [ra] 0x00007f33c1d4abc9 _dispatch_sig_thread + 8 in libdispatch.so
...
0 0x00007f33bfb1017e epoll_wait + 94 in libc.so.6
1 [ra] 0x00007f33c1d49f92 _dispatch_mgr_invoke + 129 in libdispatch.so
2 [ra] 0x00007f33c1d49efd _dispatch_mgr_thread + 108 in libdispatch.so
3 [ra] 0x00007f33c1d4d105 _dispatch_worker_thread + 628 in libdispatch.so
The CFRunLoopRunSpecific frame (from libFoundation.so) appears in the full trace — this is the libcurl runloop integration in FoundationNetworking's URLSession that the delegate-based URLSessionDataTask schedules on.
Workaround
We bypass the StreamingClient delegate path on Linux by wrapping OpenAI in a custom OpenAIAsync conformer that overrides chatsStream(query:) to drain the SSE response via URLSession.shared.bytes(for:) (a raw byte drain with no delegate, no StreamingClient). The raw byte-drain path cancels cleanly — no _MultiHandle corruption. Every other OpenAIAsync method delegates to the wrapped OpenAI unchanged. This is Linux-only (behind #if canImport(FoundationNetworking)); on Apple platforms URLSession is native and the delegate path works correctly.
Our red-capable feedback loop confirmed the diagnosis:
- MacPaw/OpenAI delegate path + concurrent
URLSession(configuration:)+ mid-flight cancel → crashes ~3/5 runs. - Raw
URLSession.shared.bytes(for:)drain + same concurrentURLSession(configuration:)+ same mid-flight cancel → 5/5 green. - The only variable changed is the SSE transport — same endpoint, same request body, same concurrent activity, same cancellation timing.
Why filing this
- The bug is in code that hasn't changed between 0.5.0 and
main(StreamingClient.swift, the delegate-basedURLSessionDataTaskpath). - Issue #70 asked about cancellation of
chatsStreambut was about the API surface, not this crash. - No existing issue mentions the
_MultiHandlecrash or Linux libcurl cancellation.
- Lingua principale
- Swift
- Stelle
- 2.9k
- Fork
- 519
- Merge medio
- 4g 9h
- PR unite (30g)
- 13
Preparare l'ambiente
- Nessun Dockerfile né file Docker Compose
- Ha un modello di pull request
- Leggi la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Altre issue di MacPaw/OpenAI
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 76/100
I maintainer di solito rispondono entro 3 giorni
-
Enable batch promptsAperta
Difficoltà 2/5 1-3 ore Idoneità per principianti 68/100
MacPaw/OpenAI#73 · 1 commento · 1 reazione ·
I maintainer di solito rispondono entro 3 giorni
-
Difficoltà 4/5 3-5 giorni Idoneità per principianti 48/100
I maintainer di solito rispondono entro 3 giorni
-
Difficoltà 4/5 3-5 giorni Idoneità per principianti 55/100
I maintainer di solito rispondono entro 3 giorni
-
Add Batch API supportAperta
Difficoltà 5/5 Più di una settimana Idoneità per principianti 35/100
I maintainer di solito rispondono entro 3 giorni
Tutte le issue di MacPaw/OpenAI
Issue simili
-
iOS: recorded video location is written without ISO 6709 fixed-width degrees, Photos drops itAperta
Difficoltà 2/5 1-3 ore Idoneità per principianti 80/100
margelo/react-native-vision-camera#4216 ·
I maintainer di solito rispondono entro 4 giorni
-
documentation good first issue
Difficoltà 2/5 1-3 ore Idoneità per principianti 78/100
-
bug
Difficoltà 2/5 1-3 ore Idoneità per principianti 62/100
compiler-explorer/compiler-explorer#9272 ·
I maintainer di solito rispondono entro 1 giorno
-
[Feature] 建议出下卸载方法Apertaenhancement
Difficoltà 1/5 1-3 ore Idoneità per principianti 66/100
I maintainer di solito rispondono entro 1 giorno
-
P2 package platform-ios team-ios
Difficoltà 2/5 1-3 ore Idoneità per principianti 76/100
I maintainer di solito rispondono entro 1 giorno