fix(frontend): cap concurrent status requests in upload polling (#4348)

The upload panel split every file still parsing into chunks of 40 and
sent all chunks at once on each poll. With a few thousand files in
flight that is 100+ parallel /api/v1/knowledge/batch requests every
few seconds, each holding a Postgres connection, which exhausts the
default max_connections=100 (FATAL: sorry, too many clients already).

Keep at most 4 status requests in flight per poll; the remaining chunks
are queried as earlier ones finish.

Claude-Session: https://claude.ai/code/session_014ENAekfB7Um4VUnzUWWAv1
main
Chris Chen 2026-10-16 23:43:26 +08:00 committed by GitHub
parent 7115cb2a61
commit 86767d77e9
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 74 additions and 20 deletions

View File

@ -58,6 +58,7 @@ function setup(overrides: Partial<UploadQueueDeps> = {}) {
concurrency: 2,
pollIntervalMs: 1000,
pollChunkSize: 2,
pollConcurrency: 4,
upload: (batch, payload, progress, signal) => new Promise((resolve, reject) => {
calls.push({ batch, payload, signal, progress, resolve, reject })
signal.addEventListener('abort', () => reject({ message: 'Network error' }))
@ -206,6 +207,43 @@ test('polls created rows until parsing settles', async () => {
assert.equal(byName('c').parseStatus, 'deleted')
})
test('a poll keeps at most `pollConcurrency` status requests in flight', async () => {
// Thousands of files still parsing used to fire every chunk at once, one
// database connection each on the server.
const pending: Array<{ ids: string[]; resolve: (rows: KnowledgeStatusRow[]) => void }> = []
const { items, batches, queue, byName } = setup({
pollConcurrency: 2,
queryStatus: (_kbId, ids) => new Promise(resolve => pending.push({ ids, resolve })),
})
batches.push({ id: 'b1', kbId: 'kb1', kbName: 'KB', targetFolder: '' })
for (const name of ['a', 'b', 'c', 'd', 'e', 'f', 'g']) {
items.push({
id: `u-${name}`, batchId: 'b1', name, relativePath: '', size: 1, loaded: 1,
transfer: 'uploaded', knowledgeId: `k-${name}`, parseStatus: 'pending',
})
}
const poll = queue.pollNow()
let done = false
void poll.then(() => { done = true })
const answered: string[][] = []
let maxInFlight = 0
while (!done) {
await flush()
maxInFlight = Math.max(maxInFlight, pending.length)
const next = pending.shift()
if (!next) continue
answered.push(next.ids)
next.resolve(next.ids.map(id => ({ id, parse_status: 'completed' })))
}
assert.equal(maxInFlight, 2)
// pollChunkSize 2: seven ids in four requests, each id asked about once.
assert.deepEqual(answered.flat().sort(), ['k-a', 'k-b', 'k-c', 'k-d', 'k-e', 'k-f', 'k-g'])
assert.equal(answered.length, 4)
assert.equal(byName('g').parseStatus, 'completed')
})
test('a row that reappears resets its missing count', async () => {
const { calls, statusRows, queue, batch, byName } = setup()
queue.add(batch(), [{ file: file('a') }])

View File

@ -60,6 +60,12 @@ export interface UploadQueueDeps {
pollIntervalMs: number
/** Most knowledge ids asked about in one status request. */
pollChunkSize: number
/**
* Most status requests one poll keeps in flight. Each one holds a database
* connection on the server, so thousands of files still parsing must not
* turn into a burst of hundreds of parallel requests.
*/
pollConcurrency: number
/** Resolves or rejects with the API's response body; the queue classifies either. */
upload: (
batch: UploadBatch,
@ -263,30 +269,37 @@ export function createUploadQueue(items: UploadItem[], batches: UploadBatch[], d
byKb.get(kbId)!.push(item)
}
const requests: Promise<void>[] = []
const chunks: Array<{ kbId: string; chunk: UploadItem[] }> = []
for (const [kbId, group] of byKb) {
for (let i = 0; i < group.length; i += deps.pollChunkSize) {
const chunk = group.slice(i, i + deps.pollChunkSize)
requests.push(deps.queryStatus(kbId, chunk.map(item => item.knowledgeId!)).then(rows => {
// A failed request just waits for the next tick.
if (!rows || startedIn !== generation) return
const byId = new Map(rows.map(row => [row.id, row]))
for (const item of chunk) {
const row = byId.get(item.knowledgeId!)
if (!row) {
const misses = (missingPolls.get(item.id) ?? 0) + 1
missingPolls.set(item.id, misses)
if (misses >= MISSING_POLLS_BEFORE_DELETED) item.parseStatus = 'deleted'
continue
}
missingPolls.delete(item.id)
item.parseStatus = row.parse_status
item.parseError = row.error_message || undefined
}
}, () => {}))
chunks.push({ kbId, chunk: group.slice(i, i + deps.pollChunkSize) })
}
}
await Promise.all(requests)
const queryChunk = async ({ kbId, chunk }: { kbId: string; chunk: UploadItem[] }) => {
const rows = await deps.queryStatus(kbId, chunk.map(item => item.knowledgeId!)).catch(() => null)
// A failed request just waits for the next tick.
if (!rows || startedIn !== generation) return
const byId = new Map(rows.map(row => [row.id, row]))
for (const item of chunk) {
const row = byId.get(item.knowledgeId!)
if (!row) {
const misses = (missingPolls.get(item.id) ?? 0) + 1
missingPolls.set(item.id, misses)
if (misses >= MISSING_POLLS_BEFORE_DELETED) item.parseStatus = 'deleted'
continue
}
missingPolls.delete(item.id)
item.parseStatus = row.parse_status
item.parseError = row.error_message || undefined
}
}
let next = 0
const worker = async () => {
while (next < chunks.length && startedIn === generation) await queryChunk(chunks[next++])
}
await Promise.all(Array.from({ length: Math.min(Math.max(1, deps.pollConcurrency), chunks.length) }, worker))
if (startedIn === generation) schedulePoll()
}

View File

@ -24,6 +24,8 @@ const CONCURRENCY = 3
const POLL_INTERVAL_MS = 3000
/** Keeps the ids=… query string of one status request well under URL length limits. */
const POLL_CHUNK_SIZE = 40
/** Status requests in flight per poll; each holds a database connection on the server. */
const POLL_CONCURRENCY = 4
/** Minimum gap between mid-batch list refreshes pushed to an open page. */
const LIST_REFRESH_INTERVAL_MS = 2000
/** Batch ends this close together produce one final refresh. */
@ -65,6 +67,7 @@ export function createUploadTasks(deps: UploadTasksDeps) {
concurrency: CONCURRENCY,
pollIntervalMs: POLL_INTERVAL_MS,
pollChunkSize: POLL_CHUNK_SIZE,
pollConcurrency: POLL_CONCURRENCY,
upload: deps.upload,
queryStatus: deps.queryStatus,
onTransferEnd: createListRefreshThrottle(