fix: prevent infinite restart loop that causes runaway API costs #693
+55
−5
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Problem
When
memorySessionIdis null (due to a race condition during session initialization), the generator enters an infinite restart loop:processAgentResponse()→ throws "memorySessionId not yet captured" ❌.finally()seespendingCount > 0→ Restarts generator after 1 secondReal-World Impact
I experienced $402 in wasted API costs before my OpenRouter key limit stopped it. The logs showed:
This repeated 24,219 times in a single day. Each restart made another LLM call that succeeded (cost tokens) but then failed to store the result.
Solution
1. Add Restart Limit (Primary Fix)
2. Add Exponential Backoff
3. Fail Fast - Check Before LLM Call (Defensive)
This check happens before the LLM call, preventing token waste.
Files Changed
worker-types.tsconsecutiveRestarts: numbertoActiveSessionSessionManager.tsconsecutiveRestarts: 0SessionRoutes.tsOpenRouterAgent.tsmemorySessionIdbefore LLM callsGeminiAgent.tsTesting
npm run build✅Notes
memorySessionIdisn't captured in some sessions) may still need investigation