Skip to content

Commit 45b36fc

Browse files
committed
Keep bounded provider error descriptions
Signed-off-by: Hampton Lintorn-Catlin <hampton@squareup.com>
1 parent 7644822 commit 45b36fc

3 files changed

Lines changed: 69 additions & 45 deletions

File tree

‎docs/HOST_APP_GUIDE.md‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -305,11 +305,12 @@ Coplan inherits from your `::ApplicationController` for layout and middleware. T
305305

306306
## AI failure diagnostics
307307

308-
Chat and transcription errors append recognized OpenAI error types and codes,
309-
such as `invalid_request_error/context_length_exceeded`. Arbitrary response
310-
messages and unknown identifiers are omitted because providers can echo plan
311-
content or credentials. Malformed bodies fall back to the existing transport
312-
error. The original exception remains available as the cause.
308+
Chat and transcription errors append the provider's error type, code and message,
309+
including gateway-specific reasons and plain-string gateway errors. The combined
310+
diagnostic is limited to 300 characters and normalized to one line. Only string
311+
fields are included; request objects and other fields are omitted. Providers are
312+
trusted to supply suitable diagnostic text. Malformed bodies fall back to the
313+
existing transport error, and the original exception remains available as the cause.
313314

314315
## Configuration reference
315316

‎engine/app/services/coplan/ai_providers/open_ai.rb‎

Lines changed: 15 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -16,18 +16,8 @@ class OpenAi
1616
# models cap how much of this they will read.
1717
MAX_PROMPT_LENGTH = 600
1818

19-
# Response text can echo prompts, API keys, or uploaded content. Only
20-
# recognized protocol identifiers are safe to add to logged errors.
21-
ERROR_TYPES = %w[
22-
invalid_request_error authentication_error permission_error
23-
not_found_error rate_limit_error server_error api_error
24-
].freeze
25-
ERROR_CODES = %w[
26-
context_length_exceeded model_not_found invalid_api_key
27-
insufficient_quota rate_limit_exceeded invalid_value invalid_type
28-
missing_required_parameter unsupported_value unsupported_parameter
29-
content_policy_violation invalid_audio audio_too_short
30-
].freeze
19+
# Bound the complete appended diagnostic, including type and code.
20+
MAX_ERROR_DETAIL = 300
3121

3222
def self.call(system_prompt:, user_content:, model: nil)
3323
new(system_prompt:, user_content:, model:).call
@@ -108,20 +98,26 @@ def call
10898
raise Error, "Chat request failed: #{e.message}#{self.class.failure_detail(e)}"
10999
end
110100

111-
# Keep the reason without copying arbitrary provider text into job logs
112-
# or transcription responses. Unknown identifiers and free-form messages
113-
# are omitted, including string-only errors from compatible gateways.
101+
# Keep the provider's explanation, including gateway-specific reasons.
102+
# Only the error's diagnostic fields are appended, never request data.
114103
def self.failure_detail(error)
115104
response = error.response
116105
body = response[:body] if response.is_a?(Hash)
117106
body = JSON.parse(body) if body.is_a?(String)
118107
detail = body.is_a?(Hash) ? body["error"] : nil
108+
detail = { "message" => detail } if detail.is_a?(String)
119109
return "" unless detail.is_a?(Hash)
120110

121-
parts = []
122-
parts << detail["type"] if ERROR_TYPES.include?(detail["type"])
123-
parts << detail["code"] if ERROR_CODES.include?(detail["code"])
124-
parts.empty? ? "" : " (#{parts.join("/")})"
111+
type, code, message = %w[type code message].map do |key|
112+
value = detail[key]
113+
next unless value.is_a?(String)
114+
115+
value.encode("UTF-8", invalid: :replace, undef: :replace)
116+
.gsub(/[[:cntrl:]]/, " ").squish.truncate(MAX_ERROR_DETAIL).presence
117+
end
118+
label = [ type, code ].compact.join("/")
119+
text = [ label.presence, message ].compact.join(": ").truncate(MAX_ERROR_DETAIL)
120+
text.empty? ? "" : " (#{text})"
125121
rescue JSON::ParserError
126122
""
127123
end

‎spec/services/ai_providers/open_ai_spec.rb‎

Lines changed: 48 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -163,11 +163,12 @@ def stub_chat
163163
end
164164
end
165165

166-
shared_examples "safe provider diagnostics" do |operation, prefix|
166+
shared_examples "bounded provider diagnostics" do |operation, prefix|
167167
let(:mock_client) { instance_double(OpenAI::Client) }
168168
let(:detail) do
169169
{ "error" => { "type" => "invalid_request_error", "code" => "context_length_exceeded",
170-
"message" => "Request contained private-plan-content and sk-secret-key" } }
170+
"message" => "This model supports at most 128000 tokens.",
171+
"request" => { "content" => "private-plan-content", "api_key" => "sk-secret-key" } } }
171172
end
172173
let(:body) { detail }
173174
let(:failure) { Faraday::BadRequestError.new("the server responded with status 400", { status: 400, body: body }) }
@@ -193,51 +194,77 @@ def request
193194

194195
let(:operation) { operation }
195196

196-
it "keeps recognized reasons without echoing the provider message" do
197+
it "keeps the provider explanation without appending other response fields" do
197198
expect { request }.to raise_error(described_class::Error,
198-
"#{prefix}: the server responded with status 400 (invalid_request_error/context_length_exceeded)") { |error|
199+
"#{prefix}: the server responded with status 400 (invalid_request_error/context_length_exceeded: This model supports at most 128000 tokens.)") { |error|
199200
expect(error.cause).to equal(failure)
200201
}
201202
end
202203

203204
context "with a JSON body" do
204205
let(:body) { detail.to_json }
205206

206-
it "keeps the same safe identifiers" do
207+
it "keeps the same provider explanation" do
207208
expect { request }.to raise_error(described_class::Error,
208-
"#{prefix}: the server responded with status 400 (invalid_request_error/context_length_exceeded)")
209+
"#{prefix}: the server responded with status 400 (invalid_request_error/context_length_exceeded: This model supports at most 128000 tokens.)")
209210
end
210211
end
211212

212213
[ nil, "", "<html>Bad gateway</html>", "{broken", "null", "[]", '"error"', [],
213-
{ "error" => "private-plan-content sk-secret-key" }, { "error" => nil }, { "error" => [] },
214-
{ "error" => {} }, { "error" => { "message" => { "prompt" => "private-plan-content" } } },
215-
{ "error" => { "type" => "sk-secret-key", "code" => "private-plan-content" } },
216-
{ "error" => { "type" => "a" * 10_000, "code" => "b" * 10_000 } },
214+
{ "error" => nil }, { "error" => [] }, { "error" => {} }, { "error" => " \n " },
215+
{ "error" => { "message" => { "prompt" => "private-plan-content" } } },
217216
{ "error" => { "type" => [ "invalid_request_error" ], "code" => { "secret" => "value" } } },
218-
{ "error" => { "type" => "invalid_request_error\nforged log line", "code" => false } }
217+
{ "error" => { "type" => true, "code" => false, "message" => 123 } }
219218
].each_with_index do |malformed_body, index|
220-
context "with an untrusted or unusable error body (#{index})" do
219+
context "with an unusable error body (#{index})" do
221220
let(:body) { malformed_body }
222221

223-
it "falls back to the original status without leaking text or masking the failure" do
222+
it "falls back to the original status without masking the failure" do
224223
expect { request }.to raise_error(described_class::Error, "#{prefix}: the server responded with status 400") { |error|
225224
expect(error.cause).to equal(failure)
226225
}
227226
end
228227
end
229228
end
230229

231-
it "retains a recognized type when the code is unknown" do
232-
detail["error"]["code"] = "sk-secret-key"
230+
it "keeps gateway-specific error types, codes and messages" do
231+
detail["error"] = { "type" => "gateway_request_error", "code" => "custom_limit", "message" => "Try a smaller request." }
233232
expect { request }.to raise_error(described_class::Error,
234-
"#{prefix}: the server responded with status 400 (invalid_request_error)")
233+
"#{prefix}: the server responded with status 400 (gateway_request_error/custom_limit: Try a smaller request.)")
235234
end
236235

237-
it "retains a recognized code when the type is unknown" do
238-
detail["error"]["type"] = "private-plan-content"
236+
it "keeps a gateway's plain-string error" do
237+
detail["error"] = "prompt too long"
238+
expect { request }.to raise_error(described_class::Error, "#{prefix}: the server responded with status 400 (prompt too long)")
239+
end
240+
241+
it "normalizes whitespace and control characters in every field" do
242+
detail["error"] = { "type" => " gateway\nerror ", "code" => " custom\tlimit ", "message" => " Try\u0000 again. " }
243+
expect { request }.to raise_error(described_class::Error,
244+
"#{prefix}: the server responded with status 400 (gateway error/custom limit: Try again.)")
245+
end
246+
247+
it "handles invalid string encoding in decoded gateway bodies" do
248+
detail["error"] = { "message" => "bad \xFF response".force_encoding("UTF-8") }
239249
expect { request }.to raise_error(described_class::Error,
240-
"#{prefix}: the server responded with status 400 (context_length_exceeded)")
250+
"#{prefix}: the server responded with status 400 (bad \uFFFD response)")
251+
end
252+
253+
%w[type code message].each do |field|
254+
it "bounds an oversized #{field}" do
255+
detail["error"] = { field => "x" * 10_000 }
256+
expect { request }.to raise_error(described_class::Error,
257+
"#{prefix}: the server responded with status 400 (#{'x' * 297}...)")
258+
end
259+
end
260+
261+
it "bounds the combined diagnostic" do
262+
detail["error"] = { "type" => "t" * 100, "code" => "c" * 100, "message" => "m" * 100 }
263+
expect { request }.to raise_error(described_class::Error) { |error|
264+
suffix = error.message.delete_prefix("#{prefix}: the server responded with status 400")
265+
expect(suffix.length).to eq(303)
266+
expect(suffix).to end_with("...)")
267+
}
241268
end
242269

243270
context "when Faraday cannot parse the gateway response" do
@@ -271,10 +298,10 @@ def request
271298
end
272299

273300
describe "chat errors" do
274-
include_examples "safe provider diagnostics", :chat, "Chat request failed"
301+
include_examples "bounded provider diagnostics", :chat, "Chat request failed"
275302
end
276303

277304
describe "transcription errors" do
278-
include_examples "safe provider diagnostics", :transcribe, "Transcription failed"
305+
include_examples "bounded provider diagnostics", :transcribe, "Transcription failed"
279306
end
280307
end

0 commit comments

Comments
 (0)