fix(server): make compatible Codex instance switches single-writer #8580
Closedvitaliyhayda(GitHub profile, opens in a new tab)wants to merge 9 commits into
main fromrefs/pull/8580/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:XL
- apps/server/src/provider/Layers/CodexAdapter.ts lines 1695 to 1695OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1665,0 +1675,21 @@1675+ });1676+1677+ const releaseSessionResources = Effect.fn("releaseSessionResources")(function* (1678+ threadId: ThreadId,1679+ runtime: CodexSessionRuntimeShape,1680+ scope: Scope.Closeable,1681+ eventFiber: Fiber.Fiber<void, never>,1682+ ) {1683+ const cleanupExit = yield* Effect.exit(1684+ runtime.close.pipe(1685+ Effect.ensuring(Scope.close(scope, Exit.void)),1686+ Effect.ensuring(Fiber.interrupt(eventFiber)),1687+ Effect.uninterruptible,1688+ ),1689+ );1690+ if (Exit.isFailure(cleanupExit)) {1691+ const cause = Cause.squash(cleanupExit.cause);1692+ return yield* new ProviderAdapterProcessError({1693+ provider: PROVIDER,1694+ threadId,1695+ detail: cause instanceof Error ? cause.message : String(cause),apps/server/src/provider/Layers/CodexSessionRuntime.ts lines 312 to 313OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -269,0 +293,21 @@293+ ExitRequirements,294+ RunningError,295+ RunningRequirements,296+>(input: {297+ readonly threadId: ThreadId;298+ readonly exitCode: Effect.Effect<number, ExitError, ExitRequirements>;299+ readonly isRunning: Effect.Effect<boolean, RunningError, RunningRequirements>;300+ readonly exitProofTimeout?: Duration.Input;301+}) =>302+ Effect.gen(function* () {303+ const childExit = yield* input.exitCode.pipe(304+ Effect.exit,305+ Effect.timeoutOption(input.exitProofTimeout ?? CODEX_APP_SERVER_EXIT_PROOF_TIMEOUT),306+ );307+ if (Option.isNone(childExit)) {308+ return yield* new CodexSessionRuntimeWriterReleaseUnprovenError({309+ threadId: input.threadId,310+ });311+ }312+ const childRunning = yield* input.isRunning.pipe(Effect.exit);313+ if (Exit.isFailure(childRunning) || childRunning.value) {
- apps/server/src/provider/Layers/CodexAdapter.ts line 98Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -93,3 +95,4 @@9395 readonly scope: Scope.Closeable;9496 readonly runtime: CodexSessionRuntimeShape;9597 readonly eventFiber: Fiber.Fiber<void, never>;98+ routable: boolean;apps/server/src/provider/Layers/CodexAdapter.ts line 1805Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1757,4 +1802,4 @@17571802 }),17581803 ).pipe(Effect.forkIn(sessionScope));175918041760- const started = yield* runtime.start().pipe(1805+ const sessionContext: CodexAdapterSessionContext = {
- apps/server/src/provider/Layers/ProviderService.ts line 260OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -232,4 +254,7 @@232254 const revokeMcpCredential =233255 options?.revokeMcpCredential ?? McpSessionRegistry.revokeActiveMcpThread;234256 const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();257+ const threadLocks = yield* SynchronizedRef.make(new Map<ThreadId, Semaphore.Semaphore>());235258 const nowIso = Effect.map(DateTime.now, DateTime.formatIso);259+260+ const getThreadLock = (threadId: ThreadId) =>
- apps/server/src/provider/Layers/ProviderService.ts line 930Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -690,8 +902,14 @@690902691- // Changing runtime mode restarts the session, so the transition is only692- // observable here, by diffing against the mode the previous session for693- // this thread was bound to. Recording it separately is what makes the694- // "started supervised, switched to full access" funnel answerable.695- const previousRuntimeMode = persistedBinding?.runtimeMode;696- if (previousRuntimeMode !== undefined && previousRuntimeMode !== input.runtimeMode) {697- yield* analytics.record("provider.runtime_mode.changed", {903+ if (handoffNativeThreadId === undefined) {904+ yield* stopStaleSessionsForThread({905+ threadId,906+ currentInstanceId: resolvedInstanceId,907+ });908+ }909+ const bindingExit = yield* Effect.exit(910+ upsertSessionBinding(sessionWithInstance, threadId, {911+ modelSelection: input.modelSelection,912+ }),913+ );914+ if (Exit.isFailure(bindingExit)) {915+ yield* stopProvisionalTarget;apps/server/src/provider/Layers/ProviderService.ts lines 258 to 258Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -175,3 +239,20 @@175239 return trimmed.length > 0 ? trimmed : undefined;176240 }177241242+function readPersistedActiveTurnId(243+ runtimePayload: ProviderSessionDirectory.ProviderRuntimeBinding["runtimePayload"],244+): unknown {245+ if (!runtimePayload || typeof runtimePayload !== "object" || Array.isArray(runtimePayload)) {246+ return undefined;247+ }248+ return "activeTurnId" in runtimePayload ? runtimePayload.activeTurnId : undefined;249+}250+251+function readCodexNativeThreadId(cursor: unknown): string | undefined {252+ if (cursor === null || typeof cursor !== "object" || Array.isArray(cursor)) {253+ return undefined;254+ }255+ const threadId = "threadId" in cursor ? cursor.threadId : undefined;256+ if (typeof threadId !== "string") return undefined;257+ const trimmed = threadId.trim();258+ return trimmed.length > 0 ? trimmed : undefined;apps/server/src/provider/Layers/CodexSessionRuntime.ts line 2348OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -2276,13 +2335,14 @@2276- }2335+ const performClose = Effect.gen(function* () {22772336 yield* settlePendingApprovals("cancel");22782337 yield* settlePendingUserInputs({});2338+ yield* Scope.close(runtimeScope, Exit.void);2339+ yield* proveCodexAppServerWriterReleased({2340+ threadId: options.threadId,2341+ exitCode: child.exitCode,2342+ isRunning: child.isRunning,2343+ });22792344 yield* updateSession(sessionRef, {22802345 status: "closed",22812346 activeTurnId: undefined,22822347 });2283- yield* emitSessionEvent("session/closed", "Session stopped").pipe(2284- Effect.catch((cause) =>2285- Effect.logError("Failed to emit Codex session closed event.", { cause }),2286- ),2287- );2288- yield* Scope.close(runtimeScope, Exit.void);2348+ const closedEvent = yield* emitSessionEvent("session/closed", "Session stopped");apps/server/src/provider/Layers/ProviderService.ts line 1094Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -859,2 +1059,21 @@1059+ model: metricModel,1060+ extra: {1061+ operation: "send",1062+ },8591063 }),8601064 }),1065+ ),1066+ );1067+ });1068+1069+ const interruptTurn: ProviderServiceMethod<"interruptTurn"> = Effect.fn("interruptTurn")(1070+ function* (rawInput) {1071+ const input = yield* decodeInputOrValidationError({1072+ operation: "ProviderService.interruptTurn",1073+ schema: ProviderInterruptTurnInput,1074+ payload: rawInput,1075+ });1076+ let metricProvider = "unknown";1077+ // Interrupt remains out of band from turn operations so it can cancel a1078+ // blocked send. The routing lock still orders it behind session handoffs.1079+ return yield* withThreadRoutingLock(
- @@ -817,20 +1006 @@817- providerTurnMetricAttributes({818- provider: metricProvider,819- model: metricModel,820- extra: {821- operation: "send",822- },823- }),824- }),825- );826- });827-828- const interruptTurn: ProviderServiceMethod<"interruptTurn"> = Effect.fn("interruptTurn")(829- function* (rawInput) {830- const input = yield* decodeInputOrValidationError({831- operation: "ProviderService.interruptTurn",832- schema: ProviderInterruptTurnInput,833- payload: rawInput,834- });835- let metricProvider = "unknown";836- return yield* Effect.gen(function* () {1006+ return yield* withThreadLock(apps/server/src/provider/Layers/ProviderService.ts lines 734 to 738Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -618,0 +706,21 @@706+ "ProviderService.startSession",707+ `Provider instance '${resolvedInstanceId}' belongs to driver '${resolvedProvider}', not '${parsed.provider}'.`,708+ );709+ }710+ const input = {711+ ...parsed,712+ threadId,713+ provider: resolvedProvider,714+ };715+ if (!instanceInfo.enabled) {716+ return yield* toValidationError(717+ "ProviderService.startSession",718+ `Provider instance '${resolvedInstanceId}' is disabled in T3 Code settings.`,719+ );720+ }721+ const persistedBinding = Option.getOrUndefined(yield* directory.getBinding(threadId));722+ const sourceInstanceId = persistedBinding?.providerInstanceId;723+ const isCodexInstanceChange =724+ resolvedProvider === "codex" &&725+ sourceInstanceId !== undefined &&726+ sourceInstanceId !== resolvedInstanceId;
shivamhwp(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.
Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID:
46734790-fb33-4451-97e4-66a48f3323eaYou can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
Comment `@coderabbitai help` to get the list of available commands.