@@ -10,6 +10,9 @@ import { getRealtimeStreamInstance } from "./v1StreamsGlobal.server";
1010
1111export 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+
1316export 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 */
289325export 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 */
345389export 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
0 commit comments