Track model quota exhaustion across retries and model fallback #1655
🤖 AI Factory started reviewing this pull request in a sandbox.
In modelFailureRegexp, the |Model\s+([a-zA-Z0-9\-\.]+)(?:\s+failed)? branch has (?:\s+failed)? marked as optional. Because modelFailedMarkerBytes matches the generic word "failed", any line containing "failed" (e.g. Model gemini-2.5-pro: Attempt 1 failed with status 429...) matches this regex during transient retries before the model has actually finished trying. The failed suffix should not be optional if matching Model <name> failed, and modelFailedMarkerBytes should use more specific markers to avoid triggering regex evaluation on every failure/error line in logs.
The condition succModel == t.currentModel || t.currentModel != "" evaluates to true whenever t.currentModel != "", ignoring whether succModel matches t.currentModel. Conversely, if t.currentModel == "", the condition evaluates to false and ignores succModel. If the intent was to accept matches or initialize an unset current model, the condition should be succModel == t.currentModel || t.currentModel == "" (and set t.currentModel = succModel if empty).
The expression t.currentModelHasQuotaError || (failModel == t.currentModel && t.currentModelHasQuotaError) simplifies to t.currentModelHasQuotaError. As written, failModel == t.currentModel is never enforced if t.currentModelHasQuotaError is true, which can result in marking failModel as quota-exceeded even when it does not match t.currentModel.
When processFailed is true, HasAmbiguousQuotaError(buf) checks the entire rolling buffer. If a task encountered a transient 429 that was successfully retried with backoff, but later failed due to an unrelated error (such as a test failure or compiler error), HasAmbiguousQuotaError(buf) evaluates to true, causing ObserveFinal to treat the failure as a fatal quota error (exit code 137) and ban the model for 4 hours. Furthermore, this check makes findUncoveredAmbiguousError(buf, baseOffset) unreachable dead code. Quota fatal status should be determined by whether the active model failed with an unresolved quota error rather than the presence of any historical 429 marker in the window.
geminitokens.ExtractAPIKeyFromError(evidence) is called inside the loop over quotaTracker.NewlyExceededModels(). Since evidence does not change across iterations, extract key once before entering the loop.
The PR addresses tracking model quota exhaustion across retries and fallback loops, but several issues need to be resolved:
ObserveFinal unconditionally treats any ambiguous quota error in the rolling window as fatal when processFailed is true, which misclassifies unrelated task failures (such as test or compilation failures after a transient 429 retry) as fatal quota exhaustion and bans the model. It also makes findUncoveredAmbiguousError unreachable.modelFailureRegexp and modelFailedMarkerBytes are overly broad: (?:\s+failed)? is optional in the regex and failed matches any log line containing the word, leading to false positive model failure detections on transient retries.processStreamEvents for model success (succModel == t.currentModel || t.currentModel != "") and model failure (t.currentModelHasQuotaError || (failModel == t.currentModel && t.currentModelHasQuotaError)) are logically flawed.client.go, API key extraction from evidence is repeatedly executed inside the loop over newly exceeded models.🤖 AI Factory started addressing review feedback for this pull request.
Thank you for the detailed review! I have updated the code to address all points:
1. ObserveFinal & Task Failures after Transient Retries:
- Updated ObserveFinal so it no longer treats any historical 429 in the rolling window as fatal when processFailed is true. Instead, a task failure is classified as fatal quota exhaustion only if the active model failed with an unresolved quota error (currentModelHasQuotaError && !currentModelSucceeded) or an uncovered quota error exists in the window. Unrelated task failures (e.g. test failures after a successful model attempt) are no longer misclassified as quota errors, and findUncoveredAmbiguousError is now reachable.
2. Regexes & Marker Bytes:
- Updated modelFailureRegexp to make the failed suffix mandatory when matching Model <name> failed (Model\s+([a-zA-Z0-9\-\.]+)\s+failed), preventing transient attempt retry lines (such as Model gemini-2.5-pro: Attempt 1 failed...) from triggering false positive model failure detections.
- Updated marker bytes to use specific prefixes (execution failed, execution encountered errors, Model ) rather than generic words.
3. Boolean Logic in processStreamEvents:
- Fixed model success handling to check succModel == t.currentModel || t.currentModel == , properly matching succModel and setting t.currentModel if unset.
- Fixed model failure handling to check (failModel == t.currentModel || t.currentModel == ) && t.currentModelHasQuotaError, ensuring failModel is only marked as quota-exceeded when it matches the current model that experienced a quota error.
4. API Key Extraction in client.go:
- Refactored client.go in both ObserveFinal and ObservePoll handlers to extract key once before iterating over quotaTracker.NewlyExceededModels().
(This comment was generated by overseer)
🤖 AI Factory started reviewing this pull request in a sandbox.
The PR addresses model quota exhaustion tracking across retries and multi-model fallback loops. However, several logic bugs and edge cases in state management and log parsing prevent quota errors from being correctly recorded or flagged.
Key areas requiring attention:
1. State Reset on Same-Model Retries: Logging Trying model: <same_model> on retry resets currentModelHasQuotaError to false, erasing quota error state from earlier attempts if a retry fails without emitting a new 429 error payload.
2. Failure Line Clearing Prevents ObserveFinal Detection: Clearing currentModelHasQuotaError when processing execution failure lines causes ObserveFinal to return false when the task process exits, missing the fatal quota failure.
3. Regex Character Class Excludes Valid Model Name Characters: The regexes for model extraction restrict names to [a-zA-Z0-9\-\.], which truncates or fails to match model names containing underscores (_) or slashes (/).
4. Silent Loss of Exceeded Model State: NewlyExceededModels() clears state upon invocation; if the API key cannot be extracted from evidence or environment variables, the exceeded models are permanently dropped without being recorded.
Resetting t.currentModelHasQuotaError = false when newModel == t.currentModel causes quota errors from prior attempts of the same model to be lost.
When a model attempt is retried and logs Trying model: <same_model>, newModel == t.currentModel evaluates to true, but currentModelHasQuotaError is unconditionally overwritten to false. If this retry attempt fails without emitting a new 429 error payload, currentModelHasQuotaError remains false, preventing the model from ever being marked as quota-exceeded.
currentModelHasQuotaError should be preserved when retrying the same model unless the attempt succeeded.
Clearing t.currentModelHasQuotaError = false on Engine execution failed prevents ObserveFinal from detecting process-level quota failures.
When a model execution fails, this line clears currentModelHasQuotaError. When the task process subsequently exits with a non-zero exit code and ObserveFinal(finalData, true) is called, ObserveFinal checks t.currentModelHasQuotaError && !t.currentModelSucceeded at line 796. Because currentModelHasQuotaError was cleared here, ObserveFinal returns false, causing task termination after quota retries fail to be misclassified as a non-quota process failure.
Evaluation order within a single log line causes quota errors on lines containing Trying model: to be overwritten.
HasAmbiguousQuotaError is evaluated before checking for Trying model:. If a single line contains both Trying model: <model> and a 429 error payload, or if Trying model: appears when t.currentModel is empty, the first block either sees t.currentModel == "" or sets currentModelHasQuotaError = true, but the subsequent Trying model: block immediately resets t.currentModelHasQuotaError = false.
The regex character class [a-zA-Z0-9\-\.] excludes underscores (_) and slashes (/), which are valid characters in Gemini model names, preview identifiers, and resource paths (e.g., gemini-1.5-flash_preview or models/gemini-1.5-pro).
Model name extraction will truncate or fail to match identifiers containing _ or /. Consider expanding the character class to [a-zA-Z0-9\-\._\/].
NewlyExceededModels() clears internal state even if key cannot be resolved, leading to lost quota tracking records.
When quotaTracker.NewlyExceededModels() is called, it returns and clears t.newlyQuotaExceededModels. If geminitokens.ExtractAPIKeyFromError(evidence) returns "" and envs[constants.KeyGeminiAPIKey] is missing or empty, key remains "", skipping AddQuotaExceededKeyAndModel. Because NewlyExceededModels() already cleared the slice in quotaTracker, those model quota failures are permanently lost.
🤖 AI Factory started addressing review feedback for this pull request.
Thank you for the review and catching these edge cases! I have addressed all the feedback points:
1. Same-Model Retries State Preservation:
- Preserved currentModelHasQuotaError when retrying the same model (newModel == t.currentModel), so prior quota errors are retained across same-model retry attempts unless the attempt explicitly succeeds.
2. ObserveFinal Detection on Task Failure:
- Removed clearing currentModelHasQuotaError = false upon matching model failure log lines (Engine execution failed with model: ...). This preserves the model quota error state so ObserveFinal(finalData, true) correctly identifies fatal quota failures when the process terminates.
3. Evaluation Order on Single Log Lines:
- Reordered line event processing in processStreamEvents so that model extraction (Trying model:) runs before quota error matching (HasAmbiguousQuotaError / IsUnambiguousFatalQuotaError). This ensures currentModel is set before inspecting that same line for quota error payloads.
4. Regex Character Class for Model Names:
- Expanded model regex character classes in both geminitokens.go and client.go to [a-zA-Z0-9\-\._\/]+, supporting model names containing underscores (_) and path slashes (/) (e.g. models/gemini-1.5-flash_preview).
5. Exceeded Model State Retention & Acknowledgement:
- Updated NewlyExceededModels() to return pending models without clearing internal state, and introduced AckExceededModels(...) and ClearNewlyExceededModels(). In client.go, models are only acknowledged/cleared once the API key is successfully resolved and recorded in AddQuotaExceededKeyAndModel, preventing silent dropped records when keys are unresolved on intermediate polls.
6. Unit Tests:
- Added unit tests covering same-model retries, ObserveFinal quota detection after failure lines, single-line model+error parsing, special characters in model names (_ and /), and pending model retention until acknowledgement.
(This comment was generated by overseer)
🤖 AI Factory started reviewing this pull request in a sandbox.
The PR implements model quota tracking across retries and fallback loops by tracking model lifecycle markers and recording quota-exceeded models in QuotaStreamTracker.
Key areas to address:
1. Fast-path byte marker prefilters (bytes.Contains) in geminitokens.go are case-sensitive, whereas the corresponding regexes use (?i). Log lines with differing capitalization may be skipped before regex evaluation.
2. Identical model tracking and quota recording logic is duplicated between flushAndCheckFinalQuota and the polling loop in client.go.
3. When an API key cannot be resolved from error evidence or environment variables in client.go, newly exceeded models remain unacknowledged and are repeatedly queried on every poll interval.
execSuccessMarkerBytes and other byte markers (tryingModelMarkerBytes, execFailedMarkerBytes, etc.) perform case-sensitive checks via bytes.Contains, whereas modelSuccessRegexp, modelStartRegexp, and modelFailureRegexp are defined with case-insensitive flags (?i). If log lines differ in capitalization (such as Execution successful with model: or trying model:), the byte prefilter will reject the line before the regex can match. Consider matching against lowercased bytes or ensuring consistent case handling.
This block for updating lastModelTried, detecting newly exceeded models, resolving the API key, and updating AddQuotaExceededKeyAndModel is duplicated verbatim in the polling loop (lines 536-555). Consider refactoring this into a helper function (e.g. c.recordExceededModels(evidence, quotaTracker, envs)) to reduce duplication.
If key cannot be resolved (i.e. ExtractAPIKeyFromError returns "" and envs[constants.KeyGeminiAPIKey] is empty), quotaTracker.AckExceededModels(newlyExceeded...) is never invoked. This causes NewlyExceededModels() to return the same slice on every subsequent poll interval. Consider adding a warning log and clearing or acknowledging the models if no key can be associated.
modelRegexp here is case-sensitive (Trying model:\s*...), whereas modelStartRegexp in geminitokens.go uses (?i). Consider adding (?i) to modelRegexp for consistency across model parsing helpers.
🤖 AI Factory started addressing review feedback for this pull request.
Thank you for the review! I have addressed all feedback points:
1. Case-Insensitive Byte Marker Prefilters:
- Introduced an allocation-free bytesContainsIgnoreCase helper in geminitokens.go along with lowercased byte markers to ensure prefilters match regardless of casing, aligning with (?i) regexes.
2. Deduplicated Model Tracking and Quota Recording in client.go:
- Consolidated model extraction, quota error recording, and model acknowledgement logic into a shared helper method c.recordExceededModels(evidence, quotaTracker, envs), eliminating code duplication between flushAndCheckFinalQuota and the polling loop.
3. Unresolved API Key Handling:
- Updated recordExceededModels so that if an API key cannot be resolved from the error evidence or environment variables, a warning is logged and the pending models are acknowledged via quotaTracker.AckExceededModels(...), preventing repeated queries on every poll tick.
4. Case-Insensitive Model Regex:
- Added (?i) flag to modelRegexp in client.go for consistent case handling across model parsing helpers.
5. Unit Tests:
- Added unit tests verifying case-insensitive model markers, case-insensitive log extraction, and model acknowledgement when API keys cannot be resolved.
(This comment was generated by overseer)
🤖 AI Factory started reviewing this pull request in a sandbox.
bytesContainsIgnoreCase converts characters in s to lowercase but assumes that lowerSubstr is already entirely lowercased. Consider adding a comment documenting that lowerSubstr must be lowercased ASCII or converting lowerSubstr defensively to prevent future mistakes when adding new marker constants.
t.pendingLine accumulates log chunks across polling cycles when lines are split, but unlike t.window, it is not bounded by maxWindowSize. If an external process emits a large stream without newline characters, t.pendingLine could grow unbounded. Consider bounding t.pendingLine (or truncating to maxWindowSize) if no newline is encountered over successive chunks.
The PR addresses quota tracking regression across multi-model fallback loops and process failures when 429 retries occur.
Key observations and recommendations:
geminitokens.go, bytesContainsIgnoreCase assumes lowerSubstr is strictly pre-lowercased ASCII; adding an explicit comment or converting lowerSubstr defensively prevents regressions if caller patterns change.processStreamEvents, t.pendingLine buffers partial lines across chunks without bounding to maxWindowSize, which could theoretically accumulate memory if incoming logs omit newlines.ObservePoll and ObserveFinal accurately identifies failed model attempts and records them via AddQuotaExceededKeyAndModel.🤖 AI Factory started addressing review feedback for this pull request.
Thank you for the review! I have addressed the feedback:
1. Defensive Case Handling in bytesContainsIgnoreCase:
- Updated bytesContainsIgnoreCase to defensively lowercase both the candidate string (s) and the substring (substr) on the fly, eliminating assumptions about caller pre-lowercasing while maintaining zero heap allocations.
- Documented the behavior and added unit tests covering uppercase and mixed-case substring matches.
2. Bounded t.pendingLine Buffer:
- Bounded t.pendingLine to maxWindowSize when accumulating log chunks across polling cycles in the absence of newline characters, preventing unbounded memory accumulation.
- Added unit tests verifying t.pendingLine length remains capped at maxWindowSize across repeated newline-less chunk appends.
(This comment was generated by overseer)
🤖 AI Factory started reviewing this pull request in a sandbox.
The PR addresses the quota tracking regression where models failing due to quota exhaustion during fallback loops or task failures were not being recorded in the exceeded models cache.
Key observations:
QuotaStreamTracker properly tracks active model attempts, quota error markers, and model outcomes across stream chunks.models/gemini-1.5-flash_preview) are handled.ObserveFinal accurately distinguishes fatal quota failures from unrelated post-execution failures when a model run has succeeded.pendingLine truncated to maxWindowSize, and steady-state poll benchmarks maintain zero allocations.🤖 AI Factory started addressing review feedback for this pull request.
Thank you for the review! All tests continue to pass and all feedback points have been verified.
(This comment was generated by overseer)
🤖 AI Factory started addressing review feedback for this pull request.
Thank you for the review and confirmation! All feedback points have been addressed and verified with comprehensive unit tests.
(This comment was generated by overseer)
Remove the license headers
🤖 AI Factory started addressing review feedback for this pull request.
🤖 AI Factory started addressing review feedback for this pull request.
🤖 AI Factory started addressing review feedback for this pull request.
Removed the license headers from factory/pkg/envd/client_test.go and the other modified files in the PR.
(This comment was generated by overseer)
Removed the license headers from the modified files in factory/pkg/ (factory/pkg/envd/client.go, factory/pkg/envd/client_test.go, factory/pkg/geminitokens/geminitokens.go, and factory/pkg/geminitokens/geminitokens_test.go).
(This comment was generated by overseer)
Removed the license headers from the modified files in the factory package as requested.
(This comment was generated by overseer)
When a model in the fallback loop fails (Engine execution failed with model: ...) and runEngine transitions to the next model (Trying model: ...), neither t.window nor t.pendingAmbiguous is reset/bounded to the new model attempt:
1. Uncovered 429 on an earlier model: If Model 1 logs an uncovered 429 / RESOURCE_EXHAUSTED line (not covered by "Retrying with backoff", such as a final error line before exiting) and then transitions to Model 2 (as in the unit tests handles single line with Trying model and quota error correctly and retains pending exceeded models until acknowledged), that uncovered 429 remains in t.window. On the next poll tick, findUncoveredAmbiguousError still sees it in buf and ObservePoll returns isFatal = true—killing the sandbox while Model 2 is running.
2. Per-model RPD / Max retries exceeded: IsUnambiguousFatalQuotaError(buf) immediately returns isFatal = true on "requests per day" or "Max retries exceeded", which causes RunTaskResilient to kill -9 the entire runEngine process group (BuildQuotaKillCmd) on Model 1 instead of allowing lib.sh to fall back to the next model in MODELS_LIST. Only IsSuspendedKeyError is immediately fatal across all models for the key while fallback models remain.
When a model attempt ends (Engine execution failed..., Engine execution successful..., or a new Trying model: ...), t.pendingAmbiguous should be reset and findUncoveredAmbiguousError / fatal quota checks should not re-trigger on bytes belonging to an already-completed model attempt.
Review Summary
Overall, this moves model quota tracking in the right direction when Retrying with backoff is present, and ensures <key>:<model> entries are persisted with a 4-hour TTL so future tasks skip exhausted models. However, there are a few issues to address:
1. High: Uncovered 429 or RPD error on an earlier model in the fallback loop kills the sandbox on the next model and blames the wrong model (see inline comments on geminitokens.go and client.go).
2. Medium: Overly broad regex alternative in modelFailureRegexp (see inline comment on geminitokens.go).
3. Medium (factory/pkg/commands/agent.go): Unlike applyEngineEnv in root.go (which calls key := getGeminiAPIKey(secret) once and passes key to both GEMINI_API_KEY and ModelsForEngine), agent.go (lines 322 and 337) calls getGeminiAPIKey(secret) twice. When TOKENSCRIPT_DIR is used, those two calls can return different keys, filtering MODELS for one key while running the sandbox with another.
4. Low / UX (GetTokensStatus / UI): Keys that have exhausted quota for some (1–5) but not all 6 DefaultModels are placed in status.ActiveList as "AIzaSyXX... (Degraded: exceeded <models>)" under 🟢 Active Keys, while 🟡 Quota Exceeded Keys (status.QuotaExceededList) remains 0 unless all 6 DefaultModels are exhausted for that key. Additionally, factory status CLI only prints status.QuotaExceededList and omits degraded keys from status.ActiveList. Consider whether partially-exhausted keys should also be surfaced under Quota Exceeded (or a dedicated Degraded section).
If ObservePoll (or ObserveFinal above) returns isFatal = true on a chunk where Model 1 failed and the script already printed Trying model: <Model 2>, c.recordExceededModels returns quotaTracker.CurrentModel() (Model 2) and overwrites lastModelTried with Model 2. Then handleQuotaOrSuspensionError(evidence, lastModelTried, envs) on line 515 calls AddQuotaExceededKeyAndModel for Model 2, falsely marking the newly started fallback model as quota-exceeded.
The task scripts only emit Engine execution failed with model: $MODEL (lib.sh) or Gemini execution encountered errors with model: $MODEL (adopt.sh, run_agent.sh).
The extra |Model\s+([a-zA-Z0-9\-\._\/]+)\s+failed branch (and the bytesContainsIgnoreCase(line, modelFailedMarkerBytes) && bytesContainsIgnoreCase(line, failedMarkerBytes) pre-check on line 758) could false-positive if a non-terminal log message or tool output contains "Model <name> failed ...". Removing that unused alternative makes failure detection stricter.
🤖 AI Factory started addressing review feedback for this pull request.
Thank you for the detailed review! I have updated the code to address all points:
1. Fallback Loop Quota Handling in ObservePoll & ObserveFinal:
- Updated ObservePoll so that when tracking active model attempts (t.currentModel != ""), per-model rate limit and quota errors (429, RESOURCE_EXHAUSTED, RPD, Max retries exceeded) cause the active model CLI attempt to fail and exit so that the fallback script (lib.sh) can fall back to the next model in MODELS_LIST without terminating the process group.
- Preserved immediate process group termination for API key suspension errors (IsSuspendedKeyError).
- Reset t.pendingAmbiguous on model attempt transitions and completions so historical errors from completed model attempts do not trigger false fatal detections on subsequent models.
2. Regex & Marker Cleanup:
- Removed the loose |Model <name> failed regex branch and unused marker bytes from modelFailureRegexp, restricting failure detection strictly to execution failure/error logs (Engine/Gemini execution failed/encountered errors with model: ...).
3. Single API Key Discovery in agent.go:
- Updated RunAgent in factory/pkg/commands/agent.go to invoke getGeminiAPIKey(secret) once into geminiKey and reuse it for both GEMINI_API_KEY and MODELS.
4. Degraded Key Reporting in factory status:
- Updated factory status CLI output in factory/pkg/commands/status.go to display partially-exhausted keys under Degraded Keys [WARN].
5. Exceeded Model Attribution in recordExceededModels:
- Updated recordExceededModels in client.go to return the newly exceeded model when present so lastModelTried accurately attributes quota failures to the model that encountered the error.
6. Unit Tests:
- Added unit tests covering model fallback transitions, key suspension during model runs, and recordExceededModels model attribution.
(This comment was generated by overseer)
Suppose Model 1 (gemini-3.7-flash) fails with a quota error (t.quotaExceededModels["gemini-3.7-flash"] = true) and runEngine falls back to Model 2 (gemini-3.6-flash).
1. If Model 2 succeeds (Engine execution successful with model: gemini-3.6-flash) and a later post-engine step in the script (e.g. git push or tests) fails (processFailed == true):
Because len(t.quotaExceededModels) > 0 is true from Model 1 (and Model 1's old logs may still be in buf for IsUnambiguousFatalQuotaError(buf) / findUncoveredAmbiguousError(buf, baseOffset) below), ObserveFinal returns true even though t.currentModelSucceeded == true. And then flushAndCheckFinalQuota marks Model 2 as quota-exceeded!
When t.currentModel != "", if t.currentModelSucceeded is true, ObserveFinal should return false (after IsSuspendedKeyError(buf)).
2. If Model 1 failed with quota and Model 2 failed for a non-quota reason (t.currentModelHasQuotaError == false):
When t.currentModel != "", ObserveFinal should not fall through to IsUnambiguousFatalQuotaError(buf) or findUncoveredAmbiguousError(buf, baseOffset) which scan stale bytes in buf from earlier models.
Consider what happens across polls when Model 1 (gemini-3.7-flash) fails with quota and is already acknowledged during ObservePoll (AckExceededModels), and then Model 2 (gemini-3.6-flash) starts and fails with a non-quota error (or succeeds and a later script step fails):
When flushAndCheckFinalQuota runs at process exit:
quotaTracker.NewlyExceededModels() is now empty (since Model 1 was already acknowledged during ObservePoll).recordExceededModels therefore falls through to if current := quotaTracker.CurrentModel(); current != "" and returns Model 2 (gemini-3.6-flash), setting lastModelTried = "gemini-3.6-flash".if isFatalQuota calls handleQuotaOrSuspensionError(evidence, lastModelTried, envs), which calls AddQuotaExceededKeyAndModel(key, "gemini-3.6-flash", 4*time.Hour)—falsely marking Model 2 as quota-exceeded!If exceeded := quotaTracker.ExceededModels(); len(exceeded) > 0, recordExceededModels has already recorded every model that actually hit quota exhaustion (or recordExceededModels should return exceeded[len(exceeded)-1] rather than CurrentModel() when CurrentModel() was not quota-exceeded, and handleQuotaOrSuspensionError should not mark a non-exceeded lastModelTried).
buf is the 8KB rolling window (t.window), so once a single "Retrying with backoff" message enters buf, ContainsRetryBackoff(buf) remains true on every subsequent poll tick (even when newData is empty or normal log output) until 8KB of new output pushes it out of the window.
This should check newData:
hasTransient := len(newData) > 0 && (ContainsRetryBackoff(newData) || HasAmbiguousQuotaError(newData))
Round 2 Review Summary
Thanks for addressing the previous feedback (agent.go, status.go, modelFailureRegexp, and ObservePoll during model fallback). Two remaining issues to address:
1. High: If Model 1 fails with quota and Model 2 succeeds (or fails for a non-quota reason), process failure still blames Model 2 in ObserveFinal / flushAndCheckFinalQuota (see inline comments on geminitokens.go and client.go).
2. Low: ObservePoll checks ContainsRetryBackoff(buf) instead of newData (see inline comment on geminitokens.go).
🤖 AI Factory started addressing review feedback for this pull request.
Thank you for the review! I have updated the code to address both points:
1. ObserveFinal Model Fallback Scoping:
- Updated ObserveFinal when t.currentModel != "" so that if t.currentModelSucceeded is true, it returns false without scanning historical quota bytes in buf (after checking for key suspension).
- If t.currentModelSucceeded is false, ObserveFinal directly returns t.currentModelHasQuotaError, preventing non-quota failures of fallback models from falling through to stale buffer scans (IsUnambiguousFatalQuotaError / findUncoveredAmbiguousError).
2. Exceeded Model Attribution in recordExceededModels:
- Updated recordExceededModels in client.go so that when newlyExceeded is empty, it returns the last exceeded model from quotaTracker.ExceededModels() rather than CurrentModel(). This prevents active non-exceeded models from being returned as lastModelTried and falsely banned.
3. Transient Detection in ObservePoll:
- Updated ObservePoll to check newData for retry backoff and ambiguous quota markers (len(newData) > 0 && (ContainsRetryBackoff(newData) || HasAmbiguousQuotaError(newData))) instead of checking the rolling buffer buf, ensuring hasTransient is only reported on the poll tick that received the message.
4. Unit Tests:
- Added unit tests verifying ObserveFinal behavior when fallback models succeed or fail with non-quota errors, transient poll-tick flag behavior, and recordExceededModels attribution.
(This comment was generated by overseer)
Approved these changes.
sdowell
hopper-coder-bot
Fixes #1604
This PR resolves the quota tracking regression introduced after PR #1440.
Problem
PR #1440 deferred killing sandboxes on transient 429 retries with backoff. However, this caused key/model quota exhaustion tracking to be missed in two situations:
1. In a multi-model fallback loop, when a model encountered 429 errors and retries failed, the bash script moved to the next model (which could succeed). Because the overall process succeeded or moved past the model, the failed model was never recorded as quota-exceeded for the API key in
.factory_quota_exceeded_keys.json. Consequently, future tasks continued attempting the quota-exhausted model before falling back.2. If a process failed after retrying 429s,
ObserveFinaldid not mark the model as quota exceeded because the 429 was near "Retrying with backoff".Changes
geminitokens.QuotaStreamTrackerto monitor active model attempts (Trying model: ...), quota error markers (429 / RESOURCE_EXHAUSTED / requests per day), and model outcomes (execution successfulvsexecution failed/ next model start).geminitokens.AddQuotaExceededKeyAndModel.ObserveFinal, if the process failed (processFailed == true), quota errors in the buffer are treated as fatal even if accompanied by backoff retries (since the retries failed to prevent task termination).---
This PR was generated by the overseer,overseer/review agent (powered by the gemini-3.7-flash model).