Repository Public
1import Foundation2import Testing3@testable import AstraCore45// Regression tests for the defects confirmed by the pre-V2 source audit (docs/v2/ARCHITECTURE_AUDIT.md, CORE-n).67private let request = GenerationRequest(model: ModelRef(provider: .openAI, modelID: "m"), messages: [.user("hi")])89private final class DelayBox: @unchecked Sendable {10 private let lock = NSLock()11 private var values: [TimeInterval] = []12 func add(_ d: TimeInterval) { lock.withLock { values.append(d) } }13 var delays: [TimeInterval] { lock.withLock { values } }14}1516@Suite struct V2OrchestratorRegressions {17 /// CORE-1: a provider-supplied negative retry delay reached `UInt64(negative)` in the default sleep, which traps.18 @Test func negativeRetryDelayIsClampedBeforeSleeping() async {19 let box = DelayBox()20 let p = ScriptedProvider([.init(events: [], error: AstraError.rateLimited(retryAfter: -5, message: nil)),21 .init(events: [.textDelta("ok"), .messageCompleted(.endOfTurn)])])22 let o = InferenceOrchestrator(sleep: { box.add($0) }) { _ in p }23 var events: [StreamEvent] = []24 for await e in o.stream(request) { events.append(e) }25 #expect(box.delays == [0])26 #expect(events.last == .messageCompleted(.endOfTurn))27 }2829 @Test func nonFiniteRetryDelayIsNotWaitedOut() async {30 for bad in [Double.nan, .infinity] {31 let box = DelayBox()32 let p = ScriptedProvider([.init(events: [], error: AstraError.rateLimited(retryAfter: bad, message: nil)),33 .init(events: [.textDelta("ok"), .messageCompleted(.endOfTurn)])])34 let o = InferenceOrchestrator(sleep: { box.add($0) }) { _ in p }35 var events: [StreamEvent] = []36 for await e in o.stream(request) { events.append(e) }37 #expect(box.delays.isEmpty)38 #expect(p.callCount == 1)39 if case .error(.rateLimited) = events.last {} else { Issue.record("expected the rate-limit error, got \(String(describing: events.last))") }40 }41 }4243 /// The default sleep itself must be total: it is the last line of defence against a bad delay.44 @Test func defaultSleepAcceptsAnyDelay() async throws {45 let o = InferenceOrchestrator { _ in ScriptedProvider([]) }46 try await o.sleep(-3)47 try await o.sleep(.nan)48 try await o.sleep(0)49 }5051 /// CORE-6: a retried attempt forwarded a second `messageStarted`.52 @Test func aRetryNeverEmitsTwoStarts() async {53 let p = ScriptedProvider([.init(events: [.messageStarted(MessageStart(responseID: "a"))], error: AstraError.overloaded(nil)),54 .init(events: [.messageStarted(MessageStart(responseID: "b")), .textDelta("ok"), .messageCompleted(.endOfTurn)])])55 let o = InferenceOrchestrator(sleep: { _ in }) { _ in p }56 var events: [StreamEvent] = []57 for await e in o.stream(request) { events.append(e) }58 let starts = events.compactMap { if case .messageStarted(let s) = $0 { s } else { nil } }59 #expect(starts.map(\.responseID) == ["b"])60 if case .messageStarted = events.first {} else { Issue.record("the start must still come first") }61 }6263 /// A start-only attempt that fails for good still yields a start before its terminal error (one start, one terminal).64 @Test func aFailedStartOnlyAttemptStillHasAStartAndOneTerminal() async {65 let p = ScriptedProvider([.init(events: [.messageStarted(MessageStart(responseID: "a"))], error: AstraError.unauthorized(nil))])66 let o = InferenceOrchestrator(sleep: { _ in }) { _ in p }67 var events: [StreamEvent] = []68 for await e in o.stream(request) { events.append(e) }69 #expect(events.count == 1 || events.count == 2)70 #expect(events.filter(\.isTerminal).count == 1)71 #expect(events.last == .error(.unauthorized(nil)))72 }7374 /// CORE-12: an idle timeout does not prove the request was not accepted (and billed); it is not re-sent automatically.75 @Test func aTimeoutIsNotRetriedAutomatically() async {76 let p = ScriptedProvider([.init(events: [], error: AstraError.timeout), .init(events: [.textDelta("ok"), .messageCompleted(.endOfTurn)])])77 let o = InferenceOrchestrator(sleep: { _ in }) { _ in p }78 var events: [StreamEvent] = []79 for await e in o.stream(request) { events.append(e) }80 #expect(p.callCount == 1)81 #expect(events.last == .error(.timeout))82 }8384 /// CORE-5: an error that is not a network error must not be retried as if it were transient.85 @Test func anUnknownErrorIsNotRetried() async {86 struct Boom: Error {}87 let p = ScriptedProvider([.init(events: [], error: Boom()), .init(events: [.textDelta("ok"), .messageCompleted(.endOfTurn)])])88 let o = InferenceOrchestrator(sleep: { _ in }) { _ in p }89 for await _ in o.stream(request) {}90 #expect(p.callCount == 1)91 }9293 /// CORE-13: a message that ends while a tool call is still open lost the call silently.94 @Test func completionWithAnOpenToolCallIsAViolation() {95 var v = StreamValidator()96 _ = try? v.accept(.toolCallStarted(id: "1", name: "t"))97 _ = try? v.accept(.toolCallDelta(id: "1", argumentsFragment: "{"))98 #expect(throws: AstraError.self) { try v.accept(.messageCompleted(.toolCalls)) }99 }100101 /// CORE-10: the patch every consumer re-implemented now lives in one place.102 @Test func anUnterminatedOutcomeIsClosedExplicitly() {103 var cancelled = GenerationOutcome(); cancelled.apply(.textDelta("par"))104 cancelled.closeIfUnterminated(cancelled: true)105 #expect(cancelled.error == .cancelled && cancelled.stopReason == .cancelled && cancelled.text == "par")106 var dropped = GenerationOutcome(); dropped.apply(.textDelta("par"))107 dropped.closeIfUnterminated(cancelled: false)108 #expect(dropped.stopReason == .error)109 if case .protocolViolation = dropped.error {} else { Issue.record("expected a protocol violation") }110 var done = GenerationOutcome(); done.apply(.messageCompleted(.endOfTurn))111 done.closeIfUnterminated(cancelled: true)112 #expect(done.error == nil && done.stopReason == .endOfTurn)113 }114}115116@Suite struct V2BudgetRegressions {117 private func long(_ n: Int) -> String { String(repeating: "word ", count: n) }118119 /// CORE-2: with a history ending in a tool exchange, the plan dropped the user turn and returned a lone tool result.120 @Test func aToolLoopTailIsNeverOrphaned() {121 let call = ToolCall(id: "c1", name: "calculator", arguments: ["expression": "1+1"])122 let messages: [PromptMessage] = [.user(long(300)), .assistant("", toolCalls: [call]), .tool("2", callID: "c1", name: "calculator")]123 let plan = ContextBudget(window: 400, reservedForOutput: 100).plan(system: nil, messages: messages)124 #expect(plan.messages == messages)125 #expect(!plan.fits)126 #expect(plan.droppedCount == 0)127 }128129 @Test func olderTurnsAreDroppedButTheAnsweredUserTurnAndItsToolExchangeStay() {130 let call = ToolCall(id: "c1", name: "calculator", arguments: ["expression": "1+1"])131 let tail: [PromptMessage] = [.user("what is 1+1?"), .assistant("", toolCalls: [call]), .tool("2", callID: "c1", name: "calculator")]132 let messages: [PromptMessage] = [.user(long(200)), .assistant(long(200))] + tail133 let plan = ContextBudget(window: 400, reservedForOutput: 100).plan(system: nil, messages: messages)134 #expect(plan.messages == tail)135 #expect(plan.fits && plan.droppedCount == 2)136 }137138 /// The leading strip works on whole units: an assistant call is never separated from its results.139 @Test func leadingStripNeverSplitsAToolExchange() {140 let call = ToolCall(id: "c1", name: "t", arguments: [:])141 let messages: [PromptMessage] = [.user(long(300)), .assistant("", toolCalls: [call]), .tool("r", callID: "c1", name: "t"),142 .assistant("done"), .user("next")]143 let plan = ContextBudget(window: 300, reservedForOutput: 100).plan(system: nil, messages: messages)144 #expect(plan.messages.contains { !$0.toolCalls.isEmpty } == plan.messages.contains { $0.role == .tool })145 #expect(plan.messages.first?.role == .user)146 #expect(plan.messages.last == .user("next"))147 }148149 /// CORE-14: provider reasoning state replayed with a tool call is sent, so it is counted.150 @Test func providerStateOfAToolCallIsCounted() {151 let bare = ToolCall(id: "c1", name: "t", arguments: [:])152 var heavy = bare153 heavy.providerState = ["thinking": .string(String(repeating: "reason ", count: 400))]154 #expect(TokenEstimator.estimate(.assistant("", toolCalls: [heavy])) > TokenEstimator.estimate(.assistant("", toolCalls: [bare])) + 500)155 }156}157158@Suite struct V2SafetyRegressions {159 /// CORE-3: non-numeric labels were discarded, so a public name with four numeric labels passed as a private address.160 @Test func numericLabelsInsideAPublicNameAreNotLocal() {161 for host in ["10.0.0.1.evil.com", "192.168.1.1.attacker.example", "evil.127.0.0.1.example.org", "+10.0.0.1", "10.0.0.1.", "10.0.0"] {162 #expect(!EndpointPolicy.isLocalHost(host), "\(host)")163 }164 for host in ["10.0.0.1", "127.0.0.1", "192.168.1.20", "172.16.0.9", "169.254.1.1", "100.64.0.1", "localhost", "printer.local", "[::1]"] {165 #expect(EndpointPolicy.isLocalHost(host), "\(host)")166 }167 #expect(throws: AstraError.self) { try EndpointPolicy.validate("http://10.0.0.1.evil.com/v1", allowInsecure: true) }168 }169170 /// CORE-4: ordinary hyphenated words and prose about bearer authentication were masked (and stored masked).171 @Test func redactorLeavesHyphenatedProseAlone() {172 for text in ["Use task-specific-instructions here", "a risk-adjusted-performance-metric", "check disk-usage-statistics-daily",173 "Bearer authentication is required.", "the bearer of this message", "flexai-compatibility-layer-settings"] {174 #expect(Redactor.redact(text) == text)175 }176 }177178 @Test func redactorStillMasksRealKeyShapes() {179 let secret = "ABCDEFGHIJKLMNOP1234567890abcd"180 for text in ["key sk-\(secret) leaked", "(sk-ant-\(secret))", "Authorization: Bearer \(secret)", "\"sk-proj-\(secret)\"", "xai-\(secret)",181 "https://h/v1?key=\(secret)", "bearer eyJhbGciOi.\(secret)"] {182 #expect(!Redactor.redact(text).contains(secret), "\(text)")183 }184 }185186 /// CORE-7a: only the Bearer scheme was masked in an Authorization value.187 @Test func otherAuthorizationSchemesAreMasked() {188 #expect(!Redactor.redact("Authorization: Basic dXNlcjpwYXNzd29yZA==").contains("dXNlcjpwYXNz"))189 #expect(!Redactor.redact("authorization: Token abcdef0123456789").contains("abcdef0123456789"))190 #expect(!Redactor.redact(#"{"Authorization":"Basic dXNlcjpwYXNzd29yZA=="}"#).contains("dXNlcjpwYXNz"))191 }192193 /// CORE-7b: the message was cut to 400 characters before redaction, so a key straddling the cut leaked its head.194 @Test func aKeyStraddlingTheTruncationPointDoesNotLeak() {195 let message = String(repeating: "x", count: 385) + " sk-ABCDEFGHIJKLMNOPQRSTUVWX1234"196 let error = mapHTTPError(status: 401, code: nil, message: message, retryAfter: nil, model: nil)197 #expect(!error.message.contains("sk-ABCDEFGH"))198 #expect(error.message.count <= 400)199 }200201 /// CORE-5: every unknown error was typed as a transient network problem.202 @Test func wrapDoesNotCallNonNetworkErrorsNetwork() {203 struct Boom: Error {}204 for error in [CredentialError.keychain(-25308) as Error, Boom(),205 DecodingError.dataCorrupted(.init(codingPath: [], debugDescription: "x"))] {206 let wrapped = AstraError.wrap(error)207 #expect(!wrapped.isTransient, "\(error)")208 #expect(wrapped.title != AstraError.network("").title, "\(error)")209 }210 if case .decoding = AstraError.wrap(DecodingError.dataCorrupted(.init(codingPath: [], debugDescription: "x"))) {} else { Issue.record("decoding error not typed as decoding") }211 // a URL error is still a network error212 #expect(AstraError.wrap(URLError(.notConnectedToInternet)).isTransient)213 }214215 @Test func wrapRedactsTheFallbackText() {216 struct Leaky: LocalizedError { var errorDescription: String? { "failed with sk-ABCDEFGHIJKLMNOPQRSTUVWX1234" } }217 #expect(!AstraError.wrap(Leaky()).message.contains("ABCDEFGHIJKL"))218 }219}220221@Suite struct V2ParsingRegressions {222 /// CORE-8a: one non-finite number turned the whole document into "null".223 @Test func aNonFiniteNumberDoesNotEraseTheDocument() {224 let text = JSONValue.object(["a": 1, "b": .number(.infinity), "c": .number(.nan)]).serialized()225 #expect(text == #"{"a":1,"b":null,"c":null}"#)226 }227228 /// CORE-9: a byte-order mark before the first field hid the first event.229 @Test func aByteOrderMarkDoesNotHideTheFirstEvent() {230 var parser = SSEParser()231 #expect(parser.feed("\u{FEFF}data: x") == nil)232 #expect(parser.feed("") == SSEEvent(data: "x"))233 // only the very first line is treated this way234 #expect(parser.feed("\u{FEFF}data: y") == nil)235 #expect(parser.feed("") == nil)236 }237}238