🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
fix(auditlog): patch llmTool and llmSchema records in auditLog (#7826)
Steffen Schmitz6a5f221567b4
diff --git a/packages/shared/prisma/migrations/20250711134738_add_patch_llm_tool_schema_audit_logs_background_migration/migration.sql b/packages/shared/prisma/migrations/20250711134738_add_patch_llm_tool_schema_audit_logs_background_migration/migration.sqlnew file mode 100644index 0000000000..af262cfc7f--- /dev/null+++ b/packages/shared/prisma/migrations/20250711134738_add_patch_llm_tool_schema_audit_logs_background_migration/migration.sql@@ -0,0 +1,2 @@+INSERT INTO background_migrations (id, name, script, args)+VALUES ('3445cac4-d9d5-4750-8b65-351135c1b85e', '20250711_1347_patch_llm_tool_schema_audit_logs', 'patchLLMToolAndLLLMSchemaAuditLogs', '{}');\ No newline at end of filediff --git a/web/src/ee/features/admin-api/server/projects/projectById/index.ts b/web/src/ee/features/admin-api/server/projects/projectById/index.tsindex d792675343..dcc5013bf7 100644--- a/web/src/ee/features/admin-api/server/projects/projectById/index.ts+++ b/web/src/ee/features/admin-api/server/projects/projectById/index.ts@@ -12,6 +12,7 @@ import { projectRetentionSchema } from "@/src/features/auth/lib/projectRetentionimport { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server/hasEntitlement";import { projectNameSchema } from "@/src/features/auth/lib/projectNameSchema";import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";+import { auditLog } from "@/src/features/audit-logs/auditLog";export async function handleUpdateProject(req: NextApiRequest,@@ -119,7 +120,7 @@ export async function handleDeleteProject(});// Mark project as deleted- await prisma.project.update({+ const project = await prisma.project.update({where: {id: projectId,orgId: scope.orgId,@@ -129,6 +130,17 @@ export async function handleDeleteProject(},});+ // Create audit log entry+ await auditLog({+ apiKeyId: scope.apiKeyId,+ orgId: scope.orgId,+ projectId,+ resourceType: "project",+ resourceId: projectId,+ before: project,+ action: "delete",+ });+// Queue project deletion jobconst projectDeleteQueue = ProjectDeleteQueue.getInstance();if (!projectDeleteQueue) {diff --git a/web/src/features/audit-logs/auditLog.ts b/web/src/features/audit-logs/auditLog.tsindex 763f49e062..6670be7a95 100644--- a/web/src/features/audit-logs/auditLog.ts+++ b/web/src/features/audit-logs/auditLog.ts@@ -30,6 +30,8 @@ export type AuditableResource =| "blobStorageIntegration"| "posthogIntegration"| "llmApiKey"+ | "llmTool"+ | "llmSchema"| "batchExport"| "stripeCheckoutSession"| "batchAction"diff --git a/web/src/features/llm-schemas/server/router.ts b/web/src/features/llm-schemas/server/router.tsindex 28960c1071..ffe12ed56b 100644--- a/web/src/features/llm-schemas/server/router.ts+++ b/web/src/features/llm-schemas/server/router.ts@@ -53,7 +53,7 @@ export const llmSchemaRouter = createTRPCRouter({await auditLog({session: ctx.session,- resourceType: "project",+ resourceType: "llmSchema",resourceId: llmSchema.id,action: "create",after: llmSchema,@@ -164,7 +164,7 @@ export const llmSchemaRouter = createTRPCRouter({await auditLog({session: ctx.session,- resourceType: "project",+ resourceType: "llmSchema",resourceId: updatedSchema.id,action: "update",before: existingSchema,@@ -217,7 +217,7 @@ export const llmSchemaRouter = createTRPCRouter({await auditLog({session: ctx.session,- resourceType: "project",+ resourceType: "llmSchema",resourceId: input.id,action: "delete",before: existingSchema,diff --git a/web/src/features/llm-tools/server/router.ts b/web/src/features/llm-tools/server/router.tsindex 87a40a3c95..f211168ace 100644--- a/web/src/features/llm-tools/server/router.ts+++ b/web/src/features/llm-tools/server/router.ts@@ -53,7 +53,7 @@ export const llmToolRouter = createTRPCRouter({await auditLog({session: ctx.session,- resourceType: "project",+ resourceType: "llmTool",resourceId: llmTool.id,action: "create",after: llmTool,@@ -164,7 +164,7 @@ export const llmToolRouter = createTRPCRouter({await auditLog({session: ctx.session,- resourceType: "project",+ resourceType: "llmTool",resourceId: updatedTool.id,action: "update",before: existingTool,@@ -217,7 +217,7 @@ export const llmToolRouter = createTRPCRouter({await auditLog({session: ctx.session,- resourceType: "project",+ resourceType: "llmTool",resourceId: input.id,action: "delete",before: existingTool,diff --git a/web/src/features/projects/server/projectsRouter.ts b/web/src/features/projects/server/projectsRouter.tsindex f08efc5951..ee19cb22c0 100644--- a/web/src/features/projects/server/projectsRouter.ts+++ b/web/src/features/projects/server/projectsRouter.ts@@ -148,24 +148,6 @@ export const projectsRouter = createTRPCRouter({projectId: ctx.session.projectId,scope: "project:delete",});- const beforeProject = await ctx.prisma.project.findUnique({- where: {- id: input.projectId,- },- });- if (!beforeProject) {- throw new TRPCError({- code: "NOT_FOUND",- message: "Project not found",- });- }- await auditLog({- session: ctx.session,- resourceType: "project",- resourceId: input.projectId,- before: beforeProject,- action: "delete",- });// API keys need to be deleted from cache. Otherwise, they will still be valid.await new ApiAuthService(ctx.prisma, redis).invalidateProjectApiKeys(@@ -180,7 +162,7 @@ export const projectsRouter = createTRPCRouter({},});- await ctx.prisma.project.update({+ const project = await ctx.prisma.project.update({where: {id: input.projectId,orgId: ctx.session.orgId,@@ -190,6 +172,14 @@ export const projectsRouter = createTRPCRouter({},});+ await auditLog({+ session: ctx.session,+ resourceType: "project",+ resourceId: input.projectId,+ before: project,+ action: "delete",+ });+const projectDeleteQueue = ProjectDeleteQueue.getInstance();if (!projectDeleteQueue) {throw new TRPCError({diff --git a/worker/src/__tests__/patchLLMToolAndLLLMSchemaAuditLogs.test.ts b/worker/src/__tests__/patchLLMToolAndLLLMSchemaAuditLogs.test.tsnew file mode 100644index 0000000000..27543b3648--- /dev/null+++ b/worker/src/__tests__/patchLLMToolAndLLLMSchemaAuditLogs.test.ts@@ -0,0 +1,275 @@+import { expect, describe, it, beforeEach } from "vitest";+import { v4 as uuidv4 } from "uuid";+import { prisma } from "@langfuse/shared/src/db";+import PatchLLMToolAndLLLMSchemaAuditLogs from "../backgroundMigrations/patchLLMToolAndLLLMSchemaAuditLogs";++describe("PatchLLMToolAndLLLMSchemaAuditLogs", () => {+ let migration: PatchLLMToolAndLLLMSchemaAuditLogs;+ let testOrgId: string;+ let testProjectId: string;++ beforeEach(async () => {+ migration = new PatchLLMToolAndLLLMSchemaAuditLogs();+ testOrgId = uuidv4();+ testProjectId = uuidv4();+ });++ it("should correctly patch various audit log scenarios", async () => {+ // Create test data with different scenarios+ const auditLogs = [+ // 1. Valid llmTool with parameters in before+ {+ id: `aa-${uuidv4()}`,+ orgId: testOrgId,+ projectId: testProjectId,+ resourceType: "project", // Wrong type, should be corrected+ resourceId: uuidv4(), // Different from project ID+ action: "create",+ before: JSON.stringify({+ name: "test-tool",+ parameters: {+ type: "object",+ properties: { input: { type: "string" } },+ },+ description: "Test tool",+ }),+ after: null,+ },+ // 2. Valid llmSchema with schema in after+ {+ id: `ab-${uuidv4()}`,+ orgId: testOrgId,+ projectId: testProjectId,+ resourceType: "project", // Wrong type, should be corrected+ resourceId: uuidv4(), // Different from project ID+ action: "update",+ before: null,+ after: JSON.stringify({+ name: "test-schema",+ schema: {+ type: "object",+ properties: { output: { type: "string" } },+ },+ description: "Test schema",+ }),+ },+ // 3. Valid llmTool with parameters in after (before is null)+ {+ id: `ac-${uuidv4()}`,+ orgId: testOrgId,+ projectId: testProjectId,+ resourceType: "project", // Wrong type, should be corrected+ resourceId: uuidv4(), // Different from project ID+ action: "create",+ before: null,+ after: JSON.stringify({+ name: "tool-after",+ parameters: {+ type: "object",+ properties: { param1: { type: "number" } },+ },+ description: "Tool with parameters in after",+ }),+ },+ // 4. Valid llmSchema with schema in before+ {+ id: `ad-${uuidv4()}`,+ orgId: testOrgId,+ projectId: testProjectId,+ resourceType: "project", // Wrong type, should be corrected+ resourceId: uuidv4(), // Different from project ID+ action: "delete",+ before: JSON.stringify({+ name: "schema-before",+ schema: { type: "array", items: { type: "string" } },+ description: "Schema with schema in before",+ }),+ after: null,+ },+ // 5. Empty parameters+ {+ id: `ae-${uuidv4()}`,+ orgId: testOrgId,+ projectId: testProjectId,+ resourceType: "project", // Wrong type, should remain project+ resourceId: uuidv4(), // Different from project ID+ action: "update",+ before: JSON.stringify({+ name: "empty-params",+ parameters: {},+ description: "Empty parameters",+ }),+ after: null,+ },+ // 6. Empty schema+ {+ id: `af-${uuidv4()}`,+ orgId: testOrgId,+ projectId: testProjectId,+ resourceType: "project", // Wrong type, should remain project+ resourceId: uuidv4(), // Different from project ID+ action: "update",+ before: JSON.stringify({+ name: "empty-schema",+ schema: {},+ description: "Empty schema",+ }),+ after: null,+ },+ // 7. Record with malformed JSON in before+ {+ id: `ah-${uuidv4()}`,+ orgId: testOrgId,+ projectId: testProjectId,+ resourceType: "project", // Wrong type, should remain project due to malformed JSON+ resourceId: uuidv4(), // Different from project ID+ action: "update",+ before: "invalid json {",+ after: null,+ },+ // 8. Record with malformed JSON in after+ {+ id: `ai-${uuidv4()}`,+ orgId: testOrgId,+ projectId: testProjectId,+ resourceType: "project", // Wrong type, should remain project due to malformed JSON+ resourceId: uuidv4(), // Different from project ID+ action: "update",+ before: null,+ after: "invalid json }",+ },+ // 9. Record with correct resource type already (should not be affected)+ {+ id: `aj-${uuidv4()}`,+ orgId: testOrgId,+ projectId: testProjectId,+ resourceType: "llmTool", // Already correct+ resourceId: uuidv4(), // Different from project ID+ action: "update",+ before: JSON.stringify({+ name: "already-correct",+ parameters: {+ type: "object",+ properties: { input: { type: "string" } },+ },+ description: "Already correct resource type",+ }),+ after: null,+ },+ // 10. Record with resourceId matching projectId (should not be affected)+ {+ id: `ak-${uuidv4()}`,+ orgId: testOrgId,+ projectId: testProjectId,+ resourceType: "project",+ resourceId: testProjectId, // Same as project ID+ action: "update",+ before: JSON.stringify({+ name: "matching-ids",+ parameters: {+ type: "object",+ properties: { input: { type: "string" } },+ },+ description: "Resource ID matches project ID",+ }),+ after: null,+ },+ // 11. Record with null/empty before and after+ {+ id: `al-${uuidv4()}`,+ orgId: testOrgId,+ projectId: testProjectId,+ resourceType: "project", // Wrong type, should remain project due to no data+ resourceId: uuidv4(), // Different from project ID+ action: "update",+ before: null,+ after: null,+ },+ ];++ // Insert test audit logs+ await prisma.auditLog.createMany({+ data: auditLogs,+ });++ // Run migration+ await migration.run();++ // Verify results+ const updatedLogs = await prisma.auditLog.findMany({+ where: {+ id: { in: auditLogs.map((log) => log.id) },+ },+ orderBy: { id: "asc" },+ });++ // Check each scenario+ expect(updatedLogs[0].resourceType).toBe("llmTool"); // Has parameters in before+ expect(updatedLogs[1].resourceType).toBe("llmSchema"); // Has schema in after+ expect(updatedLogs[2].resourceType).toBe("llmTool"); // Has parameters in after+ expect(updatedLogs[3].resourceType).toBe("llmSchema"); // Has schema in before+ expect(updatedLogs[4].resourceType).toBe("llmTool"); // Empty parameters+ expect(updatedLogs[5].resourceType).toBe("llmSchema"); // Empty schema+ expect(updatedLogs[6].resourceType).toBe("project"); // Malformed JSON in before+ expect(updatedLogs[7].resourceType).toBe("project"); // Malformed JSON in after+ expect(updatedLogs[8].resourceType).toBe("llmTool"); // Already correct, should not be affected+ expect(updatedLogs[9].resourceType).toBe("project"); // Resource ID matches project ID+ expect(updatedLogs[10].resourceType).toBe("project"); // Null/empty before and after++ // Clean up+ await prisma.auditLog.deleteMany({+ where: {+ id: { in: auditLogs.map((log) => log.id) },+ },+ });+ }, 60_000);++ it("should handle batching correctly for large datasets", async () => {+ // Create more than 1000 audit logs to test batching+ const largeDataset = Array.from({ length: 1250 }, (_, index) => ({+ id: uuidv4(),+ orgId: testOrgId,+ projectId: testProjectId,+ resourceType: "project", // Wrong type, should be corrected+ resourceId: uuidv4(), // Different from project ID+ action: "create",+ before: JSON.stringify({+ name: `test-tool-${index}`,+ parameters: {+ type: "object",+ properties: { input: { type: "string" } },+ },+ description: `Test tool ${index}`,+ }),+ after: null,+ }));++ // Insert test audit logs+ await prisma.auditLog.createMany({+ data: largeDataset,+ });++ // Run migration+ await migration.run();++ // Verify all records were processed+ const updatedLogs = await prisma.auditLog.findMany({+ where: {+ id: { in: largeDataset.map((log) => log.id) },+ },+ });++ // All should be updated to llmTool+ expect(updatedLogs.every((log) => log.resourceType === "llmTool")).toBe(+ true,+ );+ expect(updatedLogs.length).toBe(1250);++ // Clean up+ await prisma.auditLog.deleteMany({+ where: {+ id: { in: largeDataset.map((log) => log.id) },+ },+ });+ }, 60_000);+});diff --git a/worker/src/backgroundMigrations/patchLLMToolAndLLLMSchemaAuditLogs.ts b/worker/src/backgroundMigrations/patchLLMToolAndLLLMSchemaAuditLogs.tsnew file mode 100644index 0000000000..3819f679a9--- /dev/null+++ b/worker/src/backgroundMigrations/patchLLMToolAndLLLMSchemaAuditLogs.ts@@ -0,0 +1,146 @@+/**+ * This script is used to patch the LLMTool and LLMSchemaAuditLogs in the database.+ * Initially, the routers were created with a wrong resource type "project" within their audit logs,+ * instead of using llmTool and llmSchema respectively.+ * This caused inconsistent audit logs with false-positive changes on projects.+ *+ * With this migration, we'll read all audit log records for projects where there is a mismatch+ * between project_id and resource_id and try to infer the correct resource type from the before or after columns.+ */++import { IBackgroundMigration } from "./IBackgroundMigration";+import { logger } from "@langfuse/shared/src/server";+import { prisma } from "@langfuse/shared/src/db";++// This is hard-coded in our migrations and uniquely identifies the row in background_migrations table+const backgroundMigrationId = "3445cac4-d9d5-4750-8b65-351135c1b85e"; // eslint-disable-line no-unused-vars++export default class PatchLLMToolAndLLMSchemaAuditLogs+ implements IBackgroundMigration+{+ private isAborted = false;+ private isFinished = false;++ async validate(): Promise<{+ valid: boolean;+ invalidReason: string | undefined;+ }> {+ return { valid: true, invalidReason: undefined };+ }++ async run(): Promise<void> {+ const start = Date.now();+ logger.info(+ `[Background Migration] Patching audit logs for LLMTool and LLMSchema`,+ );++ const failedInferenceIds = new Set<String>();++ const batchSize = 1000;+ let processedRows = 0;+ while (!this.isAborted && !this.isFinished) {+ // Fetch a batch of audit logs that need to be patched+ const auditLogs = (+ await prisma.auditLog.findMany({+ where: {+ resourceType: "project",+ resourceId: {+ not: {+ equals: prisma.auditLog.fields.projectId,+ },+ },+ },+ take: batchSize,+ })+ ).filter((a) => !failedInferenceIds.has(a.id));++ // Try to infer whether the resource is an LLMTool or LLMToolSchema+ for (const auditLog of auditLogs) {+ try {+ const before = auditLog.before ? JSON.parse(auditLog.before) : {};+ if ("schema" in before) {+ auditLog.resourceType = "llmSchema";+ }+ if ("parameters" in before) {+ auditLog.resourceType = "llmTool";+ }+ } catch (error) {+ logger.warn(+ `[Background Migration] Failed to parse 'before' field for audit log ${auditLog.id}: ${error}`,+ );+ }++ try {+ const after = auditLog.after ? JSON.parse(auditLog.after) : {};+ if ("schema" in after) {+ auditLog.resourceType = "llmSchema";+ }+ if ("parameters" in after) {+ auditLog.resourceType = "llmTool";+ }+ } catch (error) {+ logger.warn(+ `[Background Migration] Failed to parse 'after' field for audit log ${auditLog.id}: ${error}`,+ );+ }+ // If the resourceType is still "project", we cannot infer it+ if (auditLog.resourceType === "project") {+ failedInferenceIds.add(auditLog.id);+ }+ }++ // Update the audit logs in the database+ await Promise.all(+ auditLogs.map((auditLog) =>+ prisma.auditLog.update({+ where: { id: auditLog.id },+ data: {+ resourceType: auditLog.resourceType,+ },+ }),+ ),+ );++ processedRows += auditLogs.length;++ if (auditLogs.length === 0) {+ this.isFinished = true;+ }++ if (this.isAborted) {+ logger.info(+ `[Background Migration] Patching of audit logs for LLMTool and LLMSchema aborted after processing ${processedRows} rows. Skipping cleanup.`,+ );+ return;+ }+ }+ logger.info(+ `[Background Migration] Finished patching of audit logs for LLMTool and LLMSchema in ${Date.now() - start}ms - Rows: ${processedRows}`,+ );+ }++ async abort(): Promise<void> {+ logger.info(+ `[Background Migration] Aborting patching of LLMTool and LLMSchema audit logs`,+ );+ this.isAborted = true;+ }+}++async function main() {+ const migration = new PatchLLMToolAndLLMSchemaAuditLogs();+ await migration.validate();+ await migration.run();+}++// If the script is being executed directly (not imported), run the main function+if (require.main === module) {+ main()+ .then(() => {+ process.exit(0);+ })+ .catch((error) => {+ logger.error(`Migration execution failed: ${error}`, error);+ process.exit(1); // Exit with an error code+ });+}