Skip to content

Commit e0e60ff

Browse files
adrien2pTrigger.dev RepoOps
authored andcommitted
fix(webapp): skip the .in tail read when triggering a session's first run
Mono-RevId: 6f831e3e82acccbe273ec267d9ecb9535d77fce9
1 parent 3733be7 commit e0e60ff

6 files changed

Lines changed: 123 additions & 11 deletions

File tree

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
area: webapp
3+
type: fix
4+
---
5+
6+
Starting a new chat session is faster again.

‎apps/webapp/app/services/realtime/sessionChannelAppend.server.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -289,7 +289,8 @@ export async function ensureRunThenAppend({
289289

290290
// An append that wrote no record (a lost claim) or returned no seq leaves `seq` unset. After a
291291
// lost claim the winner's own revive carries the first seq; a run started here records none, and
292-
// its ownership of a turn-complete falls back to `sessionInSeq`, the tail read at trigger.
292+
// its ownership of a turn-complete falls back to `sessionInSeq` (the tail read at trigger, or 0
293+
// for a session's first run).
293294
const settledEnsure: EnsureOutcome =
294295
io === "in" && ensure.ok
295296
? {

‎apps/webapp/app/services/realtime/sessionRunManager.server.ts‎

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { runStore } from "~/v3/runStore.server";
77
import { engine } from "~/v3/runEngine.server";
88
import type { AuthenticatedEnvironment } from "~/services/apiAuth.server";
99
import { logger } from "~/services/logger.server";
10+
import { startActiveSpan } from "~/v3/tracer.server";
1011
import { CancelTaskRunService, type CancelableTaskRun } from "~/v3/services/cancelTaskRun.server";
1112
import { TriggerTaskService } from "~/v3/services/triggerTask.server";
1213
import { isFinalRunStatus } from "~/v3/taskStatus";
@@ -258,6 +259,17 @@ export async function ensureRunForSession(
258259
environment,
259260
payloadOverrides: mergedPayloadOverrides,
260261
sessionInFirstSeq,
262+
// A session's first run is anchored at `.in` seq 0 without reading the tail. `currentRunId`
263+
// is only set by a claim and never cleared, so null means no run has ever been claimed, and
264+
// that run's agent boots with no `.out` cursor and reads `.in` from seq 0 (on a first boot
265+
// nothing on `.in` counts as applied): every message on `.in`, including one that landed
266+
// before it was triggered, is its to answer. So 0 is exact, not an approximation. It also
267+
// skips an S2 read that, on a basin that creates streams on read, would create `.in`. A run
268+
// started for messages already on `.in` (`sessionInFirstSeq`) still reads it, so its anchor
269+
// stays above its first seq as `RunAnnotations` requires. Every other trigger (a current run,
270+
// the lost-race recursion below, a swap, a revive, a continuation) reads the tail as before.
271+
// Derived from `session` so the recursion re-derives it from the fresh row.
272+
sessionInSeq: session.currentRunId || sessionInFirstSeq !== undefined ? undefined : 0,
261273
});
262274

263275
if (superseded) {
@@ -543,20 +555,23 @@ function isPendingVersionStatus(status: TaskRunStatus): boolean {
543555
* right, since the run boots from the cursor and reads it. Undefined when the streams are not S2
544556
* or the tail cannot be read: the check then falls back to timestamps, and the trigger goes on.
545557
*
546-
* Cost: one S2 tail read per session-run trigger, bounded by the S2 client's timeout; no query.
558+
* Cost: one S2 tail read per session-run trigger that has no known tail (a session's first run
559+
* passes its own, see `ensureRunForSession`), bounded by the S2 client's timeout; no query.
547560
*/
548561
async function readSessionInSeqForTrigger(
549562
session: Pick<Session, "friendlyId" | "externalId" | "streamBasinName">,
550563
environment: AuthenticatedEnvironment
551564
): Promise<number | undefined> {
552565
const [error, seq] = await tryCatch(
553-
(async () => {
566+
startActiveSpan("readSessionInSeqForTrigger()", async (span) => {
554567
const streams = getRealtimeStreamInstance(environment, "v2", { session });
555568
if (!(streams instanceof S2RealtimeStreams)) return undefined;
556-
return streams.readSessionInTailSeq(
569+
const tailSeq = await streams.readSessionInTailSeq(
557570
canonicalSessionAddressingKey(session, session.friendlyId)
558571
);
559-
})()
572+
if (tailSeq !== undefined) span.setAttribute("session.in_seq", tailSeq);
573+
return tailSeq;
574+
})
560575
);
561576
if (error) {
562577
logger.warn("Failed to read the session .in tail before triggering its run", {
@@ -579,7 +594,8 @@ async function readSessionInSeqForTrigger(
579594
* the session it belongs to is on v2. `determineRealtimeStreamsVersion`
580595
* degrades to v1 where v2 streams are not configured.
581596
*
582-
* The run always records the `.in` tail read just before the trigger (`sessionInSeq`), and, when
597+
* The run records the `.in` tail as `sessionInSeq`: the caller's, when it already knows it (a
598+
* session's first run, anchored at 0), else the tail read just before the trigger. And, when
583599
* the caller is starting it for messages already on `.in` (a revive after an append, a continuation
584600
* for unread input), the first seq it was started to answer (`sessionInFirstSeq`, below the tail).
585601
* Each field has one job, told on `RunAnnotations`.
@@ -590,6 +606,8 @@ async function triggerSessionRun(params: {
590606
environment: AuthenticatedEnvironment;
591607
payloadOverrides?: Record<string, unknown>;
592608
sessionInFirstSeq?: number;
609+
/** The `.in` tail when it is already known; read when unset. */
610+
sessionInSeq?: number;
593611
}): Promise<{ id: string; friendlyId: string; status: TaskRunStatus; createdAt?: Date }> {
594612
const { session, environment, payloadOverrides } = params;
595613
const floor = sessionVersionFloorFor(environment);
@@ -612,7 +630,8 @@ async function triggerSessionRun(params: {
612630
};
613631

614632
const { sessionInFirstSeq } = params;
615-
const sessionInSeq = await readSessionInSeqForTrigger(session, environment);
633+
const sessionInSeq =
634+
params.sessionInSeq ?? (await readSessionInSeqForTrigger(session, environment));
616635

617636
const service = new TriggerTaskService();
618637
const result = await service.call(session.taskIdentifier, environment, body, {

‎apps/webapp/test/engine/triggerTask.sessionInSeq.test.ts‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,8 @@ vi.setConfig({ testTimeout: 60_000, hookTimeout: 60_000 });
2929

3030
describe("triggerTask session input seq", () => {
3131
// Catches: the `.in` seqs a session run was triggered with being dropped on the way to the run row,
32-
// so the run-end check has nothing exact to compare against and falls back to timestamps.
32+
// so the run-end check has nothing exact to compare against and falls back to timestamps. That
33+
// includes a session's first run, anchored at 0, which a truthiness check would drop.
3334
containerTest(
3435
"stores the session input seqs in the run's annotations, in the insert that creates it",
3536
async ({ prisma, redisOptions }) => {
@@ -53,18 +54,29 @@ describe("triggerTask session input seq", () => {
5354
environment,
5455
body: { payload: { test: "x" } },
5556
});
57+
const firstRun = await service.call({
58+
taskId: taskIdentifier,
59+
environment,
60+
body: { payload: { test: "x" } },
61+
options: { sessionInSeq: 0 },
62+
});
5663
assertNonNullable(anchored);
5764
assertNonNullable(plain);
65+
assertNonNullable(firstRun);
5866

5967
const anchoredRun = await prisma.taskRun.findFirstOrThrow({ where: { id: anchored.run.id } });
6068
const plainRun = await prisma.taskRun.findFirstOrThrow({ where: { id: plain.run.id } });
69+
const firstRunRow = await prisma.taskRun.findFirstOrThrow({ where: { id: firstRun.run.id } });
6170

6271
const anchoredAnnotations = anchoredRun.annotations as Record<string, unknown>;
6372
const plainAnnotations = plainRun.annotations as Record<string, unknown>;
73+
const firstRunAnnotations = firstRunRow.annotations as Record<string, unknown>;
6474
expect(anchoredAnnotations.sessionInSeq).toBe(7);
6575
expect(anchoredAnnotations.sessionInFirstSeq).toBe(5);
6676
expect(plainAnnotations.sessionInSeq).toBeUndefined();
6777
expect(plainAnnotations.sessionInFirstSeq).toBeUndefined();
78+
expect(firstRunAnnotations.sessionInSeq).toBe(0);
79+
expect(firstRunAnnotations.sessionInFirstSeq).toBeUndefined();
6880
}
6981
);
7082
});

‎apps/webapp/test/sessionRunCompletionContinuation.test.ts‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,8 @@ const s2 = vi.hoisted(() => ({
4444
readCalls: 0,
4545
/** The `.in` tail read throws, as when S2 does not answer. */
4646
inTailThrows: false,
47+
/** How many times the `.in` tail was read. */
48+
inTailReads: 0,
4749
}));
4850

4951
// Every stream name is `${STREAM_PREFIX}/sessions/<key>/<io>`, the shape production uses.
@@ -72,6 +74,7 @@ vi.mock("~/services/realtime/v1StreamsGlobal.server", async () => {
7274
override async readSessionInTailSeq(
7375
...args: Parameters<InstanceType<typeof S2RealtimeStreams>["readSessionInTailSeq"]>
7476
) {
77+
s2.inTailReads++;
7578
if (s2.inTailThrows) throw new Error("S2 did not answer");
7679
return super.readSessionInTailSeq(...args);
7780
}
@@ -304,6 +307,7 @@ async function setup(prisma: PrismaClient) {
304307
s2.outUnreadable = false;
305308
s2.readCalls = 0;
306309
s2.inTailThrows = false;
310+
s2.inTailReads = 0;
307311

308312
// A stream key of its own, so tests that share the s2-lite container never see each other's records.
309313
return { suffix, seed, environment, key: `chat-${suffix}` };
@@ -338,6 +342,25 @@ async function sessionWithLiveRun(prisma: PrismaClient, ctx: Ctx, closed = false
338342
return { session, run: { id: runId, friendlyId, createdAt: runCreatedAt } };
339343
}
340344

345+
/** A session no run has ever been claimed for: `currentRunId` is null. */
346+
async function sessionWithoutRun(prisma: PrismaClient, ctx: Ctx) {
347+
return prisma.session.create({
348+
data: {
349+
friendlyId: `session_${ctx.suffix}`,
350+
externalId: ctx.key,
351+
type: "chat.agent",
352+
projectId: ctx.seed.projectId,
353+
runtimeEnvironmentId: ctx.seed.envId,
354+
environmentType: "PRODUCTION",
355+
organizationId: ctx.seed.organizationId,
356+
taskIdentifier: "my-chat",
357+
triggerConfig: { basePayload: {} } as never,
358+
currentRunId: null,
359+
currentRunVersion: 0,
360+
},
361+
});
362+
}
363+
341364
/** Appends records to one of the session's channels, as S2 stores them at `timestamp`. */
342365
function sessionStream(ctx: Ctx, io: "in" | "out") {
343366
const name = new S2RealtimeStreams({
@@ -1484,6 +1507,54 @@ describe("a run that recorded the .in seq it was triggered at", () => {
14841507
});
14851508

14861509
describe("the .in seq captured when a session run is triggered", () => {
1510+
// Catches: a session's first run waiting on an `.in` tail read before it is triggered (a read
1511+
// that creates the stream on a basin that creates streams on read), and anchoring that run above
1512+
// messages it answers: with no run ever claimed, its agent reads `.in` from seq 0.
1513+
postgresTest(
1514+
"a session's first run is anchored at seq 0 without reading the .in tail",
1515+
async ({ prisma }) => {
1516+
const ctx = await setup(prisma as unknown as PrismaClient);
1517+
const session = await sessionWithoutRun(prisma as unknown as PrismaClient, ctx);
1518+
await pushIn(ctx, message("m0"));
1519+
await pushIn(ctx, message("m1"));
1520+
1521+
const ensured = await ensureRunForSession({
1522+
session,
1523+
environment: ctx.environment,
1524+
reason: "initial",
1525+
});
1526+
1527+
expect(ensured.triggered).toBe(true);
1528+
expect(triggerState.calls).toHaveLength(1);
1529+
expect(triggerState.calls[0]!.options.sessionInSeq).toBe(0);
1530+
expect(s2.inTailReads).toBe(0);
1531+
}
1532+
);
1533+
1534+
// Catches: a run started for messages already on `.in` (it carries a first seq) recording a
1535+
// `sessionInSeq` of 0, below that first seq, because its session has no current run: the run-end
1536+
// check would then scan `.in` from 0 for it, and the first seq would no longer sit below the tail.
1537+
postgresTest(
1538+
"a first run started for messages already on .in still reads the tail",
1539+
async ({ prisma }) => {
1540+
const ctx = await setup(prisma as unknown as PrismaClient);
1541+
const session = await sessionWithoutRun(prisma as unknown as PrismaClient, ctx);
1542+
await pushIn(ctx, message("m0"));
1543+
await pushIn(ctx, message("m1"));
1544+
1545+
const ensured = await ensureRunForSession({
1546+
session,
1547+
environment: ctx.environment,
1548+
reason: "initial",
1549+
sessionInFirstSeq: 1,
1550+
});
1551+
1552+
expect(ensured.triggered).toBe(true);
1553+
expect(triggerState.calls[0]!.options.sessionInFirstSeq).toBe(1);
1554+
expect(triggerState.calls[0]!.options.sessionInSeq).toBe(2);
1555+
}
1556+
);
1557+
14871558
// Catches: the seq being read after the trigger (a message appended in between would then be
14881559
// below the anchor and never continued), or missing from one of the trigger paths.
14891560
postgresTest(

‎packages/core/src/v3/schemas/runEngine.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,12 @@ export const RunAnnotations = z.object({
3333
/** The endpoint (friendly id) that delivery arrived on. */
3434
webhookEndpointId: z.string().optional(),
3535
/**
36-
* For a session run: the session's `.in` tail seq (the next seq) read just before the run was
37-
* triggered. `.in` messages at or after it arrived after the run started. Where the run-end check
38-
* starts reading when the run wrote no turn of its own.
36+
* For a session run: where the run-end check starts reading `.in` when the run wrote no turn of
37+
* its own, so messages at or after it are ones this run is held to answer. It is the session's
38+
* `.in` tail seq (the next seq) read just before the run was triggered, so those messages arrived
39+
* after the run started; except for a session's first run not started for messages already on
40+
* `.in` (no `sessionInFirstSeq`), which records 0 without a read: that run reads `.in` from the
41+
* start, so every message already on it is its own.
3942
*/
4043
sessionInSeq: z.number().int().nonnegative().optional(),
4144
/**

0 commit comments

Comments
 (0)