Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions sdk/src/impl/__tests__/retry-response-body.test.ts
Original file line number Diff line number Diff line change
@@ -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()
}
})
2 changes: 2 additions & 0 deletions sdk/src/impl/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`,
Expand Down
Loading