Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import java.io.ByteArrayOutputStream
import java.io.IOException

/**
* Helper class to interact with Google's Gemini API for visual verification and UI actions.
Expand Down Expand Up @@ -93,9 +94,15 @@ class GeminiVisualTestHelper(

/**
* Request timeout for the default client. CIO's own default is 15 seconds, which a Gemini vision
* request from an emulator can exceed.
* request from an emulator can exceed; under high demand even 60 seconds is not always enough.
*/
internal const val DEFAULT_REQUEST_TIMEOUT_MILLIS = 60_000L
internal const val DEFAULT_REQUEST_TIMEOUT_MILLIS = 120_000L

/** Total attempts for one Gemini request, including the first one. */
internal const val MAX_ATTEMPTS = 3

/** Delay before the first retry; it doubles for every retry after that. */
internal const val DEFAULT_RETRY_BASE_DELAY_MILLIS = 2_000L

internal fun createDefaultHttpClient(): HttpClient = HttpClient(CIO) {
engine {
Expand Down Expand Up @@ -369,43 +376,63 @@ class GeminiVisualTestHelper(
performActionFromPrompt(prompt, uiDevice, apiKey)
}

/**
* Base delay before retrying a transient Gemini failure. Doubles on every attempt. Tests set it
* to zero.
*/
internal var retryBaseDelayMillis: Long = DEFAULT_RETRY_BASE_DELAY_MILLIS

/**
* Posts [request] to [url], retrying transient failures: request timeouts and other network
* errors, `429 Too Many Requests`, and `5xx` server errors such as `503` when the model is
* under high demand. Any other status fails immediately.
*/
private suspend fun executeWithRetry(
url: String,
apiKey: String,
request: GeminiRequest,
maxRetries: Int = 3,
maxAttempts: Int = MAX_ATTEMPTS,
): HttpResponse {
var attempts = 0
var lastResponse: HttpResponse? = null

while (attempts < maxRetries) {
attempts++
val response: HttpResponse = client.post(url) {
header(API_KEY_HEADER, apiKey)
contentType(ContentType.Application.Json)
setBody(json.encodeToString(request))
for (attempt in 1..maxAttempts) {
val isLastAttempt = attempt == maxAttempts
val response: HttpResponse = try {
client.post(url) {
header(API_KEY_HEADER, apiKey)
contentType(ContentType.Application.Json)
setBody(json.encodeToString(request))
}
} catch (e: IOException) {
// HttpRequestTimeoutException and the connect/socket timeouts are IOExceptions.
if (isLastAttempt) {
Log.e(TAG, "Gemini API request failed after $attempt attempts", e)
throw e
}
backOff(attempt, maxAttempts, "Gemini API request failed with ${e::class.simpleName}")
continue
}

if (response.status == HttpStatusCode.OK) {
return response
}

lastResponse = response
if (response.status == HttpStatusCode.TooManyRequests || response.status == HttpStatusCode.ServiceUnavailable) {
val backoffMs = 1500L * attempts
Log.w(TAG, "Transient Gemini API status ${response.status}. Retrying in ${backoffMs}ms ($attempts/$maxRetries)...")
delay(backoffMs)
} else {
break
if (isLastAttempt || !response.status.isTransient()) {
val errorBody = response.bodyAsText()
Log.e(TAG, "Gemini API failed with status ${response.status}: $errorBody")
throw IllegalStateException("Gemini API request failed with status ${response.status}:\n$errorBody")
}
backOff(attempt, maxAttempts, "Transient Gemini API status ${response.status}")
}
error("unreachable: maxAttempts must be at least 1, was $maxAttempts")
}

val finalStatus = lastResponse?.status ?: HttpStatusCode.InternalServerError
val errorBody = lastResponse?.bodyAsText() ?: "No response"
Log.e(TAG, "Gemini API failed with status $finalStatus: $errorBody")
throw IllegalStateException("Gemini API request failed with status $finalStatus:\n$errorBody")
private suspend fun backOff(attempt: Int, maxAttempts: Int, reason: String) {
val backoffMs = retryBaseDelayMillis shl (attempt - 1)
Log.w(TAG, "$reason. Retrying in ${backoffMs}ms ($attempt/$maxAttempts)...")
delay(backoffMs)
}

private fun HttpStatusCode.isTransient(): Boolean = this == HttpStatusCode.TooManyRequests || value in 500..599

private fun Bitmap.toBase64EncodedJpeg(quality: Int = 85): String {
val safeBitmap = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && config == Bitmap.Config.HARDWARE) {
copy(Bitmap.Config.ARGB_8888, false)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
/*
* Copyright 2026 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.maps.android.testing.visual

import android.graphics.Bitmap
import com.google.common.truth.Truth.assertThat
import io.ktor.client.HttpClient
import io.ktor.client.engine.mock.MockEngine
import io.ktor.client.engine.mock.respond
import io.ktor.client.plugins.HttpRequestTimeoutException
import io.ktor.http.HttpHeaders
import io.ktor.http.HttpStatusCode
import io.ktor.http.headersOf
import kotlinx.coroutines.runBlocking
import org.junit.After
import org.junit.Assert.assertThrows
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config

@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34])
class GeminiRetryTest {

private val bitmap = Bitmap.createBitmap(8, 8, Bitmap.Config.ARGB_8888)

@Before
@After
fun cleanup() {
System.clearProperty("gemini.model")
GeminiVisualTestHelper.resetSessionModel()
}

@Test
fun retriesAfterRequestTimeout() = runBlocking {
val client = scriptedClient(Outcome.Timeout, Outcome.Respond(HttpStatusCode.OK))

val result = helper(client).analyzeImage(bitmap, "Verify the map", "key")

assertThat(result).isEqualTo("PASSED")
assertThat(client.calls).isEqualTo(2)
}

@Test
fun retriesTransientServerErrors() = runBlocking {
val client = scriptedClient(
Outcome.Respond(HttpStatusCode.ServiceUnavailable),
Outcome.Respond(HttpStatusCode.InternalServerError),
Outcome.Respond(HttpStatusCode.OK),
)

val result = helper(client).analyzeImage(bitmap, "Verify the map", "key")

assertThat(result).isEqualTo("PASSED")
assertThat(client.calls).isEqualTo(3)
}

@Test
fun retriesTooManyRequests() = runBlocking {
val client = scriptedClient(Outcome.Respond(HttpStatusCode.TooManyRequests), Outcome.Respond(HttpStatusCode.OK))

val result = helper(client).analyzeImage(bitmap, "Verify the map", "key")

assertThat(result).isEqualTo("PASSED")
assertThat(client.calls).isEqualTo(2)
}

@Test
fun rethrowsTimeoutWhenEveryAttemptTimesOut() {
val client = scriptedClient(Outcome.Timeout, Outcome.Timeout, Outcome.Timeout)

assertThrows(HttpRequestTimeoutException::class.java) {
runBlocking { helper(client).analyzeImage(bitmap, "Verify the map", "key") }
}
assertThat(client.calls).isEqualTo(GeminiVisualTestHelper.MAX_ATTEMPTS)
}

@Test
fun failsWithLastStatusWhenEveryAttemptIsTransient() {
val client = scriptedClient(
Outcome.Respond(HttpStatusCode.ServiceUnavailable),
Outcome.Respond(HttpStatusCode.ServiceUnavailable),
Outcome.Respond(HttpStatusCode.ServiceUnavailable),
)

val error = assertThrows(IllegalStateException::class.java) {
runBlocking { helper(client).analyzeImage(bitmap, "Verify the map", "key") }
}
assertThat(error).hasMessageThat().contains("503")
assertThat(client.calls).isEqualTo(GeminiVisualTestHelper.MAX_ATTEMPTS)
}

@Test
fun doesNotRetryClientErrors() {
val client = scriptedClient(Outcome.Respond(HttpStatusCode.BadRequest), Outcome.Respond(HttpStatusCode.OK))

val error = assertThrows(IllegalStateException::class.java) {
runBlocking { helper(client).analyzeImage(bitmap, "Verify the map", "key") }
}
assertThat(error).hasMessageThat().contains("400")
assertThat(client.calls).isEqualTo(1)
}

@Test
fun defaultClientAllowsTwoMinutesPerRequest() {
assertThat(GeminiVisualTestHelper.DEFAULT_REQUEST_TIMEOUT_MILLIS).isEqualTo(120_000L)
}

private fun helper(client: ScriptedClient) = GeminiVisualTestHelper(preferredModel = "gemini-test-flash", client = client.httpClient).apply {
retryBaseDelayMillis = 0L
}

private sealed interface Outcome {
data object Timeout : Outcome
data class Respond(val status: HttpStatusCode) : Outcome
}

private class ScriptedClient(outcomes: List<Outcome>) {
var calls = 0
private set

val httpClient = HttpClient(
MockEngine { request ->
val outcome = outcomes[calls++]
when (outcome) {
Outcome.Timeout -> throw HttpRequestTimeoutException(request.url.toString(), 120_000L)

is Outcome.Respond -> {
val body = if (outcome.status == HttpStatusCode.OK) generateContentResponse("PASSED") else """{ "error": { "code": ${outcome.status.value} } }"""
respond(body, outcome.status, headersOf(HttpHeaders.ContentType, "application/json"))
}
}
},
)
}

private fun scriptedClient(vararg outcomes: Outcome) = ScriptedClient(outcomes.toList())
}
Loading