diff --git a/cli/src/test/kotlin/loop/cli/TranscriptReplay.kt b/cli/src/test/kotlin/loop/cli/TranscriptReplay.kt index 533b0919..670bf3cc 100644 --- a/cli/src/test/kotlin/loop/cli/TranscriptReplay.kt +++ b/cli/src/test/kotlin/loop/cli/TranscriptReplay.kt @@ -38,14 +38,18 @@ fun main(args: Array) { val transcript = Path.of(args[0]) val record = Path.of(args[1]) val argv = args.drop(2) - record.resolve("argv").writeText(argv.joinToString("\n")) + // Two attempts of one run may replay at once into the same record folder: each file is replaced atomically, since + // concurrent `Files.copy` with REPLACE_EXISTING deletes then creates the target and one of them can fail. + TranscriptReplay.replaceAtomically(record.resolve("argv")) { it.writeText(argv.joinToString("\n")) } val mcpConfig = argv .zipWithNext() .firstOrNull { it.first == "--mcp-config" } ?.second ?.let { Path.of(it) } - mcpConfig?.let { Files.copy(it, record.resolve("mcp.json"), StandardCopyOption.REPLACE_EXISTING) } + mcpConfig?.let { config -> + TranscriptReplay.replaceAtomically(record.resolve("mcp.json")) { Files.copy(config, it, StandardCopyOption.REPLACE_EXISTING) } + } // The first user message line; Claude Code with `--input-format stream-json` keeps stdin open (m3-07). readlnOrNull() val servers = @@ -77,6 +81,20 @@ fun main(args: Array) { } object TranscriptReplay { + /** Writes [target] through [write] into a temporary file of its own folder, then moves it over [target] atomically. */ + fun replaceAtomically( + target: Path, + write: (Path) -> Unit, + ) { + val temp = Files.createTempFile(target.parent, ".${target.fileName}", ".tmp") + try { + write(temp) + Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING) + } finally { + Files.deleteIfExists(temp) + } + } + data class ToolUse( val id: String, val name: String, diff --git a/docs/plugins/runner-acp.md b/docs/plugins/runner-acp.md index c5fd2345..268a2a1e 100644 --- a/docs/plugins/runner-acp.md +++ b/docs/plugins/runner-acp.md @@ -123,7 +123,9 @@ Loop ships default context windows of `1048576` tokens in `ContextConfig.DEFAULT - **Occupancy:** every `usage_update` notification with `used > 0` emits `context_usage` with `google/`, deduplicated when occupancy and model are unchanged. - **Usage:** every `session/prompt` response carrying `usage` adds its turn counts into the session's running absolute totals with `totalCostUsd = null`. - **Hard-limit interrupt:** `AgentSession.interrupt()` sends a `session/cancel` notification, answers any pending `session/request_permission` with `cancelled`, preserves `result.usage` on `stopReason: "cancelled"`, and ends the turn cleanly so Loop rotates onto a fresh session. -- **Error mapping:** structured JSON-RPC errors reporting authentication or eligibility failure (401, 403, expired login, `IneligibleTierError`), rate limit or overload (429, 503, 529), model refusal (`-32602 Unknown model ID` or `modelNotFound`), or runtime-reported network transport failure with no HTTP status map to `runner_unavailable`, as does an `agy` of another major or older than the minimum at `initialize` under `preset: agy`. All other errors, exits, and malformed lines are ordinary failures. +- **Error mapping:** structured JSON-RPC errors reporting authentication or eligibility failure (401, 403, expired login, `IneligibleTierError`), rate limit or overload (429, 503, 529), model refusal (`-32602 Unknown model ID` or `modelNotFound`), or runtime-reported network transport failure with no HTTP status map to `runner_unavailable`, as does an `agy` of another major or older than the minimum at `initialize` under `preset: agy`. All other errors, exits, and malformed lines are ordinary failures. A Google error object anywhere in the error data, nested in a string field included, maps to `runner_unavailable` when its `status` is `RESOURCE_EXHAUSTED` or an `ErrorInfo` `reason` is `QUOTA_EXHAUSTED`. The quota message text alone is free text and maps nothing. +- **Retry time and quota reset (bl-215):** a `runner_unavailable` with a status or a rate limit code sets `retryAfter`, which the run level hold uses as its period when it is longer than the backoff, so one probe runs at the reset instead of one every 1 to 15 minutes. An explicit `retryAfterMs`, `retry_after_ms`, `retryAfterSeconds`, `retry_after_seconds`, `retryAfter` or `retry_after` key of the error data comes first. Else the wait is the first valid positive value of, in order: `quotaResetTimeStamp` (RFC 3339) minus now, `quotaResetDelay`, a `RetryInfo` `retryDelay`, each searched at any depth of the error data, a JSON body inside a string field included, then `Your quota will reset after ` in the error message or a string of the data. Durations use Google's format (`4h23m27.716645894s`, `27s`, `850ms`). A past timestamp or an unparsable value is skipped, never a failure, and nothing found leaves `retryAfter` empty as before. +- **`rate_limit` event:** with a quota reset found, the turn emits `rate_limit` before `turn_failed`, with `limit_id` `gemini`, the error's `metadata.model` as `limit_name` (else `runners.acp.model`), and `reached` `quota_exhausted`. It carries no window, since a window needs a used percent that `agy` never reports, so the reset time is in the `turn_failed` reason instead: `turn_failed: (code ); the quota resets at `. `loop trace` prints it as `rate_limit limit=gemini name= reached=quota_exhausted`. Only the reset time and a plain model id are read from the error: no account id, email or token reaches the event or the reason. The JSON-RPC line itself is still echoed as runner output, like every protocol line. The decisions are in [The acp runner holds until an exhausted Gemini quota resets](../spec-decisions.md#the-acp-runner-holds-until-an-exhausted-gemini-quota-resets-extension-bl-215). - **Startup preflight (`preset: agy`):** verifies the `agy` binary is reachable, on pinned major version `1` and no older than `1.5.18`, reading the version from the line of `agy --version` that is only a version, else its last version token, so a banner such as `new version 1.6.0 available` printed before it never decides it (errors stop startup; 1.5.18 is the first version that applies permission prompts to files read or edited through `file:///` URIs, which the guards above rely on), and runs `agy models` to warn on login problems, offline failures, or a configured model not listed. ## Capabilities diff --git a/docs/spec-decisions.md b/docs/spec-decisions.md index 325ae5a6..859ff378 100644 --- a/docs/spec-decisions.md +++ b/docs/spec-decisions.md @@ -3120,6 +3120,17 @@ Under `preset: agy` each session ran with a fresh isolated `--gemini-dir` folder Tests: `plugins/runner-acp/src/test/kotlin/loop/runner/acp/AgyResumeTest.kt` (a hold keeps the folder and a resume loads it in a new process with the same folder, a respawn after a dead process, a respawn that dies fails the turn without a second one, no kept folder, a tampered `settings.json` rewritten before the load, an unexpected root entry refused, an agent without `loadSession` and a `session/load` error each giving a fresh session, a session without an id deleting its folder, and since bl-230 a kept folder surviving a new session of the issue until that one is kept, the sweep at the runner's start, a protected roots failure ending the session), `plugins/runner-acp/src/test/kotlin/loop/runner/acp/AgyIsolationDirLifetimeTest.kt` (the lookup and claim, the removal of an issue's kept folders, the sweep of a gone workspace and of a dead owner under both roots, the checks before a load, and since bl-230 the allow lists of `config/` and `antigravity-cli/`, the folder `removeKept` spares, and the pid file claim against a concurrent sweep) and `AcpRunnerContractTest` (the contract's resume cases under `preset: agy`). +### The acp runner holds until an exhausted Gemini quota resets (extension, bl-215) + +A `runner_unavailable` from an exhausted Gemini quota carried no retry key Loop read, so the run level hold probed after 1 minute, then 2, 4 and up to 15 minutes for hours until the quota reset. Google's 429 carries the reset: `agy`'s own CLI logged three, each `RESOURCE_EXHAUSTED` with an `ErrorInfo` of reason `QUOTA_EXHAUSTED` whose `metadata` holds `model`, `quotaResetDelay` and `quotaResetTimeStamp`, a `RetryInfo` `retryDelay`, and the message `Your quota will reset after `. Which of these `agy acp` passes through its JSON-RPC error is not confirmed yet, so every form is read (`AcpQuotaReset` in `plugins/runner-acp`). + +- **Classified on structured fields.** A Google error object anywhere in the error data, a JSON body inside a string field included, maps to `runner_unavailable` when its `status` is `RESOURCE_EXHAUSTED` or an `ErrorInfo` reason is `QUOTA_EXHAUSTED`. The quota message alone is free text and classifies nothing, as since `m4-08`. +- **Wait.** An explicit retry key of the error data comes first, as before. Else the first valid positive value of `quotaResetTimeStamp` minus now, `quotaResetDelay`, `retryDelay` (any depth), then the message text, becomes `TurnFailed.retryAfter`, in Google's duration format. A past timestamp or an unparsable value is skipped. `RunnerHold` is unchanged: it already takes a `retryAfter` longer than its backoff as the period, so one probe runs at the reset. +- **Telemetry.** The turn emits the `rate_limit` event of the Codex runner with `limit_id` `gemini`, the model as `limit_name` and `reached` `quota_exhausted`. `RunnerEvent.RateLimit.Window` needs a used percent that `agy` never reports, so the event carries no window and the reset instant goes in the `turn_failed` reason, `...; the quota resets at `, rather than a `plugin-api` change. +- **Redaction.** Only the reset time and a plain model id are read from the error, so no account id, email or token reaches the event or the reason. The raw JSON-RPC line is still echoed as runner output, like every protocol line. + +Tests: `plugins/runner-acp/src/test/kotlin/loop/runner/acp/AcpQuotaResetTest.kt` (from the logged 429 body: details in the error data, the body nested in a string, an array body in a string, the message text only, a past timestamp, an unparsable value, no reset at all, an explicit retry key first, the duration format, and through the fake server the `rate_limit` event and `retryAfter` of a prompt error), `spec-core/src/test/kotlin/loop/core/orchestrator/RunnerHoldTest.kt` (`bl-215 an exhausted Gemini quota holds until its reset time, not the 1 minute backoff`). + ### Claude Code rate limits (extension, bl-209) Conformance 17.5 item 13 asks a runner to extract rate limit telemetry; the Codex runner did since [m3-21](#codex-runner-usage-rate-limits-and-cost-m3-21), the Claude Code runner dropped its rate limit lines. Claude Code writes `{"type":"rate_limit_event","rate_limit_info":{...}}` lines in its stream: a `status` (`allowed`, `allowed_warning`, `rejected`), the `rateLimitType` and `resetsAt` of the window that status is about, the overage fields, and `unifiedWindows`, each window by name with its `utilization` (0 to 1), `resetsAt` (Unix seconds) and `status`. The recorded lines of `real_two_turns_one_process.jsonl` and `wake_turns_10c2f759.jsonl` name only `seven_day`. The decisions (`ClaudeRateLimits` in `plugins/runner-claude-code`): diff --git a/mcp/src/main/kotlin/loop/mcp/LoopMcpServer.kt b/mcp/src/main/kotlin/loop/mcp/LoopMcpServer.kt index 7bb34acb..2f8b7333 100644 --- a/mcp/src/main/kotlin/loop/mcp/LoopMcpServer.kt +++ b/mcp/src/main/kotlin/loop/mcp/LoopMcpServer.kt @@ -406,8 +406,10 @@ object LoopMcpServer { val server = create(version, submitResult, move, comment, trimmer, resources, ask, followup) val transport = StdioServerTransport(input.asSource().buffered(), output.asSink().buffered()) val closed = CompletableDeferred() - val session = server.createSession(transport) - session.onClose { closed.complete(Unit) } + // Listened to before createSession, which starts the transport: an input that ends at once can close it + // before createSession returns, and a listener added to the session after that would never hear the close. + transport.onClose { closed.complete(Unit) } + server.createSession(transport) closed.await() } diff --git a/mcp/src/test/kotlin/loop/mcp/LoopMcpServerTest.kt b/mcp/src/test/kotlin/loop/mcp/LoopMcpServerTest.kt index 973c38e7..162790bf 100644 --- a/mcp/src/test/kotlin/loop/mcp/LoopMcpServerTest.kt +++ b/mcp/src/test/kotlin/loop/mcp/LoopMcpServerTest.kt @@ -14,6 +14,8 @@ import kotlinx.serialization.json.jsonArray import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive import java.io.BufferedReader +import java.io.ByteArrayInputStream +import java.io.OutputStream import java.nio.channels.Channels import java.nio.channels.Pipe import kotlin.test.Test @@ -693,4 +695,32 @@ class LoopMcpServerTest { } assertTrue(!client.serving.isAlive, "the server still runs after the end of its input") } + + /** + * The transport starts reading inside `createSession`, so an input that ends at once can close the session before + * `serve` returns from it. The end is still seen: every one of these servers returns. + */ + @Test + fun `the server returns when its input ends before the session is set up`() { + repeat(200) { round -> + val serving = + Thread { + runBlocking { + LoopMcpServer.serve( + ByteArrayInputStream(ByteArray(0)), + OutputStream.nullOutputStream(), + "test", + SubmitResultHandler { ToolReply("ok") }, + MoveHandler { ToolReply("moved") }, + CommentHandler { ToolReply("commented") }, + ) + } + }.apply { + isDaemon = true + start() + } + serving.join(10_000) + assertTrue(!serving.isAlive, "server $round still runs after its input ended") + } + } } diff --git a/plugins/runner-acp/src/main/kotlin/loop/runner/acp/AcpErrors.kt b/plugins/runner-acp/src/main/kotlin/loop/runner/acp/AcpErrors.kt index c51d3f1b..4323c67b 100644 --- a/plugins/runner-acp/src/main/kotlin/loop/runner/acp/AcpErrors.kt +++ b/plugins/runner-acp/src/main/kotlin/loop/runner/acp/AcpErrors.kt @@ -8,9 +8,11 @@ import kotlinx.serialization.json.doubleOrNull import kotlinx.serialization.json.longOrNull import loop.api.RunnerEvent import java.util.Locale +import kotlin.time.Clock import kotlin.time.Duration import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.seconds +import kotlin.time.Instant /** * Classifies structured ACP JSON-RPC errors into [RunnerEvent.TurnFailed.Category.RunnerUnavailable] @@ -24,6 +26,7 @@ internal object AcpErrors { data class Classification( val category: RunnerEvent.TurnFailed.Category?, val retryAfter: Duration? = null, + val quotaReset: AcpQuotaReset.Reset? = null, ) private const val INVALID_PARAMS_CODE = -32602L @@ -80,13 +83,16 @@ internal object AcpErrors { /** * Classifies a structured JSON-RPC error response for [method]. Returns `RunnerUnavailable` only * for structured model refusals, authentication/eligibility codes or 401/403 statuses, rate limit - * or overload codes or 429/503/529 statuses, or POSIX/Node transport errno codes with no HTTP status. + * or overload codes or 429/503/529 statuses (a Google `RESOURCE_EXHAUSTED` or `QUOTA_EXHAUSTED` + * error at any depth of [data] included), or POSIX/Node transport errno codes with no HTTP status. + * A rate limit or status classification carries its wait, a quota reset measured from [now]. */ fun classify( method: String?, code: Long, message: String, data: JsonElement? = null, + now: Instant = Clock.System.now(), ): Classification { val dataObj = data as? JsonObject val httpStatus = extractHttpStatus(dataObj) @@ -102,28 +108,19 @@ internal object AcpErrors { } if (httpStatus != null && httpStatus in UNAVAILABLE_HTTP_STATUSES) { - return Classification( - category = RunnerEvent.TurnFailed.Category.RunnerUnavailable, - retryAfter = extractRetryAfter(dataObj), - ) + return unavailableWithWait(message, data, now) } if (HTTP_STATUS_LINE_PATTERNS.any { it.containsMatchIn(combined) }) { - return Classification( - category = RunnerEvent.TurnFailed.Category.RunnerUnavailable, - retryAfter = extractRetryAfter(dataObj), - ) + return unavailableWithWait(message, data, now) } if (tokens.any { it in STRUCTURED_AUTH_CODES }) { return Classification(RunnerEvent.TurnFailed.Category.RunnerUnavailable) } - if (tokens.any { it in STRUCTURED_RATE_LIMIT_CODES }) { - return Classification( - category = RunnerEvent.TurnFailed.Category.RunnerUnavailable, - retryAfter = extractRetryAfter(dataObj), - ) + if (tokens.any { it in STRUCTURED_RATE_LIMIT_CODES } || AcpQuotaReset.isQuotaExhausted(data)) { + return unavailableWithWait(message, data, now) } // m4-08: a transport failure with no HTTP status at all is RunnerUnavailable; one with an HTTP @@ -135,6 +132,21 @@ internal object AcpErrors { return Classification(category = null) } + /** + * A `RunnerUnavailable` that may carry a wait: an explicit retry key of the error data first, else the quota reset + * [AcpQuotaReset] finds (bl-215), else none. + */ + private fun unavailableWithWait( + message: String, + data: JsonElement?, + now: Instant, + ): Classification { + val unavailable = RunnerEvent.TurnFailed.Category.RunnerUnavailable + extractRetryAfter(data as? JsonObject)?.let { return Classification(unavailable, retryAfter = it) } + val reset = AcpQuotaReset.find(message, data, now) + return Classification(unavailable, retryAfter = reset?.retryAfter, quotaReset = reset) + } + private fun extractHttpStatus(data: JsonObject?): Long? { if (data == null) return null for (key in listOf("httpStatus", "httpStatusCode", "http_status", "status", "statusCode")) { diff --git a/plugins/runner-acp/src/main/kotlin/loop/runner/acp/AcpQuotaReset.kt b/plugins/runner-acp/src/main/kotlin/loop/runner/acp/AcpQuotaReset.kt new file mode 100644 index 00000000..e0a48c82 --- /dev/null +++ b/plugins/runner-acp/src/main/kotlin/loop/runner/acp/AcpQuotaReset.kt @@ -0,0 +1,166 @@ +package loop.runner.acp + +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import java.math.BigDecimal +import java.math.RoundingMode +import kotlin.time.Duration +import kotlin.time.Duration.Companion.nanoseconds +import kotlin.time.Instant + +/** + * Reads when an exhausted Gemini quota resets from a rate limit error (bl-215). Google's 429 is `RESOURCE_EXHAUSTED` + * with an `ErrorInfo` of reason `QUOTA_EXHAUSTED` whose `metadata` holds `model`, `quotaResetDelay` and + * `quotaResetTimeStamp`, a `RetryInfo` with `retryDelay`, and the message `Your quota will reset after `. + * `agy acp` may pass that body in the JSON-RPC error data, nested in a string field, or only its message, so the + * error data is searched at any depth, a JSON body inside a string included. + * + * Only the reset time and a plain model id are read: nothing else of the error, such as an account id, an email or a + * token, leaves this object. + */ +internal object AcpQuotaReset { + /** The quota resets at [resetsAt], [retryAfter] from now; [model] is the model the error named, if any. */ + data class Reset( + val retryAfter: Duration, + val resetsAt: Instant, + val model: String?, + ) + + private const val MAX_DEPTH = 16 + private const val MAX_EMBEDDED_CHARS = 1_000_000 + + private const val UNIT_PATTERN = """(?:h|ms|m|s|us|µs|ns)""" + private val DURATION_PART = Regex("""(\d+(?:\.\d+)?)($UNIT_PATTERN)""") + private val MESSAGE_RESET = + Regex("""quota will reset after\s+((?:\d+(?:\.\d+)?$UNIT_PATTERN)+)""", RegexOption.IGNORE_CASE) + private val PLAIN_MODEL_ID = Regex("""[A-Za-z0-9][A-Za-z0-9._-]{0,127}""") + + private val UNIT_NANOS = + mapOf( + "h" to BigDecimal(3_600_000_000_000L), + "m" to BigDecimal(60_000_000_000L), + "s" to BigDecimal(1_000_000_000L), + "ms" to BigDecimal(1_000_000L), + "us" to BigDecimal(1_000L), + "µs" to BigDecimal(1_000L), + "ns" to BigDecimal.ONE, + ) + + /** + * The quota reset of an error with [message] and [data], measured from [now]. The wait comes from the first valid + * positive value of, in order: `quotaResetTimeStamp` minus [now], `quotaResetDelay`, `retryDelay`, all in [data] at + * any depth, then `Your quota will reset after ` in [message] or a string of [data]. A past timestamp or + * an unparsable value is skipped. Null when none is found. + */ + fun find( + message: String, + data: JsonElement?, + now: Instant, + ): Reset? { + val scan = scan(data) + val wait = + scan.firstField("quotaResetTimeStamp") { untilTimestamp(it, now) } + ?: scan.firstField("quotaResetDelay", ::parseDuration) + ?: scan.firstField("retryDelay", ::parseDuration) + ?: (sequenceOf(message) + scan.strings).firstNotNullOfOrNull(::messageWait) + ?: return null + val model = + scan.objects + .firstNotNullOfOrNull { (it["metadata"] as? JsonObject)?.string("model") } + ?.takeIf { PLAIN_MODEL_ID.matches(it) } + return Reset(retryAfter = wait, resetsAt = now + wait, model = model) + } + + /** + * True when [data] holds, at any depth, a Google error of status `RESOURCE_EXHAUSTED` or an `ErrorInfo` of reason + * `QUOTA_EXHAUSTED`: structured fields, never free text. + */ + fun isQuotaExhausted(data: JsonElement?): Boolean = + scan(data).objects.any { it.string("status") == "RESOURCE_EXHAUSTED" || it.string("reason") == "QUOTA_EXHAUSTED" } + + /** + * Parses a duration in Google's format, one or more number and unit pairs such as `4h23m27.716645894s`, `27s` or + * `850ms` (units `h`, `m`, `s`, `ms`, `us`, `ns`). Null when [text] is anything else or not positive. + */ + fun parseDuration(text: String): Duration? { + if (text.isEmpty()) return null + var nanos = BigDecimal.ZERO + var position = 0 + while (position < text.length) { + val part = DURATION_PART.matchAt(text, position) ?: return null + nanos += BigDecimal(part.groupValues[1]) * UNIT_NANOS.getValue(part.groupValues[2]) + position = part.range.last + 1 + } + val whole = nanos.setScale(0, RoundingMode.DOWN) + if (whole.signum() <= 0 || whole > BigDecimal(Long.MAX_VALUE)) return null + return whole.toLong().nanoseconds + } + + private class Scan( + val objects: List, + val strings: List, + ) { + /** The first positive wait [read] gives from a string field [key] of any object, in document order. */ + fun firstField( + key: String, + read: (String) -> Duration?, + ): Duration? = objects.firstNotNullOfOrNull { obj -> obj.string(key)?.let(read)?.takeIf { it.isPositive() } } + } + + private fun untilTimestamp( + text: String, + now: Instant, + ): Duration? = parseInstant(text)?.let { it - now } + + private fun messageWait(text: String): Duration? = + MESSAGE_RESET + .find(text) + ?.groupValues + ?.get(1) + ?.let(::parseDuration) + + /** Every object and string of [data] in document order, descending into a JSON body embedded in a string. */ + private fun scan(data: JsonElement?): Scan { + val objects = mutableListOf() + val strings = mutableListOf() + + fun walk( + element: JsonElement, + depth: Int, + ) { + if (depth > MAX_DEPTH) return + when (element) { + is JsonObject -> { + objects += element + element.values.forEach { walk(it, depth + 1) } + } + is JsonArray -> element.forEach { walk(it, depth + 1) } + is JsonPrimitive -> + if (element.isString) { + strings += element.content + embeddedJson(element.content)?.let { walk(it, depth + 1) } + } + } + } + data?.let { walk(it, 0) } + return Scan(objects, strings) + } + + /** The JSON object or array inside [text], from its first `{` or `[` to its last `}` or `]`, if it parses. */ + private fun embeddedJson(text: String): JsonElement? { + if (text.length > MAX_EMBEDDED_CHARS) return null + val start = text.indexOfFirst { it == '{' || it == '[' } + val end = maxOf(text.lastIndexOf('}'), text.lastIndexOf(']')) + if (start < 0 || end <= start) return null + return runCatching { Json.parseToJsonElement(text.substring(start, end + 1)) } + .getOrNull() + ?.takeIf { it is JsonObject || it is JsonArray } + } + + private fun parseInstant(text: String): Instant? = runCatching { Instant.parse(text) }.getOrNull() + + private fun JsonObject.string(key: String): String? = (get(key) as? JsonPrimitive)?.takeIf { it.isString }?.content +} diff --git a/plugins/runner-acp/src/main/kotlin/loop/runner/acp/AcpRunner.kt b/plugins/runner-acp/src/main/kotlin/loop/runner/acp/AcpRunner.kt index 65f2058a..8cc1599f 100644 --- a/plugins/runner-acp/src/main/kotlin/loop/runner/acp/AcpRunner.kt +++ b/plugins/runner-acp/src/main/kotlin/loop/runner/acp/AcpRunner.kt @@ -41,6 +41,7 @@ import loop.runner.process.resolveAddedEnv import java.nio.file.Path import java.util.UUID import kotlin.io.path.isDirectory +import kotlin.time.Clock import kotlin.time.Duration import kotlin.time.Duration.Companion.seconds import kotlin.time.TimeSource @@ -70,6 +71,8 @@ class AcpRunner internal constructor( private val stopGrace: Duration = STOP_GRACE, /** Receives cleanup warnings that cannot be emitted on a turn flow (for example during `stop()`). */ private val onWarn: (String) -> Unit = { line -> System.err.println(line) }, + /** Gives the time a quota reset timestamp is measured from; a seam for tests. */ + private val clock: Clock = Clock.System, ) : AgentRunner { constructor( settings: AcpSettings, @@ -658,7 +661,7 @@ class AcpRunner internal constructor( } val classified = (step.failure as? AcpHandshakeFailure.ErrorAnswer)?.let { err -> - AcpErrors.classify(err.method, err.code, err.message, err.data) + AcpErrors.classify(err.method, err.code, err.message, err.data, clock.now()) } return killAndEnd( process, @@ -666,7 +669,7 @@ class AcpRunner internal constructor( sessionId = sessionId, turnId = turnId, exitCode = null, - reason = step.failure.reason, + reason = reportQuotaReset(classified, step.failure.reason), category = classified?.category ?: step.failure.category, retryAfter = classified?.retryAfter, ), @@ -721,10 +724,11 @@ class AcpRunner internal constructor( frame.code, frame.message, frame.data, + clock.now(), ) fail( exitCode = null, - reason = "turn_failed: ${frame.message} (code ${frame.code})", + reason = reportQuotaReset(classified, "turn_failed: ${frame.message} (code ${frame.code})"), category = classified.category, retryAfter = classified.retryAfter, ) @@ -734,6 +738,30 @@ class AcpRunner internal constructor( } } + /** + * With a quota reset in [classified] (bl-215), emits the `rate_limit` event of the exhausted quota and returns + * [reason] with its reset time. `RunnerEvent.RateLimit.Window` needs a used percent that `agy` never + * reports, so the event carries no window and the reset time goes in the `turn_failed` reason. + */ + private suspend fun reportQuotaReset( + classified: AcpErrors.Classification?, + reason: String, + ): String { + val reset = classified?.quotaReset ?: return reason + out( + RunnerEvent.RateLimit( + sessionId = sessionId, + turnId = turnId, + limitId = QUOTA_LIMIT_ID, + limitName = reset.model ?: settings.model, + primary = null, + secondary = null, + reached = QUOTA_REACHED, + ), + ) + return "$reason; the quota resets at ${reset.resetsAt}" + } + private suspend fun start() { started = true val event = @@ -832,6 +860,10 @@ class AcpRunner internal constructor( private const val FLAG_SANDBOX = "--sandbox" private const val FLAG_GEMINI_DIR = "--gemini-dir" + /** The `rate_limit` limit id and `reached` word of an exhausted Gemini quota (bl-215). */ + private const val QUOTA_LIMIT_ID = "gemini" + private const val QUOTA_REACHED = "quota_exhausted" + /** Google API env variables removed from the inherited host env by default under `preset: agy`. */ val AGY_REMOVED_ENV_NAMES: Set = setOf( diff --git a/plugins/runner-acp/src/test/kotlin/loop/runner/acp/AcpQuotaResetTest.kt b/plugins/runner-acp/src/test/kotlin/loop/runner/acp/AcpQuotaResetTest.kt new file mode 100644 index 00000000..e6893b58 --- /dev/null +++ b/plugins/runner-acp/src/test/kotlin/loop/runner/acp/AcpQuotaResetTest.kt @@ -0,0 +1,335 @@ +package loop.runner.acp + +import kotlinx.coroutines.flow.toList +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put +import loop.api.AttemptContext +import loop.api.AttemptId +import loop.api.Issue +import loop.api.ProjectId +import loop.api.RunId +import loop.api.RunnerEvent +import loop.runner.process.ProcessGroupLauncher +import org.junit.jupiter.api.io.TempDir +import java.nio.file.Path +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlin.time.Clock +import kotlin.time.Duration +import kotlin.time.Duration.Companion.hours +import kotlin.time.Duration.Companion.milliseconds +import kotlin.time.Duration.Companion.minutes +import kotlin.time.Duration.Companion.nanoseconds +import kotlin.time.Duration.Companion.seconds +import kotlin.time.Instant + +/** + * bl-215: an exhausted Gemini quota gives the hold the quota's reset time. The bodies follow the 429 that `agy`'s own + * CLI logged on 2026-10-19: `RESOURCE_EXHAUSTED` with an `ErrorInfo` of reason `QUOTA_EXHAUSTED` and a `RetryInfo`. + */ +class AcpQuotaResetTest { + @TempDir + lateinit var workspace: Path + + @TempDir + lateinit var dir: Path + + @TempDir + lateinit var home: Path + + private fun logged429( + resetTimeStamp: String? = RESET_AT.toString(), + resetDelay: String? = RESET_DELAY_TEXT, + retryDelay: String? = "15807.716645894s", + model: String? = MODEL, + message: String = QUOTA_MESSAGE, + ): String { + val metadata = + buildList { + add("\"uiMessage\":\"true\"") + add("\"consumer\":\"projects/$ACCOUNT_ID\"") + add("\"email\":\"$EMAIL\"") + model?.let { add("\"model\":\"$it\"") } + resetDelay?.let { add("\"quotaResetDelay\":\"$it\"") } + resetTimeStamp?.let { add("\"quotaResetTimeStamp\":\"$it\"") } + }.joinToString(",") + val retryInfo = + retryDelay?.let { ",{\"@type\":\"type.googleapis.com/google.rpc.RetryInfo\",\"retryDelay\":\"$it\"}" }.orEmpty() + return """ + {"error":{"code":429,"message":"$message","status":"RESOURCE_EXHAUSTED","details":[ + {"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"QUOTA_EXHAUSTED", + "domain":"cloudcode-pa.googleapis.com","metadata":{$metadata}}$retryInfo]}} + """.trimIndent().replace("\n", "") + } + + private fun parse(text: String): JsonElement = Json.parseToJsonElement(text) + + private fun classify( + message: String, + data: JsonElement?, + ) = AcpErrors.classify(AcpHandshake.METHOD_SESSION_PROMPT, -32000, message, data, now = NOW) + + @Test + fun `details in the error data give the reset timestamp minus now, and the model`() { + val result = classify("Resource exhausted", parse(logged429())) + + assertEquals(RunnerEvent.TurnFailed.Category.RunnerUnavailable, result.category) + assertEquals(RESET_DELAY, result.retryAfter) + val reset = assertNotNull(result.quotaReset) + assertEquals(RESET_AT, reset.resetsAt) + assertEquals(MODEL, reset.model) + } + + @Test + fun `the body nested in a string field is read too`() { + val data = + buildJsonObject { + put("error", "got status: 429 Too Many Requests. ${logged429()}") + } + + val result = classify("Resource exhausted", data) + + assertEquals(RunnerEvent.TurnFailed.Category.RunnerUnavailable, result.category) + assertEquals(RESET_DELAY, result.retryAfter) + assertEquals(MODEL, result.quotaReset?.model) + } + + @Test + fun `the body as an array in a string, as Google sends it, is read too`() { + val data = buildJsonObject { put("details", "[${logged429()}]") } + + assertEquals(RESET_DELAY, classify("Resource exhausted", data).retryAfter) + } + + @Test + fun `the message text only gives the duration it names`() { + val result = classify("429 Too Many Requests: $QUOTA_MESSAGE", null) + + assertEquals(RunnerEvent.TurnFailed.Category.RunnerUnavailable, result.category) + assertEquals(4.hours + 23.minutes + 27.seconds, result.retryAfter) + val reset = assertNotNull(result.quotaReset) + assertEquals(NOW + 4.hours + 23.minutes + 27.seconds, reset.resetsAt) + assertNull(reset.model) + } + + @Test + fun `a past timestamp is ignored and the delay is read next`() { + val result = classify("Resource exhausted", parse(logged429(resetTimeStamp = "2026-10-19T10:00:00Z"))) + + assertEquals(RESET_DELAY, result.retryAfter) + } + + @Test + fun `with no reset field the message inside the body is read last`() { + val data = parse(logged429(resetTimeStamp = "2026-10-19T10:00:00Z", resetDelay = null, retryDelay = null)) + + assertEquals(4.hours + 23.minutes + 27.seconds, classify("Resource exhausted", data).retryAfter) + } + + @Test + fun `a past timestamp with nothing else keeps today's behavior`() { + val data = + parse( + logged429( + resetTimeStamp = "2026-10-19T10:00:00Z", + resetDelay = null, + retryDelay = null, + message = NO_RESET_MESSAGE, + ), + ) + + val result = classify("Resource exhausted", data) + + assertEquals(RunnerEvent.TurnFailed.Category.RunnerUnavailable, result.category) + assertNull(result.retryAfter) + assertNull(result.quotaReset) + } + + @Test + fun `an unparsable timestamp or delay is ignored and the RetryInfo delay is read next`() { + val data = parse(logged429(resetTimeStamp = "tomorrow", resetDelay = "soon")) + + assertEquals(15807.seconds + 716_645_894.nanoseconds, classify("Resource exhausted", data).retryAfter) + } + + @Test + fun `no reset at all keeps today's behavior`() { + val data = parse(logged429(resetTimeStamp = null, resetDelay = null, retryDelay = null, message = NO_RESET_MESSAGE)) + + val result = classify("Resource exhausted", data) + + assertEquals(RunnerEvent.TurnFailed.Category.RunnerUnavailable, result.category) + assertNull(result.retryAfter) + assertNull(result.quotaReset) + assertNull(classify("429 Too Many Requests", null).retryAfter) + } + + @Test + fun `an explicit retry key still comes first`() { + val data = parse(logged429()) as JsonObject + val withKey = JsonObject(data + mapOf("retryAfterSeconds" to Json.parseToJsonElement("30"))) + + assertEquals(30.seconds, classify("Too many requests", withKey).retryAfter) + } + + @Test + fun `a quota reset is never read from an error that is not unavailability`() { + val result = classify("Internal error. Your quota will reset after 4h.", null) + + assertNull(result.category) + assertNull(result.retryAfter) + assertNull(result.quotaReset) + } + + @Test + fun `a model that is not a plain id is dropped`() { + val result = classify("Resource exhausted", parse(logged429(model = EMAIL))) + + assertEquals(RESET_DELAY, result.retryAfter) + assertNull(result.quotaReset?.model) + } + + @Test + fun `Google durations parse, anything else is null`() { + assertEquals(4.hours + 23.minutes + 27_700.milliseconds, AcpQuotaReset.parseDuration("4h23m27.7s")) + assertEquals(27.seconds, AcpQuotaReset.parseDuration("27s")) + assertEquals(850.milliseconds, AcpQuotaReset.parseDuration("850ms")) + assertEquals(RESET_DELAY, AcpQuotaReset.parseDuration(RESET_DELAY_TEXT)) + assertEquals(15807.seconds + 716_645_894.nanoseconds, AcpQuotaReset.parseDuration("15807.716645894s")) + assertEquals(1.minutes + 500.nanoseconds, AcpQuotaReset.parseDuration("1m500ns")) + assertEquals(3_000.nanoseconds, AcpQuotaReset.parseDuration("3us")) + listOf("", "soon", "4", "-5s", "0s", "4h 23m", "4x", "s", "1.s").forEach { + assertNull(AcpQuotaReset.parseDuration(it), it) + } + } + + @Test + fun `a prompt error with the quota body emits rate_limit and holds until the reset`() { + val errorLine = + buildJsonObject { + put("jsonrpc", "2.0") + put("id", 4) + put( + "error", + buildJsonObject { + put("code", -32000) + put("message", "Resource exhausted") + put("data", parse(logged429(model = null))) + }, + ) + }.toString() + val server = + FakeAcpServer.write(dir) { + initialize(id = 1) + sessionNew(id = 2, sessionId = "s-quota") + sessionSetModel(id = 3, configUpdateModelId = FakeAcpServer.DEFAULT_MODEL, sessionId = "s-quota") + awaitClient() + raw(errorLine) + } + + val events = runBlocking { withTimeout(20.seconds) { agyRunner(server).run(context(), "Work").toList() } } + + val failed = assertIs(events.last()) + assertEquals(RunnerEvent.TurnFailed.Category.RunnerUnavailable, failed.category) + assertEquals(RESET_DELAY, failed.retryAfter) + assertTrue("the quota resets at $RESET_AT" in failed.reason, failed.reason) + val rateLimit = events.filterIsInstance().single() + assertEquals("gemini", rateLimit.limitId) + assertEquals(FakeAcpServer.DEFAULT_MODEL, rateLimit.limitName) + assertEquals("quota_exhausted", rateLimit.reached) + assertNull(rateLimit.primary) + assertNull(rateLimit.secondary) + assertEquals(failed.turnId, rateLimit.turnId) + assertTrue(events.indexOf(rateLimit) < events.indexOf(failed)) + // The raw protocol line echo is runner output as for every frame; what the quota adds names no account. + listOf(rateLimit, failed).forEach { event -> + val text = event.toString() + assertFalse(EMAIL in text || ACCOUNT_ID in text, text) + } + } + + @Test + fun `a rate limit error with no reset emits no rate_limit event`() { + val server = + FakeAcpServer.write(dir) { + initialize(id = 1) + sessionNew(id = 2, sessionId = "s-plain") + sessionSetModel(id = 3, configUpdateModelId = FakeAcpServer.DEFAULT_MODEL, sessionId = "s-plain") + awaitClient() + error(id = 4, code = -32000, message = "429 Too Many Requests: quota exceeded") + } + + val events = runBlocking { withTimeout(20.seconds) { agyRunner(server).run(context(), "Work").toList() } } + + val failed = assertIs(events.last()) + assertNull(failed.retryAfter) + assertEquals("turn_failed: 429 Too Many Requests: quota exceeded (code -32000)", failed.reason) + assertTrue(events.none { it is RunnerEvent.RateLimit }) + } + + private fun agyRunner(server: FakeAcpServer): AcpRunner = + AcpRunner( + settings = + AcpSettings( + command = server.agyCommand, + preset = AcpSettings.PRESET_AGY, + model = FakeAcpServer.DEFAULT_MODEL, + readTimeout = FakeAcpServer.READ_TIMEOUT, + ), + hostEnv = mapOf("PATH" to System.getenv("PATH"), "HOME" to home.toString()), + removedEnvNames = emptySet(), + addedEnv = emptyMap(), + launchProcess = ProcessGroupLauncher(maxLineBytes = AcpFraming.MAX_LINE_BYTES)::launch, + clock = FixedClock(NOW), + ) + + private class FixedClock( + private val instant: Instant, + ) : Clock { + override fun now(): Instant = instant + } + + private fun context(): AttemptContext = + AttemptContext( + runId = RunId("run-1"), + projectId = ProjectId("project-1"), + issue = + Issue( + id = "issue-1", + identifier = "bl-215", + title = "Quota reset test", + state = "todo", + priority = null, + labels = emptyList(), + blockedBy = emptyList(), + description = null, + createdAt = null, + ), + attemptId = AttemptId("attempt-1"), + workspace = workspace, + env = emptyMap(), + ) + + private companion object { + const val MODEL = "gemini-4-neon-high" + const val EMAIL = "someone@example.com" + const val ACCOUNT_ID = "735190462281" + const val RESET_DELAY_TEXT = "4h23m27.716645894s" + const val QUOTA_MESSAGE = + "You have exhausted your capacity on this model. Your quota will reset after 4h23m27s." + const val NO_RESET_MESSAGE = "Resource has been exhausted (e.g. check quota)." + val RESET_AT: Instant = Instant.parse("2026-10-19T19:45:12Z") + val RESET_DELAY: Duration = 4.hours + 23.minutes + 27.seconds + 716_645_894.nanoseconds + val NOW: Instant = RESET_AT - RESET_DELAY + } +} diff --git a/spec-core/src/test/kotlin/loop/core/orchestrator/RunnerHoldTest.kt b/spec-core/src/test/kotlin/loop/core/orchestrator/RunnerHoldTest.kt index d0d83c69..6811247b 100644 --- a/spec-core/src/test/kotlin/loop/core/orchestrator/RunnerHoldTest.kt +++ b/spec-core/src/test/kotlin/loop/core/orchestrator/RunnerHoldTest.kt @@ -7,8 +7,10 @@ import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.time.Clock import kotlin.time.Duration +import kotlin.time.Duration.Companion.hours import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.minutes +import kotlin.time.Duration.Companion.nanoseconds import kotlin.time.Duration.Companion.seconds import kotlin.time.Instant @@ -85,6 +87,21 @@ class RunnerHoldTest { assertEquals(2.minutes, short.delay) } + @Test + fun `bl-215 an exhausted Gemini quota holds until its reset time, not the 1 minute backoff`() { + // What the acp runner parses from the logged 429 body (AcpQuotaResetTest): quotaResetDelay 4h23m27.716645894s. + val reset = 4.hours + 23.minutes + 27.seconds + 716_645_894.nanoseconds + + val period = assertNotNull(assertIs(unavailable(retryAfter = reset)).started) + + assertEquals(reset, period.delay) + assertEquals(FIXED_NOW + reset, period.probeAt) + clock.now = FIXED_NOW + 1.minutes + assertEquals(RunnerHold.Gate.Closed, hold.gate()) + clock.now = FIXED_NOW + reset + assertEquals(RunnerHold.Gate.Probe, hold.gate()) + } + @Test fun `a running attempt that fails before the probe is due falls into the same hold`() { unavailable("a")