@@ -7,6 +7,7 @@ import { runStore } from "~/v3/runStore.server";
77import { engine } from "~/v3/runEngine.server" ;
88import type { AuthenticatedEnvironment } from "~/services/apiAuth.server" ;
99import { logger } from "~/services/logger.server" ;
10+ import { startActiveSpan } from "~/v3/tracer.server" ;
1011import { CancelTaskRunService , type CancelableTaskRun } from "~/v3/services/cancelTaskRun.server" ;
1112import { TriggerTaskService } from "~/v3/services/triggerTask.server" ;
1213import { 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 */
548561async 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 , {
0 commit comments