Skip to content

Commit c9b346e

Browse files
authored
fix(sessions): fence transcript writes by admitted run (#121003)
* fix(sessions): fence transcript writes by admitted run * fix(agents): break terminal outcome import cycle * test(sessions): cover writer fence propagation * fix(sessions): complete admitted writer fence
1 parent 7422222 commit c9b346e

60 files changed

Lines changed: 1254 additions & 233 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎docs/.generated/plugin-sdk-api-baseline.sha256‎

Lines changed: 77 additions & 77 deletions
Large diffs are not rendered by default.
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import type { AgentRunTerminalOutcome } from "./agent-run-terminal-outcome.types.js";
2+
3+
function completedBeforeOrAtTimeout(params: {
4+
completed: AgentRunTerminalOutcome;
5+
timeout: AgentRunTerminalOutcome;
6+
}): boolean {
7+
return (
8+
params.completed.reason === "completed" &&
9+
typeof params.completed.endedAt === "number" &&
10+
typeof params.timeout.endedAt === "number" &&
11+
params.completed.endedAt <= params.timeout.endedAt
12+
);
13+
}
14+
15+
/** Merges observations without overwriting a proven cancellation or hard timeout. */
16+
export function mergeAgentRunTerminalOutcome(
17+
current: AgentRunTerminalOutcome | undefined,
18+
incoming: AgentRunTerminalOutcome,
19+
): AgentRunTerminalOutcome {
20+
if (!current) {
21+
return incoming;
22+
}
23+
if (current.reason === "superseded" || current.reason === "cancelled") {
24+
// Timestamps, not callback ordering, decide whether an earlier provider timeout won.
25+
if (
26+
incoming.reason === "hard_timeout" &&
27+
typeof incoming.endedAt === "number" &&
28+
typeof current.endedAt === "number" &&
29+
incoming.endedAt <= current.endedAt
30+
) {
31+
return incoming;
32+
}
33+
return current.reason === "superseded" || incoming.reason !== "superseded" ? current : incoming;
34+
}
35+
// A hard timeout owns the run unless an earlier completion or cancellation is proven.
36+
if (current.reason === "hard_timeout") {
37+
if (
38+
(incoming.reason === "superseded" || incoming.reason === "cancelled") &&
39+
typeof incoming.endedAt === "number" &&
40+
typeof current.endedAt === "number" &&
41+
incoming.endedAt < current.endedAt
42+
) {
43+
return incoming;
44+
}
45+
return completedBeforeOrAtTimeout({ completed: incoming, timeout: current })
46+
? incoming
47+
: current;
48+
}
49+
if (incoming.reason === "superseded" || incoming.reason === "cancelled") {
50+
return incoming;
51+
}
52+
if (incoming.reason === "hard_timeout") {
53+
return completedBeforeOrAtTimeout({ completed: current, timeout: incoming })
54+
? current
55+
: incoming;
56+
}
57+
return incoming;
58+
}

‎src/agents/agent-run-terminal-outcome.test.ts‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {
44
buildAgentRunTerminalOutcome,
55
buildAgentRunTerminalOutcomeFromLifecycleEvent,
66
classifyAgentRunTerminalOutcome,
7+
isStickyAgentRunTerminalOutcome,
78
mergeAgentRunAttemptTerminal,
89
mergeAgentRunTerminalOutcome,
910
normalizeAgentRunAttemptTerminal,
@@ -17,6 +18,7 @@ describe("agent run terminal outcome", () => {
1718
["completed", "success"],
1819
["hard_timeout", "timeout"],
1920
["timed_out", "timeout"],
21+
["superseded", "cancellation"],
2022
["cancelled", "cancellation"],
2123
["aborted", "cancellation"],
2224
["blocked", "failure"],
@@ -51,6 +53,16 @@ describe("agent run terminal outcome", () => {
5153
data: { status: "cancelled", stopReason: "relay-closed" },
5254
}),
5355
).toMatchObject({ reason: "cancelled", status: "error", stopReason: "relay-closed" });
56+
const superseded = buildAgentRunTerminalOutcomeFromLifecycleEvent({
57+
phase: "end",
58+
data: { aborted: true, status: "superseded", stopReason: "superseded" },
59+
});
60+
expect(superseded).toMatchObject({
61+
reason: "superseded",
62+
status: "error",
63+
stopReason: "superseded",
64+
});
65+
expect(isStickyAgentRunTerminalOutcome(superseded)).toBe(true);
5466
});
5567

5668
it("treats provider/preflight/post-turn timeout phases as hard run timeouts", () => {
@@ -363,6 +375,48 @@ describe("agent run terminal outcome", () => {
363375
expect(mergeAgentRunTerminalOutcome(timeout, cancellation)).toBe(timeout);
364376
expect(mergeAgentRunTerminalOutcome(cancellation, timeout)).toBe(timeout);
365377
});
378+
379+
it("keeps supersession over generic cancellation regardless of callback ordering", () => {
380+
const superseded = buildAgentRunTerminalOutcome({
381+
status: "error",
382+
stopReason: "superseded",
383+
endedAt: 200,
384+
});
385+
const cancellation = buildAgentRunTerminalOutcome({
386+
status: "error",
387+
stopReason: "rpc",
388+
endedAt: 201,
389+
});
390+
391+
expect(mergeAgentRunTerminalOutcome(superseded, cancellation)).toBe(superseded);
392+
expect(mergeAgentRunTerminalOutcome(cancellation, superseded)).toBe(superseded);
393+
});
394+
395+
it.each([
396+
{ supersededAt: 190, expected: "superseded" },
397+
{ supersededAt: 200, expected: "hard_timeout" },
398+
{ supersededAt: 210, expected: "hard_timeout" },
399+
] as const)(
400+
"keeps the first hard terminal between timeout and supersession at $supersededAt",
401+
({ supersededAt, expected }) => {
402+
const timeout = buildAgentRunTerminalOutcome({
403+
status: "timeout",
404+
timeoutPhase: "provider",
405+
endedAt: 200,
406+
});
407+
const superseded = buildAgentRunTerminalOutcome({
408+
status: "error",
409+
stopReason: "superseded",
410+
endedAt: supersededAt,
411+
});
412+
for (const [current, incoming] of [
413+
[timeout, superseded],
414+
[superseded, timeout],
415+
] as const) {
416+
expect(mergeAgentRunTerminalOutcome(current, incoming).reason).toBe(expected);
417+
}
418+
},
419+
);
366420
});
367421

368422
describe("agent run attempt terminal", () => {

‎src/agents/agent-run-terminal-outcome.ts‎

Lines changed: 45 additions & 97 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,18 @@ import {
66
isAbandonedLivenessState,
77
isBlockedLivenessState,
88
} from "../shared/agent-liveness.js";
9+
import type {
10+
AgentRunTerminalOutcome,
11+
AgentRunTerminalReason,
12+
AgentRunWaitStatus,
13+
} from "./agent-run-terminal-outcome.types.js";
914
import {
1015
AGENT_RUN_ABORTED_ERROR,
1116
AGENT_RUN_RESTART_ABORT_STOP_REASON,
17+
AGENT_RUN_SUPERSEDED_STOP_REASON,
1218
isAbortedAgentStopReason,
1319
isAgentRunRestartAbortReason,
20+
isAgentRunSupersededAbortReason,
1421
resolveAgentRunAbortLifecycleFields,
1522
} from "./run-termination.js";
1623
import {
@@ -19,8 +26,7 @@ import {
1926
type AgentRunTimeoutPhase,
2027
} from "./run-timeout-attribution.js";
2128

22-
/** Wait status reported by agent run terminal wait paths. */
23-
type AgentRunWaitStatus = "ok" | "error" | "timeout";
29+
export type { AgentRunTerminalOutcome } from "./agent-run-terminal-outcome.types.js";
2430

2531
export type AgentRunAttemptFailureSource =
2632
| "prompt"
@@ -407,28 +413,18 @@ const AGENT_RUN_TERMINAL_CLASSIFICATION = {
407413
completed: "success",
408414
hard_timeout: "timeout",
409415
timed_out: "timeout",
416+
superseded: "cancellation",
410417
cancelled: "cancellation",
411418
aborted: "cancellation",
412419
blocked: "failure",
413420
abandoned: "failure",
414421
failed: "failure",
415-
} as const;
416-
417-
/** Normalized terminal reason for an agent run. */
418-
type AgentRunTerminalReason = keyof typeof AGENT_RUN_TERMINAL_CLASSIFICATION;
422+
} as const satisfies Record<
423+
AgentRunTerminalReason,
424+
"success" | "timeout" | "cancellation" | "failure"
425+
>;
419426

420-
/** Normalized terminal outcome for an agent run. */
421-
export type AgentRunTerminalOutcome = {
422-
reason: AgentRunTerminalReason;
423-
status: AgentRunWaitStatus;
424-
error?: string;
425-
stopReason?: string;
426-
livenessState?: string;
427-
timeoutPhase?: AgentRunTimeoutPhase;
428-
providerStarted?: boolean;
429-
startedAt?: number;
430-
endedAt?: number;
431-
};
427+
export { mergeAgentRunTerminalOutcome } from "./agent-run-terminal-outcome-merge.js";
432428

433429
/** Collapses terminal reasons into the four projections shared by run consumers. */
434430
export function classifyAgentRunTerminalOutcome(outcome: Pick<AgentRunTerminalOutcome, "reason">) {
@@ -476,7 +472,11 @@ function isHardAgentRunTimeoutPhase(value: unknown): value is AgentRunTimeoutPha
476472
export function isStickyAgentRunTerminalOutcome(
477473
outcome: AgentRunTerminalOutcome | undefined | null,
478474
): boolean {
479-
return outcome?.reason === "hard_timeout" || outcome?.reason === "cancelled";
475+
return (
476+
outcome?.reason === "hard_timeout" ||
477+
outcome?.reason === "superseded" ||
478+
outcome?.reason === "cancelled"
479+
);
480480
}
481481

482482
function isCancellationStopReason(value: string | undefined): boolean {
@@ -499,6 +499,7 @@ export function buildAgentRunTerminalOutcome(
499499
const providerStarted = normalizeProviderStarted(input.providerStarted);
500500
const rawError = asNonEmptyString(input.error);
501501
const restartCancelled = stopReason === AGENT_RUN_RESTART_ABORT_STOP_REASON;
502+
const superseded = stopReason === AGENT_RUN_SUPERSEDED_STOP_REASON;
502503
// Queue and gateway-draining timeouts are wait-layer uncertainty. Provider
503504
// errors need explicit timeout attribution; providerStarted only proves reach.
504505
const hardTimeout =
@@ -517,26 +518,28 @@ export function buildAgentRunTerminalOutcome(
517518
? formatBlockedLivenessError(rawError)
518519
: aborted && !rawError
519520
? AGENT_RUN_ABORTED_ERROR
520-
: aborted || cancelled
521+
: superseded || aborted || cancelled
521522
? rawError
522523
: abandoned
523524
? formatAbandonedLivenessError(rawError)
524525
: rawError;
525526
const reason: AgentRunTerminalReason = hardTimeout
526527
? "hard_timeout"
527-
: blocked
528-
? "blocked"
529-
: aborted
530-
? "aborted"
531-
: cancelled
532-
? "cancelled"
533-
: abandoned
534-
? "abandoned"
535-
: input.status === "timeout"
536-
? "timed_out"
537-
: input.status === "error"
538-
? "failed"
539-
: "completed";
528+
: superseded
529+
? "superseded"
530+
: blocked
531+
? "blocked"
532+
: aborted
533+
? "aborted"
534+
: cancelled
535+
? "cancelled"
536+
: abandoned
537+
? "abandoned"
538+
: input.status === "timeout"
539+
? "timed_out"
540+
: input.status === "error"
541+
? "failed"
542+
: "completed";
540543
return {
541544
reason,
542545
status:
@@ -587,7 +590,8 @@ export function buildAgentRunTerminalOutcomeFromLifecycleEvent(input: {
587590
const cancellationStatus =
588591
lifecycleStatus === "cancelled" ||
589592
lifecycleStatus === "canceled" ||
590-
lifecycleStatus === "aborted";
593+
lifecycleStatus === "aborted" ||
594+
lifecycleStatus === "superseded";
591595
const cancelled = cancellationStatus || aborted;
592596
const failed =
593597
input.phase === "error" ||
@@ -599,6 +603,7 @@ export function buildAgentRunTerminalOutcomeFromLifecycleEvent(input: {
599603
cancelled &&
600604
!isAbortedAgentStopReason(stopReason) &&
601605
!isCancellationStopReason(stopReason) &&
606+
stopReason !== AGENT_RUN_SUPERSEDED_STOP_REASON &&
602607
(stopReason === undefined || cancellationStatus)
603608
? aborted
604609
? "aborted"
@@ -617,10 +622,10 @@ export function buildAgentRunTerminalOutcomeFromLifecycleEvent(input: {
617622
return stopReason && outcome.stopReason !== stopReason ? { ...outcome, stopReason } : outcome;
618623
}
619624

620-
function hasRestartAbortReason(value: unknown): boolean {
625+
function hasNestedAbortReason(value: unknown, matches: (candidate: unknown) => boolean): boolean {
621626
let candidate = value;
622627
for (let depth = 0; depth < 3; depth += 1) {
623-
if (isAgentRunRestartAbortReason(candidate)) {
628+
if (matches(candidate)) {
624629
return true;
625630
}
626631
if (!(candidate instanceof Error)) {
@@ -658,14 +663,16 @@ export function buildAgentRunTerminalOutcomeFromAttempt(input: {
658663
input.promptTimeoutOutcome?.timeoutPhase ?? (timedOutDuringPrompt ? "provider" : undefined);
659664
const providerStarted =
660665
input.promptTimeoutOutcome?.providerStarted ?? (timedOutDuringPrompt ? true : undefined);
661-
const restartAborted = hasRestartAbortReason(projected.promptError);
666+
const restartAborted = hasNestedAbortReason(projected.promptError, isAgentRunRestartAbortReason);
667+
const superseded = hasNestedAbortReason(projected.promptError, isAgentRunSupersededAbortReason);
662668
const assistantStopReason =
663669
projected.promptErrorSource !== null ? undefined : input.assistant?.stopReason;
664670
const unattributedAttemptTimeout =
665671
projected.timedOut && timeoutPhase === undefined && providerStarted !== true;
666672
const stopReason = unattributedAttemptTimeout
667673
? undefined
668-
: (abortFields.stopReason ??
674+
: ((superseded ? AGENT_RUN_SUPERSEDED_STOP_REASON : undefined) ??
675+
abortFields.stopReason ??
669676
(restartAborted ? AGENT_RUN_RESTART_ABORT_STOP_REASON : undefined) ??
670677
(!timedOut && projected.aborted ? "aborted" : undefined) ??
671678
(!timedOut ? assistantStopReason : undefined));
@@ -707,62 +714,3 @@ export function buildAgentRunTerminalOutcomeFromWaitResult(
707714
endedAt: wait?.endedAt,
708715
});
709716
}
710-
711-
function completedBeforeOrAtTimeout(params: {
712-
completed: AgentRunTerminalOutcome;
713-
timeout: AgentRunTerminalOutcome;
714-
}): boolean {
715-
return (
716-
params.completed.reason === "completed" &&
717-
typeof params.completed.endedAt === "number" &&
718-
typeof params.timeout.endedAt === "number" &&
719-
params.completed.endedAt <= params.timeout.endedAt
720-
);
721-
}
722-
723-
/** Merges later terminal observations without overwriting sticky cancellation/hard-timeout state. */
724-
export function mergeAgentRunTerminalOutcome(
725-
current: AgentRunTerminalOutcome | undefined,
726-
incoming: AgentRunTerminalOutcome,
727-
): AgentRunTerminalOutcome {
728-
if (!current) {
729-
return incoming;
730-
}
731-
if (current.reason === "cancelled") {
732-
// A cancellation callback can arrive before the already-recorded provider
733-
// timeout; timestamps, not callback ordering, identify the terminal owner.
734-
if (
735-
incoming.reason === "hard_timeout" &&
736-
typeof incoming.endedAt === "number" &&
737-
typeof current.endedAt === "number" &&
738-
incoming.endedAt <= current.endedAt
739-
) {
740-
return incoming;
741-
}
742-
return current;
743-
}
744-
// A hard timeout owns the run unless later evidence proves completion ended
745-
// before that timeout; late abort/error cleanup must not downgrade it.
746-
if (current.reason === "hard_timeout") {
747-
if (
748-
incoming.reason === "cancelled" &&
749-
typeof incoming.endedAt === "number" &&
750-
typeof current.endedAt === "number" &&
751-
incoming.endedAt < current.endedAt
752-
) {
753-
return incoming;
754-
}
755-
return completedBeforeOrAtTimeout({ completed: incoming, timeout: current })
756-
? incoming
757-
: current;
758-
}
759-
if (incoming.reason === "cancelled") {
760-
return incoming;
761-
}
762-
if (incoming.reason === "hard_timeout") {
763-
return completedBeforeOrAtTimeout({ completed: current, timeout: incoming })
764-
? current
765-
: incoming;
766-
}
767-
return incoming;
768-
}

0 commit comments

Comments
 (0)