🪢 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
feat(agent): Add additional DB columns and scoped backfill for background execution (LFE-14370) (#15291)
Lysander Kieseleec7c0a222f5
diff --git a/packages/shared/prisma/migrations/20260722070000_add_in_app_agent_run_lifecycle_fields/migration.sql b/packages/shared/prisma/migrations/20260722070000_add_in_app_agent_run_lifecycle_fields/migration.sqlnew file mode 100644index 0000000000..06fb50d4ff--- /dev/null+++ b/packages/shared/prisma/migrations/20260722070000_add_in_app_agent_run_lifecycle_fields/migration.sql@@ -0,0 +1,30 @@+-- Expand step of an expand/contract rollout (contract lands with the first+-- status reader, which backfills remaining NULLs and sets DEFAULT/NOT NULL —+-- see the add_project_id_to_observations precedent). All columns are nullable+-- so replicas that predate this code keep inserting successfully; a NULL+-- status means "row written by old code".+ALTER TABLE "in_app_agent_runs"+ ADD COLUMN "status" TEXT,+ ADD COLUMN "request" JSONB,+ ADD COLUMN "claimed_at" TIMESTAMP(3),+ ADD COLUMN "heartbeat_at" TIMESTAMP(3),+ ADD COLUMN "cancel_requested_at" TIMESTAMP(3);++-- Close only runs the app itself would already consider stale (>150s,+-- ACTIVE_RUN_STALE_AFTER_MS in web/src/ee/features/in-app-agent/server/persistence.ts).+-- Younger unfinished rows are genuinely running foreground streams and must+-- stay open, or their event flushes and finish would silently no-op.+UPDATE "in_app_agent_runs"+SET "finished_at" = NOW(),+ "error_code" = 'stale',+ "error_message" = 'Run was marked stale before starting a new run'+WHERE "finished_at" IS NULL+ AND "created_at" < NOW() - INTERVAL '150 seconds';++-- Single-active-run backstop for background execution. The app invariant+-- (stale-close before create, under the conversation row lock) already+-- guarantees at most one unfinished run per conversation, so this creates+-- cleanly even with live runs left open.+CREATE UNIQUE INDEX "in_app_agent_runs_active_conversation_key"+ ON "in_app_agent_runs" ("project_id", "conversation_id")+ WHERE "finished_at" IS NULL;diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prismaindex 2b7926ecfb..00985ca964 100644--- a/packages/shared/prisma/schema.prisma+++ b/packages/shared/prisma/schema.prisma@@ -285,11 +285,23 @@ model InAppAgentRun {errorCode String? @map("error_code")errorMessage String? @map("error_message")finishedAt DateTime? @map("finished_at")+ // Nullable until the first status reader ships (see RFC-background-execution+ // PR 4), whose migration backfills NULLs and sets DEFAULT/NOT NULL.+ // NULL means "row written by code that predates the status column".+ status String?+ request Json?+ claimedAt DateTime? @map("claimed_at")+ heartbeatAt DateTime? @map("heartbeat_at")+ cancelRequestedAt DateTime? @map("cancel_requested_at")createdAt DateTime @default(now()) @map("created_at")updatedAt DateTime @default(now()) @updatedAt @map("updated_at")events InAppAgentEvent[]+ // A conversation can have at most one unfinished run, enforced via the+ // partial unique index in_app_agent_runs_active_conversation_key on+ // (project_id, conversation_id) WHERE finished_at IS NULL, added in the+ // migration since Prisma cannot express partial uniqueness in the schema DSL.@@id([id, projectId])@@index([projectId, conversationId, createdAt], map: "in_app_agent_runs_project_conversation_created_idx")@@map("in_app_agent_runs")diff --git a/packages/shared/src/features/inAppAgent/types.ts b/packages/shared/src/features/inAppAgent/types.tsnew file mode 100644index 0000000000..ca753583d3--- /dev/null+++ b/packages/shared/src/features/inAppAgent/types.ts@@ -0,0 +1,38 @@+import z from "zod";++/**+ * Lifecycle states of an in-app agent run (`in_app_agent_runs.status`).+ *+ * Stored as a plain string column (not a PG enum) so states can be added+ * without `ALTER TYPE`, following BatchExportStatus/BatchActionStatus.+ * The column is nullable until the first status reader ships: NULL means+ * the row was written by code that predates the column.+ */+export enum InAppAgentRunStatus {+ QUEUED = "QUEUED",+ RUNNING = "RUNNING",+ AWAITING_APPROVAL = "AWAITING_APPROVAL",+ SUCCEEDED = "SUCCEEDED",+ FAILED = "FAILED",+ CANCELLED = "CANCELLED",+}++export const InAppAgentRunStatusSchema = z.enum(InAppAgentRunStatus);++/**+ * Terminal error codes of an in-app agent run (`in_app_agent_runs.error_code`).+ *+ * Constrains writers at the type level; the column itself stays a free-form+ * string and historical rows may contain other values, so readers must+ * tolerate unknown strings rather than parse against this enum.+ */+export enum InAppAgentRunErrorCode {+ /** Unfinished run lazily closed because its foreground stream died. */+ STALE = "stale",+ /** Client aborted the request. */+ CANCELLED = "cancelled",+ /** Agent loop failed while streaming. */+ AGENT_ERROR = "agent_error",+ /** Agent initialization failed before the loop started. */+ INIT_FAILED = "init_failed",+}diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.tsindex 6b057b6040..77e1c87526 100644--- a/packages/shared/src/index.ts+++ b/packages/shared/src/index.ts@@ -46,6 +46,9 @@ export * from "./features/batchAction/addToDatasetTypes";export * from "./features/batchAction/applyFieldMapping";export { BatchTableNames } from "./interfaces/tableNames";+// in-app agent+export * from "./features/inAppAgent/types";+// annotationexport * from "./features/annotation/types";diff --git a/web/src/__tests__/server/in-app-agent-persistence.servertest.ts b/web/src/__tests__/server/in-app-agent-persistence.servertest.tsindex 38b6b3b012..6f9eabf4b8 100644--- a/web/src/__tests__/server/in-app-agent-persistence.servertest.ts+++ b/web/src/__tests__/server/in-app-agent-persistence.servertest.ts@@ -12,7 +12,7 @@ import { EventType } from "@ag-ui/core";import { randomUUID } from "crypto";import { vi } from "vitest";-import type { Plan } from "@langfuse/shared";+import { InAppAgentRunErrorCode, type Plan } from "@langfuse/shared";import { prisma } from "@langfuse/shared/src/db";import {createOrgProjectAndApiKey,@@ -1369,7 +1369,7 @@ describe("in-app agent persistence", () => {prisma,runId: orphanToolRun.id,projectId,- errorCode: "aborted",+ errorCode: InAppAgentRunErrorCode.CANCELLED,errorMessage: "Aborted before tool result",});@@ -1427,7 +1427,7 @@ describe("in-app agent persistence", () => {prisma,runId: failedRun.id,projectId,- errorCode: "upstream_error",+ errorCode: InAppAgentRunErrorCode.AGENT_ERROR,errorMessage: "Failed before output",});@@ -1567,14 +1567,14 @@ describe("in-app agent persistence", () => {prisma,runId: run.id,projectId,- errorCode: "agent_error",+ errorCode: InAppAgentRunErrorCode.AGENT_ERROR,errorMessage: "Original agent error",});await finishRun({prisma,runId: run.id,projectId,- errorCode: "cancelled",+ errorCode: InAppAgentRunErrorCode.CANCELLED,errorMessage: "Client aborted request",});@@ -1659,6 +1659,34 @@ describe("in-app agent persistence", () => {).rejects.toThrow("Assistant is already responding in this conversation");});+ it("rethrows a replayed run id instead of reporting an active-run conflict", async () => {+ const { projectId, userId } = await createCaller();+ const conversation = await createConversation({ projectId, userId });++ const finished = await createConversationRun({+ projectId,+ conversationId: conversation.id,+ userId,+ });+ await finishRun({ prisma, runId: finished.id, projectId });++ // Replaying the id of a finished run violates the (id, project_id) primary+ // key, not the active-run backstop index — the caller must not be told the+ // assistant is still responding. Asserting on meta.target pins the shape+ // the createRun catch discriminates on.+ await expect(+ createConversationRun({+ projectId,+ conversationId: conversation.id,+ userId,+ runId: finished.id,+ }),+ ).rejects.toMatchObject({+ code: "P2002",+ meta: { target: ["id", "project_id"] },+ });+ });+it("marks old unfinished runs stale before starting a new run", async () => {const { projectId, userId } = await createCaller();const conversation = await createConversation({ projectId, userId });@@ -1684,12 +1712,93 @@ describe("in-app agent persistence", () => {where: { id_projectId: { id: staleRun.id, projectId } },}),).resolves.toMatchObject({+ status: "FAILED",errorCode: "stale",errorMessage: "Run was marked stale before starting a new run",});expect(newRun.finishedAt).toBeNull();});+ it("writes run lifecycle status on the foreground path", async () => {+ const { projectId, userId } = await createCaller();+ const conversation = await createConversation({ projectId, userId });++ const succeeded = await createConversationRun({+ projectId,+ conversationId: conversation.id,+ userId,+ });+ expect(succeeded.status).toBe("RUNNING");+ await finishRun({ prisma, runId: succeeded.id, projectId });++ const failed = await createConversationRun({+ projectId,+ conversationId: conversation.id,+ userId,+ });+ await finishRun({+ prisma,+ runId: failed.id,+ projectId,+ errorCode: InAppAgentRunErrorCode.AGENT_ERROR,+ errorMessage: "boom",+ });++ const cancelled = await createConversationRun({+ projectId,+ conversationId: conversation.id,+ userId,+ });+ await finishRun({+ prisma,+ runId: cancelled.id,+ projectId,+ errorCode: InAppAgentRunErrorCode.CANCELLED,+ errorMessage: "Client aborted request",+ });++ const runs = await prisma.inAppAgentRun.findMany({+ where: { projectId, conversationId: conversation.id },+ select: { id: true, status: true },+ });+ expect(new Map(runs.map((run) => [run.id, run.status]))).toEqual(+ new Map([+ [succeeded.id, "SUCCEEDED"],+ [failed.id, "FAILED"],+ [cancelled.id, "CANCELLED"],+ ]),+ );+ });++ it("enforces the single-active-run backstop index at the database level", async () => {+ const { projectId, userId } = await createCaller();+ const conversation = await createConversation({ projectId, userId });++ await createConversationRun({+ projectId,+ conversationId: conversation.id,+ userId,+ });++ // Bypass createRun's conversation lock and conflict check: the partial+ // unique index is the DB-level invariant against two unfinished runs in+ // one conversation. Asserting on meta.target pins the shape the createRun+ // catch discriminates on (Prisma resolves the raw-SQL index to its+ // column names).+ await expect(+ prisma.inAppAgentRun.create({+ data: {+ id: createInAppAgentRunId(),+ projectId,+ conversationId: conversation.id,+ },+ }),+ ).rejects.toMatchObject({+ code: "P2002",+ meta: { target: ["project_id", "conversation_id"] },+ });+ });+it("paginates conversation list with a stable cursor", async () => {const { caller, projectId, userId } = await createCaller();const idPrefix = `pagination-${randomUUID()}`;diff --git a/web/src/ee/features/in-app-agent/server/handler.ts b/web/src/ee/features/in-app-agent/server/handler.tsindex 338b9c4fe0..3350287bd8 100644--- a/web/src/ee/features/in-app-agent/server/handler.ts+++ b/web/src/ee/features/in-app-agent/server/handler.ts@@ -70,6 +70,7 @@ import {BaseError,ForbiddenError,type FilterState,+ InAppAgentRunErrorCode,InvalidRequestError,LangfuseNotFoundError,type RateLimitResult,@@ -426,7 +427,7 @@ export default async function handler(request: Request) {}const finishCurrentRun = (error?: {- errorCode: string;+ errorCode: InAppAgentRunErrorCode;errorMessage: string;}) =>finishRun({@@ -505,7 +506,7 @@ export default async function handler(request: Request) {.then(() => restorePendingToolApprovalIfRetryable()).finally(() =>finishCurrentRun({- errorCode: "cancelled",+ errorCode: InAppAgentRunErrorCode.CANCELLED,errorMessage: "Client aborted request",}),),@@ -514,7 +515,7 @@ export default async function handler(request: Request) {.then(() => restorePendingToolApprovalIfRetryable()).finally(() =>finishCurrentRun({- errorCode: "agent_error",+ errorCode: InAppAgentRunErrorCode.AGENT_ERROR,errorMessage:error instanceof Error? error.message@@ -615,7 +616,7 @@ export default async function handler(request: Request) {prisma,runId: sanitizedInput.runId,projectId,- errorCode: "init_failed",+ errorCode: InAppAgentRunErrorCode.INIT_FAILED,errorMessage:error instanceof Error? error.messagediff --git a/web/src/ee/features/in-app-agent/server/persistence.ts b/web/src/ee/features/in-app-agent/server/persistence.tsindex 91d7f518b5..cbcdb1a3f2 100644--- a/web/src/ee/features/in-app-agent/server/persistence.ts+++ b/web/src/ee/features/in-app-agent/server/persistence.ts@@ -1,16 +1,21 @@import { compactEvents } from "@ag-ui/client";import { EventType } from "@ag-ui/core";-import { LangfuseConflictError, LangfuseNotFoundError } from "@langfuse/shared";+import {+ InAppAgentRunErrorCode,+ InAppAgentRunStatus,+ LangfuseConflictError,+ LangfuseNotFoundError,+} from "@langfuse/shared";import {ChatMessageRole,ChatMessageType,LangfuseInternalTraceEnvironment,logger,} from "@langfuse/shared/src/server";+import { Prisma } from "@langfuse/shared/src/db";import type {InAppAgentConversation,- Prisma,PrismaClient,} from "@langfuse/shared/src/db";@@ -38,7 +43,6 @@ import { IN_APP_AGENT_SANDBOX_TOOL_NAMES } from "@/src/ee/features/in-app-agent/const ACTIVE_RUN_STALE_AFTER_MS = 150 * 1000;const ACTIVE_RUN_CONFLICT_MESSAGE ="Assistant is already responding in this conversation";-const STALE_RUN_ERROR_CODE = "stale";const STALE_RUN_ERROR_MESSAGE ="Run was marked stale before starting a new run";const SANDBOX_CONVERSATION_WRITE_WINDOW_MS = 8 * 60 * 60 * 1000;@@ -179,8 +183,9 @@ export async function createRun(params: {createdAt: { lt: staleBefore },},data: {+ status: InAppAgentRunStatus.FAILED,finishedAt: now,- errorCode: STALE_RUN_ERROR_CODE,+ errorCode: InAppAgentRunErrorCode.STALE,errorMessage: STALE_RUN_ERROR_MESSAGE,},});@@ -198,16 +203,35 @@ export async function createRun(params: {throw new LangfuseConflictError(ACTIVE_RUN_CONFLICT_MESSAGE);}- return tx.inAppAgentRun.create({- data: {- id: params.runId,- projectId: params.projectId,- conversationId: params.conversationId,- triggeredByUserId: params.triggeredByUserId,- model: params.model,- mcpApiKeyId: params.mcpApiKeyId,- },- });+ try {+ return await tx.inAppAgentRun.create({+ data: {+ id: params.runId,+ projectId: params.projectId,+ conversationId: params.conversationId,+ triggeredByUserId: params.triggeredByUserId,+ model: params.model,+ mcpApiKeyId: params.mcpApiKeyId,+ // The foreground path has no queue/claim step; runs start executing.+ status: InAppAgentRunStatus.RUNNING,+ },+ });+ } catch (error) {+ // Backstop: the partial unique index on active runs. The conversation+ // lock above should make this unreachable; surface it as the same+ // conflict as the primary check instead of a 500. The insert can also+ // violate the (id, project_id) primary key (a replayed runId), so only+ // map the active-run index — Prisma reports it via its column names.+ if (+ error instanceof Prisma.PrismaClientKnownRequestError &&+ error.code === "P2002" &&+ Array.isArray(error.meta?.target) &&+ error.meta.target.includes("conversation_id")+ ) {+ throw new LangfuseConflictError(ACTIVE_RUN_CONFLICT_MESSAGE);+ }+ throw error;+ }});}@@ -215,9 +239,16 @@ export async function finishRun(params: {prisma: PrismaClient;runId: string;projectId: string;- errorCode?: string | null;+ errorCode?: InAppAgentRunErrorCode | null;errorMessage?: string | null;}) {+ const errorCode = params.errorCode ?? null;+ const status =+ errorCode == null+ ? InAppAgentRunStatus.SUCCEEDED+ : errorCode === InAppAgentRunErrorCode.CANCELLED+ ? InAppAgentRunStatus.CANCELLED+ : InAppAgentRunStatus.FAILED;await params.prisma.inAppAgentRun.updateMany({where: {@@ -226,8 +257,9 @@ export async function finishRun(params: {finishedAt: null,},data: {+ status,finishedAt: new Date(),- errorCode: params.errorCode ?? null,+ errorCode,errorMessage: params.errorMessage ?? null,},})