Skip to content

🤯 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.

🐛 fix(database): stable order for connector tool queries (#22332)

Lobehub Codera4da07ef8333
diff --git a/packages/database/src/models/__tests__/connector.test.ts b/packages/database/src/models/__tests__/connector.test.ts
index 2ca58aac798..25fffc0970b 100644
--- a/packages/database/src/models/__tests__/connector.test.ts
+++ b/packages/database/src/models/__tests__/connector.test.ts
@@ -1,4 +1,4 @@
-import { eq } from 'drizzle-orm';
+import { eq, sql } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { getTestDB } from '../../core/getTestDB';
@@ -267,6 +267,72 @@ describe('ConnectorModel', () => {
});
});
+ describe('stable identifier order', () => {
+ const createConnectors = async (model: ConnectorModel, identifiers: string[]) => {
+ for (const identifier of identifiers) {
+ await model.create({
+ identifier,
+ name: identifier,
+ sourceType: 'builtin',
+ status: 'connected',
+ });
+ }
+ };
+
+ // The identifier indexes make small test tables come back sorted by accident;
+ // disable plain index scans so rows come back in physical (heap) order, as
+ // they do in production when the planner picks a seq or bitmap heap scan.
+ beforeEach(async () => {
+ await serverDB.execute(sql`SET enable_indexscan = off`);
+ await serverDB.execute(sql`SET enable_indexonlyscan = off`);
+ });
+
+ afterEach(async () => {
+ await serverDB.execute(sql`RESET enable_indexscan`);
+ await serverDB.execute(sql`RESET enable_indexonlyscan`);
+ });
+
+ it('returns connectors sorted by identifier regardless of insert, update or input order', async () => {
+ const model = new ConnectorModel(serverDB, userId);
+ // insert in reverse order so the physical row order differs from the sorted order
+ await createConnectors(model, ['slack', 'linear', 'github']);
+ const expected = ['github', 'linear', 'slack'];
+
+ const queried = await model.queryByIdentifiers(['linear', 'slack', 'github']);
+ const resolved = await model.resolveByIdentifiers(['slack', 'github', 'linear']);
+ expect(queried.map((r) => r.identifier)).toEqual(expected);
+ expect(resolved.map((r) => r.identifier)).toEqual(expected);
+ expect((await model.resolveAll()).map((r) => r.identifier)).toEqual(expected);
+
+ // an update rewrites the row and moves it in physical order
+ const github = queried.find((r) => r.identifier === 'github')!;
+ await model.update(github.id, { name: 'GitHub (renamed)' });
+
+ expect(
+ (await model.queryByIdentifiers(['github', 'linear', 'slack'])).map((r) => r.id),
+ ).toEqual(queried.map((r) => r.id));
+ expect(
+ (await model.resolveByIdentifiers(['linear', 'github', 'slack'])).map((r) => r.id),
+ ).toEqual(resolved.map((r) => r.id));
+ expect((await model.resolveAll()).map((r) => r.identifier)).toEqual(expected);
+ });
+
+ it('omits unknown identifiers and does not duplicate repeated ones', async () => {
+ const model = new ConnectorModel(serverDB, userId);
+ await createConnectors(model, ['slack', 'github']);
+
+ const identifiers = ['slack', 'missing', 'github', 'slack'];
+ expect((await model.queryByIdentifiers(identifiers)).map((r) => r.identifier)).toEqual([
+ 'github',
+ 'slack',
+ ]);
+ expect((await model.resolveByIdentifiers(identifiers)).map((r) => r.identifier)).toEqual([
+ 'github',
+ 'slack',
+ ]);
+ });
+ });
+
describe('queryReferencesByIdentifiers', () => {
it('returns scoped safe references without decrypting credentials', async () => {
const model = new ConnectorModel(serverDB, userId, undefined, gateKeeper);
diff --git a/packages/database/src/models/__tests__/connectorTool.test.ts b/packages/database/src/models/__tests__/connectorTool.test.ts
index 25006033b7a..d0d02524b4e 100644
--- a/packages/database/src/models/__tests__/connectorTool.test.ts
+++ b/packages/database/src/models/__tests__/connectorTool.test.ts
@@ -322,6 +322,56 @@ describe('ConnectorToolModel', () => {
});
});
+ describe('stable tool order', () => {
+ const toolKeys = (rows: { toolName: string; userConnectorId: string }[]) =>
+ rows.map((r) => `${r.userConnectorId}:${r.toolName}`);
+
+ it('groups tools by connector and sorts by toolName, unchanged after an upsert rewrites rows', async () => {
+ const secondConnectorId = await insertConnector({ identifier: 'notion' });
+ const model = new ConnectorToolModel(serverDB, userId);
+ // insert in reverse order so the physical row order differs from the sorted order
+ await model.upsertMany(secondConnectorId, [tool({ toolName: 'zeta' })]);
+ await model.upsertMany(connectorId, [tool({ toolName: 'zeta' }), tool({ toolName: 'beta' })]);
+ await model.upsertMany(secondConnectorId, [tool({ toolName: 'alpha' })]);
+ await model.upsertMany(connectorId, [tool({ toolName: 'alpha' })]);
+
+ const ids = [connectorId, secondConnectorId];
+ const expected = [
+ ...['alpha', 'beta', 'zeta'].map((name) => `${connectorId}:${name}`),
+ ...['alpha', 'zeta'].map((name) => `${secondConnectorId}:${name}`),
+ ].sort((a, b) => {
+ const [connA, nameA] = a.split(':');
+ const [connB, nameB] = b.split(':');
+ if (connA !== connB) return connA < connB ? -1 : 1;
+ return nameA < nameB ? -1 : nameA > nameB ? 1 : 0;
+ });
+
+ const firstAll = toolKeys(await model.queryAllByConnectorIds(ids));
+ const firstEnabled = toolKeys(await model.queryByConnectorIds(ids));
+ const firstSingle = (await model.queryByConnector(connectorId)).map((r) => r.toolName);
+ expect(firstAll).toEqual(expected);
+ expect(firstEnabled).toEqual(expected);
+ expect(firstSingle).toEqual(['alpha', 'beta', 'zeta']);
+
+ // a background refresh re-upserts existing rows (ON CONFLICT DO UPDATE writes new tuples)
+ await model.upsertMany(connectorId, [
+ tool({ description: 'refreshed', toolName: 'alpha' }),
+ tool({ description: 'refreshed', toolName: 'zeta' }),
+ ]);
+ await model.upsertMany(secondConnectorId, [
+ tool({ description: 'refreshed', toolName: 'alpha' }),
+ ]);
+
+ expect(toolKeys(await model.queryAllByConnectorIds(ids))).toEqual(firstAll);
+ expect(toolKeys(await model.queryByConnectorIds([secondConnectorId, connectorId]))).toEqual(
+ firstEnabled,
+ );
+ expect((await model.queryByConnector(connectorId)).map((r) => r.toolName)).toEqual(
+ firstSingle,
+ );
+ });
+ });
+
describe('findByToolName', () => {
it('returns the tool matching the name for the current user', async () => {
const model = new ConnectorToolModel(serverDB, userId);
diff --git a/packages/database/src/models/connector.ts b/packages/database/src/models/connector.ts
index 99ab0f5cd7f..f20837e7f1c 100644
--- a/packages/database/src/models/connector.ts
+++ b/packages/database/src/models/connector.ts
@@ -1,4 +1,4 @@
-import { and, eq, inArray, isNotNull, isNull, or, sql } from 'drizzle-orm';
+import { and, asc, eq, inArray, isNotNull, isNull, or, sql } from 'drizzle-orm';
import type { ConnectorCredentials, NewUserConnector, UserConnectorItem } from '../schemas';
import { ConnectorStatus, userConnectors, userConnectorTools } from '../schemas';
@@ -80,6 +80,14 @@ export class ConnectorModel {
*/
private baseScope = () => and(this.ownership(), isNull(userConnectors.agentId));
+ /**
+ * Deterministic connector order for runtime resolution: by identifier, then id
+ * so rows sharing an identifier have a stable tie-break. Resolved connectors
+ * drive the order of the model's tool schema array, so they must not follow
+ * the physical row order, which changes whenever a row is updated.
+ */
+ private resolutionOrder = () => [asc(userConnectors.identifier), asc(userConnectors.id)];
+
private publicSelection = {
agentId: userConnectors.agentId,
avatar: sql<string | null>`${userConnectors.metadata} ->> 'avatar'`,
@@ -304,7 +312,8 @@ export class ConnectorModel {
const rows = await this.db
.select()
.from(userConnectors)
- .where(and(this.baseScope(), inArray(userConnectors.identifier, identifiers)));
+ .where(and(this.baseScope(), inArray(userConnectors.identifier, identifiers)))
+ .orderBy(...this.resolutionOrder());
return Promise.all(rows.map((r) => decryptRow(r, gateKeeper)));
};
@@ -330,7 +339,8 @@ export class ConnectorModel {
const rows = await this.db
.select()
.from(userConnectors)
- .where(and(this.scopePredicate(agentId), inArray(userConnectors.identifier, identifiers)));
+ .where(and(this.scopePredicate(agentId), inArray(userConnectors.identifier, identifiers)))
+ .orderBy(...this.resolutionOrder());
return Promise.all(this.pickByPriority(rows, agentId).map((r) => decryptRow(r, gateKeeper)));
};
@@ -345,7 +355,11 @@ export class ConnectorModel {
agentId?: string,
gateKeeper: GateKeeper | undefined = this.gateKeeper,
): Promise<DecryptedConnector[]> => {
- const rows = await this.db.select().from(userConnectors).where(this.scopePredicate(agentId));
+ const rows = await this.db
+ .select()
+ .from(userConnectors)
+ .where(this.scopePredicate(agentId))
+ .orderBy(...this.resolutionOrder());
return Promise.all(this.pickByPriority(rows, agentId).map((r) => decryptRow(r, gateKeeper)));
};
diff --git a/packages/database/src/models/connectorTool.ts b/packages/database/src/models/connectorTool.ts
index 3e60b8ed0d8..350a493086f 100644
--- a/packages/database/src/models/connectorTool.ts
+++ b/packages/database/src/models/connectorTool.ts
@@ -1,4 +1,4 @@
-import { and, eq, inArray, ne, notInArray, sql } from 'drizzle-orm';
+import { and, asc, eq, inArray, ne, notInArray, sql } from 'drizzle-orm';
import type {
ConnectorToolPermission,
@@ -38,6 +38,17 @@ export class ConnectorToolModel {
private ownership = () =>
buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, userConnectorTools);
+ /**
+ * Deterministic tool order: grouped by connector, sorted by toolName within it.
+ * Tool lists feed the model's tool schema array, so they must not follow the
+ * physical row order, which changes whenever `upsertMany` rewrites a row.
+ * Unstable tool order invalidates provider prompt caches between runs.
+ */
+ private toolOrder = () => [
+ asc(userConnectorTools.userConnectorId),
+ asc(userConnectorTools.toolName),
+ ];
+
findById = async (toolId: string): Promise<UserConnectorToolItem | undefined> => {
const [row] = await this.db
.select()
@@ -125,7 +136,8 @@ export class ConnectorToolModel {
return this.db
.select()
.from(userConnectorTools)
- .where(and(eq(userConnectorTools.userConnectorId, userConnectorId), this.ownership()));
+ .where(and(eq(userConnectorTools.userConnectorId, userConnectorId), this.ownership()))
+ .orderBy(...this.toolOrder());
};
/**
@@ -144,7 +156,8 @@ export class ConnectorToolModel {
inArray(userConnectorTools.userConnectorId, connectorIds),
ne(userConnectorTools.permission, Permission.disabled),
),
- );
+ )
+ .orderBy(...this.toolOrder());
};
/**
@@ -157,7 +170,8 @@ export class ConnectorToolModel {
return this.db
.select()
.from(userConnectorTools)
- .where(and(this.ownership(), inArray(userConnectorTools.userConnectorId, connectorIds)));
+ .where(and(this.ownership(), inArray(userConnectorTools.userConnectorId, connectorIds)))
+ .orderBy(...this.toolOrder());
};
/**