Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(in-app-agent): ack terminal runs instead of parking them in the DLQ (#16304)

Lysander Kiesel3f75394c3734
diff --git a/worker/src/features/in-app-agent/executeInAppAgentRun.test.ts b/worker/src/features/in-app-agent/executeInAppAgentRun.test.ts
index ea23fab6f2..d1f29fe963 100644
--- a/worker/src/features/in-app-agent/executeInAppAgentRun.test.ts
+++ b/worker/src/features/in-app-agent/executeInAppAgentRun.test.ts
@@ -62,11 +62,26 @@ type AgentScenario = (ctx: {
const scenarioRef = vi.hoisted(() => ({
current: undefined as AgentScenario | undefined,
failApiKeyDelete: false,
+ failFinishClaimedRun: false,
apiKeyDeleteCalls: 0,
titleInferenceCalls: 0,
instanceEnabled: true,
}));
+const observabilityRef = vi.hoisted(() => ({
+ traceException: vi.fn(),
+}));
+
+vi.mock("@langfuse/shared/src/server", async (importOriginal) => {
+ const actual =
+ await importOriginal<typeof import("@langfuse/shared/src/server")>();
+ return {
+ ...actual,
+ traceException: (...args: unknown[]) =>
+ observabilityRef.traceException(...args),
+ };
+});
+
vi.mock("./runtime/agent", async (importOriginal) => {
const actual = await importOriginal<typeof import("./runtime/agent")>();
return {
@@ -124,6 +139,28 @@ vi.mock(
},
);
+vi.mock(
+ "@langfuse/shared/in-app-agent/server/runLifecycle",
+ async (importOriginal) => {
+ const actual =
+ await importOriginal<
+ typeof import("@langfuse/shared/in-app-agent/server/runLifecycle")
+ >();
+
+ return {
+ ...actual,
+ finishClaimedRun: async (
+ ...args: Parameters<typeof actual.finishClaimedRun>
+ ) => {
+ if (scenarioRef.failFinishClaimedRun) {
+ throw new Error("simulated persist failure");
+ }
+ return actual.finishClaimedRun(...args);
+ },
+ };
+ },
+);
+
vi.mock("@langfuse/shared/src/server/auth/apiKeys", async (importOriginal) => {
const actual =
await importOriginal<
@@ -293,6 +330,8 @@ describe("executeInAppAgentRun", () => {
beforeEach(() => {
scenarioRef.titleInferenceCalls = 0;
scenarioRef.instanceEnabled = true;
+ scenarioRef.failFinishClaimedRun = false;
+ observabilityRef.traceException.mockClear();
});
it("does not regenerate the conversation title after executing a user-message run", async () => {
@@ -698,7 +737,7 @@ describe("executeInAppAgentRun", () => {
await expect(
executeInAppAgentRun({ projectId, runId: run.id }),
- ).rejects.toThrow("adapter teardown crashed");
+ ).resolves.toBeUndefined();
const failed = await getRun(projectId, run.id);
expect(failed.status).toBe("FAILED");
@@ -706,7 +745,7 @@ describe("executeInAppAgentRun", () => {
expect(await getInAppAgentApiKeys(projectId)).toHaveLength(0);
});
- it("classifies a loop-phase stream error as agent_error, not init_failed, in the outer catch", async () => {
+ it("acknowledges a loop-phase error after the run is already FAILED so the job does not land in the DLQ", async () => {
const { projectId, run } = await seedBackgroundRun();
scenarioRef.current = async ({ options }) => {
@@ -716,13 +755,37 @@ describe("executeInAppAgentRun", () => {
await expect(
executeInAppAgentRun({ projectId, runId: run.id }),
- ).rejects.toThrow("persistence blew up");
+ ).resolves.toBeUndefined();
const failed = await getRun(projectId, run.id);
expect(failed.status).toBe("FAILED");
expect(failed.errorCode).toBe("agent_error");
expect(failed.errorMessage).toBe("persistence blew up");
expect(await getInAppAgentApiKeys(projectId)).toHaveLength(0);
+ expect(observabilityRef.traceException).toHaveBeenCalledWith(
+ expect.objectContaining({ message: "persistence blew up" }),
+ );
+ });
+
+ it("still fails the job when terminal persist throws", async () => {
+ const { projectId, run } = await seedBackgroundRun();
+
+ scenarioRef.failFinishClaimedRun = true;
+ scenarioRef.current = async ({ options }) => {
+ await options.onEvent(textChunk("partial"));
+ throw new Error("loop died");
+ };
+
+ try {
+ await expect(
+ executeInAppAgentRun({ projectId, runId: run.id }),
+ ).rejects.toThrow("simulated persist failure");
+ } finally {
+ scenarioRef.failFinishClaimedRun = false;
+ }
+
+ const unfinished = await getRun(projectId, run.id);
+ expect(unfinished.status).toBe("RUNNING");
});
it("deletes the MCP key exactly once when the loop's onFinish races the outer catch", async () => {
@@ -743,7 +806,7 @@ describe("executeInAppAgentRun", () => {
await expect(
executeInAppAgentRun({ projectId, runId: run.id }),
- ).rejects.toThrow("persist failed");
+ ).resolves.toBeUndefined();
await vi.waitFor(async () => {
expect(await getInAppAgentApiKeys(projectId)).toHaveLength(0);
@@ -755,6 +818,60 @@ describe("executeInAppAgentRun", () => {
expect(scenarioRef.apiKeyDeleteCalls).toBe(1);
});
+ it("reconciles a stale RUNNING delivery and acknowledges without starting the agent loop", async () => {
+ const { projectId, run } = await seedBackgroundRun({ status: "RUNNING" });
+ const twoMinutesAgo = new Date(Date.now() - 2 * 60_000);
+ await prisma.inAppAgentRun.update({
+ where: { id_projectId: { id: run.id, projectId } },
+ data: {
+ claimedAt: twoMinutesAgo,
+ heartbeatAt: twoMinutesAgo,
+ },
+ });
+
+ scenarioRef.current = async () => {
+ throw new Error(
+ "agent loop must not start on stale unclaimable delivery",
+ );
+ };
+
+ await expect(
+ executeInAppAgentRun({ projectId, runId: run.id }),
+ ).resolves.toBeUndefined();
+
+ const failed = await getRun(projectId, run.id);
+ expect(failed.status).toBe("FAILED");
+ expect(failed.errorCode).toBe("worker_lost");
+ expect(failed.finishedAt).not.toBeNull();
+ });
+
+ it("acknowledges delivery against an already-FAILED run without changing it", async () => {
+ const { projectId, run } = await seedBackgroundRun({ status: "FAILED" });
+ const finishedAt = new Date("2026-08-01T00:00:00.000Z");
+ await prisma.inAppAgentRun.update({
+ where: { id_projectId: { id: run.id, projectId } },
+ data: {
+ finishedAt,
+ errorCode: "agent_error",
+ errorMessage: "already terminal",
+ },
+ });
+
+ scenarioRef.current = async () => {
+ throw new Error("agent loop must not start on terminal delivery");
+ };
+
+ await expect(
+ executeInAppAgentRun({ projectId, runId: run.id }),
+ ).resolves.toBeUndefined();
+
+ const unchanged = await getRun(projectId, run.id);
+ expect(unchanged.status).toBe("FAILED");
+ expect(unchanged.errorCode).toBe("agent_error");
+ expect(unchanged.errorMessage).toBe("already terminal");
+ expect(unchanged.finishedAt?.toISOString()).toBe(finishedAt.toISOString());
+ });
+
it("fails revalidation at claim as FAILED (init_failed) when AI features are disabled", async () => {
const { projectId, run } = await seedBackgroundRun({
aiFeaturesEnabled: false,
@@ -770,6 +887,7 @@ describe("executeInAppAgentRun", () => {
expect(failed.status).toBe("FAILED");
expect(failed.errorCode).toBe("init_failed");
expect(await getInAppAgentApiKeys(projectId)).toHaveLength(0);
+ expect(observabilityRef.traceException).not.toHaveBeenCalled();
});
it("fails revalidation at claim as FAILED (init_failed) when in-app agent is instance-disabled", async () => {
diff --git a/worker/src/features/in-app-agent/executeInAppAgentRun.ts b/worker/src/features/in-app-agent/executeInAppAgentRun.ts
index cf817a79c4..f5e20f25f1 100644
--- a/worker/src/features/in-app-agent/executeInAppAgentRun.ts
+++ b/worker/src/features/in-app-agent/executeInAppAgentRun.ts
@@ -4,6 +4,7 @@ import {
getLangfuseAITraceSinkParams,
logger,
redis,
+ traceException,
} from "@langfuse/shared/src/server";
import {
createAndAddApiKeysToDb,
@@ -37,6 +38,7 @@ import {
clearRunMcpApiKeyPointer,
finishClaimedRun,
heartbeatClaimedRun,
+ reconcileConversationRuns,
} from "@langfuse/shared/in-app-agent/server/runLifecycle";
import {
createInAppAgentMcpRunOverride,
@@ -82,7 +84,7 @@ export async function executeInAppAgentRun(params: {
const awsProfile = env.AWS_PROFILE ?? env.LANGFUSE_IN_APP_AGENT_AWS_PROFILE;
// Claim CAS: zero rows means duplicate delivery or a run reconciled away
- // while queued — ack and exit, Postgres owns correctness.
+ // while queued. Reconcile then ack — Postgres owns correctness.
const run = await claimQueuedRun({ prisma, projectId, runId });
if (!run) {
@@ -90,6 +92,20 @@ export async function executeInAppAgentRun(params: {
projectId,
runId,
});
+
+ const existing = await prisma.inAppAgentRun.findUnique({
+ where: { id_projectId: { id: runId, projectId } },
+ select: { conversationId: true },
+ });
+
+ if (existing) {
+ await reconcileConversationRuns({
+ prisma,
+ projectId,
+ conversationId: existing.conversationId,
+ });
+ }
+
return;
}
@@ -574,9 +590,12 @@ export async function executeInAppAgentRun(params: {
}),
});
await cleanupMcpApiKeyLogged();
-
+ // Terminal persist succeeded; ACK so the job does not sit in the DLQ.
+ // Loop failures used to rethrow. Record the APM error without failing
+ // the BullMQ job. Init failures were already ACK'd and stay off
+ // Error Tracking.
if (!(error instanceof InAppAgentRunInitError)) {
- throw error;
+ traceException(error);
}
} finally {
if (heartbeatTimer) clearInterval(heartbeatTimer);
diff --git a/worker/src/services/dlq/dlqRetryService.ts b/worker/src/services/dlq/dlqRetryService.ts
index 04706b2765..ca7be526fb 100644
--- a/worker/src/services/dlq/dlqRetryService.ts
+++ b/worker/src/services/dlq/dlqRetryService.ts
@@ -12,6 +12,7 @@ export class DlqRetryService {
QueueName.ScoreDelete,
QueueName.BatchActionQueue,
QueueName.DataRetentionProcessingQueue,
+ QueueName.InAppAgentRunQueue,
] as const;
// called each 10 minutes, defined by the bull cron job