forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAIBackendErrorNormalizationTests.swift
More file actions
183 lines (161 loc) · 7.55 KB
/
Copy pathAIBackendErrorNormalizationTests.swift
File metadata and controls
183 lines (161 loc) · 7.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
import XCTest
@testable import Omi_Computer
final class AIBackendErrorNormalizationTests: XCTestCase {
func testEmbeddingTrialExpiredIsProductGateAndNotSentryActionable() {
let error = EmbeddingService.EmbeddingError.serverError(
statusCode: 402,
body: #"{"error":"trial_expired"}"#)
XCTAssertEqual(error.reasonCode, "product_gate")
XCTAssertTrue(error.isExpectedProductState)
XCTAssertTrue(error.isNonActionableForSentry)
XCTAssertEqual(
error.localizedDescription,
"Embedding API unavailable: active plan or BYOK keys required.")
}
func testEmbeddingRateLimitAndUnavailableAreTransient() {
let rateLimited = EmbeddingService.EmbeddingError.serverError(
statusCode: 429,
body: #"{"error":"rate limit exceeded"}"#)
let unavailable = EmbeddingService.EmbeddingError.serverError(
statusCode: 503,
body: #"{"error":"service unavailable"}"#)
XCTAssertEqual(rateLimited.reasonCode, "rate_limited")
XCTAssertTrue(rateLimited.isTransient)
XCTAssertTrue(rateLimited.isNonActionableForSentry)
XCTAssertEqual(unavailable.reasonCode, "temporarily_unavailable")
XCTAssertTrue(unavailable.isTransient)
XCTAssertTrue(unavailable.isNonActionableForSentry)
}
func testEmbeddingMalformedResponseRemainsActionable() {
let error = EmbeddingService.EmbeddingError.invalidResponse
XCTAssertEqual(error.reasonCode, "malformed_response")
XCTAssertFalse(error.isNonActionableForSentry)
}
func testEmbeddingMissingConfigurationRemainsActionable() {
let error = EmbeddingService.EmbeddingError.missingAPIKey
XCTAssertEqual(error.reasonCode, "missing_api_key")
XCTAssertFalse(error.isExpectedProductState)
XCTAssertFalse(error.isNonActionableForSentry)
}
func testGeminiTrialExpiredIsExpectedProductState() {
let error = GeminiClient.GeminiClientError.apiError("HTTP 402: trial_expired")
XCTAssertTrue(error.isExpectedProductState)
XCTAssertFalse(error.isTransient)
XCTAssertEqual(error.localizedDescription, "AI features require an active plan or BYOK keys.")
}
func testGeminiQuotaExceededUsesProductGateMessage() {
let error = GeminiClient.GeminiClientError.apiError("quota exceeded")
XCTAssertTrue(error.isExpectedProductState)
XCTAssertFalse(error.isTransient)
XCTAssertEqual(error.localizedDescription, "AI features require an active plan or BYOK keys.")
}
func testGeminiRetryRequiresTypedBackendAuthorization() throws {
let body = Data(#"{"error":"provider_unavailable"}"#.utf8)
let authorizedResponse = try XCTUnwrap(
HTTPURLResponse(
url: URL(string: "https://api.omi.me/v1/proxy/gemini")!,
statusCode: 503,
httpVersion: nil,
headerFields: ["X-Omi-Retryable": "true"]
))
let deniedResponse = try XCTUnwrap(
HTTPURLResponse(
url: URL(string: "https://api.omi.me/v1/proxy/gemini")!,
statusCode: 503,
httpVersion: nil,
headerFields: ["X-Omi-Retryable": "false"]
))
let absentResponse = try XCTUnwrap(
HTTPURLResponse(
url: URL(string: "https://api.omi.me/v1/proxy/gemini")!,
statusCode: 503,
httpVersion: nil,
headerFields: nil
))
let authorized = try XCTUnwrap(GeminiClient.httpError(response: authorizedResponse, data: body))
let denied = try XCTUnwrap(GeminiClient.httpError(response: deniedResponse, data: body))
let absent = try XCTUnwrap(GeminiClient.httpError(response: absentResponse, data: body))
XCTAssertTrue(GeminiClient.shouldAutoRetry(authorized))
XCTAssertFalse(GeminiClient.shouldAutoRetry(denied))
XCTAssertFalse(GeminiClient.shouldAutoRetry(absent))
}
/// A *response* still needs the backend's `X-Omi-Retryable` authorization to be replayed
/// — that contract is unchanged and asserted above. A transport failure produces no
/// response, so there is no authority to consult, and the previous policy discarded it
/// after a single attempt.
///
/// That excluded the one error class most worth retrying.
/// `NSURLErrorNetworkConnectionLost` (-1005) is a stale pooled-connection race, not an
/// outage: URLSession reuses a keep-alive socket the server has already closed and the
/// request dies in milliseconds. Measured on a live desktop session, 12 of 13 suggestion
/// evaluations failed this way — 4-7s apart, with plain requests to the same host
/// returning 200 in ~0.4s throughout — and every one was dropped without a second try.
///
/// Replay is safe here because every call this client makes is a `generateContent`
/// inference: prompt plus image in, text out, no server-side state change. A duplicate
/// costs one extra inference and nothing else.
func testTransportFailuresAreReplayedWithoutBackendAuthorization() {
for code in [
URLError.Code.networkConnectionLost, .timedOut, .cannotConnectToHost,
.notConnectedToInternet, .dnsLookupFailed, .cannotFindHost,
] {
XCTAssertTrue(
GeminiClient.shouldAutoRetry(URLError(code)),
"expected transport failure \(code.rawValue) to be replayable")
}
}
/// The widened replay must stay bounded to transport failures. A cancelled request is the
/// user or a superseding evaluation withdrawing the work, and replaying it would resurrect
/// work nobody is waiting for.
func testNonTransportURLErrorsAreStillNotReplayed() {
XCTAssertFalse(GeminiClient.shouldAutoRetry(URLError(.cancelled)))
XCTAssertFalse(GeminiClient.shouldAutoRetry(URLError(.badURL)))
XCTAssertFalse(GeminiClient.shouldAutoRetry(URLError(.userAuthenticationRequired)))
}
func testGeminiPlanGatedIsNotRetriedAndIsExpectedProductState() {
let error = GeminiClient.GeminiClientError.planGated
XCTAssertFalse(error.shouldAutoRetry)
XCTAssertFalse(error.isTransient)
XCTAssertTrue(error.isExpectedProductState)
XCTAssertFalse(GeminiClient.shouldAutoRetry(error))
XCTAssertEqual(error.localizedDescription, "AI features require an active plan or BYOK keys.")
}
func testGeminiHTTP402PlanGatedBodyMapsToPlanGatedAndIsNotRetried() throws {
let body = Data(#"{"detail":{"error":"plan_gated","plan_type":"basic"}}"#.utf8)
let response = try XCTUnwrap(
HTTPURLResponse(
url: URL(string: "https://api.omi.me/v1/proxy/gemini")!,
statusCode: 402,
httpVersion: nil,
headerFields: ["X-Omi-Retryable": "true"]
))
let error = try XCTUnwrap(GeminiClient.httpError(response: response, data: body))
guard case .planGated = error else {
return XCTFail("expected planGated, got \(error)")
}
XCTAssertFalse(GeminiClient.shouldAutoRetry(error))
}
func testGeminiHTTP402ChatQuotaBodyStaysApiError() throws {
let body = Data(#"{"error":"trial_expired"}"#.utf8)
let response = try XCTUnwrap(
HTTPURLResponse(
url: URL(string: "https://api.omi.me/v1/proxy/gemini")!,
statusCode: 402,
httpVersion: nil,
headerFields: nil
))
let error = try XCTUnwrap(GeminiClient.httpError(response: response, data: body))
guard case .apiError(let message, _) = error else {
return XCTFail("expected apiError for non-plan_gated 402, got \(error)")
}
XCTAssertTrue(message.contains("trial_expired"))
}
func testRequireManagedProactivityThrowsOnlyWhenGated() {
XCTAssertNoThrow(try GeminiClient.requireManagedProactivity(.allowManagedProactivity))
XCTAssertThrowsError(try GeminiClient.requireManagedProactivity(.planGated)) { error in
guard case GeminiClient.GeminiClientError.planGated = error else {
return XCTFail("expected planGated")
}
}
}
}