fix(server): reconcile orphaned provider sessions (#7719)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com> Co-authored-by: maria <[email protected]>
This commit is contained in:
1 parent
aa17ec6e7d
commit
0929907ff9
4 files changed
+743
No files matched your search
@@ -0,0 +1,296 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import {
|
||||
type OrchestrationCommand,
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import { OrchestrationCommandInvariantError } from "./orchestration/Errors.ts";
|
||||
import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts";
|
||||
import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { ProviderSessionDirectoryPersistenceError } from "./provider/Errors.ts";
|
||||
import * as ProviderService from "./provider/Services/ProviderService.ts";
|
||||
import * as ProviderSessionDirectory from "./provider/Services/ProviderSessionDirectory.ts";
|
||||
import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
|
||||
|
||||
const providerInstanceId = ProviderInstanceId.make("codex");
|
||||
const updatedAt = "2026-08-20T12:00:00.000Z";
|
||||
|
||||
const makeThread = (
|
||||
id: string,
|
||||
status: "starting" | "running" | "ready" | "stopped" | "error",
|
||||
activeTurnId: TurnId | null = null,
|
||||
archivedAt: string | null = null,
|
||||
) => ({
|
||||
id: ThreadId.make(id),
|
||||
archivedAt,
|
||||
deletedAt: null,
|
||||
session: {
|
||||
threadId: ThreadId.make(id),
|
||||
status,
|
||||
providerName: "codex" as const,
|
||||
providerInstanceId,
|
||||
runtimeMode: "full-access" as const,
|
||||
activeTurnId,
|
||||
lastError: null,
|
||||
updatedAt,
|
||||
},
|
||||
});
|
||||
|
||||
const makeProviderService = (liveThreadIds: ReadonlyArray<ThreadId> = []) =>
|
||||
({
|
||||
startSession: () => Effect.die("unused"),
|
||||
sendTurn: () => Effect.die("unused"),
|
||||
interruptTurn: () => Effect.die("unused"),
|
||||
respondToRequest: () => Effect.die("unused"),
|
||||
respondToUserInput: () => Effect.die("unused"),
|
||||
stopSession: () => Effect.die("unused"),
|
||||
listSessions: () => Effect.succeed(liveThreadIds.map((threadId) => ({ threadId }) as never)),
|
||||
getCapabilities: () => Effect.die("unused"),
|
||||
getInstanceInfo: () => Effect.die("unused"),
|
||||
rollbackConversation: () => Effect.die("unused"),
|
||||
streamEvents: Stream.empty,
|
||||
}) satisfies ProviderService.ProviderService["Service"];
|
||||
|
||||
const queryWithThreads = (threads: ReadonlyArray<ReturnType<typeof makeThread>>) =>
|
||||
({
|
||||
getCommandReadModel: () => Effect.succeed({ threads } as never),
|
||||
}) as unknown as ProjectionSnapshotQuery.ProjectionSnapshotQuery["Service"];
|
||||
|
||||
const runReconciliation = (input: {
|
||||
readonly threads: ReadonlyArray<ReturnType<typeof makeThread>>;
|
||||
readonly liveThreadIds?: ReadonlyArray<ThreadId>;
|
||||
readonly directory: ProviderSessionDirectory.ProviderSessionDirectory["Service"];
|
||||
readonly dispatch: OrchestrationEngine.OrchestrationEngineService["Service"]["dispatch"];
|
||||
}) =>
|
||||
ServerRuntimeStartup.reconcileProviderSessions.pipe(
|
||||
Effect.provideService(
|
||||
ProjectionSnapshotQuery.ProjectionSnapshotQuery,
|
||||
queryWithThreads(input.threads),
|
||||
),
|
||||
Effect.provideService(
|
||||
ProviderService.ProviderService,
|
||||
makeProviderService(input.liveThreadIds),
|
||||
),
|
||||
Effect.provideService(ProviderSessionDirectory.ProviderSessionDirectory, input.directory),
|
||||
Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
|
||||
readEvents: () => Stream.empty,
|
||||
dispatch: input.dispatch,
|
||||
streamDomainEvents: Stream.empty,
|
||||
latestSequence: Effect.succeed(0),
|
||||
}),
|
||||
Effect.provide(NodeServices.layer),
|
||||
);
|
||||
|
||||
it.effect("reconciles multiple active and archived orphans but skips live sessions", () => {
|
||||
const starting = makeThread("thread-starting", "starting");
|
||||
const running = makeThread("thread-running", "running", TurnId.make("turn-running"));
|
||||
const staleActiveTurn = makeThread(
|
||||
"thread-stale-active-turn",
|
||||
"ready",
|
||||
TurnId.make("turn-stale-active"),
|
||||
);
|
||||
const archived = makeThread(
|
||||
"thread-archived",
|
||||
"running",
|
||||
TurnId.make("turn-archived"),
|
||||
updatedAt,
|
||||
);
|
||||
const live = makeThread("thread-live", "running", TurnId.make("turn-live"));
|
||||
const settled = makeThread("thread-ready", "ready");
|
||||
const dispatched: OrchestrationCommand[] = [];
|
||||
const bindingReads: ThreadId[] = [];
|
||||
const upserts: ProviderSessionDirectory.ProviderRuntimeBinding[] = [];
|
||||
|
||||
return runReconciliation({
|
||||
threads: [starting, running, staleActiveTurn, archived, live, settled],
|
||||
liveThreadIds: [live.id],
|
||||
directory: {
|
||||
getBinding: (candidate) =>
|
||||
Effect.sync(() => bindingReads.push(candidate)).pipe(
|
||||
Effect.as(
|
||||
Option.some({
|
||||
threadId: candidate,
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
providerInstanceId,
|
||||
status: "running" as const,
|
||||
resumeCursor: { cursor: candidate },
|
||||
runtimePayload: { activeTurnId: "stale", unrelated: candidate },
|
||||
}),
|
||||
),
|
||||
),
|
||||
upsert: (binding) => Effect.sync(() => upserts.push(binding)),
|
||||
getProvider: () => Effect.die("unused"),
|
||||
listThreadIds: () => Effect.die("unused"),
|
||||
listBindings: () => Effect.die("unused"),
|
||||
},
|
||||
dispatch: (command) =>
|
||||
Effect.sync(() => dispatched.push(command)).pipe(Effect.as({ sequence: dispatched.length })),
|
||||
}).pipe(
|
||||
Effect.tap(() =>
|
||||
Effect.sync(() => {
|
||||
const orphanIds = [starting.id, running.id, staleActiveTurn.id, archived.id];
|
||||
assert.deepStrictEqual(bindingReads, orphanIds);
|
||||
assert.deepStrictEqual(
|
||||
dispatched.map((command) => command.type === "thread.session.set" && command.threadId),
|
||||
orphanIds,
|
||||
);
|
||||
assert.deepStrictEqual(
|
||||
dispatched.map((command) =>
|
||||
command.type === "thread.session.set"
|
||||
? {
|
||||
status: command.session.status,
|
||||
activeTurnId: command.session.activeTurnId,
|
||||
}
|
||||
: null,
|
||||
),
|
||||
orphanIds.map(() => ({ status: "error" as const, activeTurnId: null })),
|
||||
);
|
||||
assert.equal(upserts.length, orphanIds.length);
|
||||
for (const binding of upserts) {
|
||||
assert.equal(binding.status, "stopped");
|
||||
assert.deepStrictEqual(binding.runtimePayload, { activeTurnId: null });
|
||||
assert.deepStrictEqual(binding.resumeCursor, { cursor: binding.threadId });
|
||||
}
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"settles projections when directory bindings are absent, corrupt, or fail to upsert",
|
||||
() => {
|
||||
const absent = makeThread("thread-binding-absent", "starting");
|
||||
const corrupt = makeThread("thread-binding-corrupt", "running");
|
||||
const upsertFailure = makeThread("thread-binding-upsert-failure", "running");
|
||||
const dispatched: OrchestrationCommand[] = [];
|
||||
const corruptFailure = new ProviderSessionDirectoryPersistenceError({
|
||||
operation: "ProviderSessionDirectory.getBinding",
|
||||
detail: "corrupt persisted binding",
|
||||
});
|
||||
const writeFailure = new ProviderSessionDirectoryPersistenceError({
|
||||
operation: "ProviderSessionDirectory.upsert",
|
||||
detail: "failed binding write",
|
||||
});
|
||||
|
||||
return runReconciliation({
|
||||
threads: [absent, corrupt, upsertFailure],
|
||||
directory: {
|
||||
getBinding: (candidate) =>
|
||||
candidate === absent.id
|
||||
? Effect.succeed(Option.none())
|
||||
: candidate === corrupt.id
|
||||
? Effect.fail(corruptFailure)
|
||||
: Effect.succeed(
|
||||
Option.some({
|
||||
threadId: candidate,
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
providerInstanceId,
|
||||
}),
|
||||
),
|
||||
upsert: () => Effect.fail(writeFailure),
|
||||
getProvider: () => Effect.die("unused"),
|
||||
listThreadIds: () => Effect.die("unused"),
|
||||
listBindings: () => Effect.die("unused"),
|
||||
},
|
||||
dispatch: (command) =>
|
||||
Effect.sync(() => dispatched.push(command)).pipe(
|
||||
Effect.as({ sequence: dispatched.length }),
|
||||
),
|
||||
}).pipe(
|
||||
Effect.tap(() =>
|
||||
Effect.sync(() => {
|
||||
assert.deepStrictEqual(
|
||||
dispatched.map((command) => command.type === "thread.session.set" && command.threadId),
|
||||
[absent.id, corrupt.id, upsertFailure.id],
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.effect("retries failed projections and continues after a persistent failure", () => {
|
||||
const transient = makeThread("thread-dispatch-transient-failure", "running");
|
||||
const persistent = makeThread("thread-dispatch-persistent-failure", "running");
|
||||
const later = makeThread("thread-dispatch-success", "running");
|
||||
const attempted: ThreadId[] = [];
|
||||
let transientAttempts = 0;
|
||||
const failure = new OrchestrationCommandInvariantError({
|
||||
commandType: "thread.session.set",
|
||||
detail: "simulated startup reconciliation failure",
|
||||
});
|
||||
|
||||
return runReconciliation({
|
||||
threads: [transient, persistent, later],
|
||||
directory: {
|
||||
getBinding: () => Effect.succeed(Option.none()),
|
||||
upsert: () => Effect.void,
|
||||
getProvider: () => Effect.die("unused"),
|
||||
listThreadIds: () => Effect.die("unused"),
|
||||
listBindings: () => Effect.die("unused"),
|
||||
},
|
||||
dispatch: (command) => {
|
||||
if (command.type !== "thread.session.set") {
|
||||
return Effect.die("unexpected command");
|
||||
}
|
||||
attempted.push(command.threadId);
|
||||
if (command.threadId === transient.id && transientAttempts++ === 0) {
|
||||
return Effect.fail(failure);
|
||||
}
|
||||
return command.threadId === persistent.id
|
||||
? Effect.fail(failure)
|
||||
: Effect.succeed({ sequence: attempted.length });
|
||||
},
|
||||
}).pipe(
|
||||
Effect.tap(() =>
|
||||
Effect.sync(() =>
|
||||
assert.deepStrictEqual(attempted, [
|
||||
transient.id,
|
||||
transient.id,
|
||||
persistent.id,
|
||||
persistent.id,
|
||||
later.id,
|
||||
]),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("does not fail startup when the live provider session inventory cannot be read", () => {
|
||||
let queried = false;
|
||||
return ServerRuntimeStartup.reconcileProviderSessions.pipe(
|
||||
Effect.provideService(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () =>
|
||||
Effect.sync(() => {
|
||||
queried = true;
|
||||
return { threads: [] } as never;
|
||||
}),
|
||||
} as unknown as ProjectionSnapshotQuery.ProjectionSnapshotQuery["Service"]),
|
||||
Effect.provideService(ProviderService.ProviderService, {
|
||||
...makeProviderService(),
|
||||
listSessions: () => Effect.die("provider inventory unavailable"),
|
||||
}),
|
||||
Effect.provideService(ProviderSessionDirectory.ProviderSessionDirectory, {
|
||||
getBinding: () => Effect.die("unused"),
|
||||
upsert: () => Effect.die("unused"),
|
||||
getProvider: () => Effect.die("unused"),
|
||||
listThreadIds: () => Effect.die("unused"),
|
||||
listBindings: () => Effect.die("unused"),
|
||||
}),
|
||||
Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
|
||||
readEvents: () => Stream.empty,
|
||||
dispatch: () => Effect.die("unused"),
|
||||
streamDomainEvents: Stream.empty,
|
||||
latestSequence: Effect.succeed(0),
|
||||
}),
|
||||
Effect.provide(NodeServices.layer),
|
||||
Effect.tap(() => Effect.sync(() => assert.equal(queried, false))),
|
||||
);
|
||||
});
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Console from "effect/Console";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
@@ -33,6 +34,8 @@ import * as ServerSettings from "./serverSettings.ts";
|
||||
import * as AnalyticsService from "./telemetry/AnalyticsService.ts";
|
||||
import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
|
||||
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
|
||||
import * as ProviderService from "./provider/Services/ProviderService.ts";
|
||||
import * as ProviderSessionDirectory from "./provider/Services/ProviderSessionDirectory.ts";
|
||||
import * as ProviderSessionReaper from "./provider/Services/ProviderSessionReaper.ts";
|
||||
import { forkParked } from "./serverActivation.ts";
|
||||
import * as ServiceLauncherClient from "./cloud/serviceLauncherClient.ts";
|
||||
@@ -290,6 +293,89 @@ const runStartupPhase = <A, E, R>(phase: string, effect: Effect.Effect<A, E, R>)
|
||||
Effect.withSpan(`server.startup.${phase}`),
|
||||
);
|
||||
|
||||
const ORPHANED_PROVIDER_SESSION_ERROR =
|
||||
"Provider session did not survive a server restart. Send a new message to continue.";
|
||||
|
||||
export const reconcileProviderSessions = Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
|
||||
const orchestrationEngine = yield* OrchestrationEngine.OrchestrationEngineService;
|
||||
const providerService = yield* ProviderService.ProviderService;
|
||||
const query = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
|
||||
|
||||
const liveThreadIds = new Set(
|
||||
(yield* providerService.listSessions()).map((session) => session.threadId),
|
||||
);
|
||||
const { threads } = yield* query.getCommandReadModel();
|
||||
const orphanedThreads = threads.filter(
|
||||
(thread) =>
|
||||
thread.session !== null &&
|
||||
(thread.session.status === "starting" ||
|
||||
thread.session.status === "running" ||
|
||||
thread.session.activeTurnId !== null) &&
|
||||
!liveThreadIds.has(thread.id),
|
||||
);
|
||||
|
||||
for (const thread of orphanedThreads) {
|
||||
const session = thread.session;
|
||||
if (session === null) {
|
||||
continue;
|
||||
}
|
||||
yield* Effect.gen(function* () {
|
||||
const binding = yield* directory.getBinding(thread.id);
|
||||
if (Option.isSome(binding)) {
|
||||
yield* directory.upsert({
|
||||
...binding.value,
|
||||
status: "stopped",
|
||||
runtimePayload: { activeTurnId: null },
|
||||
});
|
||||
}
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Cause.hasInterrupts(cause)
|
||||
? Effect.failCause(cause)
|
||||
: Effect.logWarning("failed to reconcile orphaned provider session directory binding", {
|
||||
threadId: thread.id,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const reconciledAt = DateTime.formatIso(yield* DateTime.now);
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.make(yield* crypto.randomUUIDv4),
|
||||
threadId: thread.id,
|
||||
session: {
|
||||
...session,
|
||||
status: "error",
|
||||
activeTurnId: null,
|
||||
lastError: ORPHANED_PROVIDER_SESSION_ERROR,
|
||||
updatedAt: reconciledAt,
|
||||
},
|
||||
createdAt: reconciledAt,
|
||||
});
|
||||
}).pipe(
|
||||
Effect.retry({ times: 1 }),
|
||||
Effect.catchCause((cause) =>
|
||||
Cause.hasInterrupts(cause)
|
||||
? Effect.failCause(cause)
|
||||
: Effect.logWarning("failed to settle orphaned provider session projection", {
|
||||
threadId: thread.id,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Cause.hasInterrupts(cause)
|
||||
? Effect.failCause(cause)
|
||||
: Effect.logWarning("provider session startup reconciliation failed", { cause }),
|
||||
),
|
||||
);
|
||||
|
||||
interface StartupOptions {
|
||||
readonly activate?: Effect.Effect<void>;
|
||||
readonly awaitAuxiliaryParked?: Effect.Effect<void>;
|
||||
@@ -354,6 +440,8 @@ export const make = (options?: StartupOptions) =>
|
||||
}),
|
||||
);
|
||||
|
||||
yield* runStartupPhase("provider-sessions.reconcile", reconcileProviderSessions);
|
||||
|
||||
const welcomeBase = yield* resolveWelcomeBase;
|
||||
const environment = yield* serverEnvironment.getDescriptor;
|
||||
yield* Effect.logDebug("startup phase: preparing welcome payload");
|
||||
|
||||
Reference in new issue
Block a user