Repository Public
1import Foundation2import Testing3import AstraCore4@testable import AstraProviders56// Regression tests for the defects confirmed by the pre-V2 source audit (docs/v2/FINDINGS_REGISTER.md, PROV-n).78@Suite struct V2ProviderRegressions {9 /// PROV-1: a huge or non-finite Retry-After reached `Int(Double)` when the error message was rendered, and trapped.10 @Test(arguments: ["1e30", "inf", "-inf", "nan", "-5"]) func anAbsurdRetryAfterDoesNotCrash(_ value: String) async {11 let transport = FixtureTransport(.json(429, Adapter.custom.errorBody(type: "rate_limit_error", message: "Slow down."), headers: ["Retry-After": value]))12 let collected = await collect(Adapter.custom.make(transport).stream(Adapter.custom.request))13 #expect(collected.error?.message.isEmpty == false)14 if case .rateLimited(let after, _)? = collected.error, let after { #expect(after.isFinite && after >= 0 && after <= 86_400) }15 }1617 /// PROV-2: complete calls sent one per chunk without `index` were fused into one call.18 @Test func completeCallsWithoutIndexStaySeparate() throws {19 var decoder = ChatCompletionsStreamDecoder(modelID: "m")20 _ = try decoder.consume(#"{"id":"r","choices":[{"index":0,"delta":{"tool_calls":[{"id":"call_a","function":{"name":"sum","arguments":"{\"a\":1}"}}]}}]}"#)21 _ = try decoder.consume(#"{"id":"r","choices":[{"index":0,"delta":{"tool_calls":[{"id":"call_b","function":{"name":"mul","arguments":"{\"b\":2}"}}]},"finish_reason":"tool_calls"}]}"#)22 let calls = decoder.finish().compactMap { if case .toolCallCompleted(let c) = $0 { c } else { nil } }23 #expect(calls.map(\.name) == ["sum", "mul"])24 #expect(calls.map(\.id) == ["call_a", "call_b"])25 #expect(calls.first?.arguments == ["a": 1] && calls.last?.arguments == ["b": 2])26 }2728 /// The same when a server reuses index 0 for each new call.29 @Test func aNewIdAtAnOccupiedIndexStartsANewCall() throws {30 var decoder = ChatCompletionsStreamDecoder(modelID: "m")31 _ = try decoder.consume(#"{"id":"r","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_a","function":{"name":"sum","arguments":"{\"a\":"}}]}}]}"#)32 _ = try decoder.consume(#"{"id":"r","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"1}"}}]}}]}"#)33 _ = try decoder.consume(#"{"id":"r","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_b","function":{"name":"mul","arguments":"{\"b\":2}"}}]},"finish_reason":"tool_calls"}]}"#)34 let calls = decoder.finish().compactMap { if case .toolCallCompleted(let c) = $0 { c } else { nil } }35 #expect(calls.map(\.name) == ["sum", "mul"])36 #expect(calls.first?.arguments == ["a": 1] && calls.last?.arguments == ["b": 2])37 }3839 /// The ordinary shape (index per call, id on the first fragment only, arguments in pieces) is unchanged.40 @Test func interleavedIndexedCallsStillAssemble() throws {41 var decoder = ChatCompletionsStreamDecoder(modelID: "m")42 _ = try decoder.consume(#"{"id":"r","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"a","function":{"name":"sum","arguments":""}},{"index":1,"id":"b","function":{"name":"mul","arguments":""}}]}}]}"#)43 _ = try decoder.consume(#"{"id":"r","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"{\"b\":2}"}},{"index":0,"function":{"arguments":"{\"a\":1}"}}]},"finish_reason":"tool_calls"}]}"#)44 let calls = decoder.finish().compactMap { if case .toolCallCompleted(let c) = $0 { c } else { nil } }45 #expect(calls.map(\.id) == ["a", "b"])46 #expect(calls.first?.arguments == ["a": 1] && calls.last?.arguments == ["b": 2])47 }4849 /// PROV-5: arguments sent as a JSON object (not a string) were dropped.50 @Test func argumentsSentAsAnObjectAreKept() throws {51 var decoder = ChatCompletionsStreamDecoder(modelID: "m")52 _ = try decoder.consume(#"{"id":"r","choices":[{"index":0,"message":{"tool_calls":[{"id":"c1","function":{"name":"get_weather","arguments":{"city":"Paris"}}}]},"finish_reason":"tool_calls"}]}"#)53 let calls = decoder.finish().compactMap { if case .toolCallCompleted(let c) = $0 { c } else { nil } }54 #expect(calls.first?.arguments == ["city": "Paris"])55 }5657 /// PROV-17: a call whose name never arrives cannot run; the turn must not claim it ended with tool calls.58 @Test func aCallWithoutANameDoesNotEndTheTurnAsToolCalls() throws {59 var decoder = ChatCompletionsStreamDecoder(modelID: "m")60 _ = try decoder.consume(#"{"id":"r","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"c1","function":{"arguments":"{}"}}]},"finish_reason":"tool_calls"}]}"#)61 let events = decoder.finish()62 #expect(!events.contains { if case .toolCallCompleted = $0 { true } else { false } })63 #expect(events.last != .messageCompleted(.toolCalls))64 }6566 /// PROV-4: token counts are a server's word; sums must not overflow.67 @Test func absurdUsageNeverTraps() {68 let chat = ChatCompletionsStreamDecoder.usage(JSONValue.parse(#"{"prompt_tokens":8e18,"completion_tokens":8e18}"#))69 _ = chat?.totalTokens70 let anthropic = AnthropicStreamDecoder.usage(JSONValue.parse(#"{"input_tokens":8e18,"cache_read_input_tokens":8e18,"cache_creation_input_tokens":8e18,"output_tokens":8e18}"#))71 _ = anthropic?.totalTokens72 let gemini = GeminiStreamDecoder.usage(JSONValue.parse(#"{"promptTokenCount":8e18,"candidatesTokenCount":8e18,"thoughtsTokenCount":8e18}"#))73 _ = gemini?.totalTokens74 #expect((anthropic?.inputTokens ?? 0) >= 0 && (gemini?.outputTokens ?? 0) >= 0)75 #expect(TokenUsage(inputTokens: -5, outputTokens: 3).inputTokens == nil)76 #expect(GenerationTiming(timeToFirstToken: 0, totalTime: 2).tokensPerSecond(outputTokens: 10, reasoningTokens: 4) == 3)77 }7879 /// PROV-14: an in-stream error message is cut to 400 characters; a key straddling the cut left its head on screen.80 @Test func aKeyCutByTheMessageLimitLeavesNoFragment() {81 let key = "leakcheck-opaque-token-7f3a9c"82 let message = String(repeating: "a", count: 385) + " " + key83 let error = mapHTTPError(status: 500, code: nil, message: message, retryAfter: nil, model: nil)84 let scrubbed = Secrets.scrub(error, secrets: [key])85 #expect(!scrubbed.message.contains("leakcheck"))86 }8788 /// PROV-15: a Keychain failure is not "no API key".89 @Test func aCredentialStoreFailureIsNotAMissingKey() async {90 let provider = OpenAIProvider(transport: FixtureTransport(), apiKey: { throw CredentialError.keychain(-25308) })91 let collected = await collect(provider.stream(request(.openAI, "gpt-5.2")))92 if case .missingCredential? = collected.error { Issue.record("a store failure was reported as a missing key") }93 #expect(collected.error != nil)94 }9596 /// PROV-16: the specific in-stream codes are tested before the generic "invalid".97 @Test func inStreamKeyAndModelErrorsKeepTheirType() {98 if case .unauthorized = ResponsesStreamDecoder.streamError(code: "invalid_api_key", message: "bad", modelID: "m") {} else { Issue.record("invalid_api_key is not unauthorized") }99 if case .modelNotFound = ResponsesStreamDecoder.streamError(code: "model_not_found", message: "the model is invalid", modelID: "m") {} else { Issue.record("model_not_found is not modelNotFound") }100 if case .invalidRequest = ResponsesStreamDecoder.streamError(code: "invalid_request_error", message: "bad", modelID: "m") {} else { Issue.record("invalid_request_error changed") }101 }102103 /// PROV-8: a thinking budget must not push `max_tokens` above what the model accepts.104 @Test func anthropicMaxTokensStaysWithinTheModelCap() throws {105 let entry = try #require(CuratedCatalog.anthropic("claude-sonnet-4-5"))106 let cap = entry.maxOutputTokens107 let body = AnthropicProvider.body(request(.anthropic, "claude-sonnet-4-5", parameters: GenerationParameters(maxOutputTokens: cap, reasoning: .high)))108 let maxTokens = try #require(body["max_tokens"]?.intValue)109 let budget = try #require(body["thinking"]?["budget_tokens"]?.intValue)110 #expect(maxTokens <= cap)111 #expect(budget < maxTokens)112 }113114 /// PROV-7: an API call that is redirected is not followed, so no credential header can reach another host.115 @Test func apiRedirectsAreRefusedByTheTransport() {116 let delegate = SameOriginRedirectPolicy()117 let done = DispatchSemaphore(value: 0)118 nonisolated(unsafe) var followed: URLRequest? = URLRequest(url: URL(string: "https://x.example")!)119 let session = URLSession(configuration: .ephemeral)120 let task = session.dataTask(with: URL(string: "https://api.example.com/v1")!)121 let response = HTTPURLResponse(url: URL(string: "https://api.example.com/v1")!, statusCode: 307, httpVersion: nil, headerFields: ["Location": "https://evil.example/c"])!122 delegate.urlSession(session, task: task, willPerformHTTPRedirection: response, newRequest: URLRequest(url: URL(string: "https://evil.example/c")!)) { followed = $0; done.signal() }123 done.wait()124 #expect(followed == nil)125 // a hop on the same host over https is still followed (canonical paths, trailing slashes)126 nonisolated(unsafe) var same: URLRequest?127 let again = DispatchSemaphore(value: 0)128 delegate.urlSession(session, task: task, willPerformHTTPRedirection: response, newRequest: URLRequest(url: URL(string: "https://API.example.com/v1/")!)) { same = $0; again.signal() }129 again.wait()130 #expect(same != nil)131 // and a downgrade to plain http on the same host is not132 nonisolated(unsafe) var downgraded: URLRequest? = URLRequest(url: URL(string: "https://x.example")!)133 let third = DispatchSemaphore(value: 0)134 delegate.urlSession(session, task: task, willPerformHTTPRedirection: response, newRequest: URLRequest(url: URL(string: "http://api.example.com/v1/")!)) { downgraded = $0; third.signal() }135 third.wait()136 #expect(downgraded == nil)137 }138}139