Skip to content

Commit 4ed63d4

Browse files
adrien2pTrigger.dev RepoOps
authored andcommitted
fix(webapp): read past several trim records when peeking a session's .out tail
Mono-RevId: 3f5a6b6beb4d13d16e50b958b6db8087f904c532
1 parent 523400f commit 4ed63d4

8 files changed

Lines changed: 840 additions & 117 deletions
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+
Fix a chat message sent just as an agent run was ending occasionally going unanswered until the next message arrived.

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

Lines changed: 238 additions & 93 deletions
Large diffs are not rendered by default.

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

Lines changed: 73 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@ import { getRealtimeStreamInstance } from "./v1StreamsGlobal.server";
1010

1111
export const SESSION_RUN_COMPLETION_JOB = "sessionRun.continueIfInputUnread" as const;
1212

13+
/** How many times the queue runs the job before it gives up (its retry setting on the worker). */
14+
export const SESSION_RUN_COMPLETION_MAX_ATTEMPTS = 8;
15+
1316
export const SessionRunCompletionPayloadSchema = z.object({
1417
/** The run that ended: `TaskRun.id`. */
1518
runId: z.string(),
@@ -41,6 +44,11 @@ export type SessionContinuationOutcome =
4144
/** A failed run that died inside a turn: left to the user, see `continueSessionIfInputUnread`. */
4245
| "failed-mid-turn"
4346
| "not-a-session-run"
47+
/**
48+
* `.out` holds only S2 command records, so the run's last turn cannot be read: a final answer,
49+
* not retried, nothing continued. See `hasUnreadSessionMessage`.
50+
*/
51+
| "out-commands-only"
4452
| "unreadable";
4553

4654
/** Records read per page when looking for an unread message, and how many pages at most. */
@@ -90,6 +98,9 @@ type SessionInputStreams = Pick<
9098
* after); a cursorless one says nothing about whose it is, so it is not taken as the run's. Without
9199
* either, the run's own iff stored at or after the run was created.
92100
*
101+
* A `.out` that holds only S2 command records answers "out-commands-only", without looking at
102+
* `.in`: the turn this run wrote can no longer be read, so nothing says what it answered.
103+
*
93104
* Cost: a run with a cursor, or an anchor, reads forward from it, at most `UNREAD_SCAN_MAX_PAGES`
94105
* pages. A run with neither reads at most that many pages of `UNREAD_SCAN_PAGE_SIZE` records from
95106
* the tail, and the usual answer on a long session (nothing new) is one read of one page. There a
@@ -102,10 +113,16 @@ async function hasUnreadSessionMessage(
102113
outcome: SessionRunOutcome | undefined
103114
): Promise<
104115
| { status: "unread"; firstSeq: number | undefined }
105-
| { status: "nothing-unread" | "failed-mid-turn" | "unreadable" }
116+
| { status: "nothing-unread" | "failed-mid-turn" | "out-commands-only" | "unreadable" }
106117
> {
107118
const outTail = await streams.peekSessionOutTail(addressingKey);
108119
if (outTail.kind === "unknown") return { status: "unreadable" };
120+
// `.out` was read and holds no record to go on (a trim deleted the turn-complete or every
121+
// record, or the agent trimmed several times after it): the run's last turn is gone, and retrying cannot bring
122+
// it back. Not "empty": that would scan `.in` from the run's start and could start a run that
123+
// re-answers messages whose turn-complete was deleted. A message the run never read may go
124+
// unanswered until the user's next one, which starts a run; a duplicate reply is the worse miss.
125+
if (outTail.kind === "commands-only") return { status: "out-commands-only" };
109126

110127
const ownershipSeq = run.sessionInFirstSeq ?? run.sessionInSeq;
111128
const wroteOwnTurn =
@@ -282,14 +299,35 @@ export async function enqueueSessionRunCompletionCheck(params: {
282299
return queued;
283300
}
284301

302+
/**
303+
* Thrown when the session streams could not be read, on every attempt. It carries
304+
* `logLevel: "warn"` (the worker logs a failed attempt, and the move to its dead-letter queue after
305+
* the last one, at the level its error carries), which keeps the worker's lines out of the error
306+
* reporter. The check logs the unreadable streams once at error level on the last attempt, with
307+
* the run, the session and the stream names.
308+
*/
309+
class SessionStreamsUnreadableError extends Error {
310+
readonly logLevel = "warn" as const;
311+
312+
constructor(runId: string) {
313+
super(`Could not read the session streams for run ${runId}`);
314+
this.name = "SessionStreamsUnreadableError";
315+
}
316+
}
317+
285318
/**
286319
* The body of the queued job. Fails the attempt when the streams could not be read, so the queue
287-
* retries it instead of acking a check that looked at nothing.
320+
* retries it instead of acking a check that looked at nothing. `attempt` is the worker's
321+
* zero-based attempt count: on the last attempt the check logs the failure at error level before
322+
* the job throws, so one unreadable run is one error and not one per retry, and the job still
323+
* reaches the dead-letter queue, where it can be replayed.
288324
*/
289325
export async function runSessionRunCompletionJob(
290326
payload: z.infer<typeof SessionRunCompletionPayloadSchema>,
291-
deps: { findEnvironment: (id: string) => Promise<AuthenticatedEnvironment | null> }
327+
deps: { findEnvironment: (id: string) => Promise<AuthenticatedEnvironment | null> },
328+
attempt = 0
292329
): Promise<void> {
330+
const lastAttempt = attempt + 1 >= SESSION_RUN_COMPLETION_MAX_ATTEMPTS;
293331
const outcome = await continueSessionIfInputUnread(
294332
{
295333
run: {
@@ -300,12 +338,17 @@ export async function runSessionRunCompletionJob(
300338
},
301339
environmentId: payload.environmentId,
302340
outcome: payload.outcome,
341+
lastAttempt,
303342
},
304343
deps
305344
);
306-
// Only "unreadable" is retried: "failed-mid-turn" is a final answer.
345+
// Only "unreadable" is retried: every other outcome, "failed-mid-turn" and "out-commands-only"
346+
// included, is a final answer. The last attempt throws too, so the worker moves the check to its
347+
// dead-letter queue (logged at warn, the level the error carries) and it can be replayed once the
348+
// streams can be read. The check itself logged the failure once at error level on that attempt;
349+
// that log is wiring, and no test asserts it.
307350
if (outcome === "unreadable") {
308-
throw new Error(`Could not read the session streams for run ${payload.runId}`);
351+
throw new SessionStreamsUnreadableError(payload.runId);
309352
}
310353
}
311354

@@ -340,17 +383,20 @@ export async function runSessionRunCompletionJob(
340383
*
341384
* Cost: one indexed `Session.currentRunId` lookup; for a session's current run one S2 tail peek
342385
* and one `.in` tail read, then at most three bounded pages of `.in` records. Throws on a failure
343-
* so the queue retries it; "unreadable" (S2 gave no answer) is for the caller to retry as well.
386+
* so the queue retries it; "unreadable" (S2 gave no answer) is for the caller to retry as well, and
387+
* "out-commands-only" (`.out` read, only command records in it) is final.
344388
*/
345389
export async function continueSessionIfInputUnread(
346390
params: {
347391
run: { id: string; createdAt: Date; sessionInSeq?: number; sessionInFirstSeq?: number };
348392
environmentId: string;
349393
outcome?: SessionRunOutcome;
394+
/** The queue will not retry after this check: an unreadable stream is logged at error. */
395+
lastAttempt?: boolean;
350396
},
351397
deps: { findEnvironment: (id: string) => Promise<AuthenticatedEnvironment | null> }
352398
): Promise<SessionContinuationOutcome> {
353-
const { run, environmentId, outcome } = params;
399+
const { run, environmentId, outcome, lastAttempt } = params;
354400

355401
const session = await prisma.session.findFirst({
356402
where: {
@@ -378,12 +424,26 @@ export async function continueSessionIfInputUnread(
378424
const streams = getRealtimeStreamInstance(environment, "v2", { session });
379425
if (!(streams instanceof S2RealtimeStreams)) return "not-a-session-run";
380426

381-
const unread = await hasUnreadSessionMessage(
382-
streams,
383-
canonicalSessionAddressingKey(session, session.friendlyId),
384-
run,
385-
outcome
386-
);
427+
const addressingKey = canonicalSessionAddressingKey(session, session.friendlyId);
428+
const unread = await hasUnreadSessionMessage(streams, addressingKey, run, outcome);
429+
if (unread.status === "unreadable" || unread.status === "out-commands-only") {
430+
const context = {
431+
runId: run.id,
432+
sessionId: session.friendlyId,
433+
outStream: streams.toSessionStreamName(addressingKey, "out"),
434+
inStream: streams.toSessionStreamName(addressingKey, "in"),
435+
};
436+
if (unread.status === "out-commands-only") {
437+
logger.warn(
438+
"The session's .out holds only command records, so the run's last turn can't be read; not continuing the session",
439+
context
440+
);
441+
} else if (lastAttempt) {
442+
logger.error("Could not read the session streams after the last attempt", context);
443+
} else {
444+
logger.warn("Could not read the session streams, the check will be retried", context);
445+
}
446+
}
387447
if (unread.status !== "unread") return unread.status;
388448

389449
// The messages are already on `.in`: start the run for the first one it will answer. Unknown

‎apps/webapp/app/v3/commonWorker.server.ts‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import {
2424
import { findEnvironmentById } from "~/models/runtimeEnvironment.server";
2525
import {
2626
runSessionRunCompletionJob,
27+
SESSION_RUN_COMPLETION_MAX_ATTEMPTS,
2728
SESSION_RUN_COMPLETION_JOB,
2829
SessionRunCompletionPayloadSchema,
2930
} from "~/services/realtime/sessionRunCompletion.server";
@@ -322,7 +323,7 @@ function initializeWorker() {
322323
schema: SessionRunCompletionPayloadSchema,
323324
visibilityTimeoutMs: 60_000,
324325
retry: {
325-
maxAttempts: 8,
326+
maxAttempts: SESSION_RUN_COMPLETION_MAX_ATTEMPTS,
326327
},
327328
},
328329
"org.convergeRunsEnabled": {
@@ -399,8 +400,12 @@ function initializeWorker() {
399400
"attio.syncUser": async ({ payload }) => {
400401
await runAttioUserSync(payload);
401402
},
402-
[SESSION_RUN_COMPLETION_JOB]: async ({ payload }) => {
403-
await runSessionRunCompletionJob(payload, { findEnvironment: findEnvironmentById });
403+
[SESSION_RUN_COMPLETION_JOB]: async ({ payload, attempt }) => {
404+
await runSessionRunCompletionJob(
405+
payload,
406+
{ findEnvironment: findEnvironmentById },
407+
attempt
408+
);
404409
},
405410
"attio.syncMember": async ({ payload }) => {
406411
await runAttioMemberSync(payload);

‎apps/webapp/test/s2RealtimeStreamsSessionPeek.test.ts‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,43 @@ describe("S2RealtimeStreams session peek", () => {
9292
expect(elapsed).toBeLessThan(5000);
9393
});
9494

95+
// Catches: the walk past command records running to its record bound however long it takes,
96+
// so a slow S2 holds every reconnect for the whole peek deadline; and a walk that ran out of
97+
// time reading as "commands-only" (a final answer, never retried) instead of a failed read.
98+
it("reads a .out peek whose walk runs out of its budget as unknown", async () => {
99+
// The first read answers at once with the last two records (seq 98 and 99), both commands. The
100+
// reads after it answer one command record each, 250 ms apart: four of them are more than
101+
// the walk's budget, though each is far inside the peek deadline.
102+
handler = (request, response) => {
103+
const url = new URL(request.url ?? "", "http://localhost");
104+
const isFirst = url.searchParams.has("tail_offset");
105+
const first = isFirst ? 98 : Number(url.searchParams.get("seq_num"));
106+
const count = Number(url.searchParams.get("count"));
107+
setTimeout(
108+
() => {
109+
response.writeHead(200, { "Content-Type": "application/json" });
110+
response.end(
111+
JSON.stringify({
112+
records: Array.from({ length: count }, (_, i) => ({
113+
seq_num: first + i,
114+
timestamp: 1,
115+
body: "",
116+
headers: [["", "trim"]],
117+
})),
118+
})
119+
);
120+
},
121+
isFirst ? 0 : 250
122+
);
123+
};
124+
125+
const startedAt = Date.now();
126+
await expect(createStreams().peekSessionOutTail("chat_1")).resolves.toEqual({
127+
kind: "unknown",
128+
});
129+
expect(Date.now() - startedAt).toBeLessThan(1000);
130+
});
131+
95132
it("reads the .out tail record past a trim command", async () => {
96133
handler = (request, response) => {
97134
expect(decodeURIComponent(request.url ?? "")).toContain("/sessions/chat_1/out/records?");

0 commit comments

Comments
 (0)