cutawan icon indicating copy to clipboard operation
cutawan copied to clipboard

ChatGPT/Codex: one 5-minute call timeout aborts the whole Get clips run (no retry)

Open Ramadas108 opened this issue 3 weeks ago • 0 comments

Summary

On the ChatGPT/Codex connection, every analysis request is given one hard 300 s budget (AbortSignal.timeout(5 * 60_000) in src/main/subscription.ts), shared with the preceding codex login status call, and the subscription route has no retry: only the API-compatible route is wrapped in withRetries. When that budget expires, subscriptionJSON rejects with Local provider cancelled or timed out., the error is wrapped in SubscriptionError, rethrowBlocked rethrows it, and the whole Get clips run is lost even though every earlier stage was already cached.

Environment

  • Cutawan 0.14.0, installed Windows build (not a source checkout)
  • Windows 11
  • Codex CLI 0.162.1; codex login status prints Logged in using ChatGPT
  • Connection: ChatGPT/Codex subscription, model gpt-6-luna (the app forces reasoning effort low)
  • Source video about 2 h 07 min, transcript already saved, so transcription was skipped

Symptom

Pressing Get clips on a project that already has a transcript eventually shows Local provider cancelled or timed out. under the button, and no clips are saved. Retrying works only because the completed stages are cached, so the retry reruns the tail.

What was ruled out, by measurement

Replaying the exact codexArguments() argument set, the environment scrubbing and the stdin protocol from a PowerShell harness, with a two-field schema and a one-line prompt: exit 0, valid response.json, four runs at 14.0 s / 7.3 s / 5.1 s / 5.1 s, thread.started within 0.1-0.3 s. So CLI resolution, the model name, sign-in, schema plumbing and the network path are all healthy on this machine. Transcript reuse is also fine; its segments are identical before and after.

Timeline reconstructed from app state

  • 15 provider calls completed and cached over about three minutes: clip discovery, clip endings, nine visual assessments, four editorial review batches. Each took 1-46 s.
  • The usage ledger then incremented for a 16th call, which never wrote a cached result.
  • No further cache write for 47 minutes, until a later manual retry of the same project.
  • Consistent with call 16 starting and the 300 s timer expiring inside the editorial stage, either the last review batch or the diversity pass that follows it.

There is no app-level log, and the child's stderr is discarded on abort, so what consumed the 300 s cannot be separated after the fact between a provider-side stall and a launcher that finished but kept its stdio pipe open. Both are addressed below.

Why it is fatal rather than local

chatJSON() returns subscriptionJSON() directly for this connection while the API route is wrapped in withRetries, so one expired budget aborts analyzeProject instead of one stage.

Proposed change (not compiled or run by the reporter)

  1. Give the login check its own short budget so it cannot consume the analysis budget.
  2. If the run fails but a complete response.json exists on disk, accept that answer instead of spending another request, because a stalled launcher can write the final message before it hangs.
  3. Retry once, only when our own timer fired and the caller did not cancel. Each attempt keeps its own reservation, so the daily cap still bounds spend.
diff --git a/src/main/subscription.ts b/src/main/subscription.ts
index 21a59eb..e8476c2 100644
--- a/src/main/subscription.ts
+++ b/src/main/subscription.ts
@@ -207,6 +207,22 @@ function waitForPrevious(previous: Promise<unknown>, signal?: AbortSignal): Prom
   })
 }
 
+const ANALYSIS_TIMEOUT_MS = 5 * 60_000
+const LOGIN_TIMEOUT_MS = 15_000
+// One retry covers a provider stall or a local launcher that answers late; it
+// is safe because every attempt reserves its own usage slot and the response is
+// cached only on success.
+const ANALYSIS_ATTEMPTS = 2
+
+/** A stalled launcher may have written the final message before it hung. */
+async function hasCompleteResponse(path: string): Promise<boolean> {
+  try {
+    const raw = await readFile(path, 'utf8')
+    JSON.parse(raw)
+    return true
+  } catch { return false }
+}
+
 export async function subscriptionJSON<T>(messages: ChatMessage[], schema: Record<string, unknown>, signal?: AbortSignal): Promise<T> {
   const config = { ...preferences }
   const key = createHash('sha256').update(JSON.stringify({ version: 1, model: config.codexModel, reasoning: 'low', messages, schema })).digest('hex')
@@ -221,9 +237,8 @@ export async function subscriptionJSON<T>(messages: ChatMessage[], schema: Recor
     if (existsSync(cache)) return JSON.parse(await readFile(cache, 'utf8')) as T
     const used = await requestsToday()
     if (used >= config.dailyRequestLimit) throw new Error(`ChatGPT daily request cap reached (${used}/${config.dailyRequestLimit}). Cached results still work. Change the cap in Settings to allow more; no paid API fallback is used.`)
-    const timeout = AbortSignal.timeout(5 * 60_000)
-    const combined = signal ? AbortSignal.any([signal, timeout]) : timeout
-    await assertChatGptLogin(config, combined)
+    const loginBudget = AbortSignal.timeout(LOGIN_TIMEOUT_MS)
+    await assertChatGptLogin(config, signal ? AbortSignal.any([signal, loginBudget]) : loginBudget)
     const dir = await mkdtemp(join(root, 'request-'))
     try {
       const images: string[] = []
@@ -245,10 +260,28 @@ export async function subscriptionJSON<T>(messages: ChatMessage[], schema: Recor
         sections.push(`${message.role.toUpperCase()} MESSAGE\n${text.join('\n')}`)
       }
       await writeFile(join(dir, 'schema.json'), JSON.stringify(schema))
-      // Serialize only the reservation; independent model requests can overlap.
-      // Count failures too: retries cannot quietly spend more.
-      await reserveRequest(config.dailyRequestLimit)
-      await run(config.codexPath, codexArguments(config.codexModel, dir, images), sections.join('\n\n'), combined)
+      let settled = false
+      for (let attempt = 1; attempt <= ANALYSIS_ATTEMPTS; attempt++) {
+        // Serialize only the reservation; independent model requests can overlap.
+        // Count failures too: retries cannot quietly spend more.
+        await reserveRequest(config.dailyRequestLimit)
+        const timeout = AbortSignal.timeout(ANALYSIS_TIMEOUT_MS)
+        const combined = signal ? AbortSignal.any([signal, timeout]) : timeout
+        try {
+          await run(config.codexPath, codexArguments(config.codexModel, dir, images), sections.join('\n\n'), combined)
+          settled = true
+          break
+        } catch (error) {
+          // A user cancel must never be retried, and a non-timeout failure is
+          // reported as-is. A stalled launcher can still have written a complete
+          // answer, so accept that before spending another request.
+          if (signal?.aborted) throw error
+          if (await hasCompleteResponse(join(dir, 'response.json'))) { settled = true; break }
+          if (!timeout.aborted || attempt === ANALYSIS_ATTEMPTS) throw error
+          await rm(join(dir, 'response.json'), { force: true })
+        }
+      }
+      if (!settled) throw new Error('Local provider did not answer. Retry the analysis; cached results are kept.')
       const response = await readFile(join(dir, 'response.json'), 'utf8')
       const result = JSON.parse(response) as T
       await writeFile(cache, JSON.stringify(result))

Diagnostics that would have shortened this

  • Say why the call was aborted: timed out after 300 s versus cancelled. Today both produce the same string, which reads like a user cancel.
  • Keep the last few KB of the child's stderr on abort instead of discarding it.
  • Optional: a per-stage budget, since editorial review batches are the slowest calls here.

Risks in the patch

  • A retry can double-spend one request slot when the first attempt actually completed remotely. Both attempts are counted, so the daily cap still bounds it.
  • Accepting a response.json from a stalled launcher assumes the file is fully written; the caller already validates the parsed shape, and the stalled child still needs to be reaped.

Happy to turn this into a PR with tests and a CHANGELOG line if the direction is acceptable.

Ramadas108 avatar Nov 11 '26 10:11 Ramadas108