diff --git a/sdk/src/impl/__tests__/retry-response-body.test.ts b/sdk/src/impl/__tests__/retry-response-body.test.ts new file mode 100644 index 0000000000..add3afef9b --- /dev/null +++ b/sdk/src/impl/__tests__/retry-response-body.test.ts @@ -0,0 +1,60 @@ +import { afterEach, expect, jest, spyOn, test } from 'bun:test' + +import { onFakeRetryClock } from '../../../test/fake-retry-clock' +import { startAgentRun } from '../database' + +import type { Logger } from '@codebuff/common/types/contracts/logger' + +afterEach(() => jest.useRealTimers()) + +test('releases discarded retry bodies and still returns the successful run', async () => { + const events: string[] = [] + const success = Response.json({ runId: 'retried-run' }) + let requests = 0 + const fetchImpl = Object.assign( + async () => { + const attempt = ++requests + events.push(`request ${attempt}`) + if (attempt === 3) return success + return new Response( + new ReadableStream({ + cancel() { + events.push(`cancel ${attempt}`) + if (attempt === 1) throw new Error('cleanup failed') + }, + }), + { status: 503 }, + ) + }, + { preconnect: globalThis.fetch.preconnect }, + ) + const fetchSpy = spyOn(globalThis, 'fetch').mockImplementation(fetchImpl) + const logger = { + debug: () => {}, + info: () => {}, + warn: () => {}, + error: () => {}, + } as Logger + + try { + const runId = await onFakeRetryClock(() => + startAgentRun({ + apiKey: 'fixture', + agentId: 'fixture', + ancestorRunIds: [], + logger, + }), + ) + expect(runId).toBe('retried-run') + expect(events).toEqual([ + 'request 1', + 'cancel 1', + 'request 2', + 'cancel 2', + 'request 3', + ]) + expect(success.bodyUsed).toBe(true) + } finally { + fetchSpy.mockRestore() + } +}) diff --git a/sdk/src/impl/database.ts b/sdk/src/impl/database.ts index 610596ca34..777437019a 100644 --- a/sdk/src/impl/database.ts +++ b/sdk/src/impl/database.ts @@ -94,6 +94,8 @@ async function fetchWithRetry( // Retryable error - log and continue to retry if (attempt < MAX_RETRIES_PER_MESSAGE) { + // Discard this body before retrying so its connection can be released. + await response.body?.cancel().catch(() => {}) logger?.warn( { status: response.status, attempt: attempt + 1, url: String(url) }, `Retryable HTTP error, retrying in ${backoffDelay}ms`,