🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(file): stop a burst of image rehosts from deadlocking the DB pool (#22290)
Arvin Xu56802b0afc6d
diff --git a/apps/server/src/services/file/__tests__/index.test.ts b/apps/server/src/services/file/__tests__/index.test.tsindex d9154d62de9..a8e8bc6d802 100644--- a/apps/server/src/services/file/__tests__/index.test.ts+++ b/apps/server/src/services/file/__tests__/index.test.ts@@ -488,6 +488,31 @@ describe('FileService', () => {);});+ /**+ * 2026-11-02: a page-editor paste sent 78 `rehostImage` calls in one batch. Each held a pool+ * connection while waiting on the owner's row lock, and the lock holder's `checkHash` waited+ * for an 11th connection on the default 10-connection pool, so the instance hung until it+ * timed out. Every globalFiles query of the record step must run on the transaction.+ */+ it('runs the globalFiles queries on the record transaction, not the shared pool', async () => {+ const tx = { name: 'record-tx' };+ const txDb = { transaction: (run: (trx: unknown) => unknown) => run(tx) } as any;+ const txService = new FileService(txDb, mockUserId);+ vi.mocked(txService['impl'].uploadBuffer).mockResolvedValue({ key: 'images/new.png' });+ vi.mocked(txService['impl'].getFileMetadata).mockRejectedValue(new Error('NoSuchKey'));+ mockFileModel.checkHash.mockResolvedValue({ isExist: true, url: 'images/old.png' });++ await txService.uploadFromBuffer(Buffer.from('image'), 'image/png', 'images/new.png');++ expect(mockFileModel.checkHash).toHaveBeenCalledWith(expect.any(String), tx);+ expect(mockFileModel.updateGlobalFile).toHaveBeenCalledWith(+ expect.any(String),+ expect.objectContaining({ url: 'images/new.png' }),+ tx,+ );+ expect(mockFileModel.create).toHaveBeenCalledWith(expect.anything(), false, tx);+ });+it('should compute hash for deduplication', async () => {const content = Buffer.from('test content');@@ -600,10 +625,14 @@ describe('FileService', () => {url: 'new/path.txt',});- expect(mockFileModel.updateGlobalFile).toHaveBeenCalledWith('existing-hash', {- metadata: { dirname: 'new', filename: 'test.txt', path: 'new/path.txt' },- url: 'new/path.txt',- });+ expect(mockFileModel.updateGlobalFile).toHaveBeenCalledWith(+ 'existing-hash',+ {+ metadata: { dirname: 'new', filename: 'test.txt', path: 'new/path.txt' },+ url: 'new/path.txt',+ },+ undefined,+ );expect(mockFileModel.create).toHaveBeenCalledWith(expect.objectContaining({fileHash: 'existing-hash',diff --git a/apps/server/src/services/file/index.ts b/apps/server/src/services/file/index.tsindex b8cf812cf4f..6217b2dbbf4 100644--- a/apps/server/src/services/file/index.ts+++ b/apps/server/src/services/file/index.ts@@ -247,8 +247,10 @@ export class FileService {},trx?: Transaction,): Promise<{ fileId: string; url: string }> {- // Check if hash already exists in globalFiles- const existingFile = await this.fileModel.checkHash(params.fileHash);+ // Check if hash already exists in globalFiles. Every query here must go through `trx`:+ // callers such as `uploadFromBuffer` hold the owner's row lock in that transaction, and+ // a read on the shared pool would wait for a connection the lock waiters already hold.+ const existingFile = await this.fileModel.checkHash(params.fileHash, trx);const { isExist } = existingFile;let shouldRefreshGlobalFile = false;@@ -259,10 +261,14 @@ export class FileService {if (shouldRefreshGlobalFile) {// Keep global hash dedup usable when the same file is uploaded again to a// fresh object key after the previous storage object has been removed.- await this.fileModel.updateGlobalFile(params.fileHash, {- metadata: params.metadata,- url: params.url,- });+ await this.fileModel.updateGlobalFile(+ params.fileHash,+ {+ metadata: params.metadata,+ url: params.url,+ },+ trx,+ );}// Create database recorddiff --git a/packages/app-config/src/db.ts b/packages/app-config/src/db.tsindex 2c418bec35c..b3320bbd766 100644--- a/packages/app-config/src/db.ts+++ b/packages/app-config/src/db.ts@@ -5,6 +5,7 @@ export const getServerDBConfig = () => {return createEnv({runtimeEnv: {DATABASE_DRIVER: process.env.DATABASE_DRIVER || 'neon',+ DATABASE_POOL_ACQUIRE_TIMEOUT: process.env.DATABASE_POOL_ACQUIRE_TIMEOUT,DATABASE_STATEMENT_TIMEOUT: process.env.DATABASE_STATEMENT_TIMEOUT,DATABASE_TEST_URL: process.env.DATABASE_TEST_URL,DATABASE_URL: process.env.DATABASE_URL,@@ -16,6 +17,10 @@ export const getServerDBConfig = () => {},server: {DATABASE_DRIVER: z.enum(['neon', 'node']),+ // How long (in milliseconds) a query waits for a free pool connection before it fails.+ // Without a limit a request whose pool is exhausted waits forever, and every other request+ // on the same instance queues behind it. Defaults to 30s; set 0 to wait indefinitely.+ DATABASE_POOL_ACQUIRE_TIMEOUT: z.coerce.number().int().min(0).optional(),// Server-side timeout (in milliseconds) for a single SQL statement.// When set, Postgres aborts any statement running longer than this,// preventing a stuck query (e.g. lock contention) from blocking indefinitely.diff --git a/packages/database/src/core/web-server.test.ts b/packages/database/src/core/web-server.test.tsnew file mode 100644index 00000000000..b685bdcdbaa--- /dev/null+++ b/packages/database/src/core/web-server.test.ts@@ -0,0 +1,26 @@+import { describe, expect, it } from 'vitest';++import { buildPoolOptions } from './web-server';++describe('buildPoolOptions', () => {+ it('bounds the wait for a pool connection by default', () => {+ expect(buildPoolOptions({})).toEqual({ connectionTimeoutMillis: 30_000 });+ });++ it('lets DATABASE_POOL_ACQUIRE_TIMEOUT override the wait, including 0 for no limit', () => {+ expect(buildPoolOptions({ DATABASE_POOL_ACQUIRE_TIMEOUT: 5000 })).toEqual({+ connectionTimeoutMillis: 5000,+ });+ expect(buildPoolOptions({ DATABASE_POOL_ACQUIRE_TIMEOUT: 0 })).toEqual({+ connectionTimeoutMillis: 0,+ });+ });++ it('keeps the server-side statement and idle-in-transaction timeouts', () => {+ expect(buildPoolOptions({ DATABASE_STATEMENT_TIMEOUT: 60_000 })).toEqual({+ connectionTimeoutMillis: 30_000,+ idle_in_transaction_session_timeout: 60_000,+ statement_timeout: 60_000,+ });+ });+});diff --git a/packages/database/src/core/web-server.ts b/packages/database/src/core/web-server.tsindex 38207b54405..b872c3eeb69 100644--- a/packages/database/src/core/web-server.ts+++ b/packages/database/src/core/web-server.ts@@ -9,6 +9,35 @@ import { serverDBEnv } from '@/config/db';import * as schema from '../schemas';import type { LobeChatDatabase } from '../type';+const DEFAULT_POOL_ACQUIRE_TIMEOUT_MS = 30_000;++/**+ * Pool options shared by the node and neon drivers.+ *+ * `connectionTimeoutMillis` bounds the wait for a free pool connection. pg's default is 0 (wait+ * forever): on 2026-11-02 one exhausted pool hung every request on its Vercel instance for 300s+ * until the function timed out, instead of failing the requests that could not get a connection.+ */+export const buildPoolOptions = (env: {+ DATABASE_POOL_ACQUIRE_TIMEOUT?: number;+ DATABASE_STATEMENT_TIMEOUT?: number;+}) => {+ // When DATABASE_STATEMENT_TIMEOUT is set, Postgres aborts any statement (and any+ // transaction left idle) exceeding it on the server side, so a stuck query can't+ // block indefinitely. Omit the keys entirely when unset to keep Postgres' defaults.+ const statementTimeout = env.DATABASE_STATEMENT_TIMEOUT;++ return {+ connectionTimeoutMillis: env.DATABASE_POOL_ACQUIRE_TIMEOUT ?? DEFAULT_POOL_ACQUIRE_TIMEOUT_MS,+ ...(statementTimeout+ ? {+ idle_in_transaction_session_timeout: statementTimeout,+ statement_timeout: statementTimeout,+ }+ : {}),+ };+};+export const getDBInstance = (): LobeChatDatabase => {// In test environment, return a mock instance to avoid initialization errorsif (process.env.NODE_ENV === 'test') return {} as LobeChatDatabase;@@ -28,19 +57,10 @@ If you don't have it, please run \`openssl rand -base64 32\` to create one.throw new Error(`You are try to use database, but "DATABASE_URL" is not set correctly`);}- // When DATABASE_STATEMENT_TIMEOUT is set, Postgres aborts any statement (and any- // transaction left idle) exceeding it on the server side, so a stuck query can't- // block indefinitely. Omit the keys entirely when unset to keep Postgres' defaults.- const statementTimeout = serverDBEnv.DATABASE_STATEMENT_TIMEOUT;- const timeoutConfig = statementTimeout- ? {- idle_in_transaction_session_timeout: statementTimeout,- statement_timeout: statementTimeout,- }- : {};+ const poolOptions = buildPoolOptions(serverDBEnv);if (serverDBEnv.DATABASE_DRIVER === 'node') {- const client = new NodePool({ connectionString, ...timeoutConfig });+ const client = new NodePool({ connectionString, ...poolOptions });// pg.Pool emits 'error' on idle clients when the backend connection drops.// Without a listener Node escalates it to uncaughtException and exits the process.// See: https://node-postgres.com/apis/pool#error@@ -59,7 +79,7 @@ If you don't have it, please run \`openssl rand -base64 32\` to create one.neonConfig.webSocketConstructor = ws;}- const client = new NeonPool({ connectionString, ...timeoutConfig });+ const client = new NeonPool({ connectionString, ...poolOptions });// NeonPool runs over WebSocket; transient drops surface as 'error' on the pool.// Without a listener Node escalates it to uncaughtException — on Vercel this killed// the entire Lambda 1800+ times in 5 minutes (see ).diff --git a/packages/database/src/models/file.ts b/packages/database/src/models/file.tsindex 58950e6a448..48dd2e28dca 100644--- a/packages/database/src/models/file.ts+++ b/packages/database/src/models/file.ts@@ -167,8 +167,12 @@ export class FileModel {return (trx ?? this.db).update(globalFiles).set(data).where(eq(globalFiles.hashId, hashId));};- checkHash = async (hash: string) => {- const item = await this.db.query.globalFiles.findFirst({+ /**+ * Pass `trx` when calling inside a transaction: reading through `this.db` would check out a+ * second pool connection while the transaction still holds its locks.+ */+ checkHash = async (hash: string, trx?: Transaction) => {+ const item = await (trx ?? this.db).query.globalFiles.findFirst({where: eq(globalFiles.hashId, hash),});if (!item) return { isExist: false };diff --git a/src/features/EditorCanvas/rehostImage.test.ts b/src/features/EditorCanvas/rehostImage.test.tsindex 9e72dae0278..80b2c938daa 100644--- a/src/features/EditorCanvas/rehostImage.test.ts+++ b/src/features/EditorCanvas/rehostImage.test.ts@@ -5,7 +5,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { fileService } from '@/services/file';import { getFileIdForUrl, registerAttachment } from './attachmentRegistry';-import { needsImageRehost, rehostImage } from './rehostImage';+import { MAX_CONCURRENT_REHOSTS, needsImageRehost, rehostImage } from './rehostImage';vi.mock('@/services/file', () => ({ fileService: { rehostImage: vi.fn() } }));vi.mock('@lobehub/ui', () => ({ toast: { error: vi.fn() } }));@@ -69,6 +69,41 @@ describe('editor image rehosting', () => {expect(toast.error).not.toHaveBeenCalled();});+ it('keeps at most MAX_CONCURRENT_REHOSTS rehosts in flight when many images are pasted', async () => {+ let inFlight = 0;+ let peak = 0;+ const pending: (() => void)[] = [];+ vi.mocked(fileService.rehostImage).mockImplementation(async (url) => {+ inFlight += 1;+ peak = Math.max(peak, inFlight);+ await new Promise<void>((resolve) => pending.push(resolve));+ inFlight -= 1;+ return { fileId: `file-${url}`, url: `${url}?rehosted` };+ });++ const urls = Array.from({ length: 20 }, (_, i) => `https://cdn.example/paste-${i}.png`);+ const all = Promise.all(urls.map((url) => rehostImage(url)));++ while (pending.length > 0 || inFlight > 0) {+ await new Promise((resolve) => setTimeout(resolve, 0));+ pending.shift()?.();+ }++ await expect(all).resolves.toHaveLength(20);+ expect(fileService.rehostImage).toHaveBeenCalledTimes(20);+ expect(peak).toBe(MAX_CONCURRENT_REHOSTS);+ });++ it('releases the slot when a rehost fails', async () => {+ vi.mocked(fileService.rehostImage).mockRejectedValue(new Error('Download failed'));+ const failures = Array.from({ length: MAX_CONCURRENT_REHOSTS + 2 }, (_, i) =>+ rehostImage(`https://cdn.example/broken-${i}.png`).catch(() => 'failed'),+ );+ await expect(Promise.all(failures)).resolves.toEqual(+ Array.from({ length: MAX_CONCURRENT_REHOSTS + 2 }, () => 'failed'),+ );+ });+it('propagates download failures to the editor', async () => {vi.mocked(fileService.rehostImage).mockRejectedValue(new Error('Download failed'));await expect(rehostImage('https://cdn.discordapp.com/missing.png')).rejects.toThrow(diff --git a/src/features/EditorCanvas/rehostImage.ts b/src/features/EditorCanvas/rehostImage.tsindex c1bf692a31c..4d26eb658cd 100644--- a/src/features/EditorCanvas/rehostImage.ts+++ b/src/features/EditorCanvas/rehostImage.ts@@ -20,9 +20,37 @@ export const needsImageRehost = (src: string): boolean => {}};+/**+ * Pasting a page with many external images asks the editor to rehost all of them at once. Each+ * rehost is a server-side upload transaction serialized on the owner's storage lock, and tRPC+ * batches simultaneous calls into one request, so an unbounded paste (78 images on 2026-11-02)+ * lands as dozens of competing transactions on a single server instance.+ */+export const MAX_CONCURRENT_REHOSTS = 3;++let activeRehosts = 0;+const waitingRehosts: (() => void)[] = [];++const withRehostSlot = async <T>(run: () => Promise<T>): Promise<T> => {+ if (activeRehosts >= MAX_CONCURRENT_REHOSTS) {+ await new Promise<void>((resolve) => waitingRehosts.push(resolve));+ } else {+ activeRehosts += 1;+ }++ try {+ return await run();+ } finally {+ // Hand the slot straight to the next waiter so the count never dips and refills.+ const next = waitingRehosts.shift();+ if (next) next();+ else activeRehosts -= 1;+ }+};+export const rehostImage = async (src: string): Promise<{ url: string }> => {try {- const result = await fileService.rehostImage(resolveImageUrl(src).href);+ const result = await withRehostSlot(() => fileService.rehostImage(resolveImageUrl(src).href));registerAttachment(result.url, result.fileId);return { url: result.url };} catch (error) {