Skip to content

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

refactor(in-app-agent): reconcile on watch attach, not on a timer (LFE-14624) (#15812)

Lysander Kiesele37c403cbb17
diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.ts
index bad134ea5d..017a29f9ba 100644
--- a/packages/shared/src/env.ts
+++ b/packages/shared/src/env.ts
@@ -544,11 +544,6 @@ const EnvSchema = z.object({
.int()
.positive()
.default(15_000),
- LANGFUSE_IN_APP_AGENT_WATCH_RECONCILE_INTERVAL_MS: z.coerce
- .number()
- .int()
- .positive()
- .default(5_000),
LANGFUSE_IN_APP_AGENT_WATCH_MAX_CONNECTION_MS: z.coerce
.number()
.int()
diff --git a/packages/shared/src/in-app-agent/server/tunables.ts b/packages/shared/src/in-app-agent/server/tunables.ts
index b689310cc6..a1e24d463b 100644
--- a/packages/shared/src/in-app-agent/server/tunables.ts
+++ b/packages/shared/src/in-app-agent/server/tunables.ts
@@ -31,10 +31,6 @@ export const IN_APP_AGENT_WATCH_TAIL_POLL_MS =
export const IN_APP_AGENT_WATCH_KEEPALIVE_MS =
env.LANGFUSE_IN_APP_AGENT_WATCH_KEEPALIVE_MS;
-/** Reconcile on attach, then independently from the event polling cadence. */
-export const IN_APP_AGENT_WATCH_RECONCILE_INTERVAL_MS =
- env.LANGFUSE_IN_APP_AGENT_WATCH_RECONCILE_INTERVAL_MS;
-
/**
* Deliberate stream end; the client reconnects with its cursor through the
* same path as a fresh page load, so route/LB duration limits are never hit
diff --git a/packages/shared/src/in-app-agent/server/watch.test.ts b/packages/shared/src/in-app-agent/server/watch.test.ts
index ba6edada0c..e583dd2eff 100644
--- a/packages/shared/src/in-app-agent/server/watch.test.ts
+++ b/packages/shared/src/in-app-agent/server/watch.test.ts
@@ -1,5 +1,5 @@
import { EventType } from "@ag-ui/core";
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
import { InAppAgentRunStatus } from "../../index";
import type { PrismaClient } from "../../db";
@@ -23,6 +23,8 @@ type RunRow = {
status: InAppAgentRunStatus;
errorCode: string | null;
cancelRequestedAt?: Date | null;
+ claimedAt?: Date | null;
+ heartbeatAt?: Date | null;
};
function fakePrisma(polls: Array<{ events: EventRow[]; run: RunRow | null }>) {
@@ -325,4 +327,55 @@ describe("watchConversationFrames", () => {
EventType.RUN_FINISHED,
]);
});
+
+ it("reconciles once on attach and never again while the run stays healthy", async () => {
+ // The watch used to open a write-capable transaction every few seconds for
+ // every attached viewer. A healthy stream must now be pure reads after the
+ // one reconcile that covers a run dying while nothing watched it.
+ const healthy: RunRow = {
+ id: "run-1",
+ status: InAppAgentRunStatus.RUNNING,
+ errorCode: null,
+ claimedAt: new Date(-5_000),
+ heartbeatAt: new Date(0),
+ };
+ const prisma = fakePrisma([
+ { events: [], run: healthy },
+ { events: [], run: healthy },
+ { events: [], run: { ...succeeded, id: "run-1" } },
+ ]);
+ const reconcileReads = vi.spyOn(prisma.inAppAgentRun, "findMany");
+
+ await collect(prisma, -1);
+
+ expect(reconcileReads).toHaveBeenCalledTimes(1);
+ });
+
+ it("reconciles again, once, when it observes a heartbeat that already went stale", async () => {
+ // Without this the stream would poll a dead run to the connection cap and
+ // reconnect into the same state, leaving the drawer thinking indefinitely.
+ const abandoned: RunRow = {
+ id: "run-1",
+ status: InAppAgentRunStatus.RUNNING,
+ errorCode: null,
+ claimedAt: new Date(-600_000),
+ heartbeatAt: new Date(-120_000),
+ };
+ const prisma = fakePrisma([
+ { events: [], run: abandoned },
+ { events: [], run: abandoned },
+ { events: [], run: abandoned },
+ {
+ events: [],
+ run: { ...succeeded, id: "run-1", errorCode: "worker_lost" },
+ },
+ ]);
+ const reconcileReads = vi.spyOn(prisma.inAppAgentRun, "findMany");
+
+ await collect(prisma, -1);
+
+ // Attach plus exactly one staleness-triggered reconcile, however many
+ // polls observe the same dead run.
+ expect(reconcileReads).toHaveBeenCalledTimes(2);
+ });
});
diff --git a/packages/shared/src/in-app-agent/server/watch.ts b/packages/shared/src/in-app-agent/server/watch.ts
index ab83b7d8bd..e17ae348f7 100644
--- a/packages/shared/src/in-app-agent/server/watch.ts
+++ b/packages/shared/src/in-app-agent/server/watch.ts
@@ -1,6 +1,6 @@
import { EventType } from "@ag-ui/core";
-import { InAppAgentRunStatusSchema } from "../../index";
+import { InAppAgentRunStatus, InAppAgentRunStatusSchema } from "../../index";
import { Prisma, type PrismaClient } from "../../db";
import {
isActiveInAppAgentRunStatus,
@@ -9,9 +9,9 @@ import {
import type { AgUiEvent } from "../schema";
import { reconcileConversationRuns } from "./runLifecycle";
import {
+ IN_APP_AGENT_HEARTBEAT_STALE_MS,
IN_APP_AGENT_WATCH_KEEPALIVE_MS,
IN_APP_AGENT_WATCH_MAX_CONNECTION_MS,
- IN_APP_AGENT_WATCH_RECONCILE_INTERVAL_MS,
IN_APP_AGENT_WATCH_TAIL_POLL_MS,
} from "./tunables";
@@ -19,6 +19,13 @@ import {
* Tail persisted events while preserving AG-UI run framing. Synthetic frames
* never advance beyond the event they frame, so reconnect cannot skip a row.
* `null` asks the SSE transport to emit a keep-alive comment.
+ *
+ * Reconciliation here is evidence-driven, not periodic. A healthy watch issues
+ * pure reads: the only writes are one reconcile when the stream attaches, and
+ * one more if a poll ever observes a heartbeat that has already gone stale.
+ * Polling a write-capable transaction every few seconds regardless of need was
+ * the previous shape, and it put a transaction on the SSE path for every
+ * attached viewer of every conversation.
*/
export async function* watchConversationFrames(params: {
prisma: PrismaClient;
@@ -37,23 +44,23 @@ export async function* watchConversationFrames(params: {
const startedAt = now();
let cursor = params.cursor;
let lastKeepaliveAt = startedAt;
- let lastReconciledAt: number | null = null;
let openRunId: string | null = null;
let lastStatusKey: string | null = null;
+ let reconciledStaleRun = false;
- while (!params.signal?.aborted) {
- if (
- lastReconciledAt === null ||
- now() - lastReconciledAt >= IN_APP_AGENT_WATCH_RECONCILE_INTERVAL_MS
- ) {
- await reconcileConversationRuns({
- prisma: params.prisma,
- projectId: params.projectId,
- conversationId: params.conversationId,
- });
- lastReconciledAt = now();
- }
+ const reconcile = () =>
+ reconcileConversationRuns({
+ prisma: params.prisma,
+ projectId: params.projectId,
+ conversationId: params.conversationId,
+ });
+ // On attach, because the run may have died while nothing was watching. A
+ // reconnect lands here too, which is what bounds recovery for a conversation
+ // whose viewer never closes the drawer.
+ 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) => ({
@@ -68,6 +75,10 @@ export async function* watchConversationFrames(params: {
status: true,
errorCode: true,
cancelRequestedAt: true,
+ // Carried on the read we already make, so noticing a dead worker
+ // costs nothing until there is something to notice.
+ claimedAt: true,
+ heartbeatAt: true,
},
}),
events: await tx.inAppAgentEvent.findMany({
@@ -164,6 +175,17 @@ export async function* watchConversationFrames(params: {
return;
}
+ // The run claims to be active but its worker stopped signalling. Left
+ // alone, this stream would poll a dead run until the connection cap and
+ // then reconnect into the same state, so the drawer would sit thinking
+ // indefinitely. Reconcile once and let the next poll read the outcome; if
+ // the CAS lost a race, the reconnect's attach reconcile tries again.
+ if (!reconciledStaleRun && isStaleClaimedRun(latestRun, now())) {
+ reconciledStaleRun = true;
+ await reconcile();
+ continue;
+ }
+
if (now() - startedAt >= IN_APP_AGENT_WATCH_MAX_CONNECTION_MS) {
return;
}
@@ -177,6 +199,34 @@ export async function* watchConversationFrames(params: {
}
}
+/**
+ * Only a claimed run can be judged by its heartbeat. Foreground runs insert as
+ * RUNNING with neither timestamp and are stale-closed by their own 150s rule on
+ * the read path, so they must not be judged here.
+ */
+function isStaleClaimedRun(
+ run: {
+ status: string | null;
+ claimedAt?: Date | null;
+ heartbeatAt?: Date | null;
+ },
+ now: number,
+): boolean {
+ if (run.status !== InAppAgentRunStatus.RUNNING) {
+ return false;
+ }
+
+ const lastSign = run.heartbeatAt ?? run.claimedAt;
+
+ // Nullish rather than `!== null`: a legacy row can carry neither timestamp,
+ // and treating "no signal ever recorded" as stale would kill it.
+ if (!lastSign) {
+ return false;
+ }
+
+ return now - lastSign.getTime() > IN_APP_AGENT_HEARTBEAT_STALE_MS;
+}
+
/** Match foreground streaming by withholding persisted replay input. */
function toPublicEvent(event: AgUiEvent): AgUiEvent {
if (event.type !== EventType.RUN_STARTED || event.input === undefined) {