fix(server): deferred context handoffs are retried after ordinary turns #18620
main fromrefs/pull/18620/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:S
juliusmarminge added labelsmacroscope-review
- apps/server/src/orchestration-v2/ContextHandoffDelivery.ts line 86OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -79,6 +78,9 @@7978 omittedItems: pending.reduce((sum, handoff) => sum + (handoff.history?.omittedItems ?? 0), 0),8079 budget,8180 });82- if (historyCost(selected.messages, selected.context) > budget) {83- if (input.deferInline) return { context: "", delivered: Effect.void, unsent: Effect.void };84- return yield* new ContextHandoffBudgetError();81+ const selectedCost = historyCost(selected.messages, selected.context);82+ if (selectedCost > budget) {83+ // Failing here wedges every later turn while the handoff stays ready.84+ // Keep it ready instead, like /compact, and let the user message through.85+ yield* Effect.logDebug("Deferring context handoff delivery until context is available", {86+ handoffIds: pending.map((handoff) => handoff.id),
- apps/server/src/orchestration-v2/ContextHandoffDelivery.ts line 120Resolvedby Alb11747(GitHub profile, opens in a new tab)@@ -79,6 +78,13 @@7978 omittedItems: pending.reduce((sum, handoff) => sum + (handoff.history?.omittedItems ?? 0), 0),8079 budget,8180 });82- if (historyCost(selected.messages, selected.context) > budget) {83- if (input.deferInline) return { context: "", delivered: Effect.void, unsent: Effect.void };84- return yield* new ContextHandoffBudgetError();81+ const selectedCost = historyCost(selected.messages, selected.context);82+ if (selectedCost > budget) {83+ // Failing here wedges every later turn while the handoff stays ready.84+ // Keep it ready instead, like /compact, and let the user message through.85+ yield* Effect.logDebug("Deferring context handoff delivery until context is available", {86+ handoffIds: pending.map((handoff) => handoff.id),87+ budget,88+ selectedCost,89+ });90+ return { context: "", delivered: Effect.void, unsent: Effect.void };apps/server/src/orchestration-v2/ProviderTurnStartService.ts lines 253 to 257OutdatedResolvedby Alb11747(GitHub profile, opens in a new tab)@@ -249,11 +249,9 @@249249 source.id === handoff.targetRunId &&250250 (source.status === "failed" ||251251 source.status === "interrupted" ||252+ // Ordinary turns can complete while delivery is deferred for space.252253 (source.status === "completed" &&253254 handoff.delivery === undefined &&254- projection.messages.some(255- (message) =>256- message.id === source.userMessageId &&257- message.attachments.length === 0 &&258- message.text.trim().toLowerCase() === "/compact",259- ))),255+ projection.contextTransfers.find(256+ (transfer) => transfer.id === handoff.transferId,257+ )?.type !== "subagent_result")),
coderabbitai[bot](GitHub profile, opens in a new tab) approved these changes
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:S
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:M
coderabbitai[bot](GitHub profile, opens in a new tab) requested changes
apps/server/src/orchestration-v2/ProviderTurnStartService.ts lines 261 to 262OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -256,4 +256,7 @@256256 message.id === source.userMessageId &&257257 message.attachments.length === 0 &&258258 message.text.trim().toLowerCase() === "/compact",259- ))),259+ )) ||260+ // Over budget, delivery was deferred; retry once space recovers.261+ ((source.status === "completed" || source.status === "cancelled") &&262+ handoff.delivery?.status === "deferred")),- apps/server/src/orchestration-v2/ContextHandoffDelivery.ts lines 94 to 98OutdatedResolvedby Alb11747(GitHub profile, opens in a new tab)@@ -81,4 +81,18 @@8181 });82- if (historyCost(selected.messages, selected.context) > budget) {83- if (input.deferInline) return { context: "", delivered: Effect.void, unsent: Effect.void };84- return yield* new ContextHandoffBudgetError();82+ const selectedCost = historyCost(selected.messages, selected.context);83+ if (selectedCost > budget) {84+ // Failing here wedges every later turn while the handoff stays ready.85+ // Keep it ready instead, like /compact, and let the user message through.86+ // The deferred marker lets later turns retry it once space recovers.87+ yield* Effect.logDebug("Deferring context handoff delivery until context is available", {88+ handoffCount: pending.length,89+ budget,90+ selectedCost,91+ });92+ if (nativeThreadId !== undefined) {93+ yield* Effect.forEach(94+ pending,95+ (handoff) =>96+ input.persist({97+ ...handoff,98+ delivery: { nativeThreadId, status: "deferred", itemIds: [] },
- apps/server/src/orchestration-v2/ContextHandoffDelivery.ts line 102OutdatedResolvedby Alb11747(GitHub profile, opens in a new tab)@@ -84,0 +82,21 @@82+ const selectedCost = historyCost(selected.messages, selected.context);83+ if (selectedCost > budget) {84+ // Failing here wedges every later turn while the handoff stays ready.85+ // Keep it ready instead, like /compact, and let the user message through.86+ // The deferred marker lets later turns retry it once space recovers.87+ yield* Effect.logDebug("Deferring context handoff delivery until context is available", {88+ handoffCount: pending.length,89+ budget,90+ selectedCost,91+ });92+ if (nativeThreadId !== undefined) {93+ yield* Effect.forEach(94+ pending.filter(95+ (handoff) =>96+ handoff.delivery?.nativeThreadId !== nativeThreadId ||97+ handoff.delivery.status !== "deferred",98+ ),99+ (handoff) =>100+ input.persist({101+ ...handoff,102+ delivery: { nativeThreadId, status: "deferred", itemIds: [] },
coderabbitai[bot](GitHub profile, opens in a new tab) approved these changes
- apps/server/src/orchestration-v2/ProviderTurnStartService.ts line 997OutdatedResolvedby Alb11747(GitHub profile, opens in a new tab)@@ -985,4 +993,5 @@985993 (handoff) =>986994 handoff.toProviderThreadId === providerThread.id &&987995 handoff.delivery?.nativeThreadId === runningProviderThread.nativeThreadRef?.nativeId &&988- handoff.delivery?.status !== "pending",996+ handoff.delivery?.status !== "pending" &&997+ handoff.delivery?.status !== "deferred",
- apps/server/src/orchestration-v2/ContextHandoffDelivery.ts line 120Resolvedby Alb11747(GitHub profile, opens in a new tab)@@ -84,0 +99,21 @@99+ yield* Effect.logDebug("Deferring context handoff delivery until context is available", {100+ handoffCount: pending.length,101+ budget,102+ selectedCost,103+ });104+ if (nativeThreadId !== undefined) {105+ yield* Effect.forEach(106+ pending.filter(107+ (handoff) =>108+ handoff.delivery?.nativeThreadId !== nativeThreadId ||109+ handoff.delivery.status !== "deferred",110+ ),111+ (handoff) =>112+ input.persist({113+ ...handoff,114+ delivery: { nativeThreadId, status: "deferred", itemIds: [] },115+ }),116+ { discard: true },117+ );118+ }119+ return { context: "", delivered: Effect.void, unsent: Effect.void };
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:M
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
- apps/server/src/orchestration-v2/ProviderTurnStartService.ts line 1086OutdatedResolvedby Alb11747(GitHub profile, opens in a new tab)@@ -1064,0 +1066,21 @@1066+ candidate.id === source.userMessageId &&1067+ candidate.attachments.length === 0 &&1068+ candidate.text.trim().toLowerCase() === "/compact",1069+ ) &&1070+ acceptedAttempts.some(1071+ (candidate) =>1072+ candidate.id === source.activeAttemptId &&1073+ candidate.status === "completed" &&1074+ candidate.nativeThreadId !== undefined &&1075+ candidate.nativeThreadId === runningProviderThread.nativeThreadRef?.nativeId,1076+ ),1077+ );1078+ const compactedAt = compaction?.completedAt;1079+ const importedAfterCompaction = new Set(1080+ settledHandoffs.flatMap((handoff) =>1081+ compactedAt != null && DateTime.isGreaterThanOrEqualTo(handoff.updatedAt, compactedAt)1082+ ? (handoff.delivery?.itemIds ?? [])1083+ : [],1084+ ),1085+ );1086+ // Successful compaction bounds the fallback, without inventing telemetry.apps/server/src/orchestration-v2/ProviderTurnStartService.ts line 1064OutdatedResolvedby Alb11747(GitHub profile, opens in a new tab)@@ -1051,14 +1058,7 @@1051- item.runId !== null &&1052- (nativeInputRunIds.has(item.runId) ||1053- (legacyInputRunIds.has(item.runId) &&1054- !coveredItemIds.has(item.id) &&1055- !legacyRecoveredRunIds.has(item.runId)))1056- ? attachmentTokenAllowance(item.attachments)1057- : 0;1058- return (1059- sum +1060- (historical === null ? 0 : Buffer.byteLength(historical.text)) +1061- nativeAttachments1062- );1063- }, 0)1064- : 0;1058+ if (!sameNativeThread) return 0;1059+ const compaction = projection.runs.findLast(1060+ (source) =>1061+ source.ordinal < run.ordinal &&1062+ source.status === "completed" &&1063+ source.completedAt !== null &&1064+ projection.messages.some(
- apps/server/src/orchestration-v2/ProviderTurnStartService.ts line 1142Resolvedby Alb11747(GitHub profile, opens in a new tab)@@ -784,0 +799,21 @@799+ const deliveredAttemptIds = new Set(800+ projection.providerTurns.map((turn) => turn.runAttemptId),801+ );802+ const acceptedAttempts = projection.attempts.filter(803+ (source) =>804+ source.providerThreadId === providerThread.id && deliveredAttemptIds.has(source.id),805+ );806+ const acceptedAttemptsById = new Map(acceptedAttempts.map((source) => [source.id, source]));807+ const nativeId = loadedProviderThread.nativeThreadRef?.nativeId;808+ const compaction =809+ sameNativeThread && nativeId !== undefined810+ ? projection.runs.findLast((source) => {811+ const acceptedAttempt =812+ source.activeAttemptId === null813+ ? undefined814+ : acceptedAttemptsById.get(source.activeAttemptId);815+ return (816+ source.ordinal < run.ordinal &&817+ source.status === "completed" &&818+ source.completedAt !== null &&819+ compactionMessageIds.has(source.userMessageId) &&apps/server/src/orchestration-v2/ProviderTurnStartService.ts lines 843 to 845OutdatedResolvedby Alb11747(GitHub profile, opens in a new tab)@@ -796,9 +836,10 @@796836 const sameSelection =797837 previousSelection === undefined ||798838 modelSelectionsEqual(previousSelection, run.modelSelection);799- const sameNativeThread =800- loadedProviderThread.nativeThreadRef?.nativeId === providerThread.nativeThreadRef?.nativeId;801839 const threadUsage = loadedProviderThread.contextUsage ?? providerThread.contextUsage;802840 const previousUsage = measuredContext803841 ? { ...threadUsage, ...measuredContext.usage }804842 : threadUsage;843+ const staleAfterCompaction =844+ compaction !== undefined &&845+ (measuredContext === undefined || measuredContext.runOrdinal < compaction.ordinal);
- apps/server/src/orchestration-v2/ContextHandoffDelivery.ts lines 113 to 116Resolvedby Alb11747(GitHub profile, opens in a new tab)@@ -84,0 +95,21 @@95+ if (selectedCost > budget) {96+ // Failing here wedges every later turn while the handoff stays ready.97+ // Keep it ready instead, like /compact, and let the user message through.98+ // The deferred marker lets later turns retry it once space recovers.99+ yield* Effect.logDebug("Deferring context handoff delivery until context is available", {100+ handoffCount: pending.length,101+ budget,102+ selectedCost,103+ });104+ if (nativeThreadId !== undefined) {105+ yield* Effect.forEach(106+ pending.filter(107+ (handoff) =>108+ handoff.delivery?.nativeThreadId !== nativeThreadId ||109+ handoff.delivery.status !== "deferred",110+ ),111+ (handoff) =>112+ input.persist({113+ ...handoff,114+ delivery: { nativeThreadId, status: "deferred", itemIds: [] },115+ }),packages/provider-acp/src/server/adapter.ts line 4137OutdatedResolvedby Alb11747(GitHub profile, opens in a new tab)@@ -4132,3 +4134,4 @@41324134 );41334135 if (context?.nativeThreadId === notification.sessionId) {41344136 context.contextUsage = stateEvent.usage;4137+ context.hasFreshContextUsage = true;
- packages/provider-acp/src/server/adapter.ts line 6658Resolvedby Alb11747(GitHub profile, opens in a new tab)@@ -6619,3 +6621,8 @@66196621 context.input.message.attachments.length === 0 &&66206622 settledStatus === "completed"66216623 ) {6624+ // Usage reports carry no sample identity. Without a native completion6625+ // boundary, an in-turn report may still describe the pre-compact context.6626+ // Native completion already clears usage, so only later reports survive.6627+ if (!context.hasCompletedNativeCompaction) {6628+ context.contextUsage = null;apps/server/src/orchestration-v2/ProviderTurnStartService.ts line 902OutdatedResolvedby Alb11747(GitHub profile, opens in a new tab)@@ -796,9 +891,12 @@796891 const sameSelection =797892 previousSelection === undefined ||798893 modelSelectionsEqual(previousSelection, run.modelSelection);799- const sameNativeThread =800- loadedProviderThread.nativeThreadRef?.nativeId === providerThread.nativeThreadRef?.nativeId;801894 const threadUsage = loadedProviderThread.contextUsage ?? providerThread.contextUsage;802895 const previousUsage = measuredContext803896 ? { ...threadUsage, ...measuredContext.usage }804897 : threadUsage;898+ const staleAfterCompaction =899+ compaction !== undefined &&900+ measuredContext !== undefined &&901+ (measuredContext.runOrdinal < compaction.ordinal ||902+ (!compaction.explicit &&
- apps/server/src/orchestration-v2/ProviderTurnStartService.ts lines 1267 to 1270Resolvedby Alb11747(GitHub profile, opens in a new tab)@@ -796,9 +904,17 @@796904 const sameSelection =797905 previousSelection === undefined ||798906 modelSelectionsEqual(previousSelection, run.modelSelection);799- const sameNativeThread =800- loadedProviderThread.nativeThreadRef?.nativeId === providerThread.nativeThreadRef?.nativeId;801907 const threadUsage = loadedProviderThread.contextUsage ?? providerThread.contextUsage;802908 const previousUsage = measuredContext803909 ? { ...threadUsage, ...measuredContext.usage }804910 : threadUsage;911+ const staleAfterCompaction =912+ compaction !== undefined &&913+ measuredContext !== undefined &&914+ (measuredContext.runOrdinal < compaction.ordinal ||915+ (compactionUsageResetAt !== undefined &&916+ // Equal timestamps cannot establish post-compaction provenance.917+ DateTime.isLessThanOrEqualTo(918+ DateTime.makeUnsafe(measuredContext.reportedAt),919+ compactionUsageResetAt,920+ )));
- apps/server/src/orchestration-v2/ProviderTurnStartService.ts line 269Resolvedby Alb11747(GitHub profile, opens in a new tab)@@ -251,8 +261,7 @@251261 source.status === "interrupted" ||252262 (source.status === "completed" &&253263 handoff.delivery === undefined &&254- projection.messages.some(255- (message) =>256- message.id === source.userMessageId &&257- message.attachments.length === 0 &&258- message.text.trim().toLowerCase() === "/compact",264+ compactionMessageIds.has(source.userMessageId)) ||265+ // Retry deferred history once space recovers. Child results remain266+ // available through task_status after their delivery turn ends.267+ ((source.status === "completed" || source.status === "cancelled") &&apps/server/src/orchestration-v2/ProviderTurnStartService.ts lines 1182 to 1187Resolvedby Alb11747(GitHub profile, opens in a new tab)@@ -784,0 +845,21 @@845+ for (const item of projection.turnItems) {846+ if (847+ item.type !== "compaction" ||848+ item.status !== "completed" ||849+ item.providerThreadId !== providerThread.id ||850+ item.providerTurnId === null ||851+ item.runId === null852+ )853+ continue;854+ const providerTurn = providerTurnsById.get(item.providerTurnId);855+ const acceptedAttempt =856+ providerTurn?.runAttemptId == null857+ ? undefined858+ : acceptedAttemptsById.get(providerTurn.runAttemptId);859+ const source = runsById.get(item.runId);860+ if (861+ source === undefined ||862+ source.ordinal >= run.ordinal ||863+ acceptedAttempt?.nativeThreadId !== nativeId ||864+ acceptedAttempt.runId !== item.runId ||865+ providerTurn?.nodeId !== acceptedAttempt.rootNodeId
- apps/server/src/orchestration-v2/ProviderTurnStartService.ts line 1185OutdatedResolvedby Alb11747(GitHub profile, opens in a new tab)@@ -1015,3 +1177,9 @@10151177 .filter((source) => source.nativeThreadId === undefined)10161178 .map((source) => source.runId),10171179 );1180+ const acceptedRunIds = new Set(acceptedAttempts.map((source) => source.runId));1181+ // Restart may cancel after the running write but before prompt acceptance.1182+ // Its request occupies no native context and must not be replayed as missed work.1183+ const unsentCancelledRunIds = new Set(1184+ projection.runs1185+ .filter((source) => source.status === "cancelled" && !acceptedRunIds.has(source.id))apps/server/src/orchestration-v2/ProviderTurnStartService.ts line 896OutdatedResolvedby Alb11747(GitHub profile, opens in a new tab)@@ -784,0 +876,21 @@876+ compactionUsageResetAt = completedAt;877+ compactionAfterTokenCount = item.afterTokenCount;878+ }879+ continue;880+ }881+ if (882+ compaction !== undefined &&883+ !DateTime.isGreaterThan(completedAt, compaction.completedAt)884+ )885+ continue;886+ // Automatic compaction can finish before the ordinary turn fails.887+ // Its tool node is scoped through the accepted root provider turn.888+ compaction = {889+ runId: source.id,890+ ordinal: source.ordinal,891+ completedAt,892+ explicit: false,893+ summary: item.summary ?? "",894+ };895+ compactionUsageResetAt = completedAt;896+ compactionAfterTokenCount = item.afterTokenCount;
- apps/server/src/orchestration-v2/ProviderTurnStartService.ts line 899Resolvedby Alb11747(GitHub profile, opens in a new tab)@@ -667,3 +696,20 @@696+ .map((source) => [source.id, source]),697+ );698+ const completedCancelledAttempts = new Set(699+ projection.providerTurns.flatMap((turn) =>700+ turn.providerThreadId === providerThread.id &&701+ turn.status === "completed" &&702+ turn.runAttemptId !== null &&703+ cancelledNativeAttempts.get(turn.runAttemptId)?.rootNodeId === turn.nodeId704+ ? [turn.runAttemptId]705+ : [],706+ ),707+ );708+ // Adapters publish running turns on either side of prompt submission.709+ // Neither an absent nor an incomplete turn proves a cancelled request710+ // was unsent. Replace that native session to resolve uncertain occupancy.711+ const uncertainCancelledPrompt = [...cancelledNativeAttempts.keys()].some(712+ (attemptId) => !completedCancelledAttempts.has(attemptId),667713 );668714 const resumed = yield* Effect.result(669- uncertainDelivery715+ uncertainDelivery || uncertainCancelledPromptapps/server/src/orchestration-v2/ProjectionStore.ts line 3923OutdatedResolvedby Alb11747(GitHub profile, opens in a new tab)@@ -3919,4 +3919,5 @@39193919 `.pipe(Effect.flatMap(decodeRows(decodeContextTransferPayload, threadId)));39203920 const turnItems = yield* sql<PayloadRow>`39213921 SELECT payload_json FROM orchestration_v2_projection_turn_items3922- WHERE thread_id = ${threadId} AND run_id = ${runId} ORDER BY ordinal ASC, turn_item_id ASC3922+ WHERE thread_id = ${threadId}3923+ AND (run_id = ${runId} OR (type = 'compaction' AND status = 'completed'))
- apps/server/src/orchestration-v2/ProviderTurnStartService.ts line 899Resolvedby Alb11747(GitHub profile, opens in a new tab)@@ -667,3 +696,20 @@696+ .map((source) => [source.id, source]),697+ );698+ const completedCancelledAttempts = new Set(699+ projection.providerTurns.flatMap((turn) =>700+ turn.providerThreadId === providerThread.id &&701+ turn.status === "completed" &&702+ turn.runAttemptId !== null &&703+ cancelledNativeAttempts.get(turn.runAttemptId)?.rootNodeId === turn.nodeId704+ ? [turn.runAttemptId]705+ : [],706+ ),707+ );708+ // Adapters publish running turns on either side of prompt submission.709+ // Neither an absent nor an incomplete turn proves a cancelled request710+ // was unsent. Replace that native session to resolve uncertain occupancy.711+ const uncertainCancelledPrompt = [...cancelledNativeAttempts.keys()].some(712+ (attemptId) => !completedCancelledAttempts.has(attemptId),667713 );668714 const resumed = yield* Effect.result(669- uncertainDelivery715+ uncertainDelivery || uncertainCancelledPromptapps/server/src/orchestration-v2/ProviderTurnStartService.ts lines 1044 to 1049Resolvedby Alb11747(GitHub profile, opens in a new tab)@@ -714,3 +766,9 @@714766 type: "provider_resume_fallback",715767 });716768 const createdAt = yield* DateTime.now;769+ // A cancelled request must not become an instruction in the recovered770+ // session. Retain any output from its run as historical context.771+ const cancelledRequestIds = new Set(772+ projection.runs773+ .filter((source) => source.status === "cancelled")774+ .map((source) => source.userMessageId),apps/server/src/orchestration-v2/ProviderTurnStartService.ts lines 1207 to 1209Resolvedby Alb11747(GitHub profile, opens in a new tab)@@ -784,0 +903,21 @@903+ : acceptedAttemptsById.get(providerTurn.runAttemptId);904+ const source = runsById.get(item.runId);905+ if (906+ source === undefined ||907+ source.status === "rolled_back" ||908+ source.ordinal >= run.ordinal ||909+ acceptedAttempt?.nativeThreadId !== nativeId ||910+ acceptedAttempt.runId !== item.runId ||911+ providerTurn?.nodeId !== acceptedAttempt.rootNodeId912+ )913+ continue;914+ const completedAt = item.completedAt ?? item.updatedAt;915+ if (item.runId === explicitCompaction?.id) {916+ if (917+ compaction?.runId === item.runId &&918+ (compactionUsageResetAt === undefined ||919+ DateTime.isGreaterThan(completedAt, compactionUsageResetAt))920+ ) {921+ compactionUsageResetAt = completedAt;922+ compactionMarker = item;923+ }
Sign in to join this conversation.
Codex Review Summary#
This comment shows the latest Codex review activity on this pull request.
a8fe227ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.