From 9e90af5125cb2180ad48ae164824f4bd551a4be2 Mon Sep 17 00:00:00 2001 From: Alexey Milovidov Date: Fri, 27 Nov 2026 00:31:27 +0000 Subject: [PATCH 1/3] Stream reasoning deltas and stop timing out between events `HttpSseStream::get_next_event` busy-polled the event queue every 1 ms and failed with `Timeout waiting for next event` after 30 seconds without a queued event. Reasoning models routinely stay silent longer than that: Claude Opus 5.5 and Fable 5.2 always think and omit the thinking text by default, and OpenAI-compatible servers stream reasoning in fields the parser ignored, so a long reasoning phase failed the stream although the connection was alive. - The consumer now blocks on a condition variable until an event arrives or the stream completes. A stalled connection is still detected: the stream thread's HTTP read timeout fails the request, which pushes an error event and completes the stream. - Add `kStreamEventTypeReasoningDelta` with the text in `StreamEvent::reasoning_delta`, emitted for Anthropic `thinking_delta` and for the `reasoning_content` (DeepSeek, vLLM, SGLang) and `reasoning` (OpenRouter, Ollama) delta fields of OpenAI-compatible servers. Based on https://github.com/ClickHouse/ai-sdk-cpp/pull/60 by @tv1wnd. Co-Authored-By: Claude Opus 5.5 --- include/ai/types/enums.h | 5 +- include/ai/types/stream_event.h | 11 ++++ src/providers/anthropic/anthropic_stream.cpp | 8 +++ src/providers/http_sse_stream.cpp | 62 ++++++++++---------- src/providers/http_sse_stream.h | 15 +++-- src/providers/openai/openai_stream.cpp | 9 +++ tests/unit/anthropic_stream_test.cpp | 25 ++++++++ tests/unit/openai_client_test.cpp | 15 +++-- tests/unit/openai_stream_test.cpp | 40 +++++++++++++ 9 files changed, 145 insertions(+), 45 deletions(-) diff --git a/include/ai/types/enums.h b/include/ai/types/enums.h index 397d4d3..66ad3e7 100644 --- a/include/ai/types/enums.h +++ b/include/ai/types/enums.h @@ -23,7 +23,10 @@ enum StreamEventType { kStreamEventTypeStepStart, kStreamEventTypeStepFinish, kStreamEventTypeFinish, - kStreamEventTypeError + kStreamEventTypeError, + /// A fragment of the model's reasoning (thinking) text, in `reasoning_delta`. + /// It can be empty when the provider does not return the reasoning itself. + kStreamEventTypeReasoningDelta }; } // namespace ai \ No newline at end of file diff --git a/include/ai/types/stream_event.h b/include/ai/types/stream_event.h index 8646af3..444f8e7 100644 --- a/include/ai/types/stream_event.h +++ b/include/ai/types/stream_event.h @@ -29,8 +29,18 @@ struct StreamEvent { explicit StreamEvent(ToolCall call) : type(kStreamEventTypeToolCall), tool_call(std::move(call)) {} + static StreamEvent reasoning(std::string reasoning_text) { + StreamEvent event(kStreamEventTypeReasoningDelta); + event.reasoning_delta = std::move(reasoning_text); + return event; + } + bool is_text_delta() const { return type == kStreamEventTypeTextDelta; } + bool is_reasoning_delta() const { + return type == kStreamEventTypeReasoningDelta; + } + bool is_error() const { return type == kStreamEventTypeError; } bool is_tool_call() const { return type == kStreamEventTypeToolCall; } @@ -39,6 +49,7 @@ struct StreamEvent { StreamEventType type; std::string text_delta; + std::string reasoning_delta; std::optional error; std::optional usage; std::optional finish_reason; diff --git a/src/providers/anthropic/anthropic_stream.cpp b/src/providers/anthropic/anthropic_stream.cpp index 5a3b6a6..22649c2 100644 --- a/src/providers/anthropic/anthropic_stream.cpp +++ b/src/providers/anthropic/anthropic_stream.cpp @@ -119,6 +119,14 @@ void AnthropicStreamImpl::process_sse_event(const std::string& data) { push_event(StreamEvent(text)); ai::logger::log_debug("Enqueued text delta: '{}'", text); + } else if (json_event.contains("delta") && + json_event["delta"].is_object() && + string_or_empty(json_event["delta"], "type") == + "thinking_delta") { + // Empty unless the request asks for summarized thinking; recent + // models omit the thinking text by default. + push_event(StreamEvent::reasoning( + string_or_empty(json_event["delta"], "thinking"))); } else if (json_event.contains("delta") && json_event["delta"].is_object() && string_or_empty(json_event["delta"], "type") == diff --git a/src/providers/http_sse_stream.cpp b/src/providers/http_sse_stream.cpp index 292ef80..46c3c5f 100644 --- a/src/providers/http_sse_stream.cpp +++ b/src/providers/http_sse_stream.cpp @@ -2,14 +2,8 @@ #include "ai/logger.h" -#include #include -namespace { -constexpr auto kEventTimeout = static_cast(30); -constexpr auto kSleepInterval = std::chrono::milliseconds(1); -} // namespace - namespace ai { namespace providers { namespace streaming { @@ -37,7 +31,10 @@ void HttpSseStream::start_stream(const std::string& url, // Reset state for new stream should_stop_ = false; - is_complete_ = false; + { + std::lock_guard queue_lock(queue_mutex_); + is_complete_ = false; + } finish_event_pushed_ = false; stream_errored_ = false; line_buffer_.clear(); @@ -54,37 +51,30 @@ void HttpSseStream::start_stream(const std::string& url, } StreamEvent HttpSseStream::get_next_event() { - StreamEvent event(""); - auto start_time = std::chrono::steady_clock::now(); - - while (!event_queue_.try_dequeue(event)) { - if (is_complete_ && event_queue_.size_approx() == 0) { - // Stream is complete and queue is empty - ai::logger::log_debug( - "Stream complete and queue empty, returning empty event"); - return StreamEvent(""); - } - - // Check for timeout - if (std::chrono::steady_clock::now() - start_time > kEventTimeout) { - ai::logger::log_error( - "Timeout waiting for next stream event after {} seconds", - kEventTimeout.count()); - return StreamEvent(kStreamEventTypeError, - "Timeout waiting for next event"); - } - - std::this_thread::sleep_for(kSleepInterval); + // No timeout of its own here: the gaps between events can be long (e.g. + // while a model reasons without streaming its reasoning), and a stalled + // connection makes the stream thread push an error event and complete once + // its HTTP read timeout expires. + std::unique_lock lock(queue_mutex_); + queue_cv_.wait(lock, + [this] { return !event_queue_.empty() || is_complete_; }); + + if (event_queue_.empty()) { + ai::logger::log_debug( + "Stream complete and queue empty, returning empty event"); + return StreamEvent(""); } + StreamEvent event = std::move(event_queue_.front()); + event_queue_.pop_front(); ai::logger::log_debug("Dequeued event type: {}", static_cast(event.type)); return event; } bool HttpSseStream::has_more_events() const { - // No locks needed - these are atomic operations - return event_queue_.size_approx() > 0 || !is_complete_; + std::lock_guard lock(queue_mutex_); + return !event_queue_.empty() || !is_complete_; } void HttpSseStream::stop_stream() { @@ -216,7 +206,11 @@ void HttpSseStream::consume_chunk(const char* data, std::size_t length) { } void HttpSseStream::push_event(StreamEvent event) { - event_queue_.enqueue(std::move(event)); + { + std::lock_guard lock(queue_mutex_); + event_queue_.push_back(std::move(event)); + } + queue_cv_.notify_one(); } StreamEvent HttpSseStream::create_error_event(const std::string& message) { @@ -244,7 +238,11 @@ void HttpSseStream::push_finish_event_if_needed() { void HttpSseStream::mark_complete() { push_finish_event_if_needed(); - is_complete_ = true; // Atomic write + { + std::lock_guard lock(queue_mutex_); + is_complete_ = true; + } + queue_cv_.notify_all(); } void HttpSseStream::flush_all_pending_tool_calls() { diff --git a/src/providers/http_sse_stream.h b/src/providers/http_sse_stream.h index 6b9bb7d..3c72ccc 100644 --- a/src/providers/http_sse_stream.h +++ b/src/providers/http_sse_stream.h @@ -4,8 +4,9 @@ #include "providers/stream_utils.h" #include -#include +#include #include +#include #include #include #include @@ -53,7 +54,8 @@ class HttpSseStream : public internal::StreamResultImpl { process_sse_line(line); } std::size_t queued_event_count_for_testing() const { - return event_queue_.size_approx(); + std::lock_guard lock(queue_mutex_); + return event_queue_.size(); } #endif @@ -106,11 +108,16 @@ class HttpSseStream : public internal::StreamResultImpl { void consume_chunk(const char* data, std::size_t length); Options options_; - moodycamel::ConcurrentQueue event_queue_; + // Events produced by the stream thread. The consumer blocks on + // `queue_cv_` until an event arrives or the stream completes; a stalled + // connection is bounded by the HTTP read timeout of the stream thread. + mutable std::mutex queue_mutex_; + std::condition_variable queue_cv_; + std::deque event_queue_; std::thread stream_thread_; std::mutex thread_mutex_; std::string line_buffer_; - std::atomic is_complete_{false}; + bool is_complete_{false}; // Guarded by queue_mutex_. std::atomic should_stop_{false}; std::atomic finish_event_pushed_{false}; std::atomic stream_errored_{false}; diff --git a/src/providers/openai/openai_stream.cpp b/src/providers/openai/openai_stream.cpp index 6347b3a..3d6d8ea 100644 --- a/src/providers/openai/openai_stream.cpp +++ b/src/providers/openai/openai_stream.cpp @@ -43,6 +43,15 @@ void OpenAIStreamImpl::process_sse_line(std::string_view line) { push_event(StreamEvent(content)); } + // OpenAI-compatible servers stream reasoning in a field of their own: + // `reasoning_content` (DeepSeek, vLLM, SGLang) or `reasoning` + // (OpenRouter, Ollama). + for (const char* key : {"reasoning_content", "reasoning"}) { + if (delta.contains(key) && delta[key].is_string()) { + push_event(StreamEvent::reasoning(delta[key].get())); + } + } + if (delta.contains("tool_calls") && delta["tool_calls"].is_array()) { for (const auto& fragment : delta["tool_calls"]) { const auto index = fragment.value("index", std::size_t{0}); diff --git a/tests/unit/anthropic_stream_test.cpp b/tests/unit/anthropic_stream_test.cpp index ded11ba..8e2e662 100644 --- a/tests/unit/anthropic_stream_test.cpp +++ b/tests/unit/anthropic_stream_test.cpp @@ -450,5 +450,30 @@ TEST_F(AnthropicStreamEventTypesTest, MessageStopEvent) { EXPECT_THAT(event_data, testing::HasSubstr("message_stop")); } +TEST_F(AnthropicStreamEventTest, EmitsReasoningDeltasForThinking) { + anthropic::AnthropicStreamImpl stream; + stream.process_sse_chunk_for_testing( + R"(data: {"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":""}} + +data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"Weighing options"}} + +data: {"type":"content_block_delta","index":0,"delta":{"type":"signature_delta","signature":"abc"}} + +data: {"type":"content_block_stop","index":0} + +data: {"type":"content_block_delta","index":1,"delta":{"type":"text_delta","text":"Answer"}} + +)"); + + auto reasoning = stream.get_next_event(); + ASSERT_TRUE(reasoning.is_reasoning_delta()); + EXPECT_EQ(reasoning.reasoning_delta, "Weighing options"); + + auto text = stream.get_next_event(); + ASSERT_TRUE(text.is_text_delta()); + EXPECT_EQ(text.text_delta, "Answer"); + EXPECT_EQ(stream.queued_event_count_for_testing(), 0); +} + } // namespace test } // namespace ai diff --git a/tests/unit/openai_client_test.cpp b/tests/unit/openai_client_test.cpp index 3cac86b..73525cb 100644 --- a/tests/unit/openai_client_test.cpp +++ b/tests/unit/openai_client_test.cpp @@ -154,20 +154,19 @@ TEST_F(OpenAIClientTest, Gpt5FamilyUsesChatCompletionsCompatibleReasoning) { openai::OpenAIRequestBuilder builder; // GPT-5.1 and later accept "none" and reject "minimal". - for (const auto* model : - {openai::models::kGpt56, openai::models::kGpt56Luna, - openai::models::kGpt55, openai::models::kGpt54, - openai::models::kGpt54Mini, openai::models::kGpt54Nano, "gpt-5.2", - "gpt-5.1"}) { + for (const auto* model : {openai::models::kGpt56, openai::models::kGpt56Luna, + openai::models::kGpt55, openai::models::kGpt54, + openai::models::kGpt54Mini, + openai::models::kGpt54Nano, "gpt-5.2", "gpt-5.1"}) { GenerateOptions options(model, "Use a tool"); EXPECT_EQ(builder.build_request_json(options)["reasoning_effort"], "none") << model; } // The original GPT-5 models reject "none"; they get the "minimal" floor. - for (const auto* model : {"gpt-5", "gpt-5-2025-08-07", - openai::models::kGpt5Mini, - openai::models::kGpt5Nano}) { + for (const auto* model : + {"gpt-5", "gpt-5-2025-08-07", openai::models::kGpt5Mini, + openai::models::kGpt5Nano}) { GenerateOptions options(model, "Use a tool"); EXPECT_EQ(builder.build_request_json(options)["reasoning_effort"], "minimal") diff --git a/tests/unit/openai_stream_test.cpp b/tests/unit/openai_stream_test.cpp index c16ca16..15d7c50 100644 --- a/tests/unit/openai_stream_test.cpp +++ b/tests/unit/openai_stream_test.cpp @@ -6,6 +6,8 @@ #include "ai/types/stream_options.h" #include "ai/types/stream_result.h" +#include + #include #include @@ -129,6 +131,44 @@ TEST_F(StreamEventTest, EmitsOneFinishWithTerminalUsage) { EXPECT_EQ(finish_event.usage->total_tokens, 7); } +TEST_F(StreamEventTest, EmitsReasoningDeltas) { + openai::OpenAIStreamImpl stream; + stream.process_sse_line_for_testing( + R"(data: {"choices":[{"delta":{"reasoning_content":"Let me think"}}]})"); + stream.process_sse_line_for_testing( + R"(data: {"choices":[{"delta":{"reasoning":" about it"}}]})"); + stream.process_sse_line_for_testing( + R"(data: {"choices":[{"delta":{"content":"Done","reasoning_content":null}}]})"); + + auto first = stream.get_next_event(); + ASSERT_TRUE(first.is_reasoning_delta()); + EXPECT_EQ(first.reasoning_delta, "Let me think"); + EXPECT_TRUE(first.text_delta.empty()); + + auto second = stream.get_next_event(); + ASSERT_TRUE(second.is_reasoning_delta()); + EXPECT_EQ(second.reasoning_delta, " about it"); + + auto text = stream.get_next_event(); + ASSERT_TRUE(text.is_text_delta()); + EXPECT_EQ(text.text_delta, "Done"); + EXPECT_EQ(stream.queued_event_count_for_testing(), 0); +} + +TEST_F(StreamEventTest, ConsumerWaitsForEventFromAnotherThread) { + openai::OpenAIStreamImpl stream; + std::thread producer([&stream] { + stream.process_sse_line_for_testing( + R"(data: {"choices":[{"delta":{"content":"late"}}]})"); + }); + + // Blocks until the producer pushes the event; no polling, no timeout. + auto event = stream.get_next_event(); + producer.join(); + ASSERT_TRUE(event.is_text_delta()); + EXPECT_EQ(event.text_delta, "late"); +} + // Mock Stream Implementation Tests class MockStreamImpl { public: From f141720b20db065e6b0078c8ca8de7b36bc9dd63 Mon Sep 17 00:00:00 2001 From: Alexey Milovidov Date: Fri, 27 Nov 2026 19:45:30 +0000 Subject: [PATCH 2/3] Fix the merge of `anthropic_stream_test.cpp` Co-Authored-By: Claude Opus 5.5 --- tests/unit/anthropic_stream_test.cpp | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/tests/unit/anthropic_stream_test.cpp b/tests/unit/anthropic_stream_test.cpp index cc74b0a..567eed4 100644 --- a/tests/unit/anthropic_stream_test.cpp +++ b/tests/unit/anthropic_stream_test.cpp @@ -473,18 +473,19 @@ data: {"type":"content_block_delta","index":1,"delta":{"type":"text_delta","text ASSERT_TRUE(text.is_text_delta()); EXPECT_EQ(text.text_delta, "Answer"); EXPECT_EQ(stream.queued_event_count_for_testing(), 0); +} - TEST_F(AnthropicStreamEventTest, MapsRefusalToContentFilter) { - anthropic::AnthropicStreamImpl stream; - stream.process_sse_chunk_for_testing( - "data: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":" - "\"refusal\"}}\n\n" - "data: {\"type\":\"message_stop\"}\n\n"); +TEST_F(AnthropicStreamEventTest, MapsRefusalToContentFilter) { + anthropic::AnthropicStreamImpl stream; + stream.process_sse_chunk_for_testing( + "data: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":" + "\"refusal\"}}\n\n" + "data: {\"type\":\"message_stop\"}\n\n"); - auto finish_event = stream.get_next_event(); - ASSERT_TRUE(finish_event.is_finish()); - EXPECT_EQ(finish_event.finish_reason, kFinishReasonContentFilter); - } + auto finish_event = stream.get_next_event(); + ASSERT_TRUE(finish_event.is_finish()); + EXPECT_EQ(finish_event.finish_reason, kFinishReasonContentFilter); +} } // namespace test } // namespace ai From 137dd0702372c60f519b22ea40c35ff13fef92b7 Mon Sep 17 00:00:00 2001 From: Alexey Milovidov Date: Fri, 27 Nov 2026 21:20:13 +0000 Subject: [PATCH 3/3] Queue the finish event and complete the stream atomically `mark_complete` pushed the finish event (waking the consumer) and set `is_complete_` in a later critical section. A consumer that had dequeued the finish event could see an empty, incomplete queue, wait, and then yield the empty sentinel event after the finish. Both now happen under `queue_mutex_` in one step, so `has_more_events` is false once the finish event has been consumed. Reported by Cursor Bugbot in https://github.com/ClickHouse/ai-sdk-cpp/pull/65 Co-Authored-By: Claude Opus 5.5 --- src/providers/http_sse_stream.cpp | 25 ++++++++++++++++--------- src/providers/http_sse_stream.h | 5 +++-- tests/unit/openai_stream_test.cpp | 13 +++++++++++++ 3 files changed, 32 insertions(+), 11 deletions(-) diff --git a/src/providers/http_sse_stream.cpp b/src/providers/http_sse_stream.cpp index 46c3c5f..c4b8e89 100644 --- a/src/providers/http_sse_stream.cpp +++ b/src/providers/http_sse_stream.cpp @@ -218,28 +218,35 @@ StreamEvent HttpSseStream::create_error_event(const std::string& message) { return StreamEvent(kStreamEventTypeError, message); } -void HttpSseStream::push_finish_event_if_needed() { +std::optional HttpSseStream::take_finish_event() { bool expected = false; if (!finish_event_pushed_.compare_exchange_strong(expected, true)) { ai::logger::log_debug("Finish event already pushed, skipping"); - return; + return std::nullopt; } - ai::logger::log_debug("Pushing finish event to queue"); if (stream_errored_) { // Do not stamp a failed stream with a clean finish reason or usage. - push_event(StreamEvent(kStreamEventTypeFinish, kFinishReasonError)); - } else if (usage_) { - push_event(StreamEvent(kStreamEventTypeFinish, *usage_, finish_reason_)); - } else { - push_event(StreamEvent(kStreamEventTypeFinish, finish_reason_)); + return StreamEvent(kStreamEventTypeFinish, kFinishReasonError); + } + if (usage_) { + return StreamEvent(kStreamEventTypeFinish, *usage_, finish_reason_); } + return StreamEvent(kStreamEventTypeFinish, finish_reason_); } void HttpSseStream::mark_complete() { - push_finish_event_if_needed(); + auto finish_event = take_finish_event(); { + // Queue the terminal event and mark the stream complete atomically, so a + // consumer that has dequeued the finish event never sees an incomplete + // stream with an empty queue (and waits for, then yields, a spurious + // event after the finish). std::lock_guard lock(queue_mutex_); + if (finish_event) { + ai::logger::log_debug("Pushing finish event to queue"); + event_queue_.push_back(std::move(*finish_event)); + } is_complete_ = true; } queue_cv_.notify_all(); diff --git a/src/providers/http_sse_stream.h b/src/providers/http_sse_stream.h index 3c72ccc..62876a5 100644 --- a/src/providers/http_sse_stream.h +++ b/src/providers/http_sse_stream.h @@ -81,8 +81,9 @@ class HttpSseStream : public internal::StreamResultImpl { void push_event(StreamEvent event); static StreamEvent create_error_event(const std::string& message); - /// Push the terminal finish event (at most once per stream). - void push_finish_event_if_needed(); + /// The terminal finish event, or nullopt if it was already taken (it is + /// emitted at most once per stream). + std::optional take_finish_event(); /// Push the terminal finish event if still needed and mark the stream /// complete so consumers stop waiting for events. void mark_complete(); diff --git a/tests/unit/openai_stream_test.cpp b/tests/unit/openai_stream_test.cpp index 15d7c50..bda6f55 100644 --- a/tests/unit/openai_stream_test.cpp +++ b/tests/unit/openai_stream_test.cpp @@ -169,6 +169,19 @@ TEST_F(StreamEventTest, ConsumerWaitsForEventFromAnotherThread) { EXPECT_EQ(event.text_delta, "late"); } +TEST_F(StreamEventTest, NoEventsAfterFinish) { + openai::OpenAIStreamImpl stream; + stream.process_sse_line_for_testing( + R"(data: {"choices":[{"delta":{"content":"Hi"},"finish_reason":"stop"}]})"); + stream.process_sse_line_for_testing("data: [DONE]"); + + EXPECT_TRUE(stream.get_next_event().is_text_delta()); + ASSERT_TRUE(stream.get_next_event().is_finish()); + // The finish event is queued together with the completion flag, so the + // consumer stops here instead of waiting for (and yielding) another event. + EXPECT_FALSE(stream.has_more_events()); +} + // Mock Stream Implementation Tests class MockStreamImpl { public: