🤯 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: reduce capture trigger upgrade lock contention (#19570)
YuTengjing0781de383341
diff --git a/packages/database/src/repositories/ftsSearchSyncOutbox/__tests__/index.test.ts b/packages/database/src/repositories/ftsSearchSyncOutbox/__tests__/index.test.tsindex 078b8796c04..306333c189b 100644--- a/packages/database/src/repositories/ftsSearchSyncOutbox/__tests__/index.test.ts+++ b/packages/database/src/repositories/ftsSearchSyncOutbox/__tests__/index.test.ts@@ -413,6 +413,47 @@ describe('FtsSearchSyncOutboxRepository', { concurrent: false }, () => {CAPTURE_INSTALL_TEST_TIMEOUT,);+ it('upgrades v1 without dropping triggers or locking unchanged source tables', async () => {+ await dropCaptureInfrastructure();+ await installHistoricalCapture(1);+ const statements: string[] = [];+ const recordingDatabase = {+ execute: db.execute.bind(db),+ transaction: (+ callback: (transaction: { execute: (statement: SQL) => unknown }) => Promise<void>,+ ) =>+ db.transaction(async (transaction) =>+ callback({+ execute: (statement) => {+ statements.push(normalizeSql(statement));+ return transaction.execute(statement);+ },+ }),+ ),+ } as unknown as ConstructorParameters<typeof FtsSearchSyncOutboxRepository>[0];++ try {+ await new FtsSearchSyncOutboxRepository(recordingDatabase).installCaptureInfrastructure();+ expect(statements.filter((statement) => statement.startsWith('DROP TRIGGER'))).toEqual([]);+ expect(statements.filter((statement) => statement.startsWith('LOCK TABLE'))).toEqual([+ 'LOCK TABLE "public"."messages", "public"."topics" IN SHARE ROW EXCLUSIVE MODE',+ ]);+ expect(+ statements.filter((statement) => statement.startsWith('SET LOCAL lock_timeout')),+ ).toEqual(["SET LOCAL lock_timeout = '60s'"]);+ expect(+ statements+ .filter((statement) => statement.startsWith('CREATE OR REPLACE TRIGGER'))+ .map((statement) => statement.split(' ')[4])+ .sort(),+ ).toEqual(['fts_search_sync_messages', 'fts_search_sync_topics']);+ await expect(repository.assertCaptureInfrastructure()).resolves.toBeUndefined();+ } finally {+ await dropCaptureInfrastructure();+ await repository.installCaptureInfrastructure();+ }+ });+it('rolls back definitions and the version marker when an upgrade fails', async () => {await dropCaptureInfrastructure();await installHistoricalCapture(1);@@ -425,7 +466,7 @@ describe('FtsSearchSyncOutboxRepository', { concurrent: false }, () => {db.transaction(async (transaction) =>callback({execute: (statement) => {- if (normalizeSql(statement).startsWith('CREATE TRIGGER')) {+ if (/^CREATE (?:OR REPLACE )?TRIGGER/.test(normalizeSql(statement))) {throw new Error('injected trigger creation failure');}return transaction.execute(statement);diff --git a/packages/database/src/repositories/ftsSearchSyncOutbox/index.ts b/packages/database/src/repositories/ftsSearchSyncOutbox/index.tsindex 250cc73b13c..edb1476816a 100644--- a/packages/database/src/repositories/ftsSearchSyncOutbox/index.ts+++ b/packages/database/src/repositories/ftsSearchSyncOutbox/index.ts@@ -330,7 +330,7 @@ export class FtsSearchSyncOutboxRepository {*/async installCaptureInfrastructure(): Promise<void> {await this.db.transaction(async (transaction) => {- await transaction.execute(sql`SET LOCAL lock_timeout = '3s'`);+ await transaction.execute(sql`SET LOCAL lock_timeout = '60s'`);/** Serialize installers before inspecting state so two deployments cannot both create DDL. */await transaction.execute(sql`SELECT pg_advisory_xact_lock(hashtext('lobehub.fts_search_sync_capture'))`,@@ -359,8 +359,6 @@ export class FtsSearchSyncOutboxRepository {return;}- // A source-table lock closes the window between replacing the function and its triggers.- await lockCaptureSourceWrites(transaction);if (!state.persisted) {await transaction.execute(sql`INSERT INTO fts_search_sync_capture_version (id, version)@@ -373,16 +371,41 @@ export class FtsSearchSyncOutboxRepository {nextVersion++) {const next = CAPTURE_VERSIONS.find(({ version }) => version === nextVersion)!;+ const previous = CAPTURE_VERSIONS.find(({ version }) => version === nextVersion - 1)!;+ const changedTriggers = next.triggers.filter(+ (trigger) =>+ !previous.triggers.some(+ (old) =>+ old.name === trigger.name &&+ old.table === trigger.table &&+ old.definition === trigger.definition,+ ),+ );+ if (changedTriggers.length > 0) {+ const tables = sql.join(+ [...new Set(changedTriggers.map(({ table }) => table))]+ .sort()+ .map((table) => sql`${sql.identifier('public')}.${sql.identifier(table)}`),+ sql`, `,+ );+ /**+ * Acquire the replacement lock before changing functions so affected writes cannot+ * observe a mixed definition. Unlike DROP TRIGGER, this permits ordinary readers.+ * https://www.postgresql.org/docs/17/explicit-locking.html+ */+ await transaction.execute(sql`LOCK TABLE ${tables} IN SHARE ROW EXCLUSIVE MODE`);+ }if (nextVersion === CURRENT_CAPTURE_VERSION) {for (const statement of FTS_SEARCH_SYNC_CAPTURE_FUNCTION_STATEMENTS) {await transaction.execute(statement);}}- for (const { name, table } of FTS_SEARCH_SYNC_CAPTURE_TRIGGER_TARGETS) {- await transaction.execute(sql.raw(`DROP TRIGGER "${name}" ON public."${table}"`));- }- for (const trigger of next.triggers) {- await transaction.execute(sql.raw(`${trigger.definition};`));+ for (const trigger of changedTriggers) {+ await transaction.execute(+ sql.raw(+ `${trigger.definition.replace(/^CREATE TRIGGER /, 'CREATE OR REPLACE TRIGGER ')};`,+ ),+ );}await transaction.execute(sql`UPDATE fts_search_sync_capture_version SET version = ${nextVersion}