Skip to content

A platform for community discussion. Free, open, simple.

FIX: Harden JSON streaming tracker for arrays of objects (#36047)

Roman Rizzibaf4f4f46512
diff --git a/plugins/discourse-ai/lib/completions/json_streaming_tracker.rb b/plugins/discourse-ai/lib/completions/json_streaming_tracker.rb
index b4e75c08db9..21cd6b2ffee 100644
--- a/plugins/discourse-ai/lib/completions/json_streaming_tracker.rb
+++ b/plugins/discourse-ai/lib/completions/json_streaming_tracker.rb
@@ -10,16 +10,25 @@ module DiscourseAi
@current_key = nil
@current_value = nil
@tracking_array = false
+ @broken = false
@parser = DiscourseAi::Completions::JsonStreamingParser.new
@parser.key do |k|
+ next if @broken
+ if @tracking_array && @current_key.present?
+ mark_broken!
+ next
+ end
+
@current_key = k
@current_value = nil
end
@parser.value do |value|
+ next if @broken
if @current_key
if @tracking_array
+ @current_value ||= []
@current_value << value
stream_consumer.notify_progress(@current_key, @current_value)
else
@@ -30,11 +39,15 @@ module DiscourseAi
end
@parser.start_array do
+ next if @broken
+ next unless @current_key
+
@tracking_array = true
@current_value = []
end
@parser.end_array do
+ next if @broken
@tracking_array = false
@current_key = nil
@current_value = nil
@@ -74,6 +87,13 @@ module DiscourseAi
private
+ def mark_broken!
+ @broken = true
+ @tracking_array = false
+ @current_key = nil
+ @current_value = nil
+ end
+
def try_escape_and_parse(raw_json, pre_append_buffer)
if !raw_json.is_a?(String)
@broken = true
diff --git a/plugins/discourse-ai/spec/lib/completions/structured_output_spec.rb b/plugins/discourse-ai/spec/lib/completions/structured_output_spec.rb
index ef8e687e6fb..8b45aab8eec 100644
--- a/plugins/discourse-ai/spec/lib/completions/structured_output_spec.rb
+++ b/plugins/discourse-ai/spec/lib/completions/structured_output_spec.rb
@@ -122,6 +122,29 @@ RSpec.describe DiscourseAi::Completions::StructuredOutput do
expect(structured_output.read_buffered_property(:message)).to eq("Hello!\n")
end
+
+ context "when arrays contain objects" do
+ subject(:structured_output) do
+ described_class.new({ ratings: { type: "array", items: { type: "object" } } })
+ end
+
+ it "falls back to full parsing without raising" do
+ chunks = [
+ +"{\"ratings\":[{\"candidate\":\"alpha\",\"rating\":9",
+ +"},{\"candidate\":\"bravo\",\"rating\":6}]}",
+ ]
+
+ expect { structured_output << chunks[0] }.not_to raise_error
+ expect(structured_output.read_buffered_property(:ratings)).to eq(nil)
+
+ structured_output << chunks[1]
+ structured_output.finish
+
+ expect(structured_output.read_buffered_property(:ratings)).to eq(
+ [{ "candidate" => "alpha", "rating" => 9 }, { "candidate" => "bravo", "rating" => 6 }],
+ )
+ end
+ end
end
describe "dealing with non-JSON responses" do