The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
perf(tools): narrow profile and attention catalog reads (#16761)
Devin Foley5dced3c766a0
diff --git a/doc/DATABASE.md b/doc/DATABASE.mdindex f02dd88d87..c0ce8f04e5 100644--- a/doc/DATABASE.md+++ b/doc/DATABASE.md@@ -301,6 +301,18 @@ completed lookups and the separate liveness backfill are not replayed. Projectiocallers that use a transaction retain single-attempt reads. The opt-in is onlyfor a pooled database handle outside a transaction.+## Tool profile reads++Tool profile list, detail, and new-tool review queries select only the catalog+identity, selector, and review fields that they use. They do not load tool input+or output schemas, annotations, or provider metadata. Application and connection+lookups for these paths read only IDs and display names. Profile entries,+bindings, counts, review descriptions, and company filters retain their existing+behavior. The full catalog and tool execution paths still read their schemas.+Attention counts use the same catalog projection and read only invocation IDs+and connection IDs to associate pending requests. Summary queries also omit+review titles and descriptions; the separate review query still returns them.+## Execution identity row locksIdentity initialization, credential acquisition, and steering reconciliation lockdiff --git a/server/src/__tests__/tool-profile-entry-validation.test.ts b/server/src/__tests__/tool-profile-entry-validation.test.tsindex 158f0ad776..5da5b0cf8c 100644--- a/server/src/__tests__/tool-profile-entry-validation.test.ts+++ b/server/src/__tests__/tool-profile-entry-validation.test.ts@@ -5,6 +5,7 @@ import type { CreateToolProfileEntryForProfile } from "@paperclipai/shared";import { eq } from "drizzle-orm";import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";import { toolAccessService } from "../services/tool-access.js";+import { recordingDb } from "./helpers/tool-gateway-listing-fixture.js";const support = await getEmbeddedPostgresTestSupport();const describeDatabase = support.supported ? describe : describe.skip;@@ -62,6 +63,78 @@ describeDatabase("tool profile entry validation", () => {return { service: toolAccessService(counted), reads: () => selects };}+ it("keeps profile summaries and new-tool reviews complete without large schemas or connection config", async () => {+ const own = await fixture(3);+ const foreign = await fixture(1);+ const service = toolAccessService(db);+ const profile = await service.createProfile(own.company.id, {+ profileKey: `summary-${randomUUID()}`, name: "Summary profile", defaultAction: "deny",+ entries: [own.entries[0]],+ });+ // Exact selectors establish connection scope for subsequent tools. Future+ // first-seen stamps make the review independent of wall-clock timing.+ await db.update(toolCatalogEntries).set({+ firstSeenAt: new Date("2099-01-01T00:00:00Z"),+ title: "New tool", description: "Review description",+ inputSchema: { description: "large schema ".repeat(10_000) },+ outputSchema: { description: "large output ".repeat(10_000) },+ }).where(eq(toolCatalogEntries.companyId, own.company.id));+ await db.update(toolConnections).set({ config: { notes: "connection data ".repeat(10_000) } })+ .where(eq(toolConnections.id, own.connection.id));+ const recorded = recordingDb(db);+ const narrowed = toolAccessService(recorded.db);+ const [listed] = await narrowed.listProfiles(own.company.id);+ expect(listed).toMatchObject({ id: profile.id, newToolsPendingCount: 2,+ summary: { allowedToolCount: 1, totalToolCount: 3 },+ entries: [expect.objectContaining({ catalogEntryId: own.catalog[0].id })] });+ expect(await narrowed.getProfile(profile.id, own.company.id)).toEqual(listed);+ const review = await narrowed.listProfileNewTools(profile.id, own.company.id);+ expect(review.tools).toHaveLength(2);+ expect(review.tools).toEqual(expect.arrayContaining(own.catalog.slice(1).map(entry => expect.objectContaining({+ catalogEntryId: entry.id, applicationName: own.application.name, connectionName: own.connection.name,+ title: "New tool", description: "Review description", riskLevel: "read",+ }))));+ expect(JSON.stringify(review)).not.toContain(foreign.catalog[0].id);+ for (const query of recorded.statements.filter(q => q.includes('from "tool_catalog_entries"'))) {+ expect(query).not.toMatch(/"(?:input_schema|output_schema|metadata|annotations)"/);+ expect(query).toContain('"tool_catalog_entries"."company_id"');+ }+ for (const query of recorded.statements.filter(q => q.includes('from "tool_connections"'))) {+ expect(query).not.toMatch(/"(?:config|transport_config|credential_secret_refs|credential_refs)"/);+ }+ await db.update(toolCatalogEntries).set({ status: "quarantined" })+ .where(eq(toolCatalogEntries.id, own.catalog[2].id));+ const attentionReads = recordingDb(db);+ const attention = await toolAccessService(attentionReads.db).listAppsNeedingAttention(own.company.id);+ expect(attention.totals).toMatchObject({ quarantinedCatalogEntries: 1, newToolsPendingReview: 1 });+ expect(attention.apps[0]).toMatchObject({ connection: { id: own.connection.id },+ newToolsPendingProfiles: [{ profileId: profile.id, profileName: profile.name, pendingCount: 1 }] });+ for (const query of attentionReads.statements.filter(q => q.includes('from "tool_catalog_entries"'))) {+ expect(query).not.toMatch(/"(?:input_schema|output_schema|metadata|annotations|description)"/);+ }+ });++ it("keeps schema payload growth out of repeated profile summary reads", async () => {+ const own = await fixture(50);+ await toolAccessService(db).createProfile(own.company.id, {+ profileKey: `payload-${randomUUID()}`, name: "Payload profile", entries: own.entries,+ });+ const recorded = recordingDb(db);+ const service = toolAccessService(recorded.db);+ const before = await service.listProfiles(own.company.id);+ const index = recorded.statements.findIndex(query => query.includes('from "tool_catalog_entries"'));+ expect(index).toBeGreaterThanOrEqual(0);+ const query = recorded.statements[index];+ const params = recorded.statementParams[index];+ const bytesBefore = Buffer.byteLength(JSON.stringify(await db.$client.unsafe(query, params as never[])));+ await db.update(toolCatalogEntries).set({ inputSchema: { text: "schema data ".repeat(20_000) } })+ .where(eq(toolCatalogEntries.companyId, own.company.id));+ expect(await service.listProfiles(own.company.id)).toEqual(before);+ const bytesAfter = Buffer.byteLength(JSON.stringify(await db.$client.unsafe(query, params as never[])));+ expect(bytesAfter).toBe(bytesBefore);+ expect(bytesAfter).toBeLessThan(50_000);+ });+it("creates all 518 exact selectors without per-entry database reads", async () => {const { company, entries } = await fixture(518);const { service, reads } = countedService();diff --git a/server/src/services/tool-access.ts b/server/src/services/tool-access.tsindex 8ef80f0cf5..4643c43d83 100644--- a/server/src/services/tool-access.ts+++ b/server/src/services/tool-access.ts@@ -2069,9 +2069,30 @@ function toPolicy(row: typeof toolPolicies.$inferSelect): ToolPolicy {};}+// Profile summaries and new-tool counts never read schemas, annotations, or+// provider metadata. Keep those large fields out of these repeated reads.+const profileCatalogColumns = {+ id: toolCatalogEntries.id,+ applicationId: toolCatalogEntries.applicationId,+ connectionId: toolCatalogEntries.connectionId,+ toolName: toolCatalogEntries.toolName,+ riskLevel: toolCatalogEntries.riskLevel,+ status: toolCatalogEntries.status,+ firstSeenAt: toolCatalogEntries.firstSeenAt,+};+const profileReviewCatalogColumns = {+ ...profileCatalogColumns,+ title: toolCatalogEntries.title,+ description: toolCatalogEntries.description,+};+type ProfileCatalogEntry = Pick<typeof toolCatalogEntries.$inferSelect, keyof typeof profileCatalogColumns>+ & Partial<Pick<typeof toolCatalogEntries.$inferSelect, "title" | "description">>;+type ProfileApplication = Pick<typeof toolApplications.$inferSelect, "id" | "name">;+type ProfileConnection = Pick<typeof toolConnections.$inferSelect, "id" | "name">;+function profileEntryMatchesCatalog(entry: typeof toolProfileEntries.$inferSelect,- catalogEntry: typeof toolCatalogEntries.$inferSelect,+ catalogEntry: ProfileCatalogEntry,): boolean {if (entry.selectorType === "application")return entry.applicationId === catalogEntry.applicationId;@@ -2090,7 +2111,7 @@ function summarizeProfile(input: {profile: typeof toolProfiles.$inferSelect;entries: Array<typeof toolProfileEntries.$inferSelect>;bindings: Array<typeof toolProfileBindings.$inferSelect>;- catalog: Array<typeof toolCatalogEntries.$inferSelect>;+ catalog: ProfileCatalogEntry[];agentIds: string[];}): ToolProfileSummary {const includes = input.entries.filter((entry) => entry.effect === "include");@@ -2150,8 +2171,8 @@ function summarizeProfile(input: {function profileCoversCatalogScope(input: {entry: typeof toolProfileEntries.$inferSelect;- catalogEntry: typeof toolCatalogEntries.$inferSelect;- catalogById: Map<string, typeof toolCatalogEntries.$inferSelect>;+ catalogEntry: ProfileCatalogEntry;+ catalogById: Map<string, ProfileCatalogEntry>;}): boolean {if (input.entry.effect !== "include") return false;if (input.entry.selectorType === "application")@@ -2175,9 +2196,9 @@ function profileCoversCatalogScope(input: {function pendingNewToolsForProfile(input: {profile: typeof toolProfiles.$inferSelect;entries: Array<typeof toolProfileEntries.$inferSelect>;- catalog: Array<typeof toolCatalogEntries.$inferSelect>;- applicationsById?: Map<string, typeof toolApplications.$inferSelect>;- connectionsById?: Map<string, typeof toolConnections.$inferSelect>;+ catalog: ProfileCatalogEntry[];+ applicationsById?: Map<string, ProfileApplication>;+ connectionsById?: Map<string, ProfileConnection>;}): ToolProfileNewToolReviewItem[] {if (input.profile.status !== "active" ||@@ -2224,8 +2245,8 @@ function pendingNewToolsForProfile(input: {connectionName:input.connectionsById?.get(catalogEntry.connectionId)?.name ?? null,toolName: catalogEntry.toolName,- title: catalogEntry.title,- description: catalogEntry.description,+ title: catalogEntry.title ?? null,+ description: catalogEntry.description ?? null,capability: catalogEntry.riskLevel,riskLevel: catalogEntry.riskLevel,addedAt: catalogEntry.firstSeenAt,@@ -2237,10 +2258,10 @@ function buildProfileDetails(input: {profile: typeof toolProfiles.$inferSelect;entries: Array<typeof toolProfileEntries.$inferSelect>;bindings: Array<typeof toolProfileBindings.$inferSelect>;- catalog: Array<typeof toolCatalogEntries.$inferSelect>;+ catalog: ProfileCatalogEntry[];agentIds: string[];- applicationsById?: Map<string, typeof toolApplications.$inferSelect>;- connectionsById?: Map<string, typeof toolConnections.$inferSelect>;+ applicationsById?: Map<string, ProfileApplication>;+ connectionsById?: Map<string, ProfileConnection>;}): ToolProfileWithDetails {const pendingNewTools = pendingNewToolsForProfile({profile: input.profile,@@ -6078,7 +6099,7 @@ export function toolAccessService(asc(toolProfileBindings.createdAt),),dbClient- .select()+ .select(profileCatalogColumns).from(toolCatalogEntries).where(and(@@ -6091,11 +6112,11 @@ export function toolAccessService(.from(agents).where(eq(agents.companyId, profile.companyId)),dbClient- .select()+ .select({ id: toolApplications.id, name: toolApplications.name }).from(toolApplications).where(eq(toolApplications.companyId, profile.companyId)),dbClient- .select()+ .select({ id: toolConnections.id, name: toolConnections.name }).from(toolConnections).where(eq(toolConnections.companyId, profile.companyId)),]);@@ -6131,7 +6152,7 @@ export function toolAccessService().orderBy(asc(toolProfileEntries.createdAt)),db- .select()+ .select(profileReviewCatalogColumns).from(toolCatalogEntries).where(and(@@ -6141,11 +6162,11 @@ export function toolAccessService().orderBy(asc(toolCatalogEntries.toolName)),db- .select()+ .select({ id: toolApplications.id, name: toolApplications.name }).from(toolApplications).where(eq(toolApplications.companyId, profile.companyId)),db- .select()+ .select({ id: toolConnections.id, name: toolConnections.name }).from(toolConnections).where(eq(toolConnections.companyId, profile.companyId)),]);@@ -8033,7 +8054,7 @@ export function toolAccessService(),),db- .select()+ .select({ connectionId: toolCatalogEntries.connectionId }).from(toolCatalogEntries).where(and(@@ -8042,7 +8063,7 @@ export function toolAccessService(),),db- .select()+ .select({ invocationId: toolActionRequests.invocationId }).from(toolActionRequests).where(and(@@ -8052,7 +8073,7 @@ export function toolAccessService(),),db- .select()+ .select({ id: toolInvocations.id, connectionId: toolInvocations.connectionId }).from(toolInvocations).where(eq(toolInvocations.companyId, companyId)),db@@ -8064,7 +8085,7 @@ export function toolAccessService(.from(toolProfileEntries).where(eq(toolProfileEntries.companyId, companyId)),db- .select()+ .select(profileCatalogColumns).from(toolCatalogEntries).where(and(@@ -19585,7 +19606,7 @@ export function toolAccessService(asc(toolProfileBindings.createdAt),),db- .select()+ .select(profileCatalogColumns).from(toolCatalogEntries).where(and(@@ -19598,11 +19619,11 @@ export function toolAccessService(.from(agents).where(eq(agents.companyId, companyId)),db- .select()+ .select({ id: toolApplications.id, name: toolApplications.name }).from(toolApplications).where(eq(toolApplications.companyId, companyId)),db- .select()+ .select({ id: toolConnections.id, name: toolConnections.name }).from(toolConnections).where(eq(toolConnections.companyId, companyId)),]);