🪢 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(agent): cancel a conversation's run when it is deleted (#15850)
Lysander Kieselee5e0f15fb51
diff --git a/packages/shared/src/in-app-agent/server/persistence.ts b/packages/shared/src/in-app-agent/server/persistence.tsindex 61628e3ad0..ed5d85c0c7 100644--- a/packages/shared/src/in-app-agent/server/persistence.ts+++ b/packages/shared/src/in-app-agent/server/persistence.ts@@ -317,7 +317,7 @@ export async function appendRunEvents(params: {};}): Promise<boolean> {return params.prisma.$transaction(async (tx) => {- await lockConversation(tx, params.projectId, params.conversationId);+ await lockConversationRow(tx, params.projectId, params.conversationId);if (params.finish) {const finished = await tx.inAppAgentRun.updateMany({@@ -1423,23 +1423,38 @@ function stripAssistantRunIds(messages: readonly AgUiMessage[]) {export type InAppAgentTx = Prisma.TransactionClient;-/**- * Serializes every run-creating and approval-consuming mutation on one row.- * The partial unique index on active runs is only the backstop; this lock is- * what turns a race into a clean conflict error instead of a 500.- */+/** Serialize run mutations and reject conversations deleted while waiting. */export async function lockConversation(tx: InAppAgentTx,projectId: string,conversationId: string,) {- await tx.$queryRaw`- SELECT 1+ const conversation = await lockConversationRow(tx, projectId, conversationId);++ if (conversation.deletedAt) {+ throw new LangfuseNotFoundError("Agent conversation not found");+ }+}++async function lockConversationRow(+ tx: InAppAgentTx,+ projectId: string,+ conversationId: string,+) {+ const conversations = await tx.$queryRaw<Array<{ deletedAt: Date | null }>>`+ SELECT "deleted_at" AS "deletedAt"FROM "in_app_agent_conversations"WHERE "id" = ${conversationId}AND "project_id" = ${projectId}FOR UPDATE`;++ const conversation = conversations[0];+ if (!conversation) {+ throw new LangfuseNotFoundError("Agent conversation not found");+ }++ return conversation;}function parseMessages(messages: unknown[]): AgUiMessage[] {diff --git a/packages/shared/src/in-app-agent/server/runLifecycle.test.ts b/packages/shared/src/in-app-agent/server/runLifecycle.test.tsindex 037269cd11..7e2266a42a 100644--- a/packages/shared/src/in-app-agent/server/runLifecycle.test.ts+++ b/packages/shared/src/in-app-agent/server/runLifecycle.test.ts@@ -1,19 +1,62 @@+import { EventType } from "@ag-ui/core";import { describe, expect, it, vi } from "vitest";import { InAppAgentRunStatus } from "../../index";import type { PrismaClient } from "../../db";import {+ createQueuedRun,reconcileConversationRuns,requestRunCancellation,} from "./runLifecycle";describe("in-app agent run lifecycle races", () => {+ it("does not admit a run after the conversation is deleted", async () => {+ const tx = {+ $queryRaw: vi.fn().mockResolvedValue([{ deletedAt: new Date() }]),+ inAppAgentRun: {+ findMany: vi.fn().mockResolvedValue([]),+ updateMany: vi.fn().mockResolvedValue({ count: 0 }),+ findFirst: vi.fn().mockResolvedValue(null),+ create: vi.fn().mockResolvedValue({ id: "run-1" }),+ },+ inAppAgentEvent: {+ findFirst: vi.fn().mockResolvedValue(null),+ create: vi.fn().mockResolvedValue({}),+ },+ inAppAgentConversation: {+ update: vi.fn().mockResolvedValue({}),+ },+ };+ const prisma = {+ $transaction: async (callback: (transaction: typeof tx) => unknown) =>+ callback(tx),+ } as unknown as PrismaClient;++ await expect(+ createQueuedRun({+ prisma,+ runId: "run-1",+ projectId: "project-1",+ conversationId: "conversation-1",+ triggeredByUserId: "user-1",+ model: "test-model",+ request: { kind: "userMessage", context: [] },+ runStartedEvent: {+ type: EventType.RUN_STARTED,+ threadId: "conversation-1",+ runId: "run-1",+ },+ }),+ ).rejects.toThrow("Agent conversation not found");+ expect(tx.inAppAgentRun.create).not.toHaveBeenCalled();+ });+it("preserves cancellation when a worker claims the queued run concurrently", async () => {let status: InAppAgentRunStatus = InAppAgentRunStatus.QUEUED;let cancelRequestedAt: Date | null = null;const tx = {- $queryRaw: vi.fn().mockResolvedValue([]),+ $queryRaw: vi.fn().mockResolvedValue([{ deletedAt: null }]),inAppAgentRun: {findFirst: vi.fn(async () => ({ status })),updateMany: vi.fn(diff --git a/packages/shared/src/in-app-agent/server/runLifecycle.ts b/packages/shared/src/in-app-agent/server/runLifecycle.tsindex fd189f8d3c..0860474110 100644--- a/packages/shared/src/in-app-agent/server/runLifecycle.ts+++ b/packages/shared/src/in-app-agent/server/runLifecycle.ts@@ -311,6 +311,52 @@ export type CancelRunResult = {status: InAppAgentRunStatus | null;};+/** Cancel every run that is executing or waiting on user approval. */+export async function cancelConversationRunsInTransaction(params: {+ tx: InAppAgentTx;+ projectId: string;+ conversationId: string;+}): Promise<string[]> {+ await lockConversation(params.tx, params.projectId, params.conversationId);++ const runs = await params.tx.inAppAgentRun.findMany({+ where: {+ projectId: params.projectId,+ conversationId: params.conversationId,+ // Parked approvals have finishedAt set but remain unsettled.+ status: {+ in: [+ InAppAgentRunStatus.QUEUED,+ InAppAgentRunStatus.RUNNING,+ InAppAgentRunStatus.AWAITING_APPROVAL,+ ],+ },+ },+ select: { id: true, status: true },+ });++ const cancelledImmediately: string[] = [];++ for (const run of runs) {+ const parsedStatus = InAppAgentRunStatusSchema.safeParse(run.status);+ if (!parsedStatus.success) {+ continue;+ }++ const result = await cancelRunInTransaction({+ ...params,+ runId: run.id,+ runStatus: parsedStatus.data,+ });++ if (result.cancelledImmediately) {+ cancelledImmediately.push(run.id);+ }+ }++ return cancelledImmediately;+}+/** Cancel idle states immediately; signal RUNNING workers cooperatively. */export async function requestRunCancellation(params: {prisma: PrismaClient;@@ -334,85 +380,99 @@ export async function requestRunCancellation(params: {if (!parsedStatus.success) {return { cancelledImmediately: false, status: null };}- const runStatus = parsedStatus.data;- const immediateCancel =- runStatus === InAppAgentRunStatus.QUEUED+ return cancelRunInTransaction({+ tx,+ projectId: params.projectId,+ conversationId: params.conversationId,+ runId: params.runId,+ runStatus: parsedStatus.data,+ });+ });+}++async function cancelRunInTransaction(params: {+ tx: InAppAgentTx;+ projectId: string;+ conversationId: string;+ runId: string;+ runStatus: InAppAgentRunStatus;+}): Promise<CancelRunResult> {+ const immediateCancel =+ params.runStatus === InAppAgentRunStatus.QUEUED+ ? {+ errorCode: InAppAgentRunErrorCode.CANCELLED,+ errorMessage: "Cancelled before a worker picked the run up",+ }+ : params.runStatus === InAppAgentRunStatus.AWAITING_APPROVAL? {- errorCode: InAppAgentRunErrorCode.CANCELLED,- errorMessage: "Cancelled before a worker picked the run up",+ errorCode: InAppAgentRunErrorCode.APPROVAL_CANCELLED,+ errorMessage: "Approval cancelled",}- : runStatus === InAppAgentRunStatus.AWAITING_APPROVAL- ? {- errorCode: InAppAgentRunErrorCode.APPROVAL_CANCELLED,- errorMessage: "Approval cancelled",- }- : null;-- if (immediateCancel) {- const { count } = await tx.inAppAgentRun.updateMany({- where: {- id: params.runId,- projectId: params.projectId,- status: runStatus,- },- data: {- status: InAppAgentRunStatus.CANCELLED,- finishedAt: new Date(),- cancelRequestedAt: new Date(),- ...immediateCancel,- },- });+ : null;- if (count > 0) {- return {- cancelledImmediately: true,- status: InAppAgentRunStatus.CANCELLED,- };- }- } else if (runStatus !== InAppAgentRunStatus.RUNNING) {- return {- cancelledImmediately: false,- status: runStatus,- };- }-- // A worker can claim QUEUED between the read and immediate-cancel CAS.- // Signal the newly RUNNING worker instead of losing that cancel request.- const signalled = await tx.inAppAgentRun.updateMany({+ if (immediateCancel) {+ const { count } = await params.tx.inAppAgentRun.updateMany({where: {id: params.runId,projectId: params.projectId,- status: InAppAgentRunStatus.RUNNING,+ status: params.runStatus,+ },+ data: {+ status: InAppAgentRunStatus.CANCELLED,+ finishedAt: new Date(),+ cancelRequestedAt: new Date(),+ ...immediateCancel,},- data: { cancelRequestedAt: new Date() },});- if (signalled.count > 0) {+ if (count > 0) {return {- cancelledImmediately: false,- status: InAppAgentRunStatus.RUNNING,+ cancelledImmediately: true,+ status: InAppAgentRunStatus.CANCELLED,};}+ } else if (params.runStatus !== InAppAgentRunStatus.RUNNING) {+ return {+ cancelledImmediately: false,+ status: params.runStatus,+ };+ }- const current = await tx.inAppAgentRun.findFirst({- where: {- id: params.runId,- projectId: params.projectId,- conversationId: params.conversationId,- },- select: { status: true },- });-- const parsedCurrentStatus = InAppAgentRunStatusSchema.safeParse(- current?.status,- );+ // Preserve cancellation when a worker claims QUEUED between the read and CAS.+ const signalled = await params.tx.inAppAgentRun.updateMany({+ where: {+ id: params.runId,+ projectId: params.projectId,+ status: InAppAgentRunStatus.RUNNING,+ },+ data: { cancelRequestedAt: new Date() },+ });+ if (signalled.count > 0) {return {cancelledImmediately: false,- status: parsedCurrentStatus.success ? parsedCurrentStatus.data : null,+ status: InAppAgentRunStatus.RUNNING,};+ }++ const current = await params.tx.inAppAgentRun.findFirst({+ where: {+ id: params.runId,+ projectId: params.projectId,+ conversationId: params.conversationId,+ },+ select: { status: true },});++ const parsedCurrentStatus = InAppAgentRunStatusSchema.safeParse(+ current?.status,+ );++ return {+ cancelledImmediately: false,+ status: parsedCurrentStatus.success ? parsedCurrentStatus.data : null,+ };}export type ReconciledRun = {diff --git a/web/src/__tests__/server/in-app-agent-background-run.servertest.ts b/web/src/__tests__/server/in-app-agent-background-run.servertest.tsindex ed5cb45988..c73b645da1 100644--- a/web/src/__tests__/server/in-app-agent-background-run.servertest.ts+++ b/web/src/__tests__/server/in-app-agent-background-run.servertest.ts@@ -883,6 +883,60 @@ describe("in-app agent background runs", () => {});});+ it("deletes a conversation while cancelling its unsettled run", async () => {+ const { caller, projectId, userId } = await createCaller();+ const runningConversation = await createConversation({ projectId, userId });+ const parkedConversation = await createConversation({ projectId, userId });++ const runningRun = await prisma.inAppAgentRun.create({+ data: {+ id: createInAppAgentRunId(),+ projectId,+ conversationId: runningConversation.id,+ triggeredByUserId: userId,+ status: InAppAgentRunStatus.RUNNING,+ claimedAt: new Date(),+ heartbeatAt: new Date(),+ },+ });+ // Parked approvals have finishedAt set but still require cancellation.+ const parkedRunId = await parkRunForApproval({+ projectId,+ conversationId: parkedConversation.id,+ userId,+ toolCallId: "tool-call-delete",+ });++ for (const conversationId of [+ runningConversation.id,+ parkedConversation.id,+ ]) {+ await caller.deleteConversation({ projectId, conversationId });+ await expect(+ prisma.inAppAgentConversation.findFirstOrThrow({+ where: { id: conversationId, projectId },+ }),+ ).resolves.toMatchObject({ deletedAt: expect.any(Date) });+ }++ await expect(+ prisma.inAppAgentRun.findFirstOrThrow({+ where: { id: parkedRunId, projectId },+ }),+ ).resolves.toMatchObject({+ status: InAppAgentRunStatus.CANCELLED,+ errorCode: InAppAgentRunErrorCode.APPROVAL_CANCELLED,+ });+ await expect(+ prisma.inAppAgentRun.findFirstOrThrow({+ where: { id: runningRun.id, projectId },+ }),+ ).resolves.toMatchObject({+ status: InAppAgentRunStatus.RUNNING,+ cancelRequestedAt: expect.any(Date),+ });+ });+it("stops surfacing an approval that a newer message superseded", async () => {const { caller, projectId, userId } = await createCaller();const conversation = await createConversation({ projectId, userId });diff --git a/web/src/features/in-app-agent/server/backgroundRunService.ts b/web/src/features/in-app-agent/server/backgroundRunService.tsindex 7ecb55f271..144a5e35ee 100644--- a/web/src/features/in-app-agent/server/backgroundRunService.ts+++ b/web/src/features/in-app-agent/server/backgroundRunService.ts@@ -33,6 +33,7 @@ import {type PersistedConversationEvent,} from "@langfuse/shared/in-app-agent/server/persistence";import {+ cancelConversationRunsInTransaction,cleanupTerminalRunMcpApiKeys,createQueuedRun,decideToolApproval,@@ -260,6 +261,49 @@ export async function startBackgroundRun(params: {return { runId: run.id };}+/** Soft-delete a conversation and cancel its unsettled runs atomically. */+export async function deleteBackgroundConversation(params: {+ prisma: PrismaClient;+ projectId: string;+ conversationId: string;+ userId: string;+}) {+ await getOwnedConversationOrThrow({+ prisma: params.prisma,+ projectId: params.projectId,+ conversationId: params.conversationId,+ userId: params.userId,+ });++ const cancelledRunIds = await params.prisma.$transaction(async (tx) => {+ const cancelledImmediately = await cancelConversationRunsInTransaction({+ tx,+ projectId: params.projectId,+ conversationId: params.conversationId,+ });++ await tx.inAppAgentConversation.update({+ where: {+ id_projectId: {+ id: params.conversationId,+ projectId: params.projectId,+ },+ },+ data: {+ providerSessionId: null,+ deletedAt: new Date(),+ },+ });++ return cancelledImmediately;+ });++ // Avoid spending a worker slot on jobs whose runs are already cancelled.+ await Promise.all(cancelledRunIds.map(removeInAppAgentRunJob));++ return { success: true };+}+export async function cancelBackgroundRun(params: {prisma: PrismaClient;projectId: string;diff --git a/web/src/features/in-app-agent/server/router.ts b/web/src/features/in-app-agent/server/router.tsindex af20dccf78..cd420cda39 100644--- a/web/src/features/in-app-agent/server/router.ts+++ b/web/src/features/in-app-agent/server/router.ts@@ -37,6 +37,7 @@ import { assertInAppAgentRunCapacity } from "@/src/features/in-app-agent/server/import {cancelBackgroundRun,decideBackgroundApproval,+ deleteBackgroundConversation,getBackgroundConversationSnapshot,startBackgroundRun,} from "@/src/features/in-app-agent/server/backgroundRunService";@@ -283,27 +284,12 @@ export const inAppAgentRouter = createTRPCRouter({user: ctx.session.user,});- await getOwnedConversationOrThrow({+ return deleteBackgroundConversation({prisma: ctx.prisma,projectId: input.projectId,conversationId: input.conversationId,userId: ctx.session.user.id,});-- await ctx.prisma.inAppAgentConversation.update({- where: {- id_projectId: {- id: input.conversationId,- projectId: input.projectId,- },- },- data: {- providerSessionId: null,- deletedAt: new Date(),- },- });-- return { success: true };}),renameConversation: protectedProjectProcedureWithoutTracingdiff --git a/worker/src/features/in-app-agent/executeInAppAgentRun.test.ts b/worker/src/features/in-app-agent/executeInAppAgentRun.test.tsindex 77a1a93807..3e2f69ec57 100644--- a/worker/src/features/in-app-agent/executeInAppAgentRun.test.ts+++ b/worker/src/features/in-app-agent/executeInAppAgentRun.test.ts@@ -401,6 +401,39 @@ describe("executeInAppAgentRun", () => {expect(await getInAppAgentApiKeys(projectId)).toHaveLength(0);});+ it("finishes cancellation after its conversation is soft-deleted", async () => {+ const { projectId, conversation, run } = await seedBackgroundRun();++ scenarioRef.current = async ({ signal, options }) => {+ await prisma.$transaction([+ prisma.inAppAgentRun.update({+ where: { id_projectId: { id: run.id, projectId } },+ data: { cancelRequestedAt: new Date() },+ }),+ prisma.inAppAgentConversation.update({+ where: { id_projectId: { id: conversation.id, projectId } },+ data: { deletedAt: new Date() },+ }),+ ]);+ await new Promise<void>((resolve) => {+ if (signal.aborted) return resolve();+ signal.addEventListener("abort", () => resolve(), { once: true });+ });+ await options.onAbort();+ await options.onFinish();+ };++ await expect(+ executeInAppAgentRun({ projectId, runId: run.id }),+ ).resolves.toBeUndefined();++ const cancelled = await getRun(projectId, run.id);+ expect(cancelled.status).toBe("CANCELLED");+ expect(cancelled.finishedAt).not.toBeNull();+ expect(cancelled.errorCode).toBe("cancelled");+ expect(await getInAppAgentApiKeys(projectId)).toHaveLength(0);+ });+it("stops writing when fenced: an externally reconciled run keeps its recorded outcome", async () => {const { projectId, run } = await seedBackgroundRun();