🪢 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
chore(in-app-agent): collapse the watch tail poll into one statement (LFE-14629) (#15815)
Lysander Kiesel35bb36040fa8
diff --git a/packages/shared/src/in-app-agent/server/watch.test.ts b/packages/shared/src/in-app-agent/server/watch.test.tsindex 9a6126bcf8..8e04f5d1d2 100644--- a/packages/shared/src/in-app-agent/server/watch.test.ts+++ b/packages/shared/src/in-app-agent/server/watch.test.ts@@ -30,34 +30,33 @@ type RunRow = {function fakePrisma(polls: Array<{ events: EventRow[]; run: RunRow | null }>) {let pollIndex = 0;+ // Reconciliation is the only thing still reaching for a transaction; the poll+ // itself is one conversation-rooted read.const inAppAgentRun = {findMany: async () => [],updateMany: async () => ({ count: 0 }),- findFirst: async () =>- polls[Math.min(pollIndex, polls.length - 1)]?.run ?? null,- };- const inAppAgentEvent = {- findMany: async ({- where,- }: {- where: { sequenceNumber: { gt: number } };- }) => {- const poll = polls[Math.min(pollIndex, polls.length - 1)];- pollIndex += 1;-- return (poll?.events ?? []).filter(- (row) => row.sequenceNumber > where.sequenceNumber.gt,- );- },};return {$transaction: async (fn: (tx: unknown) => Promise<unknown>) =>- fn({- inAppAgentRun,- inAppAgentEvent,- }),+ fn({ inAppAgentRun }),inAppAgentRun,- inAppAgentEvent,+ inAppAgentConversation: {+ findUnique: async ({+ select,+ }: {+ select: { events: { where: { sequenceNumber: { gt: number } } } };+ }) => {+ const poll = polls[Math.min(pollIndex, polls.length - 1)];+ pollIndex += 1;++ return {+ runs: poll?.run ? [poll.run] : [],+ events: (poll?.events ?? []).filter(+ (row) => row.sequenceNumber > select.events.where.sequenceNumber.gt,+ ),+ };+ },+ },} as unknown as PrismaClient;}diff --git a/packages/shared/src/in-app-agent/server/watch.ts b/packages/shared/src/in-app-agent/server/watch.tsindex 73daee4c6c..50f76621d7 100644--- a/packages/shared/src/in-app-agent/server/watch.ts+++ b/packages/shared/src/in-app-agent/server/watch.ts@@ -1,7 +1,7 @@import { EventType } from "@ag-ui/core";import { InAppAgentRunStatus, InAppAgentRunStatusSchema } from "../../index";-import { Prisma, type PrismaClient } from "../../db";+import { type PrismaClient } from "../../db";import {isActiveInAppAgentRunStatus,type InAppAgentWatchFrame,@@ -62,15 +62,31 @@ export async function* watchConversationFrames(params: {await reconcile();while (!params.signal?.aborted) {- // Read status first: terminal CAS happens after the worker appends events.- const { latestRun, events } = await params.prisma.$transaction(- async (tx) => ({- latestRun: await tx.inAppAgentRun.findFirst({- where: {- projectId: params.projectId,- conversationId: params.conversationId,- },+ // Status and events must come from one version of the database: the worker+ // commits its final events and the terminal CAS atomically, so two+ // independent reads can straddle that commit and pair a terminal run with+ // an older event prefix — the drawer would settle as finished with its tail+ // missing (PR #15661, self-review step 4).+ //+ // A single statement takes a single snapshot, so this holds without an+ // isolation level to configure. Keep it one statement: at a 1 Hz poll per+ // attached viewer, the interactive transaction this replaces cost five+ // statements per second and held a pooled connection across two round+ // trips (LFE-14629). Rooted at the conversation, not the latest run,+ // because the tail spans runs — a continuation's events sit above a parked+ // parent's in the same cursor window.+ const conversation = await params.prisma.inAppAgentConversation.findUnique({+ where: {+ id_projectId: {+ id: params.conversationId,+ projectId: params.projectId,+ },+ },+ relationLoadStrategy: "join",+ select: {+ runs: {orderBy: { createdAt: "desc" },+ take: 1,select: {id: true,status: true,@@ -81,19 +97,17 @@ export async function* watchConversationFrames(params: {claimedAt: true,heartbeatAt: true,},- }),- events: await tx.inAppAgentEvent.findMany({- where: {- projectId: params.projectId,- conversationId: params.conversationId,- sequenceNumber: { gt: cursor },- },+ },+ events: {+ where: { sequenceNumber: { gt: cursor } },orderBy: { sequenceNumber: "asc" },select: { sequenceNumber: true, runId: true, event: true },- }),- }),- { isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead },- );+ },+ },+ });++ const latestRun = conversation?.runs[0] ?? null;+ const events = conversation?.events ?? [];for (const row of events) {const event = row.event as unknown as AgUiEvent;diff --git a/web/src/__tests__/server/in-app-agent-persistence.servertest.ts b/web/src/__tests__/server/in-app-agent-persistence.servertest.tsindex ba5cf4e6df..a11d9c2c53 100644--- a/web/src/__tests__/server/in-app-agent-persistence.servertest.ts+++ b/web/src/__tests__/server/in-app-agent-persistence.servertest.ts@@ -32,6 +32,7 @@ import {dropEmptyAssistantMessages,dropUnpairedAssistantToolCalls,type AgUiEvent,+ type InAppAgentWatchFrame,} from "@langfuse/shared/in-app-agent";import {deserializeInAppAgentDisplayState,@@ -50,6 +51,7 @@ import {shouldFlushPersistedEvent,toPersistableAgentEvent,} from "@langfuse/shared/in-app-agent/server/persistence";+import { watchConversationFrames } from "@langfuse/shared/in-app-agent/server/watch";import { createInnerTRPCContext } from "@/src/server/api/trpc";import { IN_APP_AGENT_REDIRECT_TOOL_NAME } from "@langfuse/shared/in-app-agent";@@ -2212,6 +2214,139 @@ describe("in-app agent persistence", () => {]);});+ it("tails only post-cursor events, across runs, from one conversation-rooted read", async () => {+ // The watch poll is a single joined read of the conversation's latest run+ // and its post-cursor events (LFE-14629). Its unit suite fakes that read+ // and reimplements the cursor filter in JS, so this is the only coverage+ // that the nested where/orderBy/take actually compose against Postgres.+ const { projectId, userId } = await createCaller();+ const conversation = await createConversation({ projectId, userId });++ const firstRun = await createConversationRun({+ projectId,+ conversationId: conversation.id,+ userId,+ });++ await appendRunEvents({+ prisma,+ projectId,+ conversationId: conversation.id,+ runId: firstRun.id,+ events: [+ {+ type: EventType.RUN_STARTED,+ threadId: conversation.id,+ runId: firstRun.id,+ input: {+ threadId: conversation.id,+ runId: firstRun.id,+ state: null,+ messages: [{ id: "tail-user", role: "user", content: "Look" }],+ tools: [],+ context: [],+ forwardedProps: {},+ },+ },+ {+ type: EventType.TEXT_MESSAGE_START,+ messageId: "tail-first",+ role: "assistant",+ },+ {+ type: EventType.TEXT_MESSAGE_CONTENT,+ messageId: "tail-first",+ delta: "Parked answer.",+ },+ { type: EventType.TEXT_MESSAGE_END, messageId: "tail-first" },+ ],+ finish: { status: InAppAgentRunStatus.SUCCEEDED },+ });++ const secondRun = await createConversationRun({+ projectId,+ conversationId: conversation.id,+ userId,+ });++ // A continuation's first persisted row is a plain event, not RUN_STARTED,+ // which is what forces the synthetic open in the tail below.+ await appendRunEvents({+ prisma,+ projectId,+ conversationId: conversation.id,+ runId: secondRun.id,+ events: [+ {+ type: EventType.TEXT_MESSAGE_START,+ messageId: "tail-second",+ role: "assistant",+ },+ {+ type: EventType.TEXT_MESSAGE_CONTENT,+ messageId: "tail-second",+ delta: "Continued answer.",+ },+ {+ type: EventType.RUN_FINISHED,+ threadId: conversation.id,+ runId: secondRun.id,+ },+ ],+ finish: { status: InAppAgentRunStatus.SUCCEEDED },+ });++ // Sequence 0 is the first run's RUN_STARTED and 1 its assistant+ // TEXT_MESSAGE_START, so a cursor of 1 starts the tail mid-run.+ const frames: InAppAgentWatchFrame[] = [];+ for await (const frame of watchConversationFrames({+ prisma,+ projectId,+ conversationId: conversation.id,+ cursor: 1,+ now: () => 0,+ sleep: async () => undefined,+ })) {+ if (frame !== null) {+ frames.push(frame);+ }+ }++ const relayed = frames.flatMap((frame) =>+ frame.type === "event" ? [frame.event] : [],+ );++ // A dropped cursor predicate would relay sequences 0 and 1 too, adding the+ // first run's persisted RUN_STARTED and a second TEXT_MESSAGE_START.+ expect(relayed.map((event) => event.type)).toEqual([+ EventType.RUN_STARTED,+ EventType.TEXT_MESSAGE_CONTENT,+ EventType.TEXT_MESSAGE_END,+ EventType.RUN_FINISHED,+ EventType.RUN_STARTED,+ EventType.TEXT_MESSAGE_START,+ EventType.TEXT_MESSAGE_CONTENT,+ EventType.RUN_FINISHED,+ ]);++ // The tail spans runs: the events relation is conversation-scoped, so a+ // window can hold a parked parent's rows below its continuation's.+ expect(+ relayed.flatMap((event) => ("runId" in event ? [event.runId] : [])),+ ).toEqual([firstRun.id, firstRun.id, secondRun.id, secondRun.id]);++ expect(frames.filter((frame) => frame.type === "status")).toEqual([+ {+ type: "status",+ runId: secondRun.id,+ status: InAppAgentRunStatus.SUCCEEDED,+ errorCode: null,+ cancelRequested: false,+ },+ ]);+ expect(frames.at(-1)).toEqual({ type: "done" });+ });+it("blocks a second active run in the same conversation", async () => {const { projectId, userId } = await createCaller();const conversation = await createConversation({ projectId, userId });